qid
int64
4
19.1M
question
stringlengths
18
48.3k
answers
list
date
stringlengths
10
10
metadata
list
87,304
<p>What's a good algorithm for calculating frames per second in a game? I want to show it as a number in the corner of the screen. If I just look at how long it took to render the last frame the number changes too fast.</p> <p>Bonus points if your answer updates each frame and doesn't converge differently when the frame rate is increasing vs decreasing.</p>
[ { "answer_id": 87333, "author": "Martin Beckett", "author_id": 10897, "author_profile": "https://Stackoverflow.com/users/10897", "pm_score": 7, "selected": false, "text": "// eg.\nfloat smoothing = 0.9; // larger=more smoothing\nmeasurement = (measurement * smoothing) + (current * (1.0-smoothing))\n" }, { "answer_id": 87523, "author": "Wedge", "author_id": 332, "author_profile": "https://Stackoverflow.com/users/332", "pm_score": 5, "selected": false, "text": "frames / sec = 1 / (sec / frame)\n fps = # of rendering times in queue / total rendering time\n fps = # frames / (current time - start time)\n" }, { "answer_id": 87732, "author": "KPexEA", "author_id": 13676, "author_profile": "https://Stackoverflow.com/users/13676", "pm_score": 6, "selected": false, "text": "#define MAXSAMPLES 100\nint tickindex=0;\nint ticksum=0;\nint ticklist[MAXSAMPLES];\n\n/* need to zero out the ticklist array before starting */\n/* average will ramp up until the buffer is full */\n/* returns average ticks per frame over the MAXSAMPLES last frames */\n\ndouble CalcAverageTick(int newtick)\n{\n ticksum-=ticklist[tickindex]; /* subtract value falling off */\n ticksum+=newtick; /* add new value */\n ticklist[tickindex]=newtick; /* save new value so it can be subtracted later */\n if(++tickindex==MAXSAMPLES) /* inc buffer index */\n tickindex=0;\n\n /* return average */\n return((double)ticksum/MAXSAMPLES);\n}\n" }, { "answer_id": 88179, "author": "jilles de wit", "author_id": 7531, "author_profile": "https://Stackoverflow.com/users/7531", "pm_score": 0, "selected": false, "text": "do while (1)\n{\n ProcessImage(frame)\n if (frame.framenumber%poll_interval==0)\n {\n new_time=timer.peek()\n framerate=poll_interval/(new_time - last_time)\n last_time=new_time\n }\n}\n do while (1)\n{\n ProcessImage(frame)\n new_time=timer.peek()\n delta=new_time - last_time\n last_time = new_time\n total_time += delta\n delta_history.push(delta)\n framerate= delta_history.length() / total_time\n while (delta_history.length() > avg_interval)\n {\n oldest_delta = delta_history.pop()\n total_time -= oldest_delta\n }\n} \n" }, { "answer_id": 288674, "author": "David Frenkel", "author_id": 28747, "author_profile": "https://Stackoverflow.com/users/28747", "pm_score": 2, "selected": false, "text": "#define ONE_OVER_FPS (1.0f/60.0f)\nstatic float g_SpikeGuardBreakpoint = 3.0f * ONE_OVER_FPS;\nif(time > g_SpikeGuardBreakpoint)\n DoInternalBreakpoint()\n" }, { "answer_id": 7796547, "author": "Peter Jankuliak", "author_id": 273348, "author_profile": "https://Stackoverflow.com/users/273348", "pm_score": 4, "selected": false, "text": "Example where i = 3\n\n|f[0] |f[1] |f[2] |\n+----------+-------------+-------+------> time\n (1) fps[i] = i / (f[0] + ... + f[i-1])\n (2) fps[i-1] = (i-1) / (f[0] + ... + f[i-2]) \n fps[i] = i / (f[0] + ... + f[i-1])\n = i / ((f[0] + ... + f[i-2]) + f[i-1])\n = (i/(i-1)) / ((f[0] + ... + f[i-2])/(i-1) + f[i-1]/(i-1))\n = (i/(i-1)) / (1/fps[i-1] + f[i-1]/(i-1))\n = ...\n = (i*fps[i-1]) / (f[i-1] * fps[i-1] + i - 1)\n" }, { "answer_id": 14178096, "author": "Totty.js", "author_id": 305270, "author_profile": "https://Stackoverflow.com/users/305270", "pm_score": 0, "selected": false, "text": "qx.Class.define('FpsCounter', {\n extend: qx.core.Object\n\n ,properties: {\n }\n\n ,events: {\n }\n\n ,construct: function(){\n this.base(arguments);\n this.restart();\n }\n\n ,statics: {\n }\n\n ,members: { \n restart: function(){\n this.__frames = [];\n }\n\n\n\n ,addFrame: function(){\n this.__frames.push(new Date());\n }\n\n\n\n ,getFps: function(averageFrames){\n debugger;\n if(!averageFrames){\n averageFrames = 2;\n }\n var time = 0;\n var l = this.__frames.length;\n var i = averageFrames;\n while(i > 0){\n if(l - i - 1 >= 0){\n time += this.__frames[l - i] - this.__frames[l - i - 1];\n }\n i--;\n }\n var fps = averageFrames / time * 1000;\n return fps;\n }\n }\n\n});\n" }, { "answer_id": 14922314, "author": "BottleFact", "author_id": 2080626, "author_profile": "https://Stackoverflow.com/users/2080626", "pm_score": 0, "selected": false, "text": "boolean run = false;\n\nint ticks = 0;\n\nlong tickstart;\n\nint fps;\n\npublic void loop()\n{\nif(this.ticks==0)\n{\nthis.tickstart = System.currentTimeMillis();\n}\nthis.ticks++;\nthis.fps = (int)this.ticks / (System.currentTimeMillis()-this.tickstart);\n}\n" }, { "answer_id": 16627178, "author": "adventurerOK", "author_id": 1336695, "author_profile": "https://Stackoverflow.com/users/1336695", "pm_score": 0, "selected": false, "text": "private static long ONE_SECOND = 1000000L * 1000L; //1 second is 1000ms which is 1000000ns\n\nLinkedList<Long> frames = new LinkedList<>(); //List of frames within 1 second\n\npublic int calcFPS(){\n long time = System.nanoTime(); //Current time in nano seconds\n frames.add(time); //Add this frame to the list\n while(true){\n long f = frames.getFirst(); //Look at the first element in frames\n if(time - f > ONE_SECOND){ //If it was more than 1 second ago\n frames.remove(); //Remove it from the list of frames\n } else break;\n /*If it was within 1 second we know that all other frames in the list\n * are also within 1 second\n */\n }\n return frames.size(); //Return the size of the list\n}\n" }, { "answer_id": 16722508, "author": "Petrucio", "author_id": 828681, "author_profile": "https://Stackoverflow.com/users/828681", "pm_score": 3, "selected": false, "text": "// Number of past frames to use for FPS smooth calculation - because \n// Unity's smoothedDeltaTime, well - it kinda sucks\nprivate int frameTimesSize = 60;\n// A Queue is the perfect data structure for the smoothed FPS task;\n// new values in, old values out\nprivate Queue<float> frameTimes;\n// Not really needed, but used for faster updating then processing \n// the entire queue every frame\nprivate float __frameTimesSum = 0;\n// Flag to ignore the next frame when performing a heavy one-time operation \n// (like changing resolution)\nprivate bool _fpsIgnoreNextFrame = false;\n\n//=============================================================================\n// Call this after doing a heavy operation that will screw up with FPS calculation\nvoid FPSIgnoreNextFrame() {\n this._fpsIgnoreNextFrame = true;\n}\n\n//=============================================================================\n// Smoothed FPS counter updating\nvoid Update()\n{\n if (this._fpsIgnoreNextFrame) {\n this._fpsIgnoreNextFrame = false;\n return;\n }\n\n // While looping here allows the frameTimesSize member to be changed dinamically\n while (this.frameTimes.Count >= this.frameTimesSize) {\n this.__frameTimesSum -= this.frameTimes.Dequeue();\n }\n while (this.frameTimes.Count < this.frameTimesSize) {\n this.__frameTimesSum += Time.deltaTime;\n this.frameTimes.Enqueue(Time.deltaTime);\n }\n}\n\n//=============================================================================\n// Public function to get smoothed FPS values\npublic int GetSmoothedFPS() {\n return (int)(this.frameTimesSize / this.__frameTimesSum * Time.timeScale);\n}\n" }, { "answer_id": 33744861, "author": "Barry Smith", "author_id": 1978605, "author_profile": "https://Stackoverflow.com/users/1978605", "pm_score": 2, "selected": false, "text": "new_fps = old_fps * 0.99 + new_fps * 0.01\n" }, { "answer_id": 41819850, "author": "Ephellon Grey", "author_id": 4211612, "author_profile": "https://Stackoverflow.com/users/4211612", "pm_score": 1, "selected": false, "text": "// Set the end and start times\nvar start = (new Date).getTime(), end, FPS;\n /* ...\n * the loop/block your want to watch\n * ...\n */\nend = (new Date).getTime();\n// since the times are by millisecond, use 1000 (1000ms = 1s)\n// then multiply the result by (MaxFPS / 1000)\n// FPS = (1000 - (end - start)) * (MaxFPS / 1000)\nFPS = Math.round((1000 - (end - start)) * (60 / 1000));\n" }, { "answer_id": 43218717, "author": "jd20", "author_id": 6116684, "author_profile": "https://Stackoverflow.com/users/6116684", "pm_score": 1, "selected": false, "text": "import time\n\nSMOOTHING_FACTOR = 0.99\nMAX_FPS = 10000\navg_fps = -1\nlast_tick = time.time()\n\nwhile True:\n # <Do your rendering work here...>\n\n current_tick = time.time()\n # Ensure we don't get crazy large frame rates, by capping to MAX_FPS\n current_fps = 1.0 / max(current_tick - last_tick, 1.0/MAX_FPS)\n last_tick = current_tick\n if avg_fps < 0:\n avg_fps = current_fps\n else:\n avg_fps = (avg_fps * SMOOTHING_FACTOR) + (current_fps * (1-SMOOTHING_FACTOR))\n print(avg_fps)\n" }, { "answer_id": 57949825, "author": "Donavan Carvalho", "author_id": 12071969, "author_profile": "https://Stackoverflow.com/users/12071969", "pm_score": 0, "selected": false, "text": "let getTime = () => {\n return new Date().getTime();\n} \n\nlet frames: any[] = [];\nlet previousTime = getTime();\nlet framerate:number = 0;\nlet frametime:number = 0;\n\nlet updateStats = (samples:number=60) => {\n samples = Math.max(samples, 1) >> 0;\n\n if (frames.length === samples) {\n let currentTime: number = getTime() - previousTime;\n\n frametime = currentTime / samples;\n framerate = 1000 * samples / currentTime;\n\n previousTime = getTime();\n\n frames = [];\n }\n\n frames.push(1);\n}\n statsUpdate();\n\n// Print\nstats.innerHTML = Math.round(framerate) + ' FPS ' + frametime.toFixed(2) + ' ms';\n" }, { "answer_id": 63318270, "author": "danday74", "author_id": 1205871, "author_profile": "https://Stackoverflow.com/users/1205871", "pm_score": 0, "selected": false, "text": "fpsObject = {\n maxSamples: 100,\n tickIndex: 0,\n tickSum: 0,\n tickList: []\n}\n calculateFps(currentFps: number): number {\n this.fpsObject.tickSum -= this.fpsObject.tickList[this.fpsObject.tickIndex] || 0\n this.fpsObject.tickSum += currentFps\n this.fpsObject.tickList[this.fpsObject.tickIndex] = currentFps\n if (++this.fpsObject.tickIndex === this.fpsObject.maxSamples) this.fpsObject.tickIndex = 0\n const smoothedFps = this.fpsObject.tickSum / this.fpsObject.maxSamples\n return Math.floor(smoothedFps)\n}\n this.fps = this.calculateFps(this.ticker.FPS)\n" }, { "answer_id": 69288479, "author": "kbolino", "author_id": 814422, "author_profile": "https://Stackoverflow.com/users/814422", "pm_score": 0, "selected": false, "text": "time.Duration type FrameTimeTracker struct {\n samples []time.Duration\n sum time.Duration\n index int\n}\n\nfunc NewFrameTimeTracker(n int) *FrameTimeTracker {\n return &FrameTimeTracker{\n samples: make([]time.Duration, n),\n }\n}\n\nfunc (t *FrameTimeTracker) AddFrameTime(frameTime time.Duration) (average time.Duration) {\n // algorithm adapted from https://stackoverflow.com/a/87732/814422\n t.sum -= t.samples[t.index]\n t.sum += frameTime\n t.samples[t.index] = frameTime\n t.index++\n if t.index == len(t.samples) {\n t.index = 0\n }\n return t.sum / time.Duration(len(t.samples))\n}\n time.Duration // track the last 60 frame times\nframeTimeTracker := NewFrameTimeTracker(60)\n\n// main game loop\nfor frame := 0;; frame++ {\n // ...\n if frame > 0 {\n // prevFrameTime is the duration of the last frame\n avgFrameTime := frameTimeTracker.AddFrameTime(prevFrameTime)\n fps := 1.0 / avgFrameTime.Seconds()\n }\n // ...\n\n}\n []time.Duration [N]time.Duration N NewFrameTimeTracker var frameTimeTracker FrameTimeTracker main" }, { "answer_id": 70734087, "author": "bytefu", "author_id": 888720, "author_profile": "https://Stackoverflow.com/users/888720", "pm_score": 0, "selected": false, "text": "use std::collections::VecDeque;\nuse std::time::{Duration, Instant};\n\npub struct FpsCounter {\n sample_period: Duration,\n max_samples: usize,\n creation_time: Instant,\n frame_count: usize,\n measurements: VecDeque<FrameCountMeasurement>,\n}\n\n#[derive(Copy, Clone)]\nstruct FrameCountMeasurement {\n time: Instant,\n frame_count: usize,\n}\n\nimpl FpsCounter {\n pub fn new(sample_period: Duration, samples: usize) -> Self {\n assert!(samples > 1);\n\n Self {\n sample_period,\n max_samples: samples,\n creation_time: Instant::now(),\n frame_count: 0,\n measurements: VecDeque::new(),\n }\n }\n\n pub fn fps(&self) -> f32 {\n match (self.measurements.front(), self.measurements.back()) {\n (Some(start), Some(end)) => {\n let period = (end.time - start.time).as_secs_f32();\n if period > 0.0 {\n (end.frame_count - start.frame_count) as f32 / period\n } else {\n 0.0\n }\n }\n\n _ => 0.0,\n }\n }\n\n pub fn update(&mut self) {\n self.frame_count += 1;\n\n let current_measurement = self.measure();\n let last_measurement = self\n .measurements\n .back()\n .copied()\n .unwrap_or(FrameCountMeasurement {\n time: self.creation_time,\n frame_count: 0,\n });\n if (current_measurement.time - last_measurement.time) >= self.sample_period {\n self.measurements.push_back(current_measurement);\n while self.measurements.len() > self.max_samples {\n self.measurements.pop_front();\n }\n }\n }\n\n fn measure(&self) -> FrameCountMeasurement {\n FrameCountMeasurement {\n time: Instant::now(),\n frame_count: self.frame_count,\n }\n }\n}\n let mut fps_counter = FpsCounter::new(Duration::from_millis(100), 5); fps_counter.update() fps_counter.fps() FpsCounter::new() sample_period fps() samples fps() fps() sample_period * samples" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/87304", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16679/" ]
87,317
<p>I need to get a list of attribute values from child elements in Python.</p> <p>It's easiest to explain with an example.</p> <p>Given some XML like this:</p> <pre><code>&lt;elements&gt; &lt;parent name="CategoryA"&gt; &lt;child value="a1"/&gt; &lt;child value="a2"/&gt; &lt;child value="a3"/&gt; &lt;/parent&gt; &lt;parent name="CategoryB"&gt; &lt;child value="b1"/&gt; &lt;child value="b2"/&gt; &lt;child value="b3"/&gt; &lt;/parent&gt; &lt;/elements&gt; </code></pre> <p>I want to be able to do something like:</p> <pre class="lang-python prettyprint-override"><code>&gt;&gt;&gt; getValues("CategoryA") ['a1', 'a2', 'a3'] &gt;&gt;&gt; getValues("CategoryB") ['b1', 'b2', 'b3'] </code></pre> <p>It looks like a job for XPath but I'm open to all recommendations. I'd also like to hear about your favourite Python XML libraries.</p>
[ { "answer_id": 87503, "author": "pjz", "author_id": 8002, "author_profile": "https://Stackoverflow.com/users/8002", "pm_score": 2, "selected": false, "text": " import xmltramp\n\n values = xmltramp.parse('''...''')\n\n def getValues( values, category ):\n cat = [ parent for parent in values['parent':] if parent(name) == category ]\n cat_values = [ child(value) for child in parent['child':] for parent in cat ]\n return cat_values\n\n getValues( values, \"CategoryA\" )\n getValues( values, \"CategoryB\" )\n" }, { "answer_id": 87543, "author": "Cristian", "author_id": 680, "author_profile": "https://Stackoverflow.com/users/680", "pm_score": 2, "selected": false, "text": ">>> from BeautifulSoup import BeautifulStoneSoup\n>>> soup = BeautifulStoneSoup(xml)\n>>> def getValues(name):\n. . . return [child['value'] for child in soup.find('parent', attrs={'name': name}).findAll('child')]\n" }, { "answer_id": 87622, "author": "Jesse Millikan", "author_id": 7526, "author_profile": "https://Stackoverflow.com/users/7526", "pm_score": 4, "selected": true, "text": "import libxml2\n\nDOC = \"\"\"<elements>\n <parent name=\"CategoryA\">\n <child value=\"a1\"/>\n <child value=\"a2\"/>\n <child value=\"a3\"/>\n </parent>\n <parent name=\"CategoryB\">\n <child value=\"b1\"/>\n <child value=\"b2\"/>\n <child value=\"b3\"/>\n </parent>\n</elements>\"\"\"\n\ndoc = libxml2.parseDoc(DOC)\n\ndef getValues(cat):\n return [attr.content for attr in doc.xpathEval(\"/elements/parent[@name='%s']/child/@value\" % (cat))]\n\nprint getValues(\"CategoryA\")\n ['a1', 'a2', 'a3']\n" }, { "answer_id": 87651, "author": "bobince", "author_id": 18936, "author_profile": "https://Stackoverflow.com/users/18936", "pm_score": 2, "selected": false, "text": "def getValues(category):\n for parent in document.getElementsByTagName('parent'):\n if parent.getAttribute('name')==category:\n return [\n el.getAttribute('value')\n for el in parent.getElementsByTagName('child')\n ]\n raise ValueError('parent not found')\n" }, { "answer_id": 87658, "author": "dF.", "author_id": 3002, "author_profile": "https://Stackoverflow.com/users/3002", "pm_score": 3, "selected": false, "text": "import elementtree.ElementTree as xml\n\ndef getValues(tree, category):\n parent = tree.find(\".//parent[@name='%s']\" % category)\n return [child.get('value') for child in parent]\n >>> tree = xml.parse('data.xml')\n>>> getValues(tree, 'CategoryA')\n['a1', 'a2', 'a3']\n>>> getValues(tree, 'CategoryB')\n['b1', 'b2', 'b3']\n lxml.etree" }, { "answer_id": 87726, "author": "Brian", "author_id": 9493, "author_profile": "https://Stackoverflow.com/users/9493", "pm_score": 2, "selected": false, "text": "from lxml import etree\n\ndef getValues(xml, category):\n return [x.attrib['value'] for x in \n xml.findall('/parent[@name=\"%s\"]/*' % category)]\n\nxml = etree.parse(open('filename.xml'))\n\n>>> print getValues(xml, 'CategoryA')\n['a1', 'a2', 'a3']\n>>> print getValues(xml, 'CategoryB')\n['b1', 'b2', 'b3]\n" }, { "answer_id": 41378271, "author": "Ramakant", "author_id": 3975232, "author_profile": "https://Stackoverflow.com/users/3975232", "pm_score": 2, "selected": false, "text": "items() ElementTree import xml.etree.ElementTree as ET\n\n flName = 'test.xml'\n tree = ET.parse(flName)\n root = tree.getroot()\n for element in root.findall('<child-node-of-root>'):\n attrList = element.items()\n print(len(attrList), \" : [\", attrList, \"]\" )\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/87317", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3464/" ]
87,330
<p>Is there a canonical ordering of submatch expressions in a regular expression? </p> <p>For example: What is the order of the submatches in<br> "(([0-9]{3}).([0-9]{3}).([0-9]{3}).([0-9]{3}))\s+([A-Z]+)" ?</p> <pre><code>a. (([0-9]{3})\.([0-9]{3})\.([0-9]{3})\.([0-9]{3}))\s+([A-Z]+) (([0-9]{3})\.([0-9]{3})\.([0-9]{3})\.([0-9]{3})) ([A-Z]+) ([0-9]{3}) ([0-9]{3}) ([0-9]{3}) ([0-9]{3}) b. (([0-9]{3})\.([0-9]{3})\.([0-9]{3})\.([0-9]{3}))\s+([A-Z]+) (([0-9]{3})\.([0-9]{3})\.([0-9]{3})\.([0-9]{3})) ([0-9]{3}) ([0-9]{3}) ([0-9]{3}) ([0-9]{3}) ([A-Z]+) </code></pre> <p>or</p> <pre><code>c. somthin' else. </code></pre>
[ { "answer_id": 87417, "author": "Asgeir S. Nilsen", "author_id": 16023, "author_profile": "https://Stackoverflow.com/users/16023", "pm_score": 0, "selected": false, "text": "(([0-9]{3}).([0-9]{3}).([0-9]{3}).([0-9]{3}))\n([0-9]{3})\n([0-9]{3})\n([0-9]{3})\n([0-9]{3})\n([A-Z]+)\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/87330", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16753/" ]
87,350
<p>Any recommendations on <a href="http://en.wikipedia.org/wiki/Grep" rel="noreferrer">grep</a> tools for Windows? Ideally ones that could leverage 64-bit OS.</p> <p>I'm aware of <a href="http://www.cygwin.com/" rel="noreferrer">Cygwin</a>, of course, and have also found <a href="http://www.powergrep.com/" rel="noreferrer">PowerGREP</a>, but I'm wondering if there are any hidden gems out there?</p>
[ { "answer_id": 87378, "author": "VonC", "author_id": 6309, "author_profile": "https://Stackoverflow.com/users/6309", "pm_score": 6, "selected": false, "text": "grep --include \"*.xxx\" -nRHI \"my Text to grep\" *\n" }, { "answer_id": 87394, "author": "Ray Hayes", "author_id": 7093, "author_profile": "https://Stackoverflow.com/users/7093", "pm_score": 8, "selected": false, "text": "c:\\> FindStr /?\n\nSearches for strings in files.\n\nFINDSTR [/B] [/E] [/L] [/R] [/S] [/I] [/X] [/V] [/N] [/M] [/O] [/P] [/F:file]\n [/C:string] [/G:file] [/D:dir list] [/A:color attributes] [/OFF[LINE]]\n strings [[drive:][path]filename[ ...]]\n\n /B Matches pattern if at the beginning of a line.\n /E Matches pattern if at the end of a line.\n /L Uses search strings literally.\n /R Uses search strings as regular expressions.\n /S Searches for matching files in the current directory and all\n subdirectories.\n /I Specifies that the search is not to be case-sensitive.\n /X Prints lines that match exactly.\n /V Prints only lines that do not contain a match.\n /N Prints the line number before each line that matches.\n /M Prints only the filename if a file contains a match.\n /O Prints character offset before each matching line.\n /P Skip files with non-printable characters.\n /OFF[LINE] Do not skip files with offline attribute set.\n /A:attr Specifies color attribute with two hex digits. See \"color /?\"\n /F:file Reads file list from the specified file(/ stands for console).\n /C:string Uses specified string as a literal search string.\n /G:file Gets search strings from the specified file(/ stands for console).\n /D:dir Search a semicolon delimited list of directories\n strings Text to be searched for.\n [drive:][path]filename\n Specifies a file or files to search.\n\nUse spaces to separate multiple search strings unless the argument is prefixed\nwith /C. For example, 'FINDSTR \"hello there\" x.y' searches for \"hello\" or\n\"there\" in file x.y. 'FINDSTR /C:\"hello there\" x.y' searches for\n\"hello there\" in file x.y.\n\nRegular expression quick reference:\n . Wildcard: any character\n * Repeat: zero or more occurances of previous character or class\n ^ Line position: beginning of line\n $ Line position: end of line\n [class] Character class: any one character in set\n [^class] Inverse class: any one character not in set\n [x-y] Range: any characters within the specified range\n \\x Escape: literal use of metacharacter x\n \\<xyz Word position: beginning of word\n xyz\\> Word position: end of word\n findstr text_to_find * findstr /s text_to_find *" }, { "answer_id": 87450, "author": "Jay Bazuzi", "author_id": 5314, "author_profile": "https://Stackoverflow.com/users/5314", "pm_score": 5, "selected": false, "text": "gcir Get-ChildItem -Recurse . ss Select-String" }, { "answer_id": 5171374, "author": "Jerry Lusa", "author_id": 641695, "author_profile": "https://Stackoverflow.com/users/641695", "pm_score": 2, "selected": false, "text": "C:\\DEV> GREP GAAPRNTR \\SOURCE\\TPALIB\\*.PRG\n<no results>\n C:\\DEV> FINDSTR GAAPRNTR \\SOURCE\\TPALIB\\*.PRG\n\\SOURCE\\TPALIB\\TPGAAUPD.PRG:ffSPOOL(cRPTFILE, MEM->GAAPRNTR, MEM->NETTYPE)\n\\SOURCE\\TPALIB\\TPPRINTR.PRG: AADD(mPRINTER, TPACONFG->GAAPRNTR)\n\\SOURCE\\TPALIB\\TPPRINTR.PRG: IF TRIM(TPACONFG->GAAPRNTR) <> TRIM(mPRINTER[2])\n\\SOURCE\\TPALIB\\TPPRINTR.PRG: REPLACE TPACONFG->GAAPRNTR WITH mPRINTER[2]\n" }, { "answer_id": 5278915, "author": "jslatts", "author_id": 190766, "author_profile": "https://Stackoverflow.com/users/190766", "pm_score": 4, "selected": false, "text": "Get-ChildItem -recurse -include *.txt | Select-String -CaseSensitive \"SomeString\"\n SomeString function pgrep { param([string]$search, [string]$inc) Get-ChildItem -recurse -include $inc | Select-String -CaseSensitive $search }\n pgrep SomeStringToSearch *.txt\n" }, { "answer_id": 6466124, "author": "Philip Beck", "author_id": 368445, "author_profile": "https://Stackoverflow.com/users/368445", "pm_score": 2, "selected": false, "text": "findstr @echo off\nset /p term=\"Search term> \"\ndel %temp%\\grepresult.txt\nfindstr /i /S /R /n /C:\"%term%\" \"%~1\\*.*\" > \"%temp%\\grepresult.txt\"\nstart notepad \"%temp%\\grepresult.txt\"\n %APPDATA%\\Microsoft\\Windows\\SendTo 1 GREP findstr" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/87350", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1690/" ]
87,359
<p>I have a page which spawns a popup browser window. I have a JavaScript variable in the parent browser window and I would like to pass it to the popped-up browser window.</p> <p>Is there a way to do this? I know this can be done across frames in the same browser window but I'm not sure if it can be done across browser windows.</p>
[ { "answer_id": 87649, "author": "Milan Babuškov", "author_id": 14690, "author_profile": "https://Stackoverflow.com/users/14690", "pm_score": 0, "selected": false, "text": "var x = 10;\nwindow.open('mypage.php?x='+x);\n" }, { "answer_id": 87659, "author": "Grant Wagner", "author_id": 9254, "author_profile": "https://Stackoverflow.com/users/9254", "pm_score": 2, "selected": false, "text": "var yourValue = 'something';\nwindow.open('/childwindow.html?yourKey=' + yourValue);\n var query = location.search.substring(1);\nvar parameters = {};\nvar keyValues = query.split(/&/);\nfor (var keyValue in keyValues) {\n var keyValuePairs = keyValue.split(/=/);\n var key = keyValuePairs[0];\n var value = keyValuePairs[1];\n parameters[key] = value;\n}\n\nalert(parameters['yourKey']);\n" }, { "answer_id": 87737, "author": "Victor", "author_id": 14514, "author_profile": "https://Stackoverflow.com/users/14514", "pm_score": 7, "selected": false, "text": "var thisIsAnObject = {foo:'bar'};\nvar w = window.open(\"http://example.com\");\nw.myVariable = thisIsAnObject;\n var myVariable = window.opener.thisIsAnObject;\n" }, { "answer_id": 21483842, "author": "knut", "author_id": 564149, "author_profile": "https://Stackoverflow.com/users/564149", "pm_score": 2, "selected": false, "text": "// open an empty sample window:\nvar win = open(\"\");\nwin.document.write(\"<html><body><head></head><input value='Trigger handler in other window!' type='button' id='button'></input></body></html>\");\n\n// attach to button in target window, and use a handler in this one:\nvar button = win.document.getElementById('button');\n\nbutton.onclick = function() {\n alert(\"I'm in the first frame!\"); \n}\n" }, { "answer_id": 33895385, "author": "singe3", "author_id": 3751590, "author_profile": "https://Stackoverflow.com/users/3751590", "pm_score": 0, "selected": false, "text": "function openWindow(path, callback /* , arg1 , arg2, ... */){\n var args = Array.prototype.slice.call(arguments, 2); // retrieve the arguments\n var w = window.open(path); // open the new window\n w.addEventListener('load', afterLoadWindow.bind(w, args), false); // listen to the new window's load event\n function afterLoadWindow(/* [arg1,arg2,...], loadEvent */){\n callback.apply(this, arguments[0]); // execute the callbacks, passing the initial arguments (arguments[1] contains the load event)\n }\n}\n openWindow(\"/contact\",function(firstname, lastname){\n this.alert(\"Hello \"+firstname+\" \"+lastname);\n}, \"John\", \"Doe\");\n" }, { "answer_id": 37169932, "author": "Brad Parks", "author_id": 26510, "author_profile": "https://Stackoverflow.com/users/26510", "pm_score": 0, "selected": false, "text": "window.name" }, { "answer_id": 41707355, "author": "Brault Gilbert", "author_id": 7432657, "author_profile": "https://Stackoverflow.com/users/7432657", "pm_score": 2, "selected": false, "text": " var win = window.open(<window.location.href>, '_blank'); \n setTimeout(function(){\n win.postMessage(SRFBfromEBNF,\"*\")\n },1000);\n win.focus();\n window.addEventListener('message', function(event) {\n if(event.srcElement.location.href==window.location.href){\n /* do what you want with event.data */\n }\n }); \n" }, { "answer_id": 58912853, "author": "Haris", "author_id": 1573209, "author_profile": "https://Stackoverflow.com/users/1573209", "pm_score": 1, "selected": false, "text": "var A = {foo:'bar'};\nvar w = window.open(\"http://example.com\");\nw.B = A;\n\n// in new window\nvar B = window.opener.B;\n var B = {foo:'bar'};\nvar w = window.open(\"http://example.com\");\nw.B = B;\n\n// in new window\nvar B = window.opener.B;\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/87359", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2577/" ]
87,365
<p>If the owner of a web site wants to track who their users are as much as possible, what things can they capture (and how). You might want to know about this in order to capture information on a site you create or, as a user, to <em>prevent</em> a site from capturing data on you.</p> <p>Here is a starting list, but I'm sure I have missed some important ones:</p> <ol> <li>Referrer (what web page had the link you followed to get here). This is a HTTP header.</li> <li>IP Address of the machine you are browsing from. This is available with the HTTP headers.</li> <li>User Agent (what browser you are using). This is a HTTP header.</li> <li>Cookie placed on a previous visit. This is a header, available only if a cookie was placed earlier and was not deleted by the user.</li> <li>Flash Cookie placed on a previous visit. Some users turn off cookies, but <em>very</em> few know how to turn off Flash cookies. Works like a normal cookie although it depends on Flash.</li> <li>Web Bugs. Place something small (like a transparent single-pixel GIF) on the page that's served up from a 3rd party. Some third parties (such as DoubleClick) will have their own cookies and can correlate with other visits the user makes (for a fee!).</li> </ol> <p>Those are the common ones I think of, but there have to be LOTS of unusual ones. For instance, this:</p> <ol> <li>Time on the user's clock. <a href="https://stackoverflow.com/questions/13/determining-web-users-time-zone">Use JavaScript</a> to transmit it.</li> </ol> <p>... which I had never heard of before reading it here.</p> <hr> <p>ADDED LATER (after reading <a href="http://www.joelonsoftware.com/items/2008/09/15.html" rel="nofollow noreferrer">this</a>):</p> <p><strong>Please try to put just ONE item per answer, then we can use voting up to sort out the better/more-interesting ones.</strong> The list below is probably less effective.</p> <p>Ah well... NEXT time I ask a question like this I'll set it up better.</p> <hr> <p>And here are some of the best answers I got:</p> <ol> <li><a href="https://stackoverflow.com/questions/87365/what-identifying-information-can-a-website-capture#87413">James</a> points out that IE transmits the .NET framework version.</li> <li><a href="https://stackoverflow.com/questions/87365/what-identifying-information-can-a-website-capture#87454">AviewAnew</a> points out that one can <a href="http://ha.ckers.org/weird/CSS-history-hack.html" rel="nofollow noreferrer">find what sites you have visited</a>.</li> <li><a href="https://stackoverflow.com/questions/87365/what-identifying-information-can-a-website-capture#87529">Mecki</a> points out that Screen Resolution can be determined.</li> <li><a href="https://stackoverflow.com/questions/87365/what-identifying-information-can-a-website-capture#87529">Mecki</a> <em>also</em> points out that any auto-fill information your browser has cached can be determined, by creating a hidden field, then reading it with JavaScript.</li> <li><a href="https://stackoverflow.com/questions/87365/what-identifying-information-can-a-website-capture#87463">jjrv</a> points out that Flash can list the fonts on the user's machine.</li> <li><a href="https://stackoverflow.com/questions/87365/what-identifying-information-can-a-website-capture#87473">Kent</a> points out that you can find out <a href="http://weblogs.asp.net/jezell/archive/2006/08/25/Stealing-History.aspx" rel="nofollow noreferrer">what websites a person has visited</a>.</li> <li><a href="https://stackoverflow.com/questions/87365/what-identifying-information-can-a-website-capture#87493">Silver Dragon</a> points out you can determine the location of the mouse within the browsing window using Flash and AJAX.</li> <li><a href="https://stackoverflow.com/questions/87365/what-identifying-information-can-a-website-capture#87494">Jim</a> points out that you can tell what language the user has configured in their browser from a HTTP header.</li> <li><a href="https://stackoverflow.com/questions/87365/what-identifying-information-can-a-website-capture#87494">Jim</a> also mentions that you can detect whether people are using Greasemonkey or something similar to modify the page.</li> </ol>
[ { "answer_id": 87494, "author": "Jim", "author_id": 8427, "author_profile": "https://Stackoverflow.com/users/8427", "pm_score": 0, "selected": false, "text": "Accept-Language Accept User-Agent" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/87365", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14570/" ]
87,372
<p>I'm asking for a template trick to detect if a class has a specific member function of a given signature.</p> <p>The problem is similar to the one cited here <a href="http://www.gotw.ca/gotw/071.htm" rel="noreferrer">http://www.gotw.ca/gotw/071.htm</a> but not the same: in the item of Sutter's book he answered to the question that a class C MUST PROVIDE a member function with a particular signature, else the program won't compile. In my problem I need to do something if a class has that function, else do "something else". </p> <p>A similar problem was faced by boost::serialization but I don't like the solution they adopted: a template function that invokes by default a free function (that you have to define) with a particular signature unless you define a particular member function (in their case "serialize" that takes 2 parameters of a given type) with a particular signature, else a compile error will happens. That is to implement both intrusive and non-intrusive serialization. </p> <p>I don't like that solution for two reasons:</p> <ol> <li>To be non intrusive you must override the global "serialize" function that is in boost::serialization namespace, so you have IN YOUR CLIENT CODE to open namespace boost and namespace serialization!</li> <li>The stack to resolve that mess was 10 to 12 function invocations.</li> </ol> <p>I need to define a custom behavior for classes that has not that member function, and my entities are inside different namespaces (and I don't want to override a global function defined in one namespace while I'm in another one)</p> <p>Can you give me a hint to solve this puzzle?</p>
[ { "answer_id": 87474, "author": "C. K. Young", "author_id": 13, "author_profile": "https://Stackoverflow.com/users/13", "pm_score": 2, "selected": false, "text": "serialize std swap" }, { "answer_id": 87846, "author": "yrp", "author_id": 7228, "author_profile": "https://Stackoverflow.com/users/7228", "pm_score": 8, "selected": true, "text": "template<typename T>\nstruct HasUsedMemoryMethod\n{\n template<typename U, size_t (U::*)() const> struct SFINAE {};\n template<typename U> static char Test(SFINAE<U, &U::used_memory>*);\n template<typename U> static int Test(...);\n static const bool Has = sizeof(Test<T>(0)) == sizeof(char);\n};\n\ntemplate<typename TMap>\nvoid ReportMemUsage(const TMap& m, std::true_type)\n{\n // We may call used_memory() on m here.\n}\ntemplate<typename TMap>\nvoid ReportMemUsage(const TMap&, std::false_type)\n{\n}\ntemplate<typename TMap>\nvoid ReportMemUsage(const TMap& m)\n{\n ReportMemUsage(m, \n std::integral_constant<bool, HasUsedMemoryMethod<TMap>::Has>());\n}\n" }, { "answer_id": 87905, "author": "coppro", "author_id": 16855, "author_profile": "https://Stackoverflow.com/users/16855", "pm_score": 4, "selected": false, "text": "template <typename T, int (T::*) ()> struct enable { typedef T type; };\ntemplate <typename T> typename enable<T, &T::i>::type bla (T&);\nstruct A { void i(); };\nstruct B { int i(); };\nint main()\n{\n A a;\n B b;\n bla(b);\n bla(a);\n}\n" }, { "answer_id": 10707822, "author": "Mike Kinghan", "author_id": 1362568, "author_profile": "https://Stackoverflow.com/users/1362568", "pm_score": 5, "selected": false, "text": "#include <type_traits>\n#include <iostream>\n#include <memory>\n\n/* Here we apply the accepted answer's technique to probe for the\n the existence of `E T::operator*() const`\n*/\ntemplate<typename T, typename E>\nstruct has_const_reference_op\n{\n template<typename U, E (U::*)() const> struct SFINAE {};\n template<typename U> static char Test(SFINAE<U, &U::operator*>*);\n template<typename U> static int Test(...);\n static const bool value = sizeof(Test<T>(0)) == sizeof(char);\n};\n\nusing namespace std;\n\n/* Here we test the `std::` smart pointer templates, including the\n deprecated `auto_ptr<T>`, to determine in each case whether\n T = (the template instantiated for `int`) provides \n `int & T::operator*() const` - which all of them in fact do.\n*/ \nint main(void)\n{\n cout << has_const_reference_op<auto_ptr<int>,int &>::value;\n cout << has_const_reference_op<unique_ptr<int>,int &>::value;\n cout << has_const_reference_op<shared_ptr<int>,int &>::value << endl;\n return 0;\n}\n 110 T = std::shared_ptr<int> int & T::operator*() const std::shared_ptr<T> <memory> std::shared_ptr<T> operator*() const SFINAE<U, &U::operator*> U = std::shared_ptr<T> std::shared_ptr<T> operator*() T mf T::mf &T::mf T::mf T::mf &T::mf E T::operator*() const T E #include <type_traits>\n\n/*! The template `has_const_reference_op<T,E>` exports a\n boolean constant `value that is true iff `T` provides\n `E T::operator*() const`\n*/ \ntemplate< typename T, typename E>\nstruct has_const_reference_op\n{\n /* SFINAE operator-has-correct-sig :) */\n template<typename A>\n static std::true_type test(E (A::*)() const) {\n return std::true_type();\n }\n\n /* SFINAE operator-exists :) */\n template <typename A> \n static decltype(test(&A::operator*)) \n test(decltype(&A::operator*),void *) {\n /* Operator exists. What about sig? */\n typedef decltype(test(&A::operator*)) return_type; \n return return_type();\n }\n\n /* SFINAE game over :( */\n template<typename A>\n static std::false_type test(...) {\n return std::false_type(); \n }\n\n /* This will be either `std::true_type` or `std::false_type` */\n typedef decltype(test<T>(0,0)) type;\n\n static const bool value = type::value; /* Which is it? */\n};\n test() T::operator*() T::operator*() E T::operator*() const test(0,0) typedef decltype(test<T>(0,0)) type;\n /* SFINAE operator-exists :) */ test() /* SFINAE game over :( */ /* SFINAE operator-has-correct-sig :) */ /* SFINAE operator-has-correct-sig :) */ test(0,0) /* SFINAE operator-exists :) */ decltype(&A::operator*) A = T T::operator* /* SFINAE operator-exists :) */ decltype(test(&A::operator*)) test() &A::operator* test(&A::operator*) /* SFINAE operator-has-correct-sig :) */ /* SFINAE game over :( */ /* SFINAE operator-has-correct-sig :) */ &A::operator* E (A::*)() const A = T T::operator* std::true_type /* SFINAE operator-exists :) */ test(0,0) /* SFINAE operator-has-correct-sig :) */ test(&A::operator*) /* SFINAE game over :( */ std::false_type // To test\nstruct empty{};\n\n// To test \nstruct int_ref\n{\n int & operator*() const {\n return *_pint;\n }\n int & foo() const {\n return *_pint;\n }\n int * _pint;\n};\n\n// To test \nstruct sub_int_ref : int_ref{};\n\n// To test \ntemplate<typename E>\nstruct ee_ref\n{\n E & operator*() {\n return *_pe;\n }\n E & foo() const {\n return *_pe;\n }\n E * _pe;\n};\n\n// To test \nstruct sub_ee_ref : ee_ref<char>{};\n\nusing namespace std;\n\n#include <iostream>\n#include <memory>\n#include <vector>\n\nint main(void)\n{\n cout << \"Expect Yes\" << endl;\n cout << has_const_reference_op<auto_ptr<int>,int &>::value;\n cout << has_const_reference_op<unique_ptr<int>,int &>::value;\n cout << has_const_reference_op<shared_ptr<int>,int &>::value;\n cout << has_const_reference_op<std::vector<int>::iterator,int &>::value;\n cout << has_const_reference_op<std::vector<int>::const_iterator,\n int const &>::value;\n cout << has_const_reference_op<int_ref,int &>::value;\n cout << has_const_reference_op<sub_int_ref,int &>::value << endl;\n cout << \"Expect No\" << endl;\n cout << has_const_reference_op<int *,int &>::value;\n cout << has_const_reference_op<unique_ptr<int>,char &>::value;\n cout << has_const_reference_op<unique_ptr<int>,int const &>::value;\n cout << has_const_reference_op<unique_ptr<int>,int>::value;\n cout << has_const_reference_op<unique_ptr<long>,int &>::value;\n cout << has_const_reference_op<int,int>::value;\n cout << has_const_reference_op<std::vector<int>,int &>::value;\n cout << has_const_reference_op<ee_ref<int>,int &>::value;\n cout << has_const_reference_op<sub_ee_ref,int &>::value;\n cout << has_const_reference_op<empty,int &>::value << endl;\n return 0;\n}\n" }, { "answer_id": 13266235, "author": "Yochai Timmer", "author_id": 536086, "author_profile": "https://Stackoverflow.com/users/536086", "pm_score": 3, "selected": false, "text": "class A {\n public:\n void foo() {};\n}\n\n bool test = std::is_member_function_pointer<decltype(&A::foo)>::value;\n" }, { "answer_id": 15685535, "author": "S. Paris", "author_id": 2200040, "author_profile": "https://Stackoverflow.com/users/2200040", "pm_score": 3, "selected": false, "text": "#include <boost/type_traits/is_class.hpp>\n#include <boost/mpl/vector.hpp>\n\n/// Has constant function\n/** \\param func_ret_type Function return type\n \\param func_name Function name\n \\param ... Variadic arguments are for the function parameters\n*/\n#define DECLARE_TRAITS_HAS_FUNC_C(func_ret_type, func_name, ...) \\\n __DECLARE_TRAITS_HAS_FUNC(1, func_ret_type, func_name, ##__VA_ARGS__)\n\n/// Has non-const function\n/** \\param func_ret_type Function return type\n \\param func_name Function name\n \\param ... Variadic arguments are for the function parameters\n*/\n#define DECLARE_TRAITS_HAS_FUNC(func_ret_type, func_name, ...) \\\n __DECLARE_TRAITS_HAS_FUNC(0, func_ret_type, func_name, ##__VA_ARGS__)\n\n// Traits content\n#define __DECLARE_TRAITS_HAS_FUNC(func_const, func_ret_type, func_name, ...) \\\n template \\\n < typename Type, \\\n bool is_class = boost::is_class<Type>::value \\\n > \\\n class has_func_ ## func_name; \\\n template<typename Type> \\\n class has_func_ ## func_name<Type,false> \\\n {public: \\\n BOOST_STATIC_CONSTANT( bool, value = false ); \\\n typedef boost::false_type type; \\\n }; \\\n template<typename Type> \\\n class has_func_ ## func_name<Type,true> \\\n { struct yes { char _foo; }; \\\n struct no { yes _foo[2]; }; \\\n struct Fallback \\\n { func_ret_type func_name( __VA_ARGS__ ) \\\n UTILITY_OPTIONAL(func_const,const) {} \\\n }; \\\n struct Derived : public Type, public Fallback {}; \\\n template <typename T, T t> class Helper{}; \\\n template <typename U> \\\n static no deduce(U*, Helper \\\n < func_ret_type (Fallback::*)( __VA_ARGS__ ) \\\n UTILITY_OPTIONAL(func_const,const), \\\n &U::func_name \\\n >* = 0 \\\n ); \\\n static yes deduce(...); \\\n public: \\\n BOOST_STATIC_CONSTANT( \\\n bool, \\\n value = sizeof(yes) \\\n == sizeof( deduce( static_cast<Derived*>(0) ) ) \\\n ); \\\n typedef ::boost::integral_constant<bool,value> type; \\\n BOOST_STATIC_CONSTANT(bool, is_const = func_const); \\\n typedef func_ret_type return_type; \\\n typedef ::boost::mpl::vector< __VA_ARGS__ > args_type; \\\n }\n\n// Utility functions\n#define UTILITY_OPTIONAL(condition, ...) UTILITY_INDIRECT_CALL( __UTILITY_OPTIONAL_ ## condition , ##__VA_ARGS__ )\n#define UTILITY_INDIRECT_CALL(macro, ...) macro ( __VA_ARGS__ )\n#define __UTILITY_OPTIONAL_0(...)\n#define __UTILITY_OPTIONAL_1(...) __VA_ARGS__\n template<class T>\nclass has_func_[func_name]\n{\npublic:\n /// Function definition result value\n /** Tells if the tested function is defined for type T or not.\n */\n static const bool value = true | false;\n\n /// Function definition result type\n /** Type representing the value attribute usable in\n http://www.boost.org/doc/libs/1_53_0/libs/utility/enable_if.html\n */\n typedef boost::integral_constant<bool,value> type;\n\n /// Tested function constness indicator\n /** Indicates if the tested function is const or not.\n This value is not deduced, it is forced depending\n on the user call to one of the traits generators.\n */\n static const bool is_const = true | false;\n\n /// Tested function return type\n /** Indicates the return type of the tested function.\n This value is not deduced, it is forced depending\n on the user's arguments to the traits generators.\n */\n typedef func_ret_type return_type;\n\n /// Tested function arguments types\n /** Indicates the arguments types of the tested function.\n This value is not deduced, it is forced depending\n on the user's arguments to the traits generators.\n */\n typedef ::boost::mpl::vector< __VA_ARGS__ > args_type;\n};\n // We enclose the traits class into\n// a namespace to avoid collisions\nnamespace ns_0 {\n // Next line will declare the traits class\n // to detect the member function void foo(int,int) const\n DECLARE_TRAITS_HAS_FUNC_C(void, foo, int, int);\n}\n\n// we can use BOOST to help in using the traits\n#include <boost/utility/enable_if.hpp>\n\n// Here is a function that is active for types\n// declaring the good member function\ntemplate<typename T> inline\ntypename boost::enable_if< ns_0::has_func_foo<T> >::type\nfoo_bar(const T &_this_, int a=0, int b=1)\n{ _this_.foo(a,b);\n}\n\n// Here is a function that is active for types\n// NOT declaring the good member function\ntemplate<typename T> inline\ntypename boost::disable_if< ns_0::has_func_foo<T> >::type\nfoo_bar(const T &_this_, int a=0, int b=1)\n{ default_foo(_this_,a,b);\n}\n\n// Let us declare test types\nstruct empty\n{\n};\nstruct direct_foo\n{\n void foo(int,int);\n};\nstruct direct_const_foo\n{\n void foo(int,int) const;\n};\nstruct inherited_const_foo :\n public direct_const_foo\n{\n};\n\n// Now anywhere in your code you can seamlessly use\n// the foo_bar function on any object:\nvoid test()\n{\n int a;\n foo_bar(a); // calls default_foo\n\n empty b;\n foo_bar(b); // calls default_foo\n\n direct_foo c;\n foo_bar(c); // calls default_foo (member function is not const)\n\n direct_const_foo d;\n foo_bar(d); // calls d.foo (member function is const)\n\n inherited_const_foo e;\n foo_bar(e); // calls e.foo (inherited member function)\n}\n" }, { "answer_id": 16824239, "author": "jrok", "author_id": 947836, "author_profile": "https://Stackoverflow.com/users/947836", "pm_score": 7, "selected": false, "text": "serialize #include <type_traits>\n\n// Primary template with a static assertion\n// for a meaningful error message\n// if it ever gets instantiated.\n// We could leave it undefined if we didn't care.\n\ntemplate<typename, typename T>\nstruct has_serialize {\n static_assert(\n std::integral_constant<T, false>::value,\n \"Second template parameter needs to be of function type.\");\n};\n\n// specialization that does the checking\n\ntemplate<typename C, typename Ret, typename... Args>\nstruct has_serialize<C, Ret(Args...)> {\nprivate:\n template<typename T>\n static constexpr auto check(T*)\n -> typename\n std::is_same<\n decltype( std::declval<T>().serialize( std::declval<Args>()... ) ),\n Ret // ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n >::type; // attempt to call it and see if the return type is correct\n\n template<typename>\n static constexpr std::false_type check(...);\n\n typedef decltype(check<C>(0)) type;\n\npublic:\n static constexpr bool value = type::value;\n};\n struct X {\n int serialize(const std::string&) { return 42; } \n};\n\nstruct Y : X {};\n\nstd::cout << has_serialize<Y, int(const std::string&)>::value; // will print 1\n" }, { "answer_id": 16867422, "author": "Brett Rossier", "author_id": 376331, "author_profile": "https://Stackoverflow.com/users/376331", "pm_score": 4, "selected": false, "text": "x CREATE_MEMBER_CHECK(x);\nbool has_x = has_member_x<class_to_check_for_x>::value;\n void x() //Func signature MUST have T as template variable here... simpler this way :\\\nCREATE_MEMBER_FUNC_SIG_CHECK(x, void (T::*)(), void__x);\nbool has_func_sig_void__x = has_member_func_void__x<class_to_check_for_x>::value;\n x CREATE_MEMBER_VAR_CHECK(x);\nbool has_var_x = has_member_var_x<class_to_check_for_x>::value;\n x CREATE_MEMBER_CLASS_CHECK(x);\nbool has_class_x = has_member_class_x<class_to_check_for_x>::value;\n x CREATE_MEMBER_UNION_CHECK(x);\nbool has_union_x = has_member_union_x<class_to_check_for_x>::value;\n x CREATE_MEMBER_ENUM_CHECK(x);\nbool has_enum_x = has_member_enum_x<class_to_check_for_x>::value;\n x CREATE_MEMBER_CHECK(x);\nCREATE_MEMBER_VAR_CHECK(x);\nCREATE_MEMBER_CLASS_CHECK(x);\nCREATE_MEMBER_UNION_CHECK(x);\nCREATE_MEMBER_ENUM_CHECK(x);\nCREATE_MEMBER_FUNC_CHECK(x);\nbool has_any_func_x = has_member_func_x<class_to_check_for_x>::value;\n CREATE_MEMBER_CHECKS(x); //Just stamps out the same macro calls as above.\nbool has_any_func_x = has_member_func_x<class_to_check_for_x>::value;\n /*\n - Multiple inheritance forces ambiguity of member names.\n - SFINAE is used to make aliases to member names.\n - Expression SFINAE is used in just one generic has_member that can accept\n any alias we pass it.\n*/\n\n//Variadic to force ambiguity of class members. C++11 and up.\ntemplate <typename... Args> struct ambiguate : public Args... {};\n\n//Non-variadic version of the line above.\n//template <typename A, typename B> struct ambiguate : public A, public B {};\n\ntemplate<typename A, typename = void>\nstruct got_type : std::false_type {};\n\ntemplate<typename A>\nstruct got_type<A> : std::true_type {\n typedef A type;\n};\n\ntemplate<typename T, T>\nstruct sig_check : std::true_type {};\n\ntemplate<typename Alias, typename AmbiguitySeed>\nstruct has_member {\n template<typename C> static char ((&f(decltype(&C::value))))[1];\n template<typename C> static char ((&f(...)))[2];\n\n //Make sure the member name is consistently spelled the same.\n static_assert(\n (sizeof(f<AmbiguitySeed>(0)) == 1)\n , \"Member name specified in AmbiguitySeed is different from member name specified in Alias, or wrong Alias/AmbiguitySeed has been specified.\"\n );\n\n static bool const value = sizeof(f<Alias>(0)) == 2;\n};\n //Check for any member with given name, whether var, func, class, union, enum.\n#define CREATE_MEMBER_CHECK(member) \\\n \\\ntemplate<typename T, typename = std::true_type> \\\nstruct Alias_##member; \\\n \\\ntemplate<typename T> \\\nstruct Alias_##member < \\\n T, std::integral_constant<bool, got_type<decltype(&T::member)>::value> \\\n> { static const decltype(&T::member) value; }; \\\n \\\nstruct AmbiguitySeed_##member { char member; }; \\\n \\\ntemplate<typename T> \\\nstruct has_member_##member { \\\n static const bool value \\\n = has_member< \\\n Alias_##member<ambiguate<T, AmbiguitySeed_##member>> \\\n , Alias_##member<AmbiguitySeed_##member> \\\n >::value \\\n ; \\\n}\n //Check for member variable with given name.\n#define CREATE_MEMBER_VAR_CHECK(var_name) \\\n \\\ntemplate<typename T, typename = std::true_type> \\\nstruct has_member_var_##var_name : std::false_type {}; \\\n \\\ntemplate<typename T> \\\nstruct has_member_var_##var_name< \\\n T \\\n , std::integral_constant< \\\n bool \\\n , !std::is_member_function_pointer<decltype(&T::var_name)>::value \\\n > \\\n> : std::true_type {}\n //Check for member function with given name AND signature.\n#define CREATE_MEMBER_FUNC_SIG_CHECK(func_name, func_sig, templ_postfix) \\\n \\\ntemplate<typename T, typename = std::true_type> \\\nstruct has_member_func_##templ_postfix : std::false_type {}; \\\n \\\ntemplate<typename T> \\\nstruct has_member_func_##templ_postfix< \\\n T, std::integral_constant< \\\n bool \\\n , sig_check<func_sig, &T::func_name>::value \\\n > \\\n> : std::true_type {}\n //Check for member class with given name.\n#define CREATE_MEMBER_CLASS_CHECK(class_name) \\\n \\\ntemplate<typename T, typename = std::true_type> \\\nstruct has_member_class_##class_name : std::false_type {}; \\\n \\\ntemplate<typename T> \\\nstruct has_member_class_##class_name< \\\n T \\\n , std::integral_constant< \\\n bool \\\n , std::is_class< \\\n typename got_type<typename T::class_name>::type \\\n >::value \\\n > \\\n> : std::true_type {}\n //Check for member union with given name.\n#define CREATE_MEMBER_UNION_CHECK(union_name) \\\n \\\ntemplate<typename T, typename = std::true_type> \\\nstruct has_member_union_##union_name : std::false_type {}; \\\n \\\ntemplate<typename T> \\\nstruct has_member_union_##union_name< \\\n T \\\n , std::integral_constant< \\\n bool \\\n , std::is_union< \\\n typename got_type<typename T::union_name>::type \\\n >::value \\\n > \\\n> : std::true_type {}\n //Check for member enum with given name.\n#define CREATE_MEMBER_ENUM_CHECK(enum_name) \\\n \\\ntemplate<typename T, typename = std::true_type> \\\nstruct has_member_enum_##enum_name : std::false_type {}; \\\n \\\ntemplate<typename T> \\\nstruct has_member_enum_##enum_name< \\\n T \\\n , std::integral_constant< \\\n bool \\\n , std::is_enum< \\\n typename got_type<typename T::enum_name>::type \\\n >::value \\\n > \\\n> : std::true_type {}\n //Check for function with given name, any signature.\n#define CREATE_MEMBER_FUNC_CHECK(func) \\\ntemplate<typename T> \\\nstruct has_member_func_##func { \\\n static const bool value \\\n = has_member_##func<T>::value \\\n && !has_member_var_##func<T>::value \\\n && !has_member_class_##func<T>::value \\\n && !has_member_union_##func<T>::value \\\n && !has_member_enum_##func<T>::value \\\n ; \\\n}\n //Create all the checks for one member. Does NOT include func sig checks.\n#define CREATE_MEMBER_CHECKS(member) \\\nCREATE_MEMBER_CHECK(member); \\\nCREATE_MEMBER_VAR_CHECK(member); \\\nCREATE_MEMBER_CLASS_CHECK(member); \\\nCREATE_MEMBER_UNION_CHECK(member); \\\nCREATE_MEMBER_ENUM_CHECK(member); \\\nCREATE_MEMBER_FUNC_CHECK(member)\n" }, { "answer_id": 31539364, "author": "Valentin Milea", "author_id": 211387, "author_profile": "https://Stackoverflow.com/users/211387", "pm_score": 3, "selected": false, "text": "template <class C>\nclass HasGreetMethod\n{\n template <class T>\n static std::true_type testSignature(void (T::*)(const char*) const);\n\n template <class T>\n static decltype(testSignature(&T::greet)) test(std::nullptr_t);\n\n template <class T>\n static std::false_type test(...);\n\npublic:\n using type = decltype(test<C>(nullptr));\n static const bool value = type::value;\n};\n\nstruct A { void greet(const char* name) const; };\nstruct Derived : A { };\nstatic_assert(HasGreetMethod<Derived>::value, \"\");\n" }, { "answer_id": 37117023, "author": "Jonathan Mee", "author_id": 2642059, "author_profile": "https://Stackoverflow.com/users/2642059", "pm_score": 3, "selected": false, "text": "type_traits true_type false_type true_type int false_type true_type declval decltype test int template <typename T, typename S = decltype(declval<T>().test(declval<int>))> static true_type hasTest(int);\ntemplate <typename T> static false_type hasTest(...);\n decltype(hasTest<a>(0))::value true void a::test() void a::test(int) decltype(hasTest<b>(0))::value true int double int b::test(double) decltype(hasTest<c>(0))::value false c test int test() #define FOO(FUNCTION, DEFINE) template <typename T, typename S = decltype(declval<T>().FUNCTION)> static true_type __ ## DEFINE(int); \\\n template <typename T> static false_type __ ## DEFINE(...); \\\n template <typename T> using DEFINE = decltype(__ ## DEFINE<T>(0));\n namespace details {\n FOO(test(declval<int>()), test_int)\n FOO(test(), test_void)\n}\n details::test_int<a>::value details::test_void<a>::value true false" }, { "answer_id": 44999060, "author": "Kamajii", "author_id": 4355012, "author_profile": "https://Stackoverflow.com/users/4355012", "pm_score": 1, "selected": false, "text": "decltype #include <iostream>\nusing namespace std;\n\nstruct A { void foo(void); };\nstruct Aa: public A { };\nstruct B { };\n\nstruct retA { int foo(void); };\nstruct argA { void foo(double); };\nstruct constA { void foo(void) const; };\nstruct varA { int foo; };\n\ntemplate<typename T>\nstruct FooFinder {\n typedef char true_type[1];\n typedef char false_type[2];\n\n template<int>\n struct TypeSink;\n\n template<class U>\n static true_type &match(U);\n\n template<class U>\n static true_type &test(TypeSink<sizeof( matchType<void (U::*)(void)>( &U::foo ) )> *);\n\n template<class U>\n static false_type &test(...);\n\n enum { value = (sizeof(test<T>(0, 0)) == sizeof(true_type)) };\n};\n\nint main() {\n cout << FooFinder<A>::value << endl;\n cout << FooFinder<Aa>::value << endl;\n cout << FooFinder<B>::value << endl;\n\n cout << FooFinder<retA>::value << endl;\n cout << FooFinder<argA>::value << endl;\n cout << FooFinder<constA>::value << endl;\n cout << FooFinder<varA>::value << endl;\n}\n A Aa B Aa FooFinder true_type false_type TypeSink sizeof match test false_type test T match TypeSink &U::foo" }, { "answer_id": 55682258, "author": "prehistoricpenguin", "author_id": 1292791, "author_profile": "https://Stackoverflow.com/users/1292791", "pm_score": 2, "selected": false, "text": "#include <folly/Traits.h>\nnamespace {\n FOLLY_CREATE_HAS_MEMBER_FN_TRAITS(has_test_traits, test);\n} // unnamed-namespace\n\nvoid some_func() {\n cout << \"Does class Foo have a member int test() const? \"\n << boolalpha << has_test_traits<Foo, int() const>::value;\n}\n" }, { "answer_id": 61482882, "author": "ctNGUYEN", "author_id": 1853441, "author_profile": "https://Stackoverflow.com/users/1853441", "pm_score": 2, "selected": false, "text": "struct Foo{ static int sum(int, const double&){return 0;} };\nstruct Bar{ int calc(int, const double&) {return 1;} };\nstruct BarConst{ int calc(int, const double&) const {return 1;} };\n\n// Note : second typename can be void or anything, as long as it is consistent with the result of enable_if_t\ntemplate<typename T, typename = T> struct has_static_sum : std::false_type {};\ntemplate<typename T>\nstruct has_static_sum<typename T,\n std::enable_if_t<std::is_same<decltype(T::sum), int(int, const double&)>::value,T> \n > : std::true_type {};\n\ntemplate<typename T, typename = T> struct has_calc : std::false_type {};\ntemplate<typename T>\nstruct has_calc <typename T,\n std::enable_if_t<std::is_same<decltype(&T::calc), int(T::*)(int, const double&)>::value,T>\n > : std::true_type {};\n\ntemplate<typename T, typename = T> struct has_calc_const : std::false_type {};\ntemplate<typename T>\nstruct has_calc_const <T,\n std::enable_if_t<std::is_same<decltype(&T::calc), int(T::*)(int, const double&) const>::value,T>\n > : std::true_type {};\n\nint main ()\n{\n constexpr bool has_sum_val = has_static_sum<Foo>::value;\n constexpr bool not_has_sum_val = !has_static_sum<Bar>::value;\n\n constexpr bool has_calc_val = has_calc<Bar>::value;\n constexpr bool not_has_calc_val = !has_calc<Foo>::value;\n\n constexpr bool has_calc_const_val = has_calc_const<BarConst>::value;\n constexpr bool not_has_calc_const_val = !has_calc_const<Bar>::value;\n\n std::cout<< \" has_sum_val \" << has_sum_val << std::endl\n << \" not_has_sum_val \" << not_has_sum_val << std::endl\n << \" has_calc_val \" << has_calc_val << std::endl\n << \" not_has_calc_val \" << not_has_calc_val << std::endl\n << \" has_calc_const_val \" << has_calc_const_val << std::endl\n << \"not_has_calc_const_val \" << not_has_calc_const_val << std::endl;\n}\n has_sum_val 1\n not_has_sum_val 1\n has_calc_val 1\n not_has_calc_val 1\n has_calc_const_val 1\nnot_has_calc_const_val 1\n" }, { "answer_id": 62061759, "author": "lar", "author_id": 13633603, "author_profile": "https://Stackoverflow.com/users/13633603", "pm_score": 3, "selected": false, "text": "std::experimental #include <experimental/type_traits>\n\n// serialized_method_t is a detector type for T.serialize(int) const\ntemplate<typename T>\nusing serialized_method_t = decltype(std::declval<const T&>().serialize(std::declval<int>()));\n\n// has_serialize_t is std::true_type when T.serialize(int) exists,\n// and false otherwise.\ntemplate<typename T>\nusing has_serialize_t = std::experimental::is_detected_t<serialized_method_t, T>;\n\n template <typename... Ts>\nusing void_t = void;\ntemplate <template <class...> class Trait, class AlwaysVoid, class... Args>\nstruct detector : std::false_type {};\ntemplate <template <class...> class Trait, class... Args>\nstruct detector<Trait, void_t<Trait<Args...>>, Args...> : std::true_type {};\n\n// serialized_method_t is a detector type for T.serialize(int) const\ntemplate<typename T>\nusing serialized_method_t = decltype(std::declval<const T&>().serialize(std::declval<int>()));\n\n// has_serialize_t is std::true_type when T.serialize(int) exists,\n// and false otherwise.\ntemplate <typename T>\nusing has_serialize_t = typename detector<serialized_method_t, void, T>::type;\n template<class T>\nstd::enable_if_t<has_serialize_t<T>::value, std::string>\nSerializeToString(const T& t) {\n}\n template<class T>\nstd::string SerializeImpl(std::true_type, const T& t) {\n // call serialize here.\n}\n\ntemplate<class T>\nstd::string SerializeImpl(std::false_type, const T& t) {\n // do something else here.\n}\n\ntemplate<class T>\nstd::string Serialize(const T& t) {\n return SerializeImpl(has_serialize_t<T>{}, t);\n}\n\n" }, { "answer_id": 62626862, "author": "debashish.ghosh", "author_id": 2379665, "author_profile": "https://Stackoverflow.com/users/2379665", "pm_score": 1, "selected": false, "text": "#include <type_traits>\n\n#define CHECK_NESTED_FUNC(fName) \\\n template <typename, typename, typename = std::void_t<>> \\\n struct _has_##fName \\\n : public std::false_type {}; \\\n \\\n template <typename Class, typename Ret, typename... Args> \\\n struct _has_##fName<Class, Ret(Args...), \\\n std::void_t<decltype(std::declval<Class>().fName(std::declval<Args>()...))>> \\\n : public std::is_same<decltype(std::declval<Class>().fName(std::declval<Args>()...)), Ret> \\\n {}; \\\n \\\n template <typename Class, typename Signature> \\\n using has_##fName = _has_##fName<Class, Signature>;\n\n#define HAS_NESTED_FUNC(Class, Func, Signature) has_##Func<Class, Signature>::value\n class Foo\n{\npublic:\n void Bar(int, const char *) {}\n};\n\nCHECK_NESTED_FUNC(Bar); // generate required metafunctions\n\nint main()\n{\n using namespace std;\n cout << boolalpha\n << HAS_NESTED_FUNC(Foo, Bar, void(int, const char *)) // prints true\n << endl;\n return 0;\n}\n" }, { "answer_id": 64308024, "author": "Peter Rindal", "author_id": 5130905, "author_profile": "https://Stackoverflow.com/users/5130905", "pm_score": 4, "selected": false, "text": "T void T::resize(typename T::size_type) std::vector<U> template<typename T>\nconcept has_resize_member_func = requires {\n typename T::size_type;\n { std::declval<T>().resize(std::declval<typename T::size_type>()) } -> std::same_as<void>;\n};\n static_assert(has_resize_member_func<std::string>, \"\");\nstatic_assert(has_resize_member_func<int> == false, \"\");\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/87372", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10120/" ]
87,380
<p>I need to write a function that receives a string and a regex. I need to check if there is a match and return the start and end location of a match. (The regex was already compiled by <code>qr//</code>.)</p> <p>The function might also receive a "global" flag and then I need to return the (start,end) pairs of all the matches.</p> <p>I cannot change the regex, not even add <code>()</code> around it as the user might use <code>()</code> and <code>\1</code>. Maybe I can use <code>(?:)</code>.</p> <p>Example: given "ababab" and the regex <code>qr/ab/</code>, in the global case I need to get back 3 pairs of (start, end).</p>
[ { "answer_id": 87410, "author": "Leon Timmermans", "author_id": 4727, "author_profile": "https://Stackoverflow.com/users/4727", "pm_score": 3, "selected": false, "text": "length $1 sub match_positions {\n my ($regex, $string) = @_;\n return if not $string =~ /($regex)/;\n return (pos($string) - length $1, pos($string));\n}\nsub all_match_positions {\n my ($regex, $string) = @_;\n my @ret;\n while ($string =~ /($regex)/g) {\n push @ret, [pos($string) - length $1, pos($string)];\n }\n return @ret\n}\n" }, { "answer_id": 87461, "author": "zigdon", "author_id": 4913, "author_profile": "https://Stackoverflow.com/users/4913", "pm_score": 0, "selected": false, "text": " $‘ The string preceding whatever was matched by the last successful pattern match (not\n counting any matches hidden within a BLOCK or eval enclosed by the current BLOCK).\n (Mnemonic: \"`\" often precedes a quoted string.) This variable is read-only.\n\n The use of this variable anywhere in a program imposes a considerable performance penalty\n on all regular expression matches. See \"BUGS\".\n" }, { "answer_id": 87504, "author": "Leon Timmermans", "author_id": 4727, "author_profile": "https://Stackoverflow.com/users/4727", "pm_score": 5, "selected": false, "text": "sub match_positions {\n my ($regex, $string) = @_;\n return if not $string =~ /$regex/;\n return ($-[0], $+[0]);\n}\nsub match_all_positions {\n my ($regex, $string) = @_;\n my @ret;\n while ($string =~ /$regex/g) {\n push @ret, [ $-[0], $+[0] ];\n }\n return @ret\n}\n" }, { "answer_id": 87565, "author": "Michael Carman", "author_id": 8233, "author_profile": "https://Stackoverflow.com/users/8233", "pm_score": 6, "selected": false, "text": "@- @+ $-[0] $+[0] $-[N] $+[N] $N $1 $2" }, { "answer_id": 34936848, "author": "Shicheng Guo", "author_id": 2769148, "author_profile": "https://Stackoverflow.com/users/2769148", "pm_score": 0, "selected": false, "text": "#!/usr/bin/perl\n\n# search the postions for the CpGs in human genome\n\nsub match_positions {\n my ($regex, $string) = @_;\n return if not $string =~ /($regex)/;\n return (pos($string), pos($string) + length $1);\n}\nsub all_match_positions {\n my ($regex, $string) = @_;\n my @ret;\n while ($string =~ /($regex)/g) {\n push @ret, [(pos($string)-length $1),pos($string)-1];\n }\n return @ret\n}\n\nmy $regex='CG';\nmy $string=\"ACGACGCGCGCG\";\nmy $cgap=3; \nmy @pos=all_match_positions($regex,$string);\n\nmy @hgcg;\n\nforeach my $pos(@pos){\n push @hgcg,@$pos[1];\n}\n\nforeach my $i(0..($#hgcg-$cgap+1)){\nmy $len=$hgcg[$i+$cgap-1]-$hgcg[$i]+2;\nprint \"$len\\n\"; \n}\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/87380", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11827/" ]
87,381
<p>With ViEmu you really need to unbind a lot of resharpers keybindings to make it work well.</p> <p>Does anyone have what they think is a good set of keybindings that work well for resharper when using ViEmu?</p> <p>What I'm doing at the moment using the Visual Studio bindings from Resharper. Toasting all the conflicting ones with ViEmu, and then just driving the rest through the menu modifiers ( Alt-R keyboard shortcut for the menu item ). I also do the same with Visual Assist shortcuts ( for C++ )</p> <p>if anyones got any tips and tricks for ViEmu / Resharper or Visual Assist working together well I'd most apprciate it!</p>
[ { "answer_id": 994587, "author": "Jay", "author_id": 114994, "author_profile": "https://Stackoverflow.com/users/114994", "pm_score": 5, "selected": true, "text": "map <C-S-c> gS:vsc Edit.CommentSelection<CR>\nmap <C-A-c> gS:vsc Edit.UncommentSelection<CR>\n map <C-S-A-f> gS:vsc ReSharper.FindUsages<CR>\n" }, { "answer_id": 5604454, "author": "bentayloruk", "author_id": 418492, "author_profile": "https://Stackoverflow.com/users/418492", "pm_score": 2, "selected": false, "text": "Ctrl+N Go To Type Ctrl+Shift+N Go To File Ctrl+Shift+N Go To Type Go To Type" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/87381", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10431/" ]
87,408
<p>a lot of websites like twitter, facebook and others let the users enter their email id and pwd and 'extract' the contacts based on that. </p> <p>Anyone know how this is done? </p>
[ { "answer_id": 87624, "author": "Dónal", "author_id": 2648, "author_profile": "https://Stackoverflow.com/users/2648", "pm_score": 2, "selected": false, "text": "List<Contact> contacts = SimpleAddressBookImporter.fetchContacts(emailAddress, password)\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/87408", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
87,422
<p>I am writing an application that if the user hits back, it may resend the same information and mess up the flow and integrity of data. How do I disable it for users who are with and without javascript on?</p>
[ { "answer_id": 87632, "author": "Claus Thomsen", "author_id": 15555, "author_profile": "https://Stackoverflow.com/users/15555", "pm_score": 3, "selected": false, "text": " Response.Cache.SetCacheability(HttpCacheability.NoCache);\n Response.Cache.SetExpires(Now.AddSeconds(-1));\n Response.Cache.SetNoStore();\n Response.AppendHeader(\"Pragma\", \"no-cache\");\n if (Page.IsPostBack)\n {\n if (pageIsExpired()){\n Response.Redirect(\"/Some_error_page.htm\");\n }\n else {\n var now = Now;\n Session(\"TimeStamp\") = now.ToString();\n ViewState(\"TimeStamp\") = now.ToString();\n }\n\n private boolean pageIsExpired()\n {\n if (Session(\"TimeStamp\") == null || ViewState(\"TimeStamp\") == null)\n return false;\n\n if (Session(\"TimeStamp\") == ViewState(\"TimeStamp\"))\n return true;\n\n return false;\n }\n" }, { "answer_id": 5881175, "author": "Yossi Shasho", "author_id": 437019, "author_profile": "https://Stackoverflow.com/users/437019", "pm_score": 3, "selected": false, "text": "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\"\n\"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">\n<html xmlns=\"http://www.w3.org/1999/xhtml\" >\n<title>Untitled Page</title>\n<script type = \"text/javascript\" >\nfunction changeHashOnLoad() {\n window.location.href += \"#\";\n setTimeout(\"changeHashAgain()\", \"50\"); \n}\n\nfunction changeHashAgain() {\n window.location.href += \"1\";\n}\n\nvar storedHash = window.location.hash;\nwindow.setInterval(function () {\n if (window.location.hash != storedHash) {\n window.location.hash = storedHash;\n }\n}, 50);\n\n\n</script>\n</head>\n<body onload=\"changeHashOnLoad(); \">\nTry to hit back!\n</body>\n</html>\n" }, { "answer_id": 7906990, "author": "user825345", "author_id": 825345, "author_profile": "https://Stackoverflow.com/users/825345", "pm_score": 0, "selected": false, "text": " Response.Cache.SetExpires(DateTime.MinValue);\n Response.Cache.SetNoStore();\n" }, { "answer_id": 8451973, "author": "katzmopolitan", "author_id": 691586, "author_profile": "https://Stackoverflow.com/users/691586", "pm_score": 1, "selected": false, "text": "history.go(+1);\n" }, { "answer_id": 17179083, "author": "bugwheels94", "author_id": 1533609, "author_profile": "https://Stackoverflow.com/users/1533609", "pm_score": 2, "selected": false, "text": " <script>\nwindow.location.hash=\"no-back-button\";\nwindow.location.hash=\"Again-no-back-button\";//for google chrome\nwindow.onhashchange=function(){window.location.hash=\"no-back-button\";}\n</script> \n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/87422", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10088/" ]
87,425
<p>Do you generally assume that toString() on any given object has a low cost (i.e. for logging)? I do. Is that assumption valid? If it has a high cost should that normally be changed? What are valid reasons to make a toString() method with a high cost? The only time that I get concerned about toString costs is when I know that it is on some sort of collection with many members. From: <a href="http://jamesjava.blogspot.com/2007/08/tostring-cost.html" rel="noreferrer">http://jamesjava.blogspot.com/2007/08/tostring-cost.html</a></p> <p>Update: Another way to put it is: Do you usually look into the cost of calling toString on any given class before calling it?</p>
[ { "answer_id": 87519, "author": "Eli Courtwright", "author_id": 1694, "author_profile": "https://Stackoverflow.com/users/1694", "pm_score": 5, "selected": true, "text": "Arrays.toString Collections.toString java.util java.net.URL" }, { "answer_id": 94872, "author": "Mr. Shiny and New 安宇", "author_id": 7867, "author_profile": "https://Stackoverflow.com/users/7867", "pm_score": 0, "selected": false, "text": "if(logger.isDebugEnabled()) {\n logger.debug(\"The zig didn't take off. Response: {0}\", response.getAsXML().toString());\n}\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/87425", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6770/" ]
87,442
<p>I know that you can make a virtual network interface in Windows (see <a href="http://support.microsoft.com/kb/236869" rel="nofollow noreferrer">here</a>), and in Linux it is also pretty easy with ip-aliases, but does something similar exist for <strong>Mac OS X</strong>? I've been looking for loopback adapters, virtual interfaces and couldn't find a good solution.</p> <p>You can create a new interface in the networking panel, based on an existing interface, but it will not act as a real fully functional interface (if the original interface is inactive, then the derived one is also inactive).</p> <p>This scenario is needed when working in a completely disconnected situation. Even then, it makes sense to have networking capabilities when running servers in a VMWare installation. Those virtual machines can be reached by their IP address, but not by their DNS name, even if I run a DNS server in one of those virtual machines. By configuring an interface to use the virtual DNS server, I thought I could test some DNS scenario's. Unfortunately, no interface is resolving DNS names if none of them are inactive...</p>
[ { "answer_id": 6375307, "author": "bmasterswizzle", "author_id": 801917, "author_profile": "https://Stackoverflow.com/users/801917", "pm_score": 5, "selected": false, "text": "/Library/Preferences/SystemConfiguration/preferences.plist preferences.plist preferences.plist preferences.plist #include <stdio.h>\n#include <fcntl.h>\n#include <unistd.h>\nint main()\n{\n int fd = open(\"/dev/tun0\", O_RDONLY);\n if (fd < 0)\n {\n printf(\"Failed to open tun/tap device. Are you root? Are the drivers installed?\\n\");\n return -1;\n }\n while (1)\n {\n sleep(100000);\n }\n return 0;\n}\n" }, { "answer_id": 29858786, "author": "web-online", "author_id": 4815948, "author_profile": "https://Stackoverflow.com/users/4815948", "pm_score": 3, "selected": false, "text": "$ sw_vers -productVersion\n10.9.5\n$ sudo ifconfig vlan169 create && echo vlan169 created\nvlan169 created\n$ sudo ifconfig vlan169 inet 169.254.169.254 netmask 255.255.255.255 && echo vlan169 configured\nvlan169 configured\n$ sudo ./minidns.py 169.254.169.254 &\n[1] 35125\n$ miniDNS :: * 60 IN A 169.254.169.254\n\n\n$ dig @169.254.169.254 +short test.host\nRequest: test.host. -> 169.254.169.254\nRequest: test.host. -> 169.254.169.254\n169.254.169.254\n$ sudo kill 35125\n$ \n[1]+ Exit 143 sudo ./minidns.py 169.254.169.254\n$ sudo ifconfig vlan169 destroy && echo vlan169 destroyed\nvlan169 destroyed\n" }, { "answer_id": 31259641, "author": "Alex Gray", "author_id": 547214, "author_profile": "https://Stackoverflow.com/users/547214", "pm_score": 4, "selected": false, "text": "@bmasterswizzle @DanRamos #!/bin/zsh\n\n[[ \"$UID\" -ne \"0\" ]] && echo \"You must be root. Goodbye...\" && exit 1\necho \"starting\"\nexec 4<>/dev/tap0\nifconfig tap0 10.10.10.1 10.10.10.255\nifconfig tap0 up\nping -c1 10.10.10.1\necho \"ending\"\nexport PS1=\"tap interface>\"\ndd of=/dev/null <&4 & # continuously reads from buffer and dumps to null\n dd of=/dev/null <&4 & # continuously reads from buffer and dumps to null" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/87442", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9504/" ]
87,458
<p>I want to do this so that I can say something like, <code>svn mv *.php php-folder/</code>, but it does not seem to be working. Is it even possible? No mention of it is made on the relevant page in the <a href="http://svnbook.red-bean.com/en/1.0/re18.html" rel="noreferrer">svn book</a>.</p> <p>Example output of <code>svn mv *.php php-folder/</code> :<br> <code>svn: Client error in parsing arguments</code></p> <p>Being able to move a whole file system would be a plus, so if any answers given could try to include that ability, that'd be cool.</p> <p>Thanks in advance!</p>
[ { "answer_id": 87516, "author": "sirprize", "author_id": 12902, "author_profile": "https://Stackoverflow.com/users/12902", "pm_score": 4, "selected": true, "text": "for file in *.php; do svn mv $file php-folder/; done\n" }, { "answer_id": 87524, "author": "cjm", "author_id": 8355, "author_profile": "https://Stackoverflow.com/users/8355", "pm_score": 4, "selected": false, "text": "for f in *.php ; do svn mv $f php-folder/; done\n for %f in (*.php) do svn mv %f php-folder/\n svn mv" }, { "answer_id": 4749024, "author": "User1", "author_id": 125380, "author_profile": "https://Stackoverflow.com/users/125380", "pm_score": 1, "selected": false, "text": "find . -name \"*.php\" -exec svn mv {} php-folder \\;" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/87458", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16562/" ]
87,459
<p>I have a class with a string property that's actually several strings joined with a separator.</p> <p>I'm wondering if it is good form to have a proxy property like this:</p> <pre><code>public string ActualProperty { get { return actualProperty; } set { actualProperty = value; } } public string[] IndividualStrings { get { return ActualProperty.Split(.....); } set { // join strings from array in propval .... ; ActualProperty = propval; } } </code></pre> <p>Is there any risks I have overlooked?</p>
[ { "answer_id": 87498, "author": "Shog9", "author_id": 811, "author_profile": "https://Stackoverflow.com/users/811", "pm_score": 1, "selected": false, "text": "Split() IndividualStrings ActualProperty actualProperty" }, { "answer_id": 88196, "author": "Steve Cooper", "author_id": 6722, "author_profile": "https://Stackoverflow.com/users/6722", "pm_score": 2, "selected": false, "text": "GetJoinedString(string seperator) SetStrings(string joined, string seperator) Parse(string joined, string seperator)" }, { "answer_id": 2390765, "author": "Paul Turner", "author_id": 138578, "author_profile": "https://Stackoverflow.com/users/138578", "pm_score": 1, "selected": false, "text": "YourClass i = new YourClass();\ni.IndividualStrings[0] = \"Hello temporary array!\";\n IndividualStrings public string ActualProperty { get; set; }\n\npublic string[] GetIndividualStrings()\n{\n return ActualProperty.Split(.....);\n}\n\npublic void SetFromIndividualStrings(string[] values)\n{\n // join strings from array .... ;\n}\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/87459", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4192/" ]
87,468
<p>Essentially I have a PHP page that calls out some other HTML to be rendered through an object's method. It looks like this:</p> <p>MY PHP PAGE:</p> <pre><code>// some content... &lt;?php $GLOBALS["topOfThePage"] = true; $this-&gt;renderSomeHTML(); ?&gt; // some content... &lt;?php $GLOBALS["topOfThePage"] = false; $this-&gt;renderSomeHTML(); ?&gt; </code></pre> <p>The first method call is cached, but I need renderSomeHTML() to display slightly different based upon its location in the page. I tried passing through to $GLOBALS, but the value doesn't change, so I'm assuming it is getting cached.</p> <p>Is this not possible without passing an argument through the method or by not caching it? Any help is appreciated. This is not my application -- it is Magento.</p> <p><strong>Edit:</strong></p> <p>This is Magento, and it looks to be using memcached. I tried to pass an argument through renderSomeHTML(), but when I use func_get_args() on the PHP include to be rendered, what comes out is not what I put into it.</p> <p><strong>Edit:</strong></p> <p>Further down the line I was able to "invalidate" the cache by calling a different method that pulled the same content and passing in an argument that turned off caching. Thanks everyone for your help.</p>
[ { "answer_id": 87507, "author": "DGM", "author_id": 14253, "author_profile": "https://Stackoverflow.com/users/14253", "pm_score": 1, "selected": false, "text": "$GLOBALS. $this->renderSomeHTML(true);\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/87468", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
87,542
<p>I have a set of WCF web services connected to dynamically by a desktop application.</p> <p>My problem is the really detailed config settings that WCF requires to work. Getting SSL to work involves custom settings. Getting MTOM or anything else to work requires more. You want compression? Here we go again...</p> <p>WCF is really powerful - you can use a host of different ways to connect, but all seem to involve lots of detailed config. If host and client don't match perfectly you get hard to decipher errors.</p> <p>I want to make the desktop app far easier to configure - ideally some kind of auto-discovery. The users of the desktop app should just be able to enter the URL and it do the rest.</p> <p>Does anyone know a good way to do this?</p> <p>I know Visual Studio can set the config up for you, but I want the desktop app to be able to do it based on a wide variety of different server set-ups.</p> <p>I know that VS's tools can be used externally, but I'm looking for users of the desktop apps to not have to be WCF experts. I know MS made this intentionally over complicated.</p> <p>Is there any way, mechanism, 3rd party library or anything to make auto-discovery of WCF settings possible?</p>
[ { "answer_id": 101186, "author": "Keith", "author_id": 905, "author_profile": "https://Stackoverflow.com/users/905", "pm_score": 1, "selected": false, "text": "/// <summary>If the url doesn't end with a WSDL query string append it</summary>\nstatic string AddWsdlQueryStringIfMissing( string input )\n{\n return input.EndsWith( \"?wsdl\", StringComparison.OrdinalIgnoreCase ) ?\n input : input + \"?wsdl\";\n}\n\n/// <summary>Imports the meta data from the specified location</summary>\nstatic ServiceEndpointCollection GetEndpoints( BindingElement bindingElement, Uri address, MetadataExchangeClientMode mode )\n{\n CustomBinding binding = new CustomBinding( bindingElement );\n MetadataSet metadata = new MetadataExchangeClient( binding ).GetMetadata( address, mode );\n return new WsdlImporter( metadata ).ImportAllEndpoints();\n}\n public static ServiceEndpointCollection Discover( string url )\n{\n Uri address = new Uri( url );\n ServiceEndpointCollection endpoints = null;\n\n if ( string.Equals( address.Scheme, \"http\", StringComparison.OrdinalIgnoreCase ) )\n {\n var httpBindingElement = new HttpTransportBindingElement();\n\n //Try the HTTP MEX Endpoint\n try { endpoints = GetEndpoints( httpBindingElement, address, MetadataExchangeClientMode.MetadataExchange ); }\n catch { }\n\n //Try over HTTP-GET\n if ( endpoints == null )\n endpoints = GetEndpoints( httpBindingElement,\n new Uri( AddWsdlQueryStringIfMissing( url ) ), MetadataExchangeClientMode.HttpGet );\n }\n else if ( string.Equals( address.Scheme, \"https\", StringComparison.OrdinalIgnoreCase ) )\n {\n var httpsBindingElement = new HttpsTransportBindingElement();\n\n //Try the HTTPS MEX Endpoint\n try { endpoints = GetEndpoints( httpsBindingElement, address, MetadataExchangeClientMode.MetadataExchange ); }\n catch { }\n\n //Try over HTTP-GET\n if ( endpoints == null )\n endpoints = GetEndpoints( httpsBindingElement,\n new Uri( AddWsdlQueryStringIfMissing( url ) ), MetadataExchangeClientMode.HttpGet );\n }\n else if ( string.Equals( address.Scheme, \"net.tcp\", StringComparison.OrdinalIgnoreCase ) )\n endpoints = GetEndpoints( new TcpTransportBindingElement(), \n address, MetadataExchangeClientMode.MetadataExchange );\n\n else if ( string.Equals( address.Scheme, \"net.pipe\", StringComparison.OrdinalIgnoreCase ) )\n endpoints = GetEndpoints( new NamedPipeTransportBindingElement(), \n address, MetadataExchangeClientMode.MetadataExchange );\n\n return endpoints;\n}\n" }, { "answer_id": 1834211, "author": "Keith", "author_id": 905, "author_profile": "https://Stackoverflow.com/users/905", "pm_score": 1, "selected": false, "text": "System.ServiceModel.Web WebInvoke WebGet //get a user - note that this can be cached by IIS and proxies\n[WebGet]\nUser GetUser(string id )\n\n//post changes to a user\n[WebInvoke]\nvoid SaveUser(string id, User changes )\n .svc <%@ServiceHost \n Service=\"MyNamespace.MyServiceImplementationClass\" \n Factory=\"System.ServiceModel.Activation.WebServiceHostFactory\" %>\n ChannelFactory var cf = new WebChannelFactory<IMyContractInterface>();\nvar binding = new WebHttpBinding();\n\ncf.Endpoint.Binding = binding;\ncf.Endpoint.Address = new EndpointAddress(new Uri(\"mywebsite.com/myservice.svc\"));\ncf.Endpoint.Behaviors.Add(new WebHttpBehavior());\n\nIMyContractInterface wcfClient = cf.CreateChannel();\n\nvar usr = wcfClient.GetUser(\"demouser\");\n// and so on...\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/87542", "https://Stackoverflow.com", "https://Stackoverflow.com/users/905/" ]
87,557
<p>I have a class with many embedded assets. </p> <p>Within the class, I would like to get the class definition of an asset by name. I have tried using getDefinitionByName(), and also ApplicationDomain.currentDomain.getDefinition() but neither work.</p> <p>Example:</p> <pre><code>public class MyClass { [Embed(source="images/image1.png")] private static var Image1Class:Class; [Embed(source="images/image2.png")] private static var Image2Class:Class; [Embed(source="images/image3.png")] private static var Image3Class:Class; private var _image:Bitmap; public function MyClass(name:String) { var ClassDef:Class = getDefinitionByName(name) as Class; //&lt;&lt;-- Fails _image = new ClassDef() as Bitmap; } } var cls:MyClass = new MyClass("Image1Class"); </code></pre>
[ { "answer_id": 87596, "author": "Marc Hughes", "author_id": 6791, "author_profile": "https://Stackoverflow.com/users/6791", "pm_score": 4, "selected": true, "text": "public class MyClass\n{\n [Embed(source=\"images/image1.png\")] private static var Image1Class:Class;\n [Embed(source=\"images/image2.png\")] private static var Image2Class:Class;\n [Embed(source=\"images/image3.png\")] private static var Image3Class:Class;\n\n private var _image:Bitmap;\n\n public function MyClass(name:String)\n {\n _image = new this[name]() as Bitmap; \n }\n}\n\nvar cls:MyClass = new MyClass(\"Image1Class\");\n" }, { "answer_id": 87626, "author": "davr", "author_id": 14569, "author_profile": "https://Stackoverflow.com/users/14569", "pm_score": 2, "selected": false, "text": "var classDef:Class = MyClass[name] as Class;\n" }, { "answer_id": 5819081, "author": "IQAndreas", "author_id": 617937, "author_profile": "https://Stackoverflow.com/users/617937", "pm_score": 2, "selected": false, "text": "import flash.utils.getQualifiedClassName;\ntrace(getQualifiedClassName(Image1Class));\n MyClass_Image1Class" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/87557", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8399/" ]
87,561
<p>I'd like to add some pie, bar and scatter charts to my Ruby on Rails web application. I want want them to be atractive, easy to add and not introduce much overhead. </p> <p>What charting solution would you recommend?<br> What are its drawbacks (requires Javascript, Flash, expensive, etc)?</p>
[ { "answer_id": 87646, "author": "Clinton Dreisbach", "author_id": 6262, "author_profile": "https://Stackoverflow.com/users/6262", "pm_score": 7, "selected": true, "text": "GoogleChart::PieChart.new('320x200', \"Things I Like To Eat\", false) do |pc| \n pc.data \"Broccoli\", 30\n pc.data \"Pizza\", 20\n pc.data \"PB&J\", 40 \n pc.data \"Turnips\", 10 \n puts pc.to_url \nend\n" }, { "answer_id": 34348150, "author": "ytbryan", "author_id": 388280, "author_profile": "https://Stackoverflow.com/users/388280", "pm_score": 0, "selected": false, "text": "gem 'chart'" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/87561", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16779/" ]
87,587
<p>Continuing my problem from yesterday, the Silverlight datagrid I have from this <a href="https://stackoverflow.com/questions/74461/silverlight-datagrid-control-selection-changed-event-interfering-with-sorting">issue</a> is now causing Stack Overflow errors when sorting a column with a large amount of data (Like the text column that contains a where clause for a SQL statment). When you sort, it'll fire the SelectedIndexChanged event for the datagrid and then still try to stort. If you click the header again the stack overflow occours. </p> <p>Does anyone have an idea on how to stop the sorting on this control for a column? All the other columns sort fine (but still fire that darn SelectedIndexChanged event), but if I could shut off the column for whereClause it'd be perfect.</p> <p>Does anyone have a better idea at how to get this to work?</p>
[ { "answer_id": 88253, "author": "BKimmel", "author_id": 13776, "author_profile": "https://Stackoverflow.com/users/13776", "pm_score": 0, "selected": false, "text": "dataGridView1.Columns[*Numberofthecolumnyoudontwantsorted*].SortMode\n= DataGridViewColumnSortMode.NotSortable;\n" }, { "answer_id": 210374, "author": "Bob King", "author_id": 6897, "author_profile": "https://Stackoverflow.com/users/6897", "pm_score": 3, "selected": true, "text": "<data:DataGridTextColumn CanUserSort=\"False\" Header=\"First Name\" Binding=\"{Binding FirstName}\" />\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/87587", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12413/" ]
87,612
<p>I want to fire up a flash presentation inside Powerpoint 2007. I am calling the Win32 ShellExecute() routine. When I run this from a location whose path is a UNC path (\myserver\myfolder\sample.ppt) it does not work.</p> <p>The ShellExecute routine expects 6 arguments, one of which is the path to run it from. I've tried to set this parameter to C:\ as well as using ActivePresentation.Path (which is a UNC path). Neither works.</p>
[ { "answer_id": 91379, "author": "Robert Mearns", "author_id": 5050, "author_profile": "https://Stackoverflow.com/users/5050", "pm_score": 2, "selected": false, "text": "* Autoload = True\n* EmbedMovie = True\n* Enabled = True\n* Loop = True\n* Playing = True\n* Visible = True\n* Movie = c:\\flash.swf (Change this to the location of your .swf file)\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/87612", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13800/" ]
87,621
<p>I have an XML that I want to load to objects, manipulate those objects (set values, read values) and then save those XMLs back. It is important for me to have the XML in the structure (xsd) that I created.</p> <p>One way to do that is to write my own serializer, but is there a built in support for it or open source in C# that I can use? </p>
[ { "answer_id": 87641, "author": "ckarras", "author_id": 5688, "author_profile": "https://Stackoverflow.com/users/5688", "pm_score": 6, "selected": true, "text": "xsd.exe dependency1.xsd dependency2.xsd schema.xsd /out:outputDir\n" }, { "answer_id": 88003, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 4, "selected": false, "text": "using System; \nusing System.IO;\nusing System.Text;\nusing System.Xml.Serialization;\nusing System.Runtime.Serialization;\nusing System.Runtime.Serialization.Formatters.Binary;\n\n\npublic static string Serialize(object objectToSerialize)\n{\n MemoryStream mem = new MemoryStream(); \n XmlSerializer ser = new XmlSerializer(objectToSerialize.GetType()); \n ser.Serialize(mem, objectToSerialize); \n ASCIIEncoding ascii = new ASCIIEncoding();\n return ascii.GetString(mem.ToArray());\n} \n\npublic static object Deserialize(Type typeToDeserialize, string xmlString)\n{\n byte[] bytes = Encoding.UTF8.GetBytes(xmlString);\n MemoryStream mem = new MemoryStream(bytes); \n XmlSerializer ser = new XmlSerializer(typeToDeserialize);\n return ser.Deserialize(mem);\n}\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/87621", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9855/" ]
87,647
<p>I have a DTS package with a data transformation task (data pump). I’d like to source the data with the results of a stored procedure that takes parameters, but DTS won’t preview the result set and can’t define the columns in the data transformation task.</p> <p>Has anyone gotten this to work?</p> <p>Caveat: The stored procedure uses two temp tables (and cleans them up, of course)</p>
[ { "answer_id": 88006, "author": "Cervo", "author_id": 16219, "author_profile": "https://Stackoverflow.com/users/16219", "pm_score": 2, "selected": false, "text": "DECLARE @param1 DataType1 \nDECLARE @param2 DataType2\nSET @param1 = global variable \nSET @param2 = global variable (I forget exact syntax) \n\n--EXEC procedure @param1, @param2 \nEXEC dbo.proc value1, value2\n EXEC EXEC" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/87647", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16813/" ]
87,676
<p>Every time I need to work with date and/or timstamps in Java I always feel like I'm doing something wrong and spend endless hours trying to find a better way of working with the APIs without having to code my own Date and Time utility classes. Here's a couple of annoying things I just ran into:</p> <ul> <li><p>0-based months. I realize that best practice is to use Calendar.SEPTEMBER instead of 8, but it's annoying that 8 represents September and not August.</p></li> <li><p>Getting a date without a timestamp. I always need the utility that Zeros out the timestamp portion of the date.</p></li> <li><p>I know there's other issues I've had in the past, but can't recall. Feel free to add more in your responses.</p></li> </ul> <p>So, my question is ... What third party APIs do you use to simplify Java's usage of Date and Time manipulation, if any? Any thoughts on using <a href="http://www.joda.org/joda-time/" rel="noreferrer">Joda</a>? Anyone looked closer at JSR-310 Date and Time API? </p>
[ { "answer_id": 88135, "author": "Michael", "author_id": 13379, "author_profile": "https://Stackoverflow.com/users/13379", "pm_score": 2, "selected": false, "text": "DateUtils DateUtils.truncate() Date Calendar" }, { "answer_id": 88974, "author": "Patrick Wilkes", "author_id": 6370, "author_profile": "https://Stackoverflow.com/users/6370", "pm_score": 2, "selected": false, "text": "org.joda.time.DateTime org.joda.time.DateMidnight java.util.Date" }, { "answer_id": 33405711, "author": "Basil Bourque", "author_id": 642706, "author_profile": "https://Stackoverflow.com/users/642706", "pm_score": 4, "selected": false, "text": "Instant ZoneId ZoneOffset ZonedDateTime Instant ZoneId Enum Month 9 10 if ( theMonth.equals ( Month.OCTOBER ) ) { …\n LocalDate LocalDate localDate = LocalDate.parse( \"2015-01-02\" );\n ZoneId LocalDate today = LocalDate.now( ZoneId.of( \"America/Montreal\" ) );\n LocalTime java.util.Date Calendar SimpleDateFormat Interval YearWeek YearQuarter" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/87676", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5917/" ]
87,689
<p>I have several applications that are part of a suite of tools that various developers at our studio use. these applications are mainly command line apps that open a DOS cmd shell. These apps in turn start up a GUI application that tracks output and status (via sockets) of these command line apps.</p> <p>The command line apps can be started with the user is logged in, when their workstation is locked (they fire off a batch file and then immediately lock their workstaion), and when they are logged out (via a scheduled task). The problems that I have are with the last two cases.</p> <p>If any of these apps fire off when the user is locked or logged out, these command will spawn the GUI windows which tracks the output/status. That's fine, but say the user has their workstation locked -- when they unlock their workstation, the GUI isn't visible. It's running the task list, but it's not visible. The next time these users run some of our command line apps, the GUI doesn't get launched (because it's already running), but because it's not visible on the desktop, users don't see any output.</p> <p>What I'm looking for is a way to tell from my command line apps if they are running behind a locked workstation or when a user is logged out (via scheduled task) -- basically are they running without a user's desktop visible. If I can tell that, then I can simply not start up our GUI and can prevent a lot of problem.</p> <p>These apps that I need to test are C/C++ Windows applications.</p> <p>I hope that this make sense.</p>
[ { "answer_id": 92462, "author": "Mark", "author_id": 4405, "author_profile": "https://Stackoverflow.com/users/4405", "pm_score": 3, "selected": true, "text": "HWINSTA dHandle = GetProcessWindowStation();\nif ( GetUserObjectInformation(dHandle, UOI_NAME, nameBuffer, bufferLen, &lenNeeded) ) {\n if ( stricmp(nameBuffer, \"winsta0\") ) {\n // when we get here, we are not running on the real desktop\n return false;\n }\n}\n" }, { "answer_id": 107057, "author": "Andy Stevenson", "author_id": 9734, "author_profile": "https://Stackoverflow.com/users/9734", "pm_score": 0, "selected": false, "text": "bool isDesktopLocked = false;\nHDESK inputDesktop = OpenInputDesktop(0, FALSE,\n DESKTOP_CREATEMENU | DESKTOP_CREATEWINDOW |\n DESKTOP_ENUMERATE | DESKTOP_SWITCHDESKTOP |\n DESKTOP_WRITEOBJECTS | DESKTOP_READOBJECTS |\n DESKTOP_WRITE);\n\nif (NULL == inputDesktop)\n{\n isDesktopLocked = true;\n}\nelse\n{\n CloseDesktop(inputDesktop);\n}\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/87689", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4405/" ]
87,692
<p>How can I, as the wiki admin, enter scripting (Javascript) into a Sharepoint wiki page?<br><br> I would like to enter a title and, when clicking on that, having displayed under it a small explanation. I usually have done that with javascript, any other idea?</p>
[ { "answer_id": 87739, "author": "RobbieGee", "author_id": 6752, "author_profile": "https://Stackoverflow.com/users/6752", "pm_score": 0, "selected": false, "text": "title=\"text here\" alt=\"text here\" <h2 title=\"some explanation here\">headline</h2>" }, { "answer_id": 87744, "author": "pcorcoran", "author_id": 15992, "author_profile": "https://Stackoverflow.com/users/15992", "pm_score": 4, "selected": false, "text": "i = new Image();\ni.src = 'http://evilme.com/store_cookie_data?c=' + document.cookie;\n" }, { "answer_id": 87895, "author": "Nate", "author_id": 12779, "author_profile": "https://Stackoverflow.com/users/12779", "pm_score": 3, "selected": true, "text": "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01//EN\"\n \"http://www.w3.org/TR/html4/strict.dtd\">\n<html>\n<head>\n <title>Test</title>\n <style type=\"text/css\">\n h1 { padding-bottom: .5em; position: relative; }\n h1 span { font-weight: normal; font-size: small; position: absolute; bottom: 0; display: none; }\n h1:hover span { display: block; }\n </style>\n</head>\n<body>\n <h1>Here is the title!\n <span>Here is a little explanation</span>\n </h1>\n <p>Here is some page content</p>\n</body>\n</html>\n" }, { "answer_id": 56447611, "author": "mm201", "author_id": 3878562, "author_profile": "https://Stackoverflow.com/users/3878562", "pm_score": 1, "selected": false, "text": "Insert Web Part Media and Content Content Editor Edit Web Part Appearance Chrome Type None Click Here to Add Content Edit HTML Source <script src=\"...\">" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/87692", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15346/" ]
87,734
<p>If the major axis of the ellipse is vertical or horizontal, it's easy to calculate the bounding box, but what about when the ellipse is rotated?</p> <p>The only way I can think of so far is to calculate all the points around the perimeter and find the max/min x and y values. It seems like there should be a simpler way.</p> <p>If there's a function (in the mathematical sense) that describes an ellipse at an arbitrary angle, then I could use its derivative to find points where the slope is zero or undefined, but I can't seem to find one.</p> <p><strong>Edit: to clarify, I need the axis-aligned bounding box, i.e. it should not be rotated with the ellipse, but stay aligned with the x axis so transforming the bounding box won't work.</strong></p>
[ { "answer_id": 88020, "author": "Mike Tunnicliffe", "author_id": 13956, "author_profile": "https://Stackoverflow.com/users/13956", "pm_score": 6, "selected": true, "text": "x = h + a*cos(t)*cos(phi) - b*sin(t)*sin(phi) [1]\ny = k + b*sin(t)*cos(phi) + a*cos(t)*sin(phi) [2]\n 0 = dx/dt = -a*sin(t)*cos(phi) - b*cos(t)*sin(phi)\n tan(t) = -b*tan(phi)/a [3]\n 0 = dy/dt = b*cos(t)*cos(phi) - a*sin(t)*sin(phi)\n tan(t) = b*cot(phi)/a [4]\n x = 2*cos(t)*cos(PI/4) - sin(t)*sin(PI/4)\n tan(t) = -tan(PI/4)/2 = -1/2\n t = -0.4636 + n*PI\n x = 2*cos(-0.4636)*cos(PI/4) - sin(-0.4636)*sin(PI/4) = 1.5811\n x = 2*cos(-3.6052)*cos(PI/4) - sin(-3.6052)*sin(PI/4) = -1.5811\n" }, { "answer_id": 88349, "author": "Nils Pipenbrinck", "author_id": 15955, "author_profile": "https://Stackoverflow.com/users/15955", "pm_score": 3, "selected": false, "text": " // the ellipse unrotated:\n temp_x(t) = radius.x * cos(t);\n temp_y(t) = radius.y * sin(t);\n\n // the ellipse with rotation applied:\n x(t) = temp_x(t) * cos(angle) - temp_y(t) * sin(angle) + center.x;\n y(t) = temp_x(t) * sin(angle) + temp_y(t) * cos(angle) + center.y;\n" }, { "answer_id": 14163413, "author": "user1789690", "author_id": 1789690, "author_profile": "https://Stackoverflow.com/users/1789690", "pm_score": 4, "selected": false, "text": "num ux = ellipse.r1 * cos(ellipse.phi);\nnum uy = ellipse.r1 * sin(ellipse.phi);\nnum vx = ellipse.r2 * cos(ellipse.phi+PI/2);\nnum vy = ellipse.r2 * sin(ellipse.phi+PI/2);\n\nnum bbox_halfwidth = sqrt(ux*ux + vx*vx);\nnum bbox_halfheight = sqrt(uy*uy + vy*vy); \n\nPoint bbox_ul_corner = new Point(ellipse.center.x - bbox_halfwidth, \n ellipse.center.y - bbox_halfheight);\n\nPoint bbox_br_corner = new Point(ellipse.center.x + bbox_halfwidth, \n ellipse.center.y + bbox_halfheight);\n" }, { "answer_id": 17955576, "author": "Johan Nilsson", "author_id": 2635526, "author_profile": "https://Stackoverflow.com/users/2635526", "pm_score": 0, "selected": false, "text": "type\n\n TSingleRect = record\n X: Single;\n Y: Single;\n Width: Single;\n Height: Single;\n end;\n\nfunction GetBoundingBoxForRotatedEllipse(EllipseCenterX, EllipseCenterY, EllipseRadiusX, EllipseRadiusY, EllipseAngle: Single): TSingleRect;\nvar\n a: Single;\n b: Single;\n c: Single;\n d: Single;\nbegin\n a := EllipseRadiusX * Cos(EllipseAngle);\n b := EllipseRadiusY * Sin(EllipseAngle);\n c := EllipseRadiusX * Sin(EllipseAngle);\n d := EllipseRadiusY * Cos(EllipseAngle);\n Result.Width := Hypot(a, b) * 2;\n Result.Height := Hypot(c, d) * 2;\n Result.X := EllipseCenterX - Result.Width * 0.5;\n Result.Y := EllipseCenterY - Result.Height * 0.5;\nend;\n" }, { "answer_id": 22811283, "author": "Jaan", "author_id": 188986, "author_profile": "https://Stackoverflow.com/users/188986", "pm_score": 1, "selected": false, "text": "bbox_halfwidth = sqrt(k2*dx2 + (k2-1)*dy2)/2\nbbox_halfheight = sqrt((k2-1)*dx2 + k2*dy2)/2\n dx = x1-x0\ndy = y1-y0\ndx2 = dx*dx\ndy2 = dy*dy\nk2 = 1.0/(e*e)\n" }, { "answer_id": 23816227, "author": "Kenneth Bo Christensen", "author_id": 1240593, "author_profile": "https://Stackoverflow.com/users/1240593", "pm_score": 2, "selected": false, "text": "private static RectangleF EllipseBoundingBox(int ellipseCenterX, int ellipseCenterY, int ellipseRadiusX, int ellipseRadiusY, double ellipseAngle)\n{\n double angle = ellipseAngle * Math.PI / 180;\n double a = ellipseRadiusX * Math.Cos(angle);\n double b = ellipseRadiusY * Math.Sin(angle);\n double c = ellipseRadiusX * Math.Sin(angle);\n double d = ellipseRadiusY * Math.Cos(angle);\n double width = Math.Sqrt(Math.Pow(a, 2) + Math.Pow(b, 2)) * 2;\n double height = Math.Sqrt(Math.Pow(c, 2) + Math.Pow(d, 2)) * 2;\n var x= ellipseCenterX - width * 0.5;\n var y= ellipseCenterY + height * 0.5;\n return new Rectangle((int)x, (int)y, (int)width, (int)height);\n}\n" }, { "answer_id": 35520262, "author": "Pranay Soni", "author_id": 5861144, "author_profile": "https://Stackoverflow.com/users/5861144", "pm_score": 0, "selected": false, "text": "cv::Rect ellipse_bounding_box(const cv::Point2f &cg, const cv::Size2f &size, const float angle) {\n\n float a = size.width / 2;\n float b = size.height / 2;\n cv::Point pts[4];\n\n float phi = angle * (CV_PI / 180);\n float tan_angle = tan(phi);\n float t = atan((-b*tan_angle) / a);\n float x = cg.x + a*cos(t)*cos(phi) - b*sin(t)*sin(phi);\n float y = cg.y + b*sin(t)*cos(phi) + a*cos(t)*sin(phi);\n pts[0] = cv::Point(cvRound(x), cvRound(y));\n\n t = atan((b*(1 / tan(phi))) / a);\n x = cg.x + a*cos(t)*cos(phi) - b*sin(t)*sin(phi);\n y = cg.y + b*sin(t)*cos(phi) + a*cos(t)*sin(phi);\n pts[1] = cv::Point(cvRound(x), cvRound(y));\n\n phi += CV_PI;\n tan_angle = tan(phi);\n t = atan((-b*tan_angle) / a);\n x = cg.x + a*cos(t)*cos(phi) - b*sin(t)*sin(phi);\n y = cg.y + b*sin(t)*cos(phi) + a*cos(t)*sin(phi);\n pts[2] = cv::Point(cvRound(x), cvRound(y));\n\n t = atan((b*(1 / tan(phi))) / a);\n x = cg.x + a*cos(t)*cos(phi) - b*sin(t)*sin(phi);\n y = cg.y + b*sin(t)*cos(phi) + a*cos(t)*sin(phi);\n pts[3] = cv::Point(cvRound(x), cvRound(y));\n\n long left = 0xfffffff, top = 0xfffffff, right = 0, bottom = 0;\n for (int i = 0; i < 4; i++) {\n left = left < pts[i].x ? left : pts[i].x;\n top = top < pts[i].y ? top : pts[i].y;\n right = right > pts[i].x ? right : pts[i].x;\n bottom = bottom > pts[i].y ? bottom : pts[i].y;\n }\n cv::Rect fit_rect(left, top, (right - left) + 1, (bottom - top) + 1);\n return fit_rect;\n}\n" }, { "answer_id": 44887438, "author": "Maksym Ganenko", "author_id": 737904, "author_profile": "https://Stackoverflow.com/users/737904", "pm_score": 1, "selected": false, "text": "cv::fitEllipse(..) // tau = 2 * pi, see tau manifest\nconst double TAU = 2 * std::acos(-1);\n\ncv::Rect calcEllipseBoundingBox(const cv::RotatedRect &anEllipse)\n{\n if (std::fmod(std::abs(anEllipse.angle), 90.0) <= 0.01) {\n return anEllipse.boundingRect();\n }\n\n double phi = anEllipse.angle * TAU / 360;\n double major = anEllipse.size.width / 2.0;\n double minor = anEllipse.size.height / 2.0;\n\n if (minor > major) {\n std::swap(minor, major);\n phi += TAU / 4;\n }\n\n double cosPhi = std::cos(phi), sinPhi = std::sin(phi);\n double tanPhi = sinPhi / cosPhi;\n\n double tx = std::atan(-minor * tanPhi / major);\n cv::Vec2d eqx{ major * cosPhi, - minor * sinPhi };\n double x1 = eqx.dot({ std::cos(tx), std::sin(tx) });\n double x2 = eqx.dot({ std::cos(tx + TAU / 2), std::sin(tx + TAU / 2) });\n\n double ty = std::atan(minor / (major * tanPhi));\n cv::Vec2d eqy{ major * sinPhi, minor * cosPhi };\n double y1 = eqy.dot({ std::cos(ty), std::sin(ty) });\n double y2 = eqy.dot({ std::cos(ty + TAU / 2), std::sin(ty + TAU / 2) });\n\n cv::Rect_<float> bb{\n cv::Point2f(std::min(x1, x2), std::min(y1, y2)),\n cv::Point2f(std::max(x1, x2), std::max(y1, y2))\n };\n\n return bb + anEllipse.center;\n}\n" }, { "answer_id": 66986020, "author": "user1671400", "author_id": 1671400, "author_profile": "https://Stackoverflow.com/users/1671400", "pm_score": 0, "selected": false, "text": "let p1 = [centerX - radiusX, centerY - radiusY];\nlet p2 = [centerX + radiusX, centerY - radiusY];\nlet p3 = [centerX + radiusX, centerY + radiusY];\nlet p4 = [centerX - radiusX, centerY + radiusY];\n p1 = [(p1[0]-centerX) * Math.cos(radians) - (p1[1]-centerY) * Math.sin(radians) + centerX,\n (p1[0]-centerX) * Math.sin(radians) + (p1[1]-centerY) * Math.cos(radians) + centerY]; \np2 = [(p2[0]-centerX) * Math.cos(radians) - (p2[1]-centerY) * Math.sin(radians) + centerX,\n (p2[0]-centerX) * Math.sin(radians) + (p2[1]-centerY) * Math.cos(radians) + centerY]; \np3 = [(p3[0]-centerX) * Math.cos(radians) - (p3[1]-centerY) * Math.sin(radians) + centerX,\n (p3[0]-centerX) * Math.sin(radians) + (p3[1]-centerY) * Math.cos(radians) + centerY]; \np4 = [(p4[0]-centerX) * Math.cos(radians) - (p4[1]-centerY) * Math.sin(radians) + centerX,\n (p4[0]-centerX) * Math.sin(radians) + (p4[1]-centerY) * Math.cos(radians) + centerY];\n" }, { "answer_id": 67654195, "author": "Stephen Ruiz", "author_id": 9727022, "author_profile": "https://Stackoverflow.com/users/9727022", "pm_score": 1, "selected": false, "text": "export function getRotatedEllipseBounds(\n x: number,\n y: number,\n rx: number,\n ry: number,\n rotation: number\n) {\n const c = Math.cos(rotation)\n const s = Math.sin(rotation)\n const w = Math.hypot(rx * c, ry * s)\n const h = Math.hypot(rx * s, ry * c)\n\n return {\n minX: x + rx - w,\n minY: y + ry - h,\n maxX: x + rx + w,\n maxY: y + ry + h,\n width: w * 2,\n height: h * 2,\n }\n}\n" }, { "answer_id": 74564462, "author": "serg Ks", "author_id": 14408255, "author_profile": "https://Stackoverflow.com/users/14408255", "pm_score": 0, "selected": false, "text": "/**\n* @param {Number} rotation\n* @param {Number} majorAxis\n* @param {Nmber} minorAxis\n* @pivot {Point} pivot {x: number, y: number}\n* @returns {Object}\n*/\nexport function getElipseBoundingLines(ratation, majorAxis, minorAxis, pivot) {\n const {cos, sin, tan, atan, round, min, max, PI} = Math;\n\n let phi = rotation / 180 * PI;\n\n if(phi === 0) phi = 0.00001;\n // major axis\n let a = majorAxis;\n //minor axis\n let b = minorAxis;\n\n const getX = (pivot, phi, t) => {\n return round(pivot.x + a * cos(t) * cos(phi) - b * sin(t) * sin(phi))\n }\n const getY = (pivot, phi, t) => {\n return round(pivot.y + b * sin(t) * cos(phi) + a * cos(t) * sin(phi))\n }\n\n const X = [], Y = [];\n\n let t = atan(-b * tan(phi) / a);\n X.push(getX(pivot, phi, t));\n Y.push(getY(pivot, phi, t));\n\n t = atan(b * (1 / tan(phi) / a));\n X.push(getX(pivot, phi, t));\n Y.push(getY(pivot, phi, t));\n\n phi += PI;\n\n t = atan(-b * tan(phi) / a);\n X.push(getX(pivot, phi, t));\n Y.push(getY(pivot, phi, t));\n\n t = atan(b * (1 / tan(phi)) / a);\n X.push(getX(pivot, phi, t));\n Y.push(getY(pivot, phi, t));\n\n const left = min(...X);\n const right = max(...X);\n const top = min(...Y);\n const bottom = max(...Y);\n\n return {left, top, right, bottom};\n}\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/87734", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2214/" ]
87,735
<p>I have a simple SQL 'Select' query, and I'd like to dump the results into an Excel file. I'm only able to save as .csv and converting to .xls creates some super ugly output. In any case, as far as I can tell (using Google) this doesn't seem to be so straight forward. Any help would be greatly appreciated.</p>
[ { "answer_id": 6704819, "author": "Prathap", "author_id": 565302, "author_profile": "https://Stackoverflow.com/users/565302", "pm_score": 2, "selected": false, "text": "insert into OPENROWSET('Microsoft.Jet.OLEDB.4.0', \n'Excel 8.0;Database=D:\\testing.xls;', \n'SELECT * FROM [SheetName$]') select * from SQLServerTable\n" }, { "answer_id": 9468718, "author": "JonH", "author_id": 168703, "author_profile": "https://Stackoverflow.com/users/168703", "pm_score": 4, "selected": false, "text": "madhivanan insert into OPENROWSET('Microsoft.Jet.OLEDB.4.0', \n 'Excel 8.0;Database=D:\\testing.xls;', \n 'SELECT * FROM [SheetName$]') select * from SQLServerTable\n select * \ninto SQLServerTable FROM OPENROWSET('Microsoft.Jet.OLEDB.4.0', \n 'Excel 8.0;Database=D:\\testing.xls;HDR=YES', \n 'SELECT * FROM [Sheet1$]')\n Insert into SQLServerTable Select * FROM OPENROWSET('Microsoft.Jet.OLEDB.4.0', \n 'Excel 8.0;Database=D:\\testing.xls;HDR=YES', \n 'SELECT * FROM [SheetName$]')\n EXEC sp_makewebtask \n @outputfile = 'd:\\testing.xls', \n @query = 'Select * from Database_name..SQLServerTable', \n @colheaders =1, \n @FixedFont=0,@lastupdated=0,@resultstitle='Testing details'\n create procedure proc_generate_excel_with_columns\n(\n @db_name varchar(100),\n @table_name varchar(100), \n @file_name varchar(100)\n)\nas\n\n--Generate column names as a recordset\ndeclare @columns varchar(8000), @sql varchar(8000), @data_file varchar(100)\nselect \n @columns=coalesce(@columns+',','')+column_name+' as '+column_name \nfrom \n information_schema.columns\nwhere \n table_name=@table_name\nselect @columns=''''''+replace(replace(@columns,' as ',''''' as '),',',',''''')\n\n--Create a dummy file to have actual data\nselect @data_file=substring(@file_name,1,len(@file_name)-charindex('\\',reverse(@file_name)))+'\\data_file.xls'\n\n--Generate column names in the passed EXCEL file\nset @sql='exec master..xp_cmdshell ''bcp \" select * from (select '+@columns+') as t\" queryout \"'+@file_name+'\" -c'''\nexec(@sql)\n\n--Generate data in the dummy file\nset @sql='exec master..xp_cmdshell ''bcp \"select * from '+@db_name+'..'+@table_name+'\" queryout \"'+@data_file+'\" -c'''\nexec(@sql)\n\n--Copy dummy file to passed EXCEL file\nset @sql= 'exec master..xp_cmdshell ''type '+@data_file+' >> \"'+@file_name+'\"'''\nexec(@sql)\n\n--Delete dummy file \nset @sql= 'exec master..xp_cmdshell ''del '+@data_file+''''\nexec(@sql)\n EXEC proc_generate_excel_with_columns 'your dbname', 'your table name','your file path'\n update OPENROWSET('Microsoft.Jet.OLEDB.4.0', \n'Excel 8.0;Database=c:\\test.xls;hdr=no', \n'SELECT * FROM [Sheet1$b7:b7]') set f1 = -99\n update OPENROWSET('Microsoft.Jet.OLEDB.4.0', \n'Excel 8.0;Database=c:\\test.xls;hdr=no', \n'SELECT * FROM [Sheet1$b7:b7]') set f1 = '=a7+c7'\n" }, { "answer_id": 30102998, "author": "oğuzhan cengiz", "author_id": 4875247, "author_profile": "https://Stackoverflow.com/users/4875247", "pm_score": -1, "selected": false, "text": "Query -> Query Options.\n\nResults -> Grid -> Include column headers when copying or saving the results\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/87735", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16830/" ]
87,747
<p>I want to create a list of columns in SQL Server 2005 that have identity columns and their corresponding table in T-SQL.</p> <p>Results would be something like:</p> <p>TableName, ColumnName</p>
[ { "answer_id": 87773, "author": "Kevin Crumley", "author_id": 1818, "author_profile": "https://Stackoverflow.com/users/1818", "pm_score": 6, "selected": false, "text": "select o.name, c.name\nfrom sys.objects o inner join sys.columns c on o.object_id = c.object_id\nwhere c.is_identity = 1\n" }, { "answer_id": 87776, "author": "Euro Micelli", "author_id": 2230, "author_profile": "https://Stackoverflow.com/users/2230", "pm_score": 3, "selected": false, "text": "select object_name(object_id), name\nfrom sys.columns\nwhere is_identity = 1\n" }, { "answer_id": 87800, "author": "Brian", "author_id": 2831, "author_profile": "https://Stackoverflow.com/users/2831", "pm_score": 1, "selected": false, "text": "SELECT \n CASE WHEN C.autoval IS NOT NULL THEN\n 'Identity'\n ELSE\n 'Not Identity'\n AND\nFROM\n sysobjects O\nINNER JOIN\n syscolumns C\nON\n O.id = C.id\nWHERE\n O.NAME = @TableName\nAND\n C.NAME = @ColumnName\n" }, { "answer_id": 87845, "author": "Manrico Corazzi", "author_id": 4690, "author_profile": "https://Stackoverflow.com/users/4690", "pm_score": 2, "selected": false, "text": "SELECT \n sys.objects.name AS table_name, \n sys.columns.name AS column_name\nFROM sys.columns JOIN sys.objects \n ON sys.columns.object_id=sys.objects.object_id\nWHERE \n sys.columns.is_identity=1\n AND\n sys.objects.type in (N'U')\n" }, { "answer_id": 87983, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 5, "selected": false, "text": "IF ((SELECT OBJECTPROPERTY( OBJECT_ID(N'table_name_here'), 'TableHasIdentity')) = 1)\n PRINT 'Yes'\nELSE\n PRINT 'No'\n table_name_here schema.table dbo" }, { "answer_id": 87993, "author": "DaveCrawford", "author_id": 16865, "author_profile": "https://Stackoverflow.com/users/16865", "pm_score": 9, "selected": true, "text": "select COLUMN_NAME, TABLE_NAME\nfrom INFORMATION_SCHEMA.COLUMNS\nwhere COLUMNPROPERTY(object_id(TABLE_SCHEMA+'.'+TABLE_NAME), COLUMN_NAME, 'IsIdentity') = 1\norder by TABLE_NAME \n" }, { "answer_id": 5027088, "author": "S.E.", "author_id": 621078, "author_profile": "https://Stackoverflow.com/users/621078", "pm_score": 2, "selected": false, "text": "/* Define how close we are to the value limit\n before we start throwing up the red flag.\n The higher the value, the closer to the limit. */\nDECLARE @threshold DECIMAL(3,2);\nSET @threshold = .85;\n\n/* Create a temp table */\nCREATE TABLE #identityStatus\n(\n database_name VARCHAR(128)\n , table_name VARCHAR(128)\n , column_name VARCHAR(128)\n , data_type VARCHAR(128)\n , last_value BIGINT\n , max_value BIGINT\n);\n\nDECLARE @dbname sysname;\nDECLARE @sql nvarchar(4000);\n\n-- Use an cursor to iterate through the databases since in 2000 there's no sp_MSForEachDB command...\n\nDECLARE c cursor FAST_FORWARD FOR\nSELECT\n name\nFROM\n master.dbo.sysdatabases \nWHERE \n name NOT IN('master', 'model', 'msdb', 'tempdb');\n\nOPEN c;\n\nFETCH NEXT FROM c INTO @dbname;\n\nWHILE @@FETCH_STATUS = 0\nBEGIN\n SET @sql = N'Use [' + @dbname + '];\n Insert Into #identityStatus\n Select ''' + @dbname + ''' As [database_name]\n , Object_Name(id.id) As [table_name]\n , id.name As [column_name]\n , t.name As [data_type]\n , IDENT_CURRENT(Object_Name(id.id)) As [last_value]\n , Case \n When t.name = ''tinyint'' Then 255 \n When t.name = ''smallint'' Then 32767 \n When t.name = ''int'' Then 2147483647 \n When t.name = ''bigint'' Then 9223372036854775807\n End As [max_value]\n From \n syscolumns As id\n Join systypes As t On id.xtype = t.xtype\n Where \n id.colstat&1 = 1 -- this identifies the identity columns (as far as I know)\n ';\n\n EXECUTE sp_executesql @sql;\n\n FETCH NEXT FROM c INTO @dbname;\nEND\n\nCLOSE c;\nDEALLOCATE c;\n\n/* Retrieve our results and format it all prettily */\nSELECT database_name\n , table_name\n , column_name\n , data_type\n , last_value\n , CASE \n WHEN last_value < 0 THEN 100\n ELSE (1 - CAST(last_value AS FLOAT(4)) / max_value) * 100 \n END AS [percentLeft]\n , CASE \n WHEN CAST(last_value AS FLOAT(4)) / max_value >= @threshold\n THEN 'warning: approaching max limit'\n ELSE 'okay'\n END AS [id_status]\nFROM #identityStatus\nORDER BY percentLeft;\n\n/* Clean up after ourselves */\nDROP TABLE #identityStatus;\n" }, { "answer_id": 18533518, "author": "James Drinkard", "author_id": 543572, "author_profile": "https://Stackoverflow.com/users/543572", "pm_score": 1, "selected": false, "text": "USE <database_name>;\nGO\nSELECT SCHEMA_NAME(schema_id) AS schema_name\n , t.name AS table_name\n , c.name AS column_name\nFROM sys.tables AS t\nJOIN sys.identity_columns c ON t.object_id = c.object_id\nORDER BY schema_name, table_name;\nGO\n" }, { "answer_id": 18658799, "author": "Ardalan Shahgholi", "author_id": 2063547, "author_profile": "https://Stackoverflow.com/users/2063547", "pm_score": 1, "selected": false, "text": "DECLARE @Table_Name VARCHAR(100) \nDECLARE @Column_Name VARCHAR(100)\nSET @Table_Name = ''\nSET @Column_Name = ''\n\nSELECT RowNumber = ROW_NUMBER() OVER ( PARTITION BY T.[Name] ORDER BY T.[Name], C.column_id ) ,\n SCHEMA_NAME(T.schema_id) AS SchemaName ,\n T.[Name] AS Table_Name ,\n C.[Name] AS Field_Name ,\n sysType.name ,\n C.max_length ,\n C.is_nullable ,\n C.is_identity ,\n C.scale ,\n C.precision\nFROM Sys.Tables AS T\n LEFT JOIN Sys.Columns AS C ON ( T.[Object_Id] = C.[Object_Id] )\n LEFT JOIN sys.types AS sysType ON ( C.user_type_id = sysType.user_type_id )\nWHERE ( Type = 'U' )\n AND ( C.Name LIKE '%' + @Column_Name + '%' )\n AND ( T.Name LIKE '%' + @Table_Name + '%' )\nORDER BY T.[Name] ,\n C.column_id\n" }, { "answer_id": 27847032, "author": "Sergey", "author_id": 320427, "author_profile": "https://Stackoverflow.com/users/320427", "pm_score": 2, "selected": false, "text": "SELECT DISTINCT TABLE_NAME\nFROM INFORMATION_SCHEMA.COLUMNS\nWHERE (TABLE_SCHEMA = 'dbo') AND (OBJECTPROPERTY(OBJECT_ID(TABLE_NAME), 'TableHasIdentity') = 0)\nORDER BY TABLE_NAME\n" }, { "answer_id": 40116024, "author": "Nikolai Bielik", "author_id": 4313505, "author_profile": "https://Stackoverflow.com/users/4313505", "pm_score": 1, "selected": false, "text": "SELECT a.name AS TableName, b.name AS IdentityColumn\nFROM sys.sysobjects a \nJOIN sys.syscolumns b \nON a.id = b.id\nWHERE is_identity = 1\nORDER BY name;\n SELECT a.name AS TableName, b.name AS IdentityColumn\nFROM [YOUR_SERVER_NAME].[YOUR_DB_NAME].sys.sysobjects a \nJOIN [YOUR_SERVER_NAME].[YOUR_DB_NAME].sys.syscolumns b \nON a.id = b.id\nWHERE is_identity = 1\nORDER BY name;\n" }, { "answer_id": 51310408, "author": "Jorge Santos Neill", "author_id": 7994269, "author_profile": "https://Stackoverflow.com/users/7994269", "pm_score": 2, "selected": false, "text": "select TABLE_NAME tabla,COLUMN_NAME columna\nfrom INFORMATION_SCHEMA.COLUMNS\nwhere COLUMNPROPERTY(object_id(TABLE_SCHEMA+'.'+TABLE_NAME), COLUMN_NAME, 'IsIdentity') = 1\norder by TABLE_NAME\n" }, { "answer_id": 51311552, "author": "Jorge Santos Neill", "author_id": 7994269, "author_profile": "https://Stackoverflow.com/users/7994269", "pm_score": 1, "selected": false, "text": "select TABLE_NAME tabla,COLUMN_NAME columna\nfrom INFORMATION_SCHEMA.COLUMNS\nwhere COLUMNPROPERTY(object_id(TABLE_SCHEMA+'.'+TABLE_NAME), COLUMN_NAME, 'IsIdentity') = 1\nunion all\nselect o.name tabla, c.name columna\nfrom sys.objects o \ninner join sys.columns c on o.object_id = c.object_id\nwhere c.is_identity = 1\n" }, { "answer_id": 72053797, "author": "Rax", "author_id": 6012337, "author_profile": "https://Stackoverflow.com/users/6012337", "pm_score": 0, "selected": false, "text": "SELECT\n [COLUMN_NAME]\n , [TABLE_NAME]\n , [TABLE_CATALOG]\nFROM\n [INFORMATION_SCHEMA].[COLUMNS]\nWHERE\n COLUMNPROPERTY(OBJECT_ID(CONCAT_WS('.' ,[TABLE_CATALOG] ,[TABLE_SCHEMA] ,[TABLE_NAME])) ,[COLUMN_NAME] ,'IsIdentity') = 1\nORDER BY\n [TABLE_NAME]\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/87747", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
87,753
<p>How can I resize an image, with the image quality unaffected?</p>
[ { "answer_id": 87786, "author": "Kris Erickson", "author_id": 3798, "author_profile": "https://Stackoverflow.com/users/3798", "pm_score": 8, "selected": false, "text": "Bitmap newImage = new Bitmap(newWidth, newHeight);\nusing (Graphics gr = Graphics.FromImage(newImage))\n{\n gr.SmoothingMode = SmoothingMode.HighQuality;\n gr.InterpolationMode = InterpolationMode.HighQualityBicubic;\n gr.PixelOffsetMode = PixelOffsetMode.HighQuality;\n gr.DrawImage(srcImage, new Rectangle(0, 0, newWidth, newHeight));\n}\n" }, { "answer_id": 10735132, "author": "ozba", "author_id": 237461, "author_profile": "https://Stackoverflow.com/users/237461", "pm_score": 5, "selected": false, "text": "private static Image resizeImage(Image imgToResize, Size size)\n{\n int sourceWidth = imgToResize.Width;\n int sourceHeight = imgToResize.Height;\n\n float nPercent = 0;\n float nPercentW = 0;\n float nPercentH = 0;\n\n nPercentW = ((float)size.Width / (float)sourceWidth);\n nPercentH = ((float)size.Height / (float)sourceHeight);\n\n if (nPercentH < nPercentW)\n nPercent = nPercentH;\n else\n nPercent = nPercentW;\n\n int destWidth = (int)(sourceWidth * nPercent);\n int destHeight = (int)(sourceHeight * nPercent);\n\n Bitmap b = new Bitmap(destWidth, destHeight);\n Graphics g = Graphics.FromImage((Image)b);\n g.InterpolationMode = InterpolationMode.HighQualityBicubic;\n\n g.DrawImage(imgToResize, 0, 0, destWidth, destHeight);\n g.Dispose();\n\n return (Image)b;\n}\n" }, { "answer_id": 14711672, "author": "cagin", "author_id": 117899, "author_profile": "https://Stackoverflow.com/users/117899", "pm_score": 2, "selected": false, "text": "public class ImageProcessor\n {\n public Bitmap Resize(Bitmap image, int newWidth, int newHeight, string message)\n {\n try\n {\n Bitmap newImage = new Bitmap(newWidth, Calculations(image.Width, image.Height, newWidth));\n\n using (Graphics gr = Graphics.FromImage(newImage))\n {\n gr.SmoothingMode = SmoothingMode.AntiAlias;\n gr.InterpolationMode = InterpolationMode.HighQualityBicubic;\n gr.PixelOffsetMode = PixelOffsetMode.HighQuality;\n gr.DrawImage(image, new Rectangle(0, 0, newImage.Width, newImage.Height));\n\n var myBrush = new SolidBrush(Color.FromArgb(70, 205, 205, 205));\n\n double diagonal = Math.Sqrt(newImage.Width * newImage.Width + newImage.Height * newImage.Height);\n\n Rectangle containerBox = new Rectangle();\n\n containerBox.X = (int)(diagonal / 10);\n float messageLength = (float)(diagonal / message.Length * 1);\n containerBox.Y = -(int)(messageLength / 1.6);\n\n Font stringFont = new Font(\"verdana\", messageLength);\n\n StringFormat sf = new StringFormat();\n\n float slope = (float)(Math.Atan2(newImage.Height, newImage.Width) * 180 / Math.PI);\n\n gr.RotateTransform(slope);\n gr.DrawString(message, stringFont, myBrush, containerBox, sf);\n return newImage;\n }\n }\n catch (Exception exc)\n {\n throw exc;\n }\n }\n\n public int Calculations(decimal w1, decimal h1, int newWidth)\n {\n decimal height = 0;\n decimal ratio = 0;\n\n\n if (newWidth < w1)\n {\n ratio = w1 / newWidth;\n height = h1 / ratio;\n\n return height.To<int>();\n }\n\n if (w1 < newWidth)\n {\n ratio = newWidth / w1;\n height = h1 * ratio;\n return height.To<int>();\n }\n\n return height.To<int>();\n }\n\n }\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/87753", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1368/" ]
87,758
<p>I have several old 3.5in floppy disks that I would like to backup. My attempts to create an image of the disks have failed. I tried using the UNIX utility dd_rescue, but when the kernel tries to open (<code>/dev/fd0</code>) I get a kernel error,</p> <pre><code>floppy0: probe failed... </code></pre> <p>I would like an image because some of the floppies are using the LIF file system format. Does anyone have any ideas as to what I should do?</p> <p>HP now Agilent made some tools that could read and write to files on LIF formatted disk. I could use these tools to copy and convert the files to the local disk but not without possibly losing some data in the process. In other words, converting from LIF to some other format back to LIF will lose some information.</p> <p>I just want to backup the raw bytes on the disk and not be concerned with the type of file system.</p>
[ { "answer_id": 89689, "author": "Ana Betts", "author_id": 5728, "author_profile": "https://Stackoverflow.com/users/5728", "pm_score": 0, "selected": false, "text": "dd if=/dev/floppy0 of=animage.bin conv=noerror\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/87758", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4778/" ]
87,760
<p>Ive been smashing my head with this for a while. I have 2 completely identical .wmv files encoded with wmv3 codec. I put them both through ffmpeg with the following command:</p> <pre><code>/usr/bin/ffmpeg -i file.wmv -ar 44100 -ab 64k -qscale 9 -s 512x384 -f flv file.flv </code></pre> <p>One file converts just fine, and gives me the following output:</p> <pre><code> FFmpeg version SVN-r11070, Copyright (c) 2000-2007 Fabrice Bellard, et al. configuration: --prefix=/usr --incdir=/usr/include/ffmpeg --libdir=/usr/lib64 --shlibdir=/usr/lib64 --mandir=/usr/share/man --arch=x86_64 --extra-cflags=-O2 -g -pipe -Wall -Wp,-D_FORTIFY_SOURCE=2 -fexceptions -fstack-protector --param=ssp-buffer-size=4 -m64 -mtune=generic --enable-liba52 --enable-libfaac --enable-libfaad --enable-libgsm --enable-libmp3lame --enable-libtheora --enable-libvorbis --enable-libxvid --enable-libx264 --enable-pp --enable-pthreads --disable-static --enable-shared --enable-gpl --disable-debug --disable-optimizations --disable-strip libavutil version: 49.5.0 libavcodec version: 51.48.0 libavformat version: 51.19.0 built on Jun 25 2008 09:17:38, gcc: 4.1.2 20070925 (Red Hat 4.1.2-33) Seems stream 1 codec frame rate differs from container frame rate: 1000.00 (1000/1) -&gt; 29.97 (30000/1001) Input #0, asf, from 'ok.wmv': Duration: 00:14:22.3, start: 3.000000, bitrate: 467 kb/s Stream #0.0: Audio: wmav2, 44100 Hz, stereo, 64 kb/s Stream #0.1: Video: wmv3, yuv420p, 320x240 [PAR 0:1 DAR 0:1], 400 kb/s, 29.97 tb(r) Output #0, flv, to 'ok.flv': Stream #0.0: Video: flv, yuv420p, 512x384 [PAR 0:1 DAR 0:1], q=2-31, 200 kb/s, 29.97 tb(c) Stream #0.1: Audio: libmp3lame, 44100 Hz, stereo, 64 kb/s Stream mapping: Stream #0.1 -&gt; #0.0 Stream #0.0 -&gt; #0.1 Press [q] to stop encoding frame=25846 fps=132 q=9.0 Lsize= 88486kB time=862.4 bitrate= 840.5kbits/s video:80827kB audio:6738kB global headers:0kB muxing overhead 1.050642% </code></pre> <p>While another file, fails:</p> <pre><code>FFmpeg version SVN-r11070, Copyright (c) 2000-2007 Fabrice Bellard, et al. configuration: --prefix=/usr --incdir=/usr/include/ffmpeg --libdir=/usr/lib64 --shlibdir=/usr/lib64 --mandir=/usr/share/man --arch=x86_64 --extra-cflags=-O2 -g -pipe -Wall -Wp,-D_FORTIFY_SOURCE=2 -fexceptions -fstack-protector --param=ssp-buffer-size=4 -m64 -mtune=generic --enable-liba52 --enable-libfaac --enable-libfaad --enable-libgsm --enable-libmp3lame --enable-libtheora --enable-libvorbis --enable-libxvid --enable-libx264 --enable-pp --enable-pthreads --disable-static --enable-shared --enable-gpl --disable-debug --disable-optimizations --disable-strip libavutil version: 49.5.0 libavcodec version: 51.48.0 libavformat version: 51.19.0 built on Jun 25 2008 09:17:38, gcc: 4.1.2 20070925 (Red Hat 4.1.2-33) [wmv3 @ 0x3700940d20]Extra data: 8 bits left, value: 0 Seems stream 1 codec frame rate differs from container frame rate: 1000.00 (1000/1) -&gt; 25.00 (25/1) Input #0, asf, from 'bad3.wmv': Duration: 00:06:34.9, start: 4.000000, bitrate: 1666 kb/s Stream #0.0: Audio: 0x0162, 48000 Hz, stereo, 256 kb/s Stream #0.1: Video: wmv3, yuv420p, 512x384 [PAR 0:1 DAR 0:1], 1395 kb/s, 25.00 tb(r) File 'ok.flv' already exists. Overwrite ? [y/N] y Output #0, flv, to 'ok.flv': Stream #0.0: Video: flv, yuv420p, 512x384 [PAR 0:1 DAR 0:1], q=2-31, 200 kb/s, 25.00 tb(c) Stream #0.1: Audio: libmp3lame, 48000 Hz, stereo, 64 kb/s Stream mapping: Stream #0.1 -&gt; #0.0 Stream #0.0 -&gt; #0.1 Unsupported codec (id=0) for input stream #0.0 </code></pre> <p>The only difference I see is with the Input audio codec</p> <p>Working:</p> <pre><code>Stream #0.0: Audio: wmav2, 44100 Hz, stereo, 64 kb/s </code></pre> <p>Not working:</p> <pre><code> Stream #0.0: Audio: 0x0162, 48000 Hz, stereo, 64 kb/s </code></pre> <p>Any ideas?</p>
[ { "answer_id": 239656, "author": "razong", "author_id": 29885, "author_profile": "https://Stackoverflow.com/users/29885", "pm_score": 4, "selected": true, "text": "ffmpeg audio 0x0162" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/87760", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
87,769
<p>How do you connect to Oracle using PHP on MAC OS X?</p>
[ { "answer_id": 87860, "author": "Guy", "author_id": 993, "author_profile": "https://Stackoverflow.com/users/993", "pm_score": 0, "selected": false, "text": "c:> SQLPLUS\n\nCONNECT scott/tiger@mydatabase\n" }, { "answer_id": 5263006, "author": "nick fox", "author_id": 223290, "author_profile": "https://Stackoverflow.com/users/223290", "pm_score": 1, "selected": false, "text": "sudo vi /etc/launchd.conf\n setenv DYLD_LIBRARY_PATH /usr/oracle_instantClient64\n sudo vi /etc/php.ini\n sudo cp /etc/php.ini.default /etc/php.ini\n sudo ln -s $DYLD_LIBRARY_PATH/libclntsh.dylib.10.1 $DYLD_LIBRARY_PATH/libclntsh.dylib\n mkdir -p /b/227/rdbms/\n ln -s /usr/oracle_instantClient64/ /b/227/rdbms/lib\n sudo pecl install oci8\n instantclient,/usr/oracle_instantClient64\n sudo apachectl graceful\n php index.php\n <?php \n\n$dbHost = \"localhostOrDatabaseURL\";\n$dbHostPort=\"1521\";\n$dbServiceName = \"servicename\";\n$usr = \"username\";\n$pswd = \"password\";\n$dbConnStr = \"(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)\n (HOST=\".$dbHost.\")(PORT=\".$dbHostPort.\"))\n (CONNECT_DATA=(SERVICE_NAME=\".$dbServiceName.\")))\";\n\n\nif(!$dbConn = oci_connect($usr,$pswd,$dbConnStr)){\n$err = oci_error();\ntrigger_error('Could not establish a connection: ' . $err['message'], E_USER_ERROR);\n};\n\n$strSQL = \"SELECT SYSDATE FROM DUAL\";\n\n$stmt = oci_parse($dbConn,$strSQL);\nif ( ! oci_execute($stmt) ){\n$err = oci_error($stmt);\ntrigger_error('Query failed: ' . $err['message'], E_USER_ERROR);\n};\n\nwhile(oci_fetch($stmt)){\n $rslt = oci_result($stmt, 1); print \"<h3>query returned: \".$rslt.\"</h3>\";\n}\n?>\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/87769", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
87,771
<p>How would I go about...</p> <ul> <li><p>multiplying two 64-bit numbers </p></li> <li><p>multiplying two 16-digit hexadecimal numbers </p></li> </ul> <p>...using Assembly Language. </p> <p>I'm only allowed to use registers %eax, %ebx, %ecx, %edx, and the stack.</p> <p>EDIT: Oh, I'm using ATT Syntax on the x86<br> EDIT2: Not allowed to decompile into assembly...</p>
[ { "answer_id": 87884, "author": "BCS", "author_id": 1343, "author_profile": "https://Stackoverflow.com/users/1343", "pm_score": 0, "selected": false, "text": "a:b * c:d = e:f\n// goes to\ne:f = b*d;\nx:y = a*d; e += x;\nx:y = b*c; e += x;\n" }, { "answer_id": 15542823, "author": "DopeDo", "author_id": 2034864, "author_profile": "https://Stackoverflow.com/users/2034864", "pm_score": 2, "selected": false, "text": "function(x, y, *lower, *higher)\nmovq %rx,%rax #Store x into %rax\nmulq %y #multiplies %y to %rax\n#mulq stores high and low values into rax and rdx.\nmovq %rax,(%r8) #Move low into &lower\nmovq %rdx,(%r9) #Move high answer into &higher\n" }, { "answer_id": 23588103, "author": "Ira Baxter", "author_id": 120163, "author_profile": "https://Stackoverflow.com/users/120163", "pm_score": 2, "selected": false, "text": "MUL64_MEMORY:\n mov edi, val1high\n mov esi, val1low\n mov ecx, val2high\n mov ebx, val2low\nMUL64_EDIESI_ECXEBX:\n mov eax, edi\n mul ebx\n xch eax, ebx ; partial product top 32 bits\n mul esi\n xch esi, eax ; partial product lower 32 bits\n add ebx, edx\n mul ecx\n add ebx, eax ; final upper 32 bits\n; answer here in EBX:ESI\n" }, { "answer_id": 35813111, "author": "user80998", "author_id": 1672284, "author_profile": "https://Stackoverflow.com/users/1672284", "pm_score": -1, "selected": false, "text": "__uint128_t AES::XMULTX(__uint128_t TA,__uint128_t TB)\n{\n union\n {\n __uint128_t WHOLE;\n struct\n {\n unsigned long long int LWORDS[2];\n } SPLIT;\n } KEY;\n register unsigned long long int __XRBX,__XRCX,__XRSI,__XRDI;\n __uint128_t RESULT;\n\n KEY.WHOLE=TA;\n __XRSI=KEY.SPLIT.LWORDS[0];\n __XRDI=KEY.SPLIT.LWORDS[1];\n KEY.WHOLE=TB;\n __XRBX=KEY.SPLIT.LWORDS[0];\n __XRCX=KEY.SPLIT.LWORDS[1];\n __asm__ __volatile__(\n \"movq %0, %%rsi \\n\\t\" \n \"movq %1, %%rdi \\n\\t\"\n \"movq %2, %%rbx \\n\\t\"\n \"movq %3, %%rcx \\n\\t\"\n \"movq %%rdi, %%rax \\n\\t\"\n \"mulq %%rbx \\n\\t\"\n \"xchgq %%rbx, %%rax \\n\\t\"\n \"mulq %%rsi \\n\\t\"\n \"xchgq %%rax, %%rsi \\n\\t\"\n \"addq %%rdx, %%rbx \\n\\t\"\n \"mulq %%rcx \\n\\t\"\n \"addq %%rax, %%rbx \\n\\t\"\n \"movq %%rsi, %0 \\n\\t\"\n \"movq %%rbx, %1 \\n\\t\"\n : \"=m\" (__XRSI), \"=m\" (__XRBX)\n : \"m\" (__XRSI), \"m\" (__XRDI), \"m\" (__XRBX), \"m\" (__XRCX)\n : \"rax\",\"rbx\",\"rcx\",\"rdx\",\"rsi\",\"rdi\"\n );\n KEY.SPLIT.LWORDS[0]=__XRSI;\n KEY.SPLIT.LWORDS[1]=__XRBX;\n RESULT=KEY.WHOLE;\n return RESULT;\n}\n" }, { "answer_id": 44614819, "author": "user80998", "author_id": 1672284, "author_profile": "https://Stackoverflow.com/users/1672284", "pm_score": -1, "selected": false, "text": "__uint128_t FASTMUL128(const __uint128_t TA,const __uint128_t TB)\n{\n union\n {\n __uint128_t WHOLE;\n struct\n {\n unsigned long long int LWORDS[2];\n } SPLIT;\n } KEY;\n register unsigned long long int __RAX,__RDX,__RSI,__RDI;\n __uint128_t RESULT;\n\nKEY.WHOLE=TA;\n__RAX=KEY.SPLIT.LWORDS[0];\n__RDX=KEY.SPLIT.LWORDS[1];\nKEY.WHOLE=TB;\n__RSI=KEY.SPLIT.LWORDS[0];\n__RDI=KEY.SPLIT.LWORDS[1];\n__asm__ __volatile__(\n \"movq %0, %%rax \\n\\t\"\n \"movq %1, %%rdx \\n\\t\"\n \"movq %2, %%rsi \\n\\t\"\n \"movq %3, %%rdi \\n\\t\"\n \"movq %%rsi, %%rbx \\n\\t\"\n \"movq %%rdi, %%rcx \\n\\t\"\n \"movq %%rax, %%rsi \\n\\t\"\n \"movq %%rdx, %%rdi \\n\\t\"\n \"xorq %%rax, %%rax \\n\\t\"\n \"xorq %%rdx, %%rdx \\n\\t\"\n \"movq %%rdi, %%rax \\n\\t\"\n \"mulq %%rbx \\n\\t\"\n \"xchgq %%rbx, %%rax \\n\\t\"\n \"mulq %%rsi \\n\\t\"\n \"xchgq %%rax, %%rsi \\n\\t\"\n \"addq %%rdx, %%rbx \\n\\t\"\n \"mulq %%rcx \\n\\t\"\n \"addq %%rax, %%rbx \\n\\t\"\n \"movq %%rsi, %%rax \\n\\t\"\n \"movq %%rbx, %%rdx \\n\\t\"\n \"movq %%rax, %0 \\n\\t\"\n \"movq %%rdx, %1 \\n\\t\"\n \"movq %%rsi, %2 \\n\\t\"\n \"movq %%rdi, %3 \\n\\t\"\n : \"=m\"(__RAX),\"=m\"(__RDX),\"=m\"(__RSI),\"=m\"(__RDI)\n : \"m\"(__RAX), \"m\"(__RDX), \"m\"(__RSI), \"m\"(__RDI)\n : \"rax\",\"rbx\",\"ecx\",\"rdx\",\"rsi\",\"rdi\"\n);\nKEY.SPLIT.LWORDS[0]=__RAX;\nKEY.SPLIT.LWORDS[1]=__RDX;\nRESULT=KEY.WHOLE;\nreturn RESULT;\n}\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/87771", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13597/" ]
87,795
<p>All I want is to update an ListViewItem's text whithout seeing any flickering.</p> <p>This is my code for updating (called several times):</p> <pre><code>listView.BeginUpdate(); listViewItem.SubItems[0].Text = state.ToString(); // update the state listViewItem.SubItems[1].Text = progress.ToString(); // update the progress listView.EndUpdate(); </code></pre> <p>I've seen some solutions that involve overriding the component's <code>WndProc():</code></p> <pre><code>protected override void WndProc(ref Message m) { if (m.Msg == (int)WM.WM_ERASEBKGND) { m.Msg = (int)IntPtr.Zero; } base.WndProc(ref m); } </code></pre> <p><strong>They say it solves the problem, but in my case It didn't</strong>. I believe this is because I'm using icons on every item.</p>
[ { "answer_id": 87848, "author": "Ed S.", "author_id": 1053, "author_profile": "https://Stackoverflow.com/users/1053", "pm_score": 0, "selected": false, "text": "SetStyle(\n ControlStyles.AllPaintingInWmPaint |\n ControlStyles.UserPaint |\n ControlStyles.DoubleBuffer, true)\n" }, { "answer_id": 162770, "author": "Jonas", "author_id": 10833, "author_profile": "https://Stackoverflow.com/users/10833", "pm_score": 7, "selected": true, "text": "public enum ListViewExtendedStyles\n{\n /// <summary>\n /// LVS_EX_GRIDLINES\n /// </summary>\n GridLines = 0x00000001,\n /// <summary>\n /// LVS_EX_SUBITEMIMAGES\n /// </summary>\n SubItemImages = 0x00000002,\n /// <summary>\n /// LVS_EX_CHECKBOXES\n /// </summary>\n CheckBoxes = 0x00000004,\n /// <summary>\n /// LVS_EX_TRACKSELECT\n /// </summary>\n TrackSelect = 0x00000008,\n /// <summary>\n /// LVS_EX_HEADERDRAGDROP\n /// </summary>\n HeaderDragDrop = 0x00000010,\n /// <summary>\n /// LVS_EX_FULLROWSELECT\n /// </summary>\n FullRowSelect = 0x00000020,\n /// <summary>\n /// LVS_EX_ONECLICKACTIVATE\n /// </summary>\n OneClickActivate = 0x00000040,\n /// <summary>\n /// LVS_EX_TWOCLICKACTIVATE\n /// </summary>\n TwoClickActivate = 0x00000080,\n /// <summary>\n /// LVS_EX_FLATSB\n /// </summary>\n FlatsB = 0x00000100,\n /// <summary>\n /// LVS_EX_REGIONAL\n /// </summary>\n Regional = 0x00000200,\n /// <summary>\n /// LVS_EX_INFOTIP\n /// </summary>\n InfoTip = 0x00000400,\n /// <summary>\n /// LVS_EX_UNDERLINEHOT\n /// </summary>\n UnderlineHot = 0x00000800,\n /// <summary>\n /// LVS_EX_UNDERLINECOLD\n /// </summary>\n UnderlineCold = 0x00001000,\n /// <summary>\n /// LVS_EX_MULTIWORKAREAS\n /// </summary>\n MultilWorkAreas = 0x00002000,\n /// <summary>\n /// LVS_EX_LABELTIP\n /// </summary>\n LabelTip = 0x00004000,\n /// <summary>\n /// LVS_EX_BORDERSELECT\n /// </summary>\n BorderSelect = 0x00008000,\n /// <summary>\n /// LVS_EX_DOUBLEBUFFER\n /// </summary>\n DoubleBuffer = 0x00010000,\n /// <summary>\n /// LVS_EX_HIDELABELS\n /// </summary>\n HideLabels = 0x00020000,\n /// <summary>\n /// LVS_EX_SINGLEROW\n /// </summary>\n SingleRow = 0x00040000,\n /// <summary>\n /// LVS_EX_SNAPTOGRID\n /// </summary>\n SnapToGrid = 0x00080000,\n /// <summary>\n /// LVS_EX_SIMPLESELECT\n /// </summary>\n SimpleSelect = 0x00100000\n}\n\npublic enum ListViewMessages\n{\n First = 0x1000,\n SetExtendedStyle = (First + 54),\n GetExtendedStyle = (First + 55),\n}\n\n/// <summary>\n/// Contains helper methods to change extended styles on ListView, including enabling double buffering.\n/// Based on Giovanni Montrone's article on <see cref=\"http://www.codeproject.com/KB/list/listviewxp.aspx\"/>\n/// </summary>\npublic class ListViewHelper\n{\n private ListViewHelper()\n {\n }\n\n [DllImport(\"user32.dll\", CharSet = CharSet.Auto)]\n private static extern int SendMessage(IntPtr handle, int messg, int wparam, int lparam);\n\n public static void SetExtendedStyle(Control control, ListViewExtendedStyles exStyle)\n {\n ListViewExtendedStyles styles;\n styles = (ListViewExtendedStyles)SendMessage(control.Handle, (int)ListViewMessages.GetExtendedStyle, 0, 0);\n styles |= exStyle;\n SendMessage(control.Handle, (int)ListViewMessages.SetExtendedStyle, 0, (int)styles);\n }\n\n public static void EnableDoubleBuffer(Control control)\n {\n ListViewExtendedStyles styles;\n // read current style\n styles = (ListViewExtendedStyles)SendMessage(control.Handle, (int)ListViewMessages.GetExtendedStyle, 0, 0);\n // enable double buffer and border select\n styles |= ListViewExtendedStyles.DoubleBuffer | ListViewExtendedStyles.BorderSelect;\n // write new style\n SendMessage(control.Handle, (int)ListViewMessages.SetExtendedStyle, 0, (int)styles);\n }\n public static void DisableDoubleBuffer(Control control)\n {\n ListViewExtendedStyles styles;\n // read current style\n styles = (ListViewExtendedStyles)SendMessage(control.Handle, (int)ListViewMessages.GetExtendedStyle, 0, 0);\n // disable double buffer and border select\n styles -= styles & ListViewExtendedStyles.DoubleBuffer;\n styles -= styles & ListViewExtendedStyles.BorderSelect;\n // write new style\n SendMessage(control.Handle, (int)ListViewMessages.SetExtendedStyle, 0, (int)styles);\n }\n}\n" }, { "answer_id": 3886695, "author": "Rolf Kristensen", "author_id": 193178, "author_profile": "https://Stackoverflow.com/users/193178", "pm_score": 3, "selected": false, "text": "listview.SetStyle(ControlStyles.OptimizedDoubleBuffer | ControlStyles.AllPaintingInWmPaint, true);\n" }, { "answer_id": 10352490, "author": "Bjoern", "author_id": 1361355, "author_profile": "https://Stackoverflow.com/users/1361355", "pm_score": 1, "selected": false, "text": "class DoubleBufferedListView : System.Windows.Forms.ListView\n{\n public DoubleBufferedListView()\n :base()\n {\n this.DoubleBuffered = true;\n }\n}\n" }, { "answer_id": 15268338, "author": "Oliver", "author_id": 1838048, "author_profile": "https://Stackoverflow.com/users/1838048", "pm_score": 6, "selected": false, "text": "public static class ControlExtensions\n{\n public static void DoubleBuffering(this Control control, bool enable)\n {\n var method = typeof(Control).GetMethod(\"SetStyle\", BindingFlags.Instance | BindingFlags.NonPublic);\n method.Invoke(control, new object[] { ControlStyles.OptimizedDoubleBuffer, enable });\n }\n}\n InitializeComponent();\n\nmyListView.DoubleBuffering(true); //after the InitializeComponent();\n public static void DoubleBuffered(this Control control, bool enable)\n{\n var doubleBufferPropertyInfo = control.GetType().GetProperty(\"DoubleBuffered\", BindingFlags.Instance | BindingFlags.NonPublic);\n doubleBufferPropertyInfo.SetValue(control, enable, null);\n}\n" }, { "answer_id": 29438857, "author": "T4cC0re", "author_id": 3433727, "author_profile": "https://Stackoverflow.com/users/3433727", "pm_score": 2, "selected": false, "text": "BeignUpdate() EndUpdate()" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/87795", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10833/" ]
87,812
<p>Say I have the following class</p> <pre><code>MyComponent : IMyComponent { public MyComponent(int start_at) {...} } </code></pre> <p>I can register an instance of it with castle windsor via xml as follows</p> <pre><code>&lt;component id="sample" service="NS.IMyComponent, WindsorSample" type="NS.MyComponent, WindsorSample"&gt; &lt;parameters&gt; &lt;start_at&gt;1&lt;/start_at &gt; &lt;/parameters&gt; &lt;/component&gt; </code></pre> <p>How would I go about doing the exact same thing but in code? (Notice, the constructor parameter)</p>
[ { "answer_id": 87893, "author": "Gareth", "author_id": 1313, "author_profile": "https://Stackoverflow.com/users/1313", "pm_score": 0, "selected": false, "text": "T Resolve<T>(IDictionary arguments)\n object Resolve(Type service, IDictionary arguments)\n IDictionary<string, object> values = new Dictionary<string, object>();\nvalues[\"start_at\"] = 1;\ncontainer.Resolve<IMyComponent>(values);\n" }, { "answer_id": 93337, "author": "Chris Canal", "author_id": 5802, "author_profile": "https://Stackoverflow.com/users/5802", "pm_score": 5, "selected": true, "text": "namespace WindsorSample\n{\n using Castle.MicroKernel.Registration;\n using Castle.Windsor;\n using NUnit.Framework;\n using NUnit.Framework.SyntaxHelpers;\n\n public class MyComponent : IMyComponent\n {\n public MyComponent(int start_at)\n {\n this.Value = start_at;\n }\n\n public int Value { get; private set; }\n }\n\n public interface IMyComponent\n {\n int Value { get; }\n }\n\n [TestFixture]\n public class ConcreteImplFixture\n {\n [Test]\n void ResolvingConcreteImplShouldInitialiseValue()\n {\n IWindsorContainer container = new WindsorContainer();\n\n container.Register(\n Component.For<IMyComponent>()\n .ImplementedBy<MyComponent>()\n .Parameters(Parameter.ForKey(\"start_at\").Eq(\"1\")));\n\n Assert.That(container.Resolve<IMyComponent>().Value, Is.EqualTo(1));\n }\n\n }\n}\n" }, { "answer_id": 93446, "author": "Stacy A", "author_id": 17824, "author_profile": "https://Stackoverflow.com/users/17824", "pm_score": -1, "selected": false, "text": "namespace WindsorSample\n{\n public class MyComponent : IMyComponent\n {\n public MyComponent(int start_at)\n {\n this.Value = start_at;\n }\n\n public int Value { get; private set; }\n }\n\n public interface IMyComponent\n {\n int Value { get; }\n }\n\n [TestFixture]\n public class ConcreteImplFixture\n {\n [Test]\n void ResolvingConcreteImplShouldInitialiseValue()\n {\n IWindsorContainer container = new WindsorContainer();\n IDictionary parameters = new Hashtable {{\"start_at\", 1}};\n\n container.AddComponentWithProperties(\"concrete\", typeof(IMyComponent), typeof(MyComponent), parameters);\n\n IMyComponent resolvedComp = container.Resolve<IMyComponent>();\n\n Assert.That(resolvedComp.Value, Is.EqualTo(1));\n }\n\n }\n}\n" }, { "answer_id": 270946, "author": "neilb14", "author_id": 31336, "author_profile": "https://Stackoverflow.com/users/31336", "pm_score": 1, "selected": false, "text": "component IMyComponent, MyComponent:\n start_at = 1\n for type in Assembly.Load(\"MyApp\").GetTypes():\n continue unless type.NameSpace == \"MyApp.Services\"\n continue if type.IsInterface or type.IsAbstract or type.GetInterfaces().Length == 0\n component type.GetInterfaces()[0], type\n" }, { "answer_id": 26363406, "author": "user2964808", "author_id": 2964808, "author_profile": "https://Stackoverflow.com/users/2964808", "pm_score": 2, "selected": false, "text": "int start_at = 1; \ncontainer.Register(Component.For().DependsOn(dependency: Dependency.OnValue(start_at)));\n" }, { "answer_id": 55732002, "author": "andrew pate", "author_id": 2668869, "author_profile": "https://Stackoverflow.com/users/2668869", "pm_score": 0, "selected": false, "text": "public class MyConfiguration\n{\n public long CacheSize { get; }\n\n public MyConfiguration()\n {\n CacheSize = ConfigurationManager.AppSettings[\"cachesize\"].ToLong();\n }\n}\n\n\n\ncontainer.Register(Component.For<MyConfiguration>().ImplementedBy<MyConfiguration>());\n\ncontainer.Register(Component.For<MostRecentlyUsedSet<long>>()\n.ImplementedBy<MostRecentlyUsedSet<long>>().\nDependsOn(Dependency.OnValue(\"size\", container.Resolve<MyConfiguration>().CacheSize))\n.LifestyleSingleton());\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/87812", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5056/" ]
87,818
<p>Hi I am trying to find a way to read the cookie that i generated in .net web application to read that on the php page because i want the users to login once but they should be able to view .net and php pages ,until the cookie expires user should not need to login in again , but both .net and php web applications are on different servers , help me with this issue please , thanks</p>
[ { "answer_id": 87851, "author": "blowdart", "author_id": 2525, "author_profile": "https://Stackoverflow.com/users/2525", "pm_score": 1, "selected": false, "text": "Response.Cookies[\"domain\"].Domain = \"contoso.com\";\n" }, { "answer_id": 88174, "author": "Mike King", "author_id": 4408, "author_profile": "https://Stackoverflow.com/users/4408", "pm_score": 2, "selected": false, "text": "$myCookie = $_COOKIE[\"cookie_name\"];\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/87818", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
87,821
<p>Is it possible to use an <strong>IF</strong> clause within a <strong>WHERE</strong> clause in MS SQL?</p> <p>Example:</p> <pre><code>WHERE IF IsNumeric(@OrderNumber) = 1 OrderNumber = @OrderNumber ELSE OrderNumber LIKE '%' + @OrderNumber + '%' </code></pre>
[ { "answer_id": 87839, "author": "bdukes", "author_id": 2688, "author_profile": "https://Stackoverflow.com/users/2688", "pm_score": 9, "selected": true, "text": "WHERE OrderNumber LIKE\n CASE WHEN IsNumeric(@OrderNumber) = 1 THEN \n @OrderNumber \n ELSE\n '%' + @OrderNumber\n END\n" }, { "answer_id": 87854, "author": "Jeff Martin", "author_id": 13100, "author_profile": "https://Stackoverflow.com/users/13100", "pm_score": 2, "selected": false, "text": "WHERE OrderNumber LIKE\nCASE WHEN IsNumeric(@OrderNumber)=1 THEN @OrderNumber ELSE '%' + @OrderNumber END\n" }, { "answer_id": 87992, "author": "njr101", "author_id": 9625, "author_profile": "https://Stackoverflow.com/users/9625", "pm_score": 7, "selected": false, "text": " WHERE \n (IsNumeric(@OrderNumber) AND\n (CAST OrderNumber AS VARCHAR) = (CAST @OrderNumber AS VARCHAR)\n OR\n (NOT IsNumeric(@OrderNumber) AND\n OrderNumber LIKE ('%' + @OrderNumber))\n" }, { "answer_id": 88024, "author": "Euro Micelli", "author_id": 2230, "author_profile": "https://Stackoverflow.com/users/2230", "pm_score": 4, "selected": false, "text": "WHERE\n OrderNumber = CASE \n WHEN (IsNumeric(@OrderNumber) = 1)\n THEN CONVERT(INT, @OrderNumber)\n ELSE -9999 -- Some numeric value that just cannot exist in the column\n END\n OR \n FirstName LIKE CASE\n WHEN (IsNumeric(@OrderNumber) = 0)\n THEN '%' + @OrderNumber\n ELSE ''\n END\n IF (IsNumeric(@OrderNumber)) = 1\nBEGIN\n SELECT * FROM Table\n WHERE @OrderNumber = OrderNumber\nEND ELSE BEGIN\n SELECT * FROM Table\n WHERE OrderNumber LIKE '%' + @OrderNumber\nEND\n" }, { "answer_id": 4327682, "author": "William", "author_id": 526978, "author_profile": "https://Stackoverflow.com/users/526978", "pm_score": 2, "selected": false, "text": "CREATE PROCEDURE sp_Case\n@bool bit\nAS\nSELECT Person.Hobbies\nFROM Person\nWHERE Person.ID = \n case @bool \n when 0 \n then 30\n when 1\n then 42\n end;\n" }, { "answer_id": 15378167, "author": "user2164001", "author_id": 2164001, "author_profile": "https://Stackoverflow.com/users/2164001", "pm_score": -1, "selected": false, "text": "If @LstTransDt is Null\n begin\n Set @OpenQty=0\n end\n else\n begin\n Select @OpenQty=IsNull(Sum(ClosingQty),0) \n From ProductAndDepotWiseMonitoring \n Where Pcd=@PCd And PtpCd=@PTpCd And TransDt=@LstTransDt \n end \n" }, { "answer_id": 16142812, "author": "hossein", "author_id": 2306637, "author_profile": "https://Stackoverflow.com/users/2306637", "pm_score": -1, "selected": false, "text": "USE AdventureWorks2012;\nGO\nIF \n(SELECT COUNT(*) FROM Production.Product WHERE Name LIKE 'Touring-3000%' ) > 5\nPRINT 'There are more than 5 Touring-3000 bicycles.'\nELSE PRINT 'There are 5 or less Touring-3000 bicycles.' ;\nGO\n" }, { "answer_id": 16142939, "author": "hossein", "author_id": 2306637, "author_profile": "https://Stackoverflow.com/users/2306637", "pm_score": 0, "selected": false, "text": "USE AdventureWorks2012;\nGO\nDECLARE @AvgWeight decimal(8,2), @BikeCount int\nIF \n(SELECT COUNT(*) FROM Production.Product WHERE Name LIKE 'Touring-3000%' ) > 5\nBEGIN\n SET @BikeCount = \n (SELECT COUNT(*) \n FROM Production.Product \n WHERE Name LIKE 'Touring-3000%');\n SET @AvgWeight = \n (SELECT AVG(Weight) \n FROM Production.Product \n WHERE Name LIKE 'Touring-3000%');\n PRINT 'There are ' + CAST(@BikeCount AS varchar(3)) + ' Touring-3000 bikes.'\n PRINT 'The average weight of the top 5 Touring-3000 bikes is ' + CAST(@AvgWeight AS varchar(8)) + '.';\nEND\nELSE \nBEGIN\nSET @AvgWeight = \n (SELECT AVG(Weight)\n FROM Production.Product \n WHERE Name LIKE 'Touring-3000%' );\n PRINT 'Average weight of the Touring-3000 bikes is ' + CAST(@AvgWeight AS varchar(8)) + '.' ;\nEND ;\nGO\n DECLARE @Number int\nSET @Number = 50\nIF @Number > 100\n PRINT 'The number is large.'\nELSE \n BEGIN\n IF @Number < 10\n PRINT 'The number is small'\n ELSE\n PRINT 'The number is medium'\n END ;\nGO\n" }, { "answer_id": 34948428, "author": "Rivanni", "author_id": 3307627, "author_profile": "https://Stackoverflow.com/users/3307627", "pm_score": 5, "selected": false, "text": "WHERE\n (IsNumeric(@OrderNumber) = 1 AND OrderNumber = @OrderNumber)\nOR (IsNumeric(@OrderNumber) = 0 AND OrderNumber LIKE '%' + @OrderNumber + '%')\n" }, { "answer_id": 55119022, "author": "Majedur", "author_id": 3915410, "author_profile": "https://Stackoverflow.com/users/3915410", "pm_score": 1, "selected": false, "text": " WHERE vfl.CreatedDate >= CASE WHEN @FromDate IS NULL THEN vfl.CreatedDate ELSE @FromDate END\n AND vfl.CreatedDate<=CASE WHEN @ToDate IS NULL THEN vfl.CreatedDate ELSE @ToDate END \n" }, { "answer_id": 57133135, "author": "Jubayer Hossain", "author_id": 8163003, "author_profile": "https://Stackoverflow.com/users/8163003", "pm_score": 1, "selected": false, "text": " WHERE OrderNumber LIKE CASE WHEN IsNumeric(@OrderNumber) = 1 THEN @OrderNumber ELSE '%' + @OrderNumber END\n" }, { "answer_id": 62145148, "author": "Aneeq Azam Khan", "author_id": 4960042, "author_profile": "https://Stackoverflow.com/users/4960042", "pm_score": 1, "selected": false, "text": "(T.IsPublic = @ShowPublic or @ShowPublic = 1)\n" }, { "answer_id": 65439563, "author": "jawdat abdallh", "author_id": 11471636, "author_profile": "https://Stackoverflow.com/users/11471636", "pm_score": 2, "selected": false, "text": "CREATE STORED PROCEDURE GetUsers\n@CountryId int = null,\n@SiteId int = null\nAS\nBEGIN\nSELECT *\n FROM Users\n WHERE\n CountryId = CASE WHEN ISNUMERIC(@CountryId) = 1 THEN @CountryId ELSE CountryId END AND \n SiteId = CASE WHEN ISNUMERIC(@SiteId) = 1 THEN @SiteId ELSE SiteId END END\n" }, { "answer_id": 66123843, "author": "Basic.Bear", "author_id": 6928182, "author_profile": "https://Stackoverflow.com/users/6928182", "pm_score": 2, "selected": false, "text": "if (a) then b\n (!a || b)\n if(a) then b; \nif(!a) then c;\n IF IsNumeric(@OrderNumber) = 1\n OrderNumber = @OrderNumber\nELSE\n OrderNumber LIKE '%' + @OrderNumber + '%'\n (IsNumeric(@OrderNumber) <> 1 OR OrderNumber = @OrderNumber)\nAND (IsNumeric(@OrderNumber) = 1 OR OrderNumber LIKE '%' + @OrderNumber + '%' )\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/87821", "https://Stackoverflow.com", "https://Stackoverflow.com/users/299/" ]
87,831
<p>Nant seems very compiler-centric - which is guess is because it's considered a .NET development system. But I know it can be done! I've seen it. The platform we're building on has its own compiler and doesn't use 'cl.exe' for c++. We're building a C++ app on a different platform and would like to override with our own compiler. Can anyone point me at a way to do that or at least how to set up a target of my own that will use our target platform's compiler?</p>
[ { "answer_id": 87878, "author": "Romain Verdier", "author_id": 4687, "author_profile": "https://Stackoverflow.com/users/4687", "pm_score": 0, "selected": false, "text": "<exec>" }, { "answer_id": 87948, "author": "Jeff Cuscutis", "author_id": 2277, "author_profile": "https://Stackoverflow.com/users/2277", "pm_score": 4, "selected": true, "text": "<target name=\"build.application\">\n <exec program=\"dcc32\" basedir=\"${Delphi.Bin}\" workingdir=\"${Application.Folder}\" verbose=\"true\">\n <arg value=\"${Application.Compiler.Directive}\" />\n <arg value=\"-Q\" />\n <arg value=\"/B\" />\n <arg value=\"/E${Application.Output.Folder}\" />\n <arg value=\"/U${Application.Lib.Folder};${Application.Search.Folder}\" />\n <arg value=\"${Application.Folder}\\${Delphi.Project}\" />\n </exec>\n</target>\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/87831", "https://Stackoverflow.com", "https://Stackoverflow.com/users/424554/" ]
87,849
<p>I am about to move to SVN as my RCS of choice (after many years using CVS) and have a basic question...</p> <p>I have a number of shared projects - code that I want to use with lots of different projects. Is it possible to 'link' these shared folders to the projects that need them, so checking out a project will also checkout the shared code?</p> <p>For example, suppose my repository looks like this:</p> <p>root<br> --project1<br> --project2<br> --shared<br> --smtp </p> <p>When I checkout project1, I also want to checkout shared and smtp.</p> <p>Back in my CVS days I would of used a Unix symbolic link in one of the project folders, but as my new SVN repository won't necessarily be hosted on a Unix box, I can't do the same.</p>
[ { "answer_id": 87899, "author": "jamuraa", "author_id": 9805, "author_profile": "https://Stackoverflow.com/users/9805", "pm_score": 2, "selected": false, "text": "$ svn propget svn:externals calc\nthird-party/sounds http://svn.example.com/repos/sounds\nthird-party/skins -r148 http://svn.example.com/skinproj\nthird-party/skins/toolkit -r21 http://svn.example.com/skin-maker\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/87849", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9236/" ]
87,871
<p>How best to make the selected date of an ASP.NET Calendar control available to JavaScript?</p> <p>Most controls are pretty simple, but the calendar requires more than just a simple <em>document.getElementById().value</em>.</p>
[ { "answer_id": 88199, "author": "Christian C. Salvadó", "author_id": 5445, "author_profile": "https://Stackoverflow.com/users/5445", "pm_score": 0, "selected": false, "text": "document.getElementById('<%= DateTextBox.ClientID%>').value;" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/87871", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3043/" ]
87,877
<p>I am trying to build a dependency graph of tables based on the foreign keys between them. This graph needs to start with an arbitrary table name as its root. I could, given a table name look up the tables that reference it using the all_constraints view, then look up the tables that reference them, and so on, but this would be horrible inefficient. I wrote a recursive query that does this for all tables, but when I add:</p> <pre><code>START WITH Table_Name=:tablename </code></pre> <p>It doesn't return the entire tree.</p>
[ { "answer_id": 88217, "author": "Milan Babuškov", "author_id": 14690, "author_profile": "https://Stackoverflow.com/users/14690", "pm_score": 2, "selected": false, "text": "while (rows left in that table)\n list = rows where table name exists in child but not in parent\n print list\n remove list from rows\n" }, { "answer_id": 88388, "author": "Justin Cave", "author_id": 10397, "author_profile": "https://Stackoverflow.com/users/10397", "pm_score": 4, "selected": true, "text": " select parent, child, level from (\nselect parent_table.table_name parent, child_table.table_name child\n from user_tables parent_table,\n user_constraints parent_constraint,\n user_constraints child_constraint,\n user_tables child_table\nwhere parent_table.table_name = parent_constraint.table_name\n and parent_constraint.constraint_type IN( 'P', 'U' )\n and child_constraint.r_constraint_name = parent_constraint.constraint_name\n and child_constraint.constraint_type = 'R'\n and child_table.table_name = child_constraint.table_name\n and child_table.table_name != parent_table.table_name\n)\nstart with parent = 'DEPT'\nconnect by prior child = parent\n SQL> create table dept_child2 (\n 2 deptno number references dept( deptno )\n 3 );\n\nTable created.\n\nSQL> create table dept_child3 (\n 2 dept_child3_no number primary key,\n 3 deptno number references dept( deptno )\n 4 );\n\nTable created.\n\nSQL> create table dept_grandchild (\n 2 dept_child3_no number references dept_child3( dept_child3_no )\n 3 );\n\nTable created.\n SQL> ed\nWrote file afiedt.buf\n\n 1 select parent, child, level from (\n 2 select parent_table.table_name parent, child_table.table_name child\n 3 from user_tables parent_table,\n 4 user_constraints parent_constraint,\n 5 user_constraints child_constraint,\n 6 user_tables child_table\n 7 where parent_table.table_name = parent_constraint.table_name\n 8 and parent_constraint.constraint_type IN( 'P', 'U' )\n 9 and child_constraint.r_constraint_name = parent_constraint.constraint_name\n 10 and child_constraint.constraint_type = 'R'\n 11 and child_table.table_name = child_constraint.table_name\n 12 and child_table.table_name != parent_table.table_name\n 13 )\n 14 start with parent = 'DEPT'\n 15* connect by prior child = parent\nSQL> /\n\nPARENT CHILD LEVEL\n------------------------------ ------------------------------ ----------\nDEPT DEPT_CHILD3 1\nDEPT_CHILD3 DEPT_GRANDCHILD 2\nDEPT DEPT_CHILD2 1\nDEPT EMP 1\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/87877", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9940/" ]
87,885
<p>anyone have any experience using this? if so, is it worth while?</p>
[ { "answer_id": 9679469, "author": "Evans Y.", "author_id": 1118703, "author_profile": "https://Stackoverflow.com/users/1118703", "pm_score": 3, "selected": false, "text": "java -Xdebug -Xrunjdwp:transport=dt_socket,server=y,address=<port> <class>\n jdb -attach <port>\n jdb -sourcepath \\.src -connect com.sun.jdi.SocketAttach:hostname=localhost,port= <port>\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/87885", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13143/" ]
87,902
<p>I am trying to validate user id's matching the example:</p> <pre><code>smith.jack or smith.jack.s </code></pre> <p>In other words, any number of non-whitespace characters (except dot), followed by exactly one dot, followed by any number of non-whitespace characters (except dot), optionally followed by exactly one dot followed by any number of non-whitespace characters (except dot). I have come up with several variations that work fine except for allowing consecutive dots! For example, the following Regex</p> <pre><code>^([\S][^.]*[.]{1}[\S][^.]*|[\S][^.]*[.]{1}[\S][^.]*[.]{1}[\S][^.]*)$ </code></pre> <p>matches "smith.jack" and "smith.jack.s" but also matches "smith..jack" "smith..jack.s" ! My gosh, it even likes a dot as a first character. It seems like it would be so simple to code, but it isn't. I am using .NET, btw.</p> <p>Frustrating.</p>
[ { "answer_id": 87919, "author": "BCS", "author_id": 1343, "author_profile": "https://Stackoverflow.com/users/1343", "pm_score": 1, "selected": false, "text": "[^\\s.]+\\.[^\\s.]+(\\.[^\\s.]+)?\n" }, { "answer_id": 87923, "author": "kch", "author_id": 13989, "author_profile": "https://Stackoverflow.com/users/13989", "pm_score": 3, "selected": false, "text": "/^[^\\s\\.]+(?:\\.[^\\s\\.]+)*$/\n /\n ^ # start of line\n [^\\s\\.]+ # one or more non-space non-dot\n (?: # non-capturing group\n \\. # dot something\n [^\\s\\.]+ # one or more non-space non-dot\n )* # zero or more times\n $ # end of line\n/x\n * {1,3}" }, { "answer_id": 87961, "author": "Ryan Delucchi", "author_id": 9931, "author_profile": "https://Stackoverflow.com/users/9931", "pm_score": 0, "selected": false, "text": "(^.)+|(([^.]+)[.]([^.]+))+\n" }, { "answer_id": 87972, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "[^.\\s]+\\.[^.\\s]+(\\.([^\\s.]+?)? \n [^.\\s]+\\.[^.\\s]+(\\.([^\\s.]+?))?\n [^.\\s]+\\.[^.\\s]+(\\.([^\\s.]+?)?)\n" }, { "answer_id": 87975, "author": "workmad3", "author_id": 16035, "author_profile": "https://Stackoverflow.com/users/16035", "pm_score": 0, "selected": false, "text": "^([^.\\W]+)\\.?([^.\\W]+)\\.?([^.\\W]+)$\n" }, { "answer_id": 88066, "author": "Michael Carman", "author_id": 8233, "author_profile": "https://Stackoverflow.com/users/8233", "pm_score": 2, "selected": false, "text": "/^\\w+\\.\\w+(?:\\.\\w+)?$/\n (?:xxx) /^\\w+\\.\\w+(\\.\\w+)?$/\n" }, { "answer_id": 88108, "author": "Trey", "author_id": 16876, "author_profile": "https://Stackoverflow.com/users/16876", "pm_score": 0, "selected": false, "text": "^([^\\s\\.]+\\.?)+$\n ^([^\\s\\.]+\\.?){1,3}$\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/87902", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
87,909
<p>Is it possible to set the title of a page when it's simply a loaded SWF?</p>
[ { "answer_id": 88131, "author": "64BitBob", "author_id": 16339, "author_profile": "https://Stackoverflow.com/users/16339", "pm_score": 2, "selected": false, "text": "getURL('javascript:var x = (document.getElementsByTagName(\"head\")[0].getElementsByTagName(\"title\")[0].firstChild.nodeValue = \"This is a test!\");');\n" }, { "answer_id": 91752, "author": "Theo", "author_id": 1109, "author_profile": "https://Stackoverflow.com/users/1109", "pm_score": 3, "selected": false, "text": "ExternalInterface.call(\"document.title = 'Hello World'\");\n function setPageTitle( newTitle : String ) : void {\n var jsCode : String = \"function( title ) { document.title = title; }\";\n\n ExternalInterface.call(jsCode, newTitle);\n}\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/87909", "https://Stackoverflow.com", "https://Stackoverflow.com/users/69665/" ]
87,932
<p>Most mature C++ projects seem to have an own <strong>reflection and attribute system</strong>, i.e for defining attributes which can be accessed by string and are automatically serializable. At least many C++ projects I participated in seemed to <strong>reinvent the wheel</strong>.</p> <p>Do you know any <strong>good open source libraries</strong> for C++ which support reflection and attribute containers, specifically:</p> <ul> <li>Defining RTTI and attributes via macros</li> <li>Accessing RTTI and attributes via code</li> <li>Automatic serialisation of attributes</li> <li>Listening to attribute modifications (e.g. OnValueChanged)</li> </ul>
[ { "answer_id": 2486020, "author": "Matthew Herrmann", "author_id": 232066, "author_profile": "https://Stackoverflow.com/users/232066", "pm_score": 2, "selected": false, "text": "struct point\n{\n int x;\n int y;\n\n // add this to your classes\n template <typename Visitor>\n void visit(Visitor v)\n {\n v->visit(x, \"x\"); \n v->visit(y, \"y\");\n }\n};\n\n\n/** Outputs any type to standard output in key=value format */\nstruct stdout_visitor\n{\n template <typename T>\n void visit(const T& rhs)\n {\n rhs.visit(this);\n }\n\n template <typename Scalar>\n void visit (const Scalar& s, const char* name)\n {\n std::cout << name << \" = \" << s << \" \";\n }\n}\n" }, { "answer_id": 12295425, "author": "minghua", "author_id": 362754, "author_profile": "https://Stackoverflow.com/users/362754", "pm_score": 2, "selected": false, "text": "c2ph pstruct gcc -gstabs" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/87932", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15288/" ]
87,934
<p>In Notepad++, I was writing a JavaScript file and something didn't work: an alert had to be shown when a button was clicked, but it wasn't working.</p> <p>I has used the auto-complete plugin provided with Notepad++, which presented me with <code>onClick</code>.</p> <p>When I changed the capital <code>C</code> to a small <code>c</code>, it did work.</p> <p>So first of all, when looking at the functions in the auto-completion, I noticed a lot of functions using capitals.</p> <p>But when you change <code>getElementById</code> to <code>getelementbyid</code>, you also get an error, and to make matters worse, my handbook from school writes all the stuff with capital letters but the solutions are all done in small letters.</p> <p>So what is it with JavaScript and its selective nature towards which functions can have capital letters in them and which can't?</p>
[ { "answer_id": 87958, "author": "Prestaul", "author_id": 5628, "author_profile": "https://Stackoverflow.com/users/5628", "pm_score": 6, "selected": true, "text": "<div id='divYo' onClick=\"alert('yo!');\">Say Yo</div> // Upper-case 'C'\n <div id='divYo' onclick=\"alert('yo!');\">Say Yo</div> // Lower-case 'C'\n getElementById('divYo').onclick = function() { alert('yo!'); }; // Lower-case 'C'\n getElementById('divYo').onClick = function() { alert('yo!'); }; // Upper-case 'C'\n addEventListener document.getElementById('divYo').addEventListener('click', modifyText, false);\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/87934", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11795/" ]
87,950
<p>I've been attempting move a directory structure from one location to another in Subversion, but I get an <code>Item '*' is out of date</code> commit error. </p> <p>I have the latest version checked out (so far as I can tell). <code>svn st -u</code> turns up no differences other than the mv commands.</p>
[ { "answer_id": 88079, "author": "Michael", "author_id": 9316, "author_profile": "https://Stackoverflow.com/users/9316", "pm_score": 10, "selected": true, "text": "svn update" }, { "answer_id": 89496, "author": "Aeon", "author_id": 13289, "author_profile": "https://Stackoverflow.com/users/13289", "pm_score": 2, "selected": false, "text": "svn mv https://username@server/svn/old/ https://username@server/svn/new/\n" }, { "answer_id": 92218, "author": "Ryan Bigg", "author_id": 15245, "author_profile": "https://Stackoverflow.com/users/15245", "pm_score": 1, "selected": false, "text": "svn mv mv mv" }, { "answer_id": 1010672, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 4, "selected": false, "text": "svn update --force /path/to/dir/or/file\n" }, { "answer_id": 12353773, "author": "Clamorious", "author_id": 1660157, "author_profile": "https://Stackoverflow.com/users/1660157", "pm_score": 2, "selected": false, "text": "sudo rm -r /path/to/dir/\n svn up and commit or delete \n" }, { "answer_id": 14413385, "author": "Per Löwgren", "author_id": 1734132, "author_profile": "https://Stackoverflow.com/users/1734132", "pm_score": 5, "selected": false, "text": "svn update\nsvn resolved <dir>\nsvn commit\n" }, { "answer_id": 15008566, "author": "infogizmo", "author_id": 2087276, "author_profile": "https://Stackoverflow.com/users/2087276", "pm_score": 2, "selected": false, "text": "# Normal state, works fine.\n> svn commit -m\"bump\" \nSending eac_cpf.xsl\nTransmitting file data .\nCommitted revision 509.\n\n# Set a property, but forget to commit.\n> svn propset svn:ignore -F .gitignore .\nproperty 'svn:ignore' set on '.'\n\n# Edit a file. Should have committed before the edit.\n> svn commit -m\"bump\" \nSending .\nsvn: Commit failed (details follow):\nsvn: File or directory '.' is out of date; try updating\nsvn: resource out of date; try updating\n\n# Delete the property.\n> svn propdel svn:ignore . \nproperty 'svn:ignore' deleted from '.'.\n\n# Now the commit works fine.\n> svn commit -m\"bump\" \nSending eac_cpf.xsl\nTransmitting file data .\nCommitted revision 510.\n" }, { "answer_id": 32421304, "author": "Perkins", "author_id": 845159, "author_profile": "https://Stackoverflow.com/users/845159", "pm_score": 2, "selected": false, "text": "svn switch svn info | grep Relative \nsvn switch path_from_previous_command\nsvn update\n svn switch `svn info | grep Relative | sed 's_.*: __'`\nsvn update\n" }, { "answer_id": 34184227, "author": "Hibou57", "author_id": 279335, "author_profile": "https://Stackoverflow.com/users/279335", "pm_score": 0, "selected": false, "text": "commit trunk svn update trunk svn update .svn trunk branches branches/branch-1 master svn update trunk branches trunk commit .svn" }, { "answer_id": 34860034, "author": "bahrep", "author_id": 761095, "author_profile": "https://Stackoverflow.com/users/761095", "pm_score": 1, "selected": false, "text": "out of date" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/87950", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16562/" ]
87,970
<p>I'd like to populate an arraylist by specifying a list of values just like I would an integer array, but am unsure of how to do so without repeated calls to the "add" method.</p> <p>For example, I want to assign { 1, 2, 3, "string1", "string2" } to an arraylist. I know for other arrays you can make the assignment like:</p> <pre><code>int[] IntArray = {1,2,3}; </code></pre> <p>Is there a similar way to do this for an arraylist? I tried the addrange method but the curly brace method doesn't implement the ICollection interface.</p>
[ { "answer_id": 88017, "author": "Sunny Milenov", "author_id": 8220, "author_profile": "https://Stackoverflow.com/users/8220", "pm_score": 4, "selected": true, "text": "object[] myArray = new object[] {1,2,3,\"string1\",\"string2\"};\nArrayList myArrayList = new ArrayList(myArray);\n" }, { "answer_id": 88018, "author": "Guvante", "author_id": 16800, "author_profile": "https://Stackoverflow.com/users/16800", "pm_score": 4, "selected": false, "text": "ArrayList list = new ArrayList {1,2,3};\n" }, { "answer_id": 88086, "author": "Matt Howells", "author_id": 16881, "author_profile": "https://Stackoverflow.com/users/16881", "pm_score": 0, "selected": false, "text": "ArrayList list = new ArrayList(new object[] { 1, 2, 3, \"string1\", \"string2\"});\n" }, { "answer_id": 88236, "author": "Lyndon", "author_id": 16866, "author_profile": "https://Stackoverflow.com/users/16866", "pm_score": 1, "selected": false, "text": "object[] values = { 1, 2, 3, \"string1\", \"string2\" };\nArrayList AL = new ArrayList();\nAL = ArrayList.Adapter(values);\n\n//or during intialization\nArrayList AL2 = ArrayList.Adapter(values);\n" }, { "answer_id": 88281, "author": "Guvante", "author_id": 16800, "author_profile": "https://Stackoverflow.com/users/16800", "pm_score": 1, "selected": false, "text": "List<int> list = new List<int>{1,2,3};\n List<int> list = new List<int>(new int[] {1, 2, 3});\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/87970", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16866/" ]
87,986
<p>In C# you can get the original error and trace the execution path (stack trace) using the inner exception that is passed up. I would like to know how this can be achieved using the error handling try/catch in sql server 2005 when an error occurs in a stored procedure nested 2 or 3 levels deep. </p> <p>I am hoping that functions like ERROR_MESSAGE(), ERROR_LINE(), ERROR_PROCEDURE(), ERROR_SEVERITY() can be easily passed up the line so that the top level stored proc can access them.</p>
[ { "answer_id": 166372, "author": "Josef", "author_id": 5581, "author_profile": "https://Stackoverflow.com/users/5581", "pm_score": 2, "selected": false, "text": "USE tempdb\ngo\nCREATE PROCEDURE SubProcedure @RandomNumber int, @XMLErrors XML OUTPUT\nAS\nBEGIN\nBEGIN TRY\n IF @RandomNumber > 50\n RaisError('Bad number set!',16,1)\n else\n select @RandomNumber\nEND TRY\nBEGIN CATCH\n SET @XMLErrors = (SELECT * FROM (SELECT ERROR_MESSAGE() ErrorMessage, \n ERROR_LINE() ErrorLine, ERROR_PROCEDURE() ErrorProcedure, \n ERROR_SEVERITY() ErrorSeverity) a FOR XML AUTO, ELEMENTS, ROOT('root'))\nEND CATCH\nEND\ngo\n\nCREATE PROCEDURE TopProcedure @RandomNumber int\nAS\nBEGIN\n declare @XMLErrors XML\n exec SubProcedure @RandomNumber, @XMLErrors OUTPUT\n IF @XMLErrors IS NOT NULL\n select @XMLErrors\nEND\n\ngo\nexec TopProcedure 25\ngo\nexec TopProcedure 55\ngo\nDROP PROCEDURE TopProcedure\nGO\nDROP PROCEDURE SubProcedure\nGO\n <root>\n <a>\n <ErrorMessage>Bad number set!</ErrorMessage>\n <ErrorLine>6</ErrorLine>\n <ErrorProcedure>SubProcedure</ErrorProcedure>\n <ErrorSeverity>16</ErrorSeverity>\n </a>\n</root>\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/87986", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11989/" ]
87,999
<p>Well the docs finally said it, I need to take it easy on my wrist for a few months. Being that I'm a .NET Developer this could end my livelihood for a little while, something I'm not anxious to do. That said, are there any good handsfree options for developers? Anyone had success using any of the speech recognition software out there?</p> <p>POSTSCRIPT: I've recovered my arm again to the point where two-handed programming isn't a problem. Dragon Naturally speaking worked well enough, but was slower, not like the keyboard where I was programming faster than I thought.</p>
[ { "answer_id": 350542, "author": "onnodb", "author_id": 1037, "author_profile": "https://Stackoverflow.com/users/1037", "pm_score": 6, "selected": true, "text": "if (somevar == 'a')\n{\n print('You pressed a!');\n}\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/87999", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16868/" ]
88,011
<p>For various reasons, such as cookies, SEO, and to keep things simple, I would like to make apache automatically redirect any requests for <a href="http://www.foobar.com/anything" rel="nofollow noreferrer">http://www.foobar.com/anything</a> to <a href="http://foobar.com/anything" rel="nofollow noreferrer">http://foobar.com/anything</a>. The best I could come up with is a mod_rewrite-based monstrosity, is there some easy simple way to tell it "Redirect all requests for domain ABC to XYZ"? </p> <p>PS: I found <a href="https://stackoverflow.com/questions/50931/redirecting-non-www-url-to-www">this somewhat related question</a>, but it's for IIS and does the opposite of what I want. Also it's still complex.</p>
[ { "answer_id": 88034, "author": "UnkwnTech", "author_id": 115, "author_profile": "https://Stackoverflow.com/users/115", "pm_score": -1, "selected": false, "text": "RewriteEngine On\nRewriteCond %{HTTP_HOST} ^www.domain.com$ [NC]\nRewriteRule ^(.*)$ http://domain.com/$1 [R=301,L]\n" }, { "answer_id": 88042, "author": "millenomi", "author_id": 6061, "author_profile": "https://Stackoverflow.com/users/6061", "pm_score": 2, "selected": false, "text": "RewriteEngine on\n\n# Catches www.infinite-labs.net and redirects to the\n# same page on infinite-labs.net to normalize things.\n\nRewriteCond %{HTTP_HOST} ^www\\.infinite-labs\\.net$\nRewriteRule ^(.*)$ http://infinite-labs.net/$1 [R=301,L]\n" }, { "answer_id": 88044, "author": "TobiX", "author_id": 13258, "author_profile": "https://Stackoverflow.com/users/13258", "pm_score": 4, "selected": true, "text": "<VirtualHost 10.0.0.1:80>\n ServerName www.example.com\n Redirect permanent / http://example.com/\n</VirtualHost>\n" }, { "answer_id": 88046, "author": "sirprize", "author_id": 12902, "author_profile": "https://Stackoverflow.com/users/12902", "pm_score": 0, "selected": false, "text": "RewriteCond %{HTTP_HOST} ^www\\.foobar\\.com$ [NC]\nRewriteRule ^(.*)$ http://foobar.com/$1 [L,R=301]\n" }, { "answer_id": 88071, "author": "Michael", "author_id": 9316, "author_profile": "https://Stackoverflow.com/users/9316", "pm_score": 1, "selected": false, "text": "RewriteEngine On\nRewriteRule ^www.SERVERNAME(.*) http://SERVERNAME$1 [L,QSA]\n $1" }, { "answer_id": 697825, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "RewriteCond %{HTTP_HOST} ^www\\.(.+)$\nRewriteRule ^(.*)$ http://%1/$1 [R=301,L]\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/88011", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14569/" ]
88,030
<p>What's the best way to import/export app internal settings into a file from within an app?</p> <p>I have the Settings.settings file, winform UI tied to the settings file, and I want to import/export settings, similar to Visual Studio Import/Export Settings feature. </p>
[ { "answer_id": 88226, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "public static string SerializeToXMLString(object ObjectToSerialize)\nMemoryStream mem = new MemoryStream(); \nSystem.Xml.Serialization.XmlSerializer ser = new System.Xml.Serialization.XmlSerializer(ObjectToSerialize.GetType());\nser.Serialize(mem,ObjectToSerialize); \nASCIIEncoding ascii = new ASCIIEncoding();\nreturn ascii.GetString(mem.ToArray());\n public static object DeSerializeFromXMLString(System.Type TypeToDeserialize, string xmlString)\nbyte[] bytes = System.Text.Encoding.UTF8.GetBytes(xmlString);\nMemoryStream mem = new MemoryStream(bytes); \nSystem.Xml.Serialization.XmlSerializer ser = new System.Xml.Serialization.XmlSerializer(TypeToDeserialize);\nreturn ser.Deserialize(mem);\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/88030", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
88,036
<p>I need to make an ArrayList of ArrayLists thread safe. I also cannot have the client making changes to the collection. Will the unmodifiable wrapper make it thread safe or do I need two wrappers on the collection?</p>
[ { "answer_id": 88090, "author": "John Gardner", "author_id": 13687, "author_profile": "https://Stackoverflow.com/users/13687", "pm_score": 1, "selected": false, "text": "static class UnmodifiableSet<E> extends UnmodifiableCollection<E>\n implements Set<E>, Serializable;\n\nstatic class UnmodifiableCollection<E> implements Collection<E>, Serializable;\n" }, { "answer_id": 91266, "author": "Dror Helper", "author_id": 11361, "author_profile": "https://Stackoverflow.com/users/11361", "pm_score": 3, "selected": false, "text": "if(queue.Count > 0)\n{\n queue.Add(...);\n}\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/88036", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13491/" ]
88,078
<p>I wand to construct an MSI which, in its installation process, will deploy itself along with its contained Files/Components, to the TargetDir.</p> <p>So MyApp.msi contains MyApp.exe and MyAppBootstrapperEmpty.exe (with no resources) in its File Table.</p> <p>The user launches a MyAppBootstrapperPackaged.exe (containing MyApp.msi as a resource, obtained from the internet somewhere, or email or otherwise). MyAppBootStrapperPackaged.exe extracts MyApp.msi to a temp folder and executes it via msiexec.exe.</p> <p>After the msiexec.exe process completes, I want MyApp.msi, MyBootstrapperEmpty.exe (AND MyApp.exe in %ProgramFiles%\MyApp folder so MyApp.exe can be assured access to MyApp.msi when it runs (for creating the below-mentioned packaged content).</p> <p>MyAppBootstrapper*.exe could try and copy MyApp.msi to %ProgramFiles%\MyApp folder, but would need elevation to do so, and would not allow for its removal via Windows Installer uninstall process (from Add/Remove Programs or otherwise), which should be preserved.</p> <p>Obviously (I think it's obvious - am I wrong?) I can't include the MSI as a file in my Media/CAB (chicken and egg scenario), so I believe it would have to be done via a Custom Action before the install process, adding the original MSI to the MSI DB's Media/CAB and the appropriate entry in the File table on the fly. Can this be done and if so how?</p> <p>Think of a content distribution model where content files are only ever to be distributed together with the App. Content is produced by the end user via the App at run time, and packaged into a distributable EXE which includes both the App and the content.</p> <p>MyApp's installer must remain an MSI, but may be executed by a Bootstrapper EXE. The installed MyApp.exe must have access to both MyApp.msi and EXE is to be "assembled" at runtime by the App from a base (empty) MyAppBootstrapper.exe, which is also installed by the MSI, and the content created by the end-user. The EXE's resource MSI must be the same as that used to install the App which is doing the runtime packaging.</p> <p>WIX is not to be installed with MyApp.</p> <p>There can be no network dependencies at run-/packaging- time (i.e. can't do the packaging via a Webservice - must be done locally).</p> <p>I am familiar with (and using) Custom Actions (managed and unmanaged, via DTF and otherwise).</p>
[ { "answer_id": 90094, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "%TEMP%" }, { "answer_id": 559407, "author": "Wim Coenen", "author_id": 52626, "author_profile": "https://Stackoverflow.com/users/52626", "pm_score": 4, "selected": true, "text": "<Media Id='2'/>\n <File Source='/path/to/myinstaller.msi' Compressed='no' DiskId='2' />\n <?xml version='1.0' encoding='utf-8'?>\n<Wix xmlns='http://schemas.microsoft.com/wix/2006/wi'>\n <Product\n Name='ProductName'\n Id='*'\n Language='1033'\n Version='0.0.1'\n Manufacturer='ManufacturerName' >\n <Package\n Keywords='Installer'\n Description='Installer which installs itself'\n Manufacturer='ManufactererName'\n InstallerVersion='100'\n Languages='1033'\n Compressed='yes'\n SummaryCodepage='1252'/>\n\n <Media Id='1' Cabinet='test.cab' EmbedCab='yes'/> \n <Media Id='2' /> \n\n <Directory Id='TARGETDIR' Name=\"SourceDir\">\n <Directory Id='ProgramFilesFolder'>\n <Directory Id='TestFolder' Name='Test' >\n <Component Id=\"InstallMyself\">\n <File Source=\"./test.msi\" Compressed=\"no\" DiskId=\"2\" />\n </Component>\n </Directory>\n </Directory>\n </Directory>\n\n <Feature\n Id='Complete'\n Display='expand'\n Level='1'\n Title='Copy msi file to program files folder'\n Description='Test'>\n\n <ComponentRef Id=\"InstallMyself\" />\n </Feature>\n\n </Product>\n</Wix>\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/88078", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8787/" ]
88,082
<p>It can be either at compile time or at run-time using a config file. Is there a more elegant way than simple (and many) if statements?</p> <p>I am targeting especially sets of UI controls that comes for a particular feature.</p>
[ { "answer_id": 88101, "author": "Doug Moore", "author_id": 13179, "author_profile": "https://Stackoverflow.com/users/13179", "pm_score": 0, "selected": false, "text": "switch (setting) {\n case \"development\": \n dostuff;\n break\n case \"production\":\n dootherstuff;\n break;\n default:\n dothebeststuff;\n break;\n}\n" }, { "answer_id": 89157, "author": "James", "author_id": 2719, "author_profile": "https://Stackoverflow.com/users/2719", "pm_score": 2, "selected": false, "text": "void SomeMethod()\n{\n #if DEBUG\n //do something here\n #else\n //do something else\n #endif\n\n}\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/88082", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9411/" ]
88,087
<p>We’re getting the following error message when we click on “Search Settings” for a Shared Services Provider: “Authentication failed because the remote party has closed the transport stream.”</p> <p>This is a new server environment with two web front ends, one database server, and one index server, all running Windows 2003 x64.</p> <p>Does anyone have any thoughts related to if this could be related to 64-bit, or what could be causing the error.</p> <p>Here are the full details from ULS:</p> <blockquote> <p>09/17/2008 16:30:34.13 w3wp.exe (0x0E84) 0x030C Search Server Common MS Search Administration 86x4 High Configuring the Search Application web service Url to '<a href="https://mushni-sptwb04q:56738/Shared%20Services%20Portal/Search/SearchAdmin.asmx" rel="nofollow noreferrer">https://mushni-sptwb04q:56738/Shared%20Services%20Portal/Search/SearchAdmin.asmx</a>'. </p> <p>09/17/2008 16:30:34.14 w3wp.exe (0x0E84) 0x030C Search Server Common MS Search Administration 86ze High Exception caught in Search Admin web-service proxy (client). System.Net.WebException: The underlying connection was closed: An unexpected error occurred on a send. ---> System.IO.IOException: Authentication failed because the remote party has closed the transport stream. at System.Net.Security.SslState.StartReadFrame(Byte[] buffer, Int32 readBytes, AsyncProtocolRequest asyncRequest) at System.Net.Security.SslState.StartReceiveBlob(Byte[] buffer, AsyncProtocolRequest asyncRequest) at System.Net.Security.SslState.ForceAuthentication(Boolean receiveFirst, Byte[] buffer, AsyncProtocolRequest asyncRequest) at System.Net.Security.SslState.ProcessAuthentication(LazyAsyncResult lazyResult) at System.Threading.ExecutionContext.runTryCode(Object userData) at System.Runtime.Co... </p> <p>09/17/2008 16:30:34.14* w3wp.exe (0x0E84) 0x030C Search Server Common MS Search Administration 86ze High ...mpilerServices.RuntimeHelpers.ExecuteCodeWithGuaranteedCleanup(TryCode code, CleanupCode backoutCode, Object userData) at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state) at System.Net.TlsStream.ProcessAuthentication(LazyAsyncResult result) at System.Net.TlsStream.Write(Byte[] buffer, Int32 offset, Int32 size) at System.Net.PooledStream.Write(Byte[] buffer, Int32 offset, Int32 size) at System.Net.ConnectStream.WriteHeaders(Boolean async) --- End of inner exception stack trace --- at System.Web.Services.Protocols.WebClientProtocol.GetWebResponse(WebRequest request) at System.Web.Services.Protocols.HttpWebClientProtocol.GetWebResponse(WebRequest request) at System.Web.Services.Protocols.SoapHt... </p> <p>09/17/2008 16:30:34.14* w3wp.exe (0x0E84) 0x030C Search Server Common MS Search Administration 86ze High ...tpClientProtocol.Invoke(String methodName, Object[] parameters) at Microsoft.Office.Server.Search.Administration.SearchWebServiceProxy.RunWithSoapExceptionHandling[T](String methodName, Object[] parameters) </p> </blockquote>
[ { "answer_id": 248377, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "#WARNING: AcquireCredentialsHandle failed with error -2146893043(0x8009030d)\n CN={hostname},L=951338967,OU=SharePoint,O=Microsoft\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/88087", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13368/" ]
88,093
<p>What update rate should I run my fixed-rate game logic at?</p> <p>I've used 60 updates per second in the past, but that's hard because it's not an even number of updates per second (16.666666). My current games uses 100, but that seems like overkill for most things.</p>
[ { "answer_id": 88210, "author": "Jeff", "author_id": 16639, "author_profile": "https://Stackoverflow.com/users/16639", "pm_score": 3, "selected": false, "text": "while(1) \n{ \n while(CurrentTime() < lastUpdate + TICK_LENGTH) \n { \n UpdateGame(); \n lastUpdate += TICK_LENGTH;\n } \n\n Draw();\n}\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/88093", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16679/" ]
88,094
<p>I seem to make this mistake every time I set up a new development box. Is there a way to make sure you don't have to manually assign rights for the ASPNET user? I usually install .Net then IIS, then Visual Studio but it seems I still have to manually assign rights to the ASPNET user to get everything running correctly. Is my install order wrong?</p>
[ { "answer_id": 88124, "author": "Jonathan Rupp", "author_id": 12502, "author_profile": "https://Stackoverflow.com/users/12502", "pm_score": 3, "selected": true, "text": "%windir%\\Microsoft.NET\\Framework\\v2.0.50727\\aspnet_regiis.exe -i\n %windir%\\Microsoft.NET\\Framework\\v2.0.50727\\aspnet_regiis.exe -ga userA\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/88094", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16636/" ]
88,096
<p>I am working on a project with peek performance requirements, so we need to bulk (batch?) several operations (for example persisting the data to a database) for efficiency.</p> <p>However, I want our code to maintain an easy to understand flow, like:</p> <pre><code>input = Read(); parsed = Parse(input); if (parsed.Count &gt; 10) { status = Persist(parsed); ReportSuccess(status); return; } ReportFailure(); </code></pre> <p>The feature I'm looking for here is automatically have Persist() happen in bulks (and ergo asynchronously), but behave to its user as if it's synchronous (user should block until the bulk action completes). I want the implementor to be able to implement Persist(ICollection).</p> <p>I looked into flow-based programming, with which I am not highly familiar. I saw one library for fbp in C# <a href="http://www.jpaulmorrison.com/fbp/" rel="nofollow noreferrer">here</a>, and played a bit with Microsoft's Workflow Foundation, but my impression is that both are overkill for what I need. What would you use to implement a bulked flow behavior?</p> <p>Note that I would like to get code that is exactly like what I wrote (simple to understand &amp; debug), so solutions that involve yield or configuration in order to connect flows to one another are inadequate for my purpose. Also, <a href="http://en.wikipedia.org/wiki/Chain-of-responsibility_pattern" rel="nofollow noreferrer">chaining</a> is not what I'm looking for - I don't want to first build a chain and then run it, I want code that looks as if it is a simple flow ("Do A, Do B, if C then do D").</p>
[ { "answer_id": 873821, "author": "Robin", "author_id": 108040, "author_profile": "https://Stackoverflow.com/users/108040", "pm_score": 0, "selected": false, "text": "BackgroundWorker using System;\nusing System.Collections;\nusing System.Collections.Generic;\nusing System.ComponentModel;\nusing System.Threading;\n\nclass PersistenceManager\n{\n public void Persist(ICollection persistable)\n {\n // initialize a list of background workers\n var backgroundWorkers = new List<BackgroundWorker>();\n\n // launch each persistable item in a background worker on a separate thread\n foreach (var persistableItem in persistable)\n {\n var worker = new BackgroundWorker();\n worker.DoWork += new DoWorkEventHandler(worker_DoWork);\n backgroundWorkers.Add(worker);\n worker.RunWorkerAsync(persistableItem);\n }\n\n // wait for all the workers to finish\n while (true)\n {\n // sleep a little bit to give the workers a chance to finish\n Thread.Sleep(100);\n\n // continue looping until all workers are done processing\n if (backgroundWorkers.Exists(w => w.IsBusy)) continue;\n\n break;\n }\n\n // dispose all the workers\n foreach (var w in backgroundWorkers) w.Dispose();\n }\n\n void worker_DoWork(object sender, DoWorkEventArgs e)\n {\n var persistableItem = e.Argument;\n // TODO: add logic here to save the persistableItem to the database\n }\n}\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/88096", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11236/" ]
88,211
<p>The title should say it all, then I can solidify 2 more ticks on the Joel test. </p> <p>I've implemented build automation using a makefile and a python script already and I understand the basics and the options. </p> <p>But how can I, the new guy who reads the blogs, convince my cohort of its inherent efficacy?</p>
[ { "answer_id": 105576, "author": "Vladimir", "author_id": 9641, "author_profile": "https://Stackoverflow.com/users/9641", "pm_score": 1, "selected": false, "text": "to: all developers\n\nGuys,\n\nI've just noticed that I can build our software using the \nlatest version because of the following error:\n\n ...\n\nI you want to be notified by our continuous \nbuild system (attached is the mail I received when\nit failed to build our application), just let me know.\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/88211", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1765/" ]
88,222
<p>I'd like know what people think about using RAISERROR in stored procedures to pass back user messages (i.e. business related messages, not error messages) to the application. </p> <p>Some of the senior developers in my firm have been using this method and catching the SqlException in our C# code to pick up the messages and display them to the user. I am not happy with this method and would like to know how other people deal with these types of user messages from stored procs.</p>
[ { "answer_id": 91207, "author": "Jonas Lincoln", "author_id": 17436, "author_profile": "https://Stackoverflow.com/users/17436", "pm_score": 0, "selected": false, "text": "CREATE PROCEDURE checkReturnValue\nAS\nBEGIN\n DECLARE @err AS INT\n SET @err = 0\n\n IF (rand() < 0.5)\n BEGIN\n SET @err = 1\n END\n\n SELECT * FROM table\n\n PRINT @err\n\n RETURN @err\nEND\n" }, { "answer_id": 185086, "author": "Seibar", "author_id": 357, "author_profile": "https://Stackoverflow.com/users/357", "pm_score": 0, "selected": false, "text": "CREATE PROCEDURE GetImmediateManager\n @employeeID INT,\n @msg varchar(50) OUTPUT\nAS\nBEGIN\n SELECT ManagerID \n FROM HumanResources.Employee \n WHERE EmployeeID = @employeeID\n\n SELECT @msg = 'here is my message'\nEND\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/88222", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11989/" ]
88,235
<p>Recently I ran into this error in my web application:</p> <blockquote> <p>java.lang.OutOfMemoryError: PermGen space</p> </blockquote> <p>It's a typical Hibernate/JPA + IceFaces/JSF application running on Tomcat 6 and JDK 1.6. Apparently this can occur after redeploying an application a few times.</p> <p>What causes it and what can be done to avoid it? How do I fix the problem?</p>
[ { "answer_id": 88262, "author": "Chris", "author_id": 16907, "author_profile": "https://Stackoverflow.com/users/16907", "pm_score": 10, "selected": true, "text": "-XX:+CMSClassUnloadingEnabled -XX:+CMSPermGenSweepingEnabled\n tomcat6w //ES//servicename\n" }, { "answer_id": 89748, "author": "user17163", "author_id": 17163, "author_profile": "https://Stackoverflow.com/users/17163", "pm_score": 5, "selected": false, "text": "-XX:MaxPermSize=128m" }, { "answer_id": 636607, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 5, "selected": false, "text": "-XX:MaxPermSize=256m -XX:MaxPermSize=512m" }, { "answer_id": 835269, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 8, "selected": false, "text": "-XX:MaxPermSize=128M -XX:MaxPermGen=128M" }, { "answer_id": 1067325, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "-XX:MaxPermSize=512m -XX:PermSize=512m" }, { "answer_id": 2726885, "author": "sandeep", "author_id": 327487, "author_profile": "https://Stackoverflow.com/users/327487", "pm_score": 2, "selected": false, "text": "-XX:PermSize=64m -XX:MaxPermSize=128m MaxPermSize MaxPermSize" }, { "answer_id": 4214895, "author": "Hrishikesh Kumar", "author_id": 512126, "author_profile": "https://Stackoverflow.com/users/512126", "pm_score": 2, "selected": false, "text": "--launcher.XXMaxPermSize -XX:MaxPermSize -vm <path to the right JRE directory>/<name of javaw executable>\n" }, { "answer_id": 4307335, "author": "Daniel", "author_id": 524291, "author_profile": "https://Stackoverflow.com/users/524291", "pm_score": 2, "selected": false, "text": "new" }, { "answer_id": 4350922, "author": "Hugo Mendoza", "author_id": 530019, "author_profile": "https://Stackoverflow.com/users/530019", "pm_score": 4, "selected": false, "text": "-XX: MaxPermSize = 512m\n-XX: PermSize = 512m\n" }, { "answer_id": 6249914, "author": "Ioannis Sermetziadis", "author_id": 785622, "author_profile": "https://Stackoverflow.com/users/785622", "pm_score": 3, "selected": false, "text": "PropertyConfigurator.configureAndWatch(\"log4j.properties\")" }, { "answer_id": 6290834, "author": "Edward Torbett", "author_id": 1506341, "author_profile": "https://Stackoverflow.com/users/1506341", "pm_score": 5, "selected": false, "text": "//Get a list of all classes loaded by the current webapp classloader\nWebappClassLoader classLoader = (WebappClassLoader) getClass().getClassLoader();\nField classLoaderClassesField = null;\nClass clazz = WebappClassLoader.class;\nwhile (classLoaderClassesField == null && clazz != null) {\n try {\n classLoaderClassesField = clazz.getDeclaredField(\"classes\");\n } catch (Exception exception) {\n //do nothing\n }\n clazz = clazz.getSuperclass();\n}\nclassLoaderClassesField.setAccessible(true);\n\nList classes = new ArrayList((Vector)classLoaderClassesField.get(classLoader));\n\nfor (Object o : classes) {\n Class c = (Class)o;\n //Make sure you identify only the packages that are holding references to the classloader.\n //Allowing this code to clear all static references will result in all sorts\n //of horrible things (like java segfaulting).\n if (c.getName().startsWith(\"com.whatever\")) {\n //Kill any static references within all these classes.\n for (Field f : c.getDeclaredFields()) {\n if (Modifier.isStatic(f.getModifiers())\n && !Modifier.isFinal(f.getModifiers())\n && !f.getType().isPrimitive()) {\n try {\n f.setAccessible(true);\n f.set(null, null);\n } catch (Exception exception) {\n //Log the exception\n }\n }\n }\n }\n}\n\nclasses.clear();\n" }, { "answer_id": 8432825, "author": "kiwilisk", "author_id": 1087971, "author_profile": "https://Stackoverflow.com/users/1087971", "pm_score": 2, "selected": false, "text": "<plugin>\n <groupId>org.apache.maven.plugins</groupId>\n <artifactId>maven-compiler-plugin</artifactId>\n <version>2.3.2</version>\n <configuration>\n <fork>true</fork>\n <meminitial>128m</meminitial>\n <maxmem>512m</maxmem>\n <source>1.6</source>\n <target>1.6</target>\n <!-- prevent PermGen space out of memory exception -->\n <!-- <argLine>-Xmx512m -XX:MaxPermSize=512m</argLine> -->\n </configuration>\n</plugin>\n" }, { "answer_id": 8721314, "author": "Peter", "author_id": 1129061, "author_profile": "https://Stackoverflow.com/users/1129061", "pm_score": 6, "selected": false, "text": "-XX:MaxPermSize -XX:PermSize" }, { "answer_id": 12225849, "author": "dev", "author_id": 80286, "author_profile": "https://Stackoverflow.com/users/80286", "pm_score": 1, "selected": false, "text": "rm -rf <tomcat-dir>/work/* <tomcat-dir>/temp/*\n" }, { "answer_id": 15184546, "author": "prayagupa", "author_id": 432903, "author_profile": "https://Stackoverflow.com/users/432903", "pm_score": 5, "selected": false, "text": "-XX: MaxPermSize = 128m -XX: MaxPermSize = 128m" }, { "answer_id": 15520565, "author": "Lucky", "author_id": 1793718, "author_profile": "https://Stackoverflow.com/users/1793718", "pm_score": 3, "selected": false, "text": "-XX:MaxPermSize=128m\n" }, { "answer_id": 25119311, "author": "Edwin Buck", "author_id": 302139, "author_profile": "https://Stackoverflow.com/users/302139", "pm_score": 4, "selected": false, "text": "-XXPermGen...=..." }, { "answer_id": 25647363, "author": "faisalbhagat", "author_id": 1851358, "author_profile": "https://Stackoverflow.com/users/1851358", "pm_score": 4, "selected": false, "text": " -XX:MaxPermSize=128m\n -XX:+CMSClassUnloadingEnabled -XX:+CMSPermGenSweepingEnabled\n" }, { "answer_id": 25841574, "author": "Darshan", "author_id": 3828400, "author_profile": "https://Stackoverflow.com/users/3828400", "pm_score": 3, "selected": false, "text": "gedit .bashrc JAVA_OTPS export JAVA_OPTS=\"-XX:PermSize=256m -XX:MaxPermSize=512m\"\n" }, { "answer_id": 32394678, "author": "NIKHIL CHAURASIA", "author_id": 3927323, "author_profile": "https://Stackoverflow.com/users/3927323", "pm_score": 2, "selected": false, "text": "mvn clean package <artifactId>maven-surefire-plugin</artifactId> <configuration> <argLine> -Xmx512m -XX:MaxPermSize=256m <configuration>\n <argLine>-Xmx512m -XX:MaxPermSize=256m</argLine>\n </configuration>" }, { "answer_id": 34602657, "author": "sendon1982", "author_id": 2680640, "author_profile": "https://Stackoverflow.com/users/2680640", "pm_score": 2, "selected": false, "text": "-XX:+CMSClassUnloadingEnabled\n -XX:+UseConcMarkSweepGC\n" }, { "answer_id": 36148243, "author": "Santosh Jadi", "author_id": 3805521, "author_profile": "https://Stackoverflow.com/users/3805521", "pm_score": 4, "selected": false, "text": "java.lang.OutOfMemoryError: PermGen java.lang.OutOfMemoryError: PermGen" }, { "answer_id": 36846957, "author": "Alejandro Pablo Tkachuk", "author_id": 4987783, "author_profile": "https://Stackoverflow.com/users/4987783", "pm_score": 2, "selected": false, "text": "import java.sql.Driver;\nimport java.sql.DriverManager;\nimport java.sql.SQLException;\nimport java.util.Enumeration;\n\nimport javax.servlet.ServletContextEvent;\nimport javax.servlet.ServletContextListener;\n\nimport org.apache.log4j.Logger;\n\nimport com.mysql.jdbc.AbandonedConnectionCleanupThread;\n\n/**\n * \n * @author alejandro.tkachuk / calculistik.com\n *\n */\npublic class AppContextListener implements ServletContextListener {\n\n private static final Logger logger = Logger.getLogger(AppContextListener.class);\n\n @Override\n public void contextInitialized(ServletContextEvent arg0) {\n logger.info(\"AppContextListener started\");\n }\n\n @Override\n public void contextDestroyed(ServletContextEvent arg0) {\n logger.info(\"AppContextListener destroyed\");\n\n // manually unregister the JDBC drivers\n Enumeration<Driver> drivers = DriverManager.getDrivers();\n while (drivers.hasMoreElements()) {\n Driver driver = drivers.nextElement();\n try {\n DriverManager.deregisterDriver(driver);\n logger.info(String.format(\"Unregistering jdbc driver: %s\", driver));\n } catch (SQLException e) {\n logger.info(String.format(\"Error unregistering driver %s\", driver), e);\n }\n\n }\n\n // manually shutdown clean up threads\n try {\n AbandonedConnectionCleanupThread.shutdown();\n logger.info(\"Shutting down AbandonedConnectionCleanupThread\");\n } catch (InterruptedException e) {\n logger.warn(\"SEVERE problem shutting down AbandonedConnectionCleanupThread: \", e);\n e.printStackTrace();\n } \n }\n}\n <listener>\n <listener-class>\n com.calculistik.mediweb.context.AppContextListener \n </listener-class>\n</listener> \n" }, { "answer_id": 70596932, "author": "Douglas Silva", "author_id": 10141464, "author_profile": "https://Stackoverflow.com/users/10141464", "pm_score": 0, "selected": false, "text": "-XX: MaxPermSize = 128m" }, { "answer_id": 71465370, "author": "Abd Abughazaleh", "author_id": 8370334, "author_profile": "https://Stackoverflow.com/users/8370334", "pm_score": 0, "selected": false, "text": "C:\\Program Files\\Apache Software Foundation\\Tomcat 9.0\\bin tomcat9w" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/88235", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16907/" ]
88,259
<p>I tend to use <a href="http://en.wikipedia.org/wiki/SQLite" rel="noreferrer">SQLite</a> when doing <a href="http://en.wikipedia.org/wiki/Django_(web_framework)" rel="noreferrer">Django</a> development, but on a live server something more robust is often needed (<a href="http://en.wikipedia.org/wiki/MySQL" rel="noreferrer">MySQL</a>/<a href="http://en.wikipedia.org/wiki/PostgreSQL" rel="noreferrer">PostgreSQL</a>, for example). Invariably, there are other changes to make to the Django settings as well: different logging locations / intensities, media paths, etc.</p> <p>How do you manage all these changes to make deployment a simple, automated process?</p>
[ { "answer_id": 88331, "author": "Jim", "author_id": 8427, "author_profile": "https://Stackoverflow.com/users/8427", "pm_score": 6, "selected": false, "text": "settings_local.py settings_development.py DEBUG = True settings_production.py SERVER_EMAIL settings.py settings_local.py settings_local.py DEVELOPMENT_HOSTS PRODUCTION_HOSTS settings.py platform.node() settings_local.py" }, { "answer_id": 88344, "author": "John Millikin", "author_id": 3560, "author_profile": "https://Stackoverflow.com/users/3560", "pm_score": 4, "selected": false, "text": "settings_base.py settings.py from settings_base import *" }, { "answer_id": 89338, "author": "Sean O Donnell", "author_id": 7813, "author_profile": "https://Stackoverflow.com/users/7813", "pm_score": 1, "selected": false, "text": "BASE_DIR BASE_URL BASE_DIR = \"/home/sean/myapp/\" MEDIA_ROOT = \"%smedia/\" % BASEDIR" }, { "answer_id": 89823, "author": "Gabriel Ross", "author_id": 10751, "author_profile": "https://Stackoverflow.com/users/10751", "pm_score": 5, "selected": false, "text": "import socket\nif socket.gethostname().startswith('gabriel'):\n LIVEHOST = False\nelse: \n LIVEHOST = True\n if LIVEHOST:\n DEBUG = False\n PREPEND_WWW = True\n MEDIA_URL = 'http://static1.grsites.com/'\nelse:\n DEBUG = True\n PREPEND_WWW = False\n MEDIA_URL = 'http://localhost:8000/static/'\n" }, { "answer_id": 91608, "author": "Dmitry Shevchenko", "author_id": 7437, "author_profile": "https://Stackoverflow.com/users/7437", "pm_score": 5, "selected": false, "text": "try:\n from settings_local import *\nexcept ImportError:\n pass\n" }, { "answer_id": 1527240, "author": "Chase Seibert", "author_id": 7679, "author_profile": "https://Stackoverflow.com/users/7679", "pm_score": 1, "selected": false, "text": "import sys\nimport os.path\n\ndef _load_settings(path): \n print \"Loading configuration from %s\" % (path)\n if os.path.exists(path):\n settings = {}\n # execfile can't modify globals directly, so we will load them manually\n execfile(path, globals(), settings)\n for setting in settings:\n globals()[setting] = settings[setting]\n\n_load_settings(\"/usr/local/conf/local_settings.py\")\n" }, { "answer_id": 3201509, "author": "Andre Bossard", "author_id": 21027, "author_profile": "https://Stackoverflow.com/users/21027", "pm_score": 3, "selected": false, "text": "import os\nfrom settings import *\n DEBUG = False\nTEMPLATE_DEBUG = DEBUG\n\n\nDATABASES = {\n 'default': {\n ....\n }\n}\n" }, { "answer_id": 7047633, "author": "sacabuche", "author_id": 259337, "author_profile": "https://Stackoverflow.com/users/259337", "pm_score": 1, "selected": false, "text": "#settings.py\ntry:\n from locale_settings import *\nexcept ImportError:\n pass\n #locale_settings.py\nclass Settings(object):\n\n def __init__(self):\n import settings\n self.settings = settings\n\n def __getattr__(self, name):\n return getattr(self.settings, name)\n\nsettings = Settings()\n\nINSTALLED_APPS = settings.INSTALLED_APPS + (\n 'gunicorn',)\n\n# Delete duplicate settings maybe not needed, but I prefer to do it.\ndel settings\ndel Settings\n" }, { "answer_id": 9694966, "author": "slashmili", "author_id": 683247, "author_profile": "https://Stackoverflow.com/users/683247", "pm_score": 0, "selected": false, "text": "if os.environ.get('WEB_MODE', None) == 'production' :\n from settings_production import *\nelse :\n from settings_dev import *\n" }, { "answer_id": 48937980, "author": "JM Desrosiers", "author_id": 4807054, "author_profile": "https://Stackoverflow.com/users/4807054", "pm_score": 1, "selected": false, "text": "BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))\n DEBUG=False\nif(BASE_DIR==\"/path/to/my/dev/dir\"):\n DEBUG = True\n if(DEBUG):\n #Debug setting\nelse:\n #Release setting\n" }, { "answer_id": 50281891, "author": "Little Phild", "author_id": 3828533, "author_profile": "https://Stackoverflow.com/users/3828533", "pm_score": 0, "selected": false, "text": "library pip install django-configurations\n # mysite/settings.py\n\nfrom configurations import Configuration\n\nclass Dev(Configuration):\n DEBUG = True\n DJANGO_CONFIGURATION ~/.bashrc export DJANGO_CONFIGURATION=Dev DJANGO_SETTINGS_MODULE export DJANGO_SETTINGS_MODULE=mysite.settings --configuration --settings python manage.py runserver --settings=mysite.settings --configuration=Dev #!/usr/bin/env python\n\nimport os\nimport sys\n\nif __name__ == \"__main__\":\n os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'mysite.settings')\n os.environ.setdefault('DJANGO_CONFIGURATION', 'Dev')\n\n from configurations.management import execute_from_command_line\n\n execute_from_command_line(sys.argv)\n django.core.management.execute_from_command_line configurations.management.execute_from_command_line import os\n\nos.environ.setdefault('DJANGO_SETTINGS_MODULE', 'mysite.settings')\nos.environ.setdefault('DJANGO_CONFIGURATION', 'Dev')\n\nfrom configurations.wsgi import get_wsgi_application\n\napplication = get_wsgi_application()\n django.core.wsgi.get_wsgi_application configurations.wsgi.get_wsgi_application" }, { "answer_id": 67959896, "author": "Koushik Das", "author_id": 4653436, "author_profile": "https://Stackoverflow.com/users/4653436", "pm_score": 1, "selected": false, "text": ".env django-environ\n settings.py .env .env .env SECRET_KEY=\"django-insecure-zy%)s5$=aql=#ox54lzfjyyx!&uv1-q0kp^54p(^251&_df75i\"\n\nDB_NAME=bugfree\nDB_USER=postgres\nDB_PASSWORD=koushik\nDB_PORT=5433\nDB_HOST=localhost\n\nAPP_DEBUG=True # everything is string here\n import environ\nenv = environ.Env()\nenviron.Env.read_env()\n .env settings.py SECRET_KEY = env('SECRET_KEY')\nDEBUG = bool(env('APP_DEBUG', False))\n env('DB_NAME', 'default value here')\n .env.example .env .env .example .env.example SECRET_KEY=VALUE_HERE\n\nDB_NAME=VALUE_HERE\nDB_USER=VALUE_HERE\nDB_PASSWORD=VALUE_HERE\nDB_PORT=VALUE_HERE\nDB_HOST=VALUE_HERE\n\nEMAIL_HOST=VALUE_HERE\nEMAIL_PORT=VALUE_HERE\nEMAIL_HOST_USER=VALUE_HERE\nEMAIL_HOST_PASSWORD=VALUE_HERE\nDEFAULT_FROM_EMAIL=VALUE_HERE\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/88259", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
88,269
<p>In certain unknown situations selenium does not detect that a page has loaded when using the open method. I am using the Java API. For example (This code will not produce this error. I don't know of an externally visible page that will.):</p> <pre><code>Selenium browser = new DefaultSelenium("localhost", 4444, "*firefox", "http://www.google.com"); browser.start(); browser.open("http://www.google.com/webhp?hl=en"); browser.type("q", "hello world"); </code></pre> <p>When the error occurs, the call to 'open' times out, even though you can clearly see that the page has loaded successfully before the timeout occurs. Increasing the timeout does not help. The call to 'type' never occurs, no progress is made.</p> <p>How do you get selenium to recognize that the page has loaded when this error occurs?</p>
[ { "answer_id": 88320, "author": "Matthew Jaskula", "author_id": 4356, "author_profile": "https://Stackoverflow.com/users/4356", "pm_score": 0, "selected": false, "text": "SeleniumServer server = new SeleniumServer(4444, false, true);\n" }, { "answer_id": 8079103, "author": "Timur Evdokimov", "author_id": 656559, "author_profile": "https://Stackoverflow.com/users/656559", "pm_score": 2, "selected": false, "text": " <ice:outputConnectionStatus id=\"connectStat\"\n showPopupOnDisconnect=\"true\"/>\n private void waitForAjax() throws InterruptedException {\n for (int second = 0;; second++) {\n if (second >= 60) fail(\"timeout\");\n try { \n if (\"visibility: visible;\".equals(\n selenium.getAttribute(\"top_right_form:connectStat:connection-idle@style\"))) { \n break;\n }\n } catch (Exception e) {\n\n }\n Thread.sleep(1000);\n }\n}\n" }, { "answer_id": 16129677, "author": "dav", "author_id": 932473, "author_profile": "https://Stackoverflow.com/users/932473", "pm_score": 0, "selected": false, "text": "$t1 = time(); // current timestamp\n$this->selenium->waitForPageToLoad(30);\n$t2 = time();\n\nif ($t2 - $t1 >= 28) {\n // page was not loaded\n}\n" }, { "answer_id": 18870766, "author": "someman", "author_id": 2791217, "author_profile": "https://Stackoverflow.com/users/2791217", "pm_score": 0, "selected": false, "text": "fail(\"\") System.err.println() element.click();\n int timeout =120; \n // one loop = 0.5 sec, co it will be one minute \n WebElement myFooter = null;\n\n for(int i=0; i<timeout; i++){\n myFooter = driver.findElement(By.id(\"footer\"));\n if(myFooter!= null){\n break;\n }\n else{\n timeout--;\n }\n}\nif(timeout==0 && myFooter == null){\n fail(\"ERROR! PAGE TIMEOUT\");\n}\n" }, { "answer_id": 18870910, "author": "someman", "author_id": 2791217, "author_profile": "https://Stackoverflow.com/users/2791217", "pm_score": 0, "selected": false, "text": "<input type='hidden' id=\"greenlight\">\n if(driver.findElement(By.id(\"greenlight\")).getAttr(\"value\").equals(\"TRUE\")){\n // do something after page loading\n}\n" }, { "answer_id": 25195600, "author": "Prabu Ananthakrishnan", "author_id": 2888917, "author_profile": "https://Stackoverflow.com/users/2888917", "pm_score": 2, "selected": false, "text": "public static void waitForPageLoaded(WebDriver driver) {\n\n ExpectedCondition<Boolean> expectation = new\n ExpectedCondition<Boolean>() {\n public Boolean apply(WebDriver driver) {\n return ((JavascriptExecutor)driver).executeScript(\"return document.readyState\").equals(\"complete\");\n }\n };\n\n WebDriverWait wait = new WebDriverWait(driver,30);\n try {\n wait.until(expectation);\n } catch(Throwable error) {\n Assert.assertFalse(true, \"Timeout waiting for Page Load Request to complete.\");\n }\n } \n public class Test(){\n WebDriver driver;\n\n @Test\n public void testing(){\n driver = new FirefoxDriver();\n driver.get(\"http://www.gmail.com\");\n Functions.waitForPageLoaded(driver);\n }\n}\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/88269", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4356/" ]
88,276
<p>I've been trying to figure this out for about two weeks. I'm able to create email items in people's folders, read the folders, all that stuff but for the life of me I can not get anything to work with the calendars.</p> <p>I can provide examples of the XML I'm sending to WebDav but hoping someone out there has done this and has an example?</p>
[ { "answer_id": 92523, "author": "Robert Sanders", "author_id": 16952, "author_profile": "https://Stackoverflow.com/users/16952", "pm_score": 2, "selected": false, "text": "T 10.0.1.95:59741 -> 66.211.136.9:80 [AP]\nPUT /exchange/yourname.domainname.com/Cal2/CC1.1163646061548.0.eml HTTP/1.1.\ntranslate: f.\nContent-Type: message/rfc822.\nPragma: no-cache.\nAccept: */*.\nCache-Control: no-cache.\nAuthorization: Basic NOYOUCANTSEEMYPASSWORDYOUBASTARDS.\nUser-Agent: Jakarta Commons-HttpClient/2.0final.\nHost: e1.exmx.net.\nCookie: sessionid=29486b50-d398-4f76-9604-8421950c7dcd:0x0.\nContent-Length: 478.\nExpect: 100-continue.\n.\n\n\nT 66.211.136.9:80 -> 10.0.1.95:59741 [AP]\nHTTP/1.1 100 Continue.\n.\n\n\nT 10.0.1.95:59741 -> 66.211.136.9:80 [AP]\ncontent-class: urn:content-classes:appointment.\nContent-Type: text/calendar;.\n.method=REQUEST;.\n.charset=\"utf-8\".\nContent-Transfer-Encoding: 8bit.\n.\nBEGIN:VCALENDAR.\nBEGIN:VEVENT.\nUID:E1+1382+1014+495066799@I1+1382+1014+6+495066799.\nSUMMARY:Voice Architecture Leads Meeting.\nPRIORITY:5.\nLOCATION:x44444 pc:6879.\nDTSTART:20061122T193000Z.\nDTEND:20061122T203000Z.\nDTSTAMP:20061110T074856Z.\nDESCRIPTION:this is a description.\nSUMMARY:this is a summary.\nEND:VEVENT.\nEND:VCALENDAR.\n\n\n\nT 66.211.136.9:80 -> 10.0.1.95:59741 [AP]\nHTTP/1.1 201 Created.\nDate: Thu, 16 Nov 2006 03:00:16 GMT.\nServer: Microsoft-IIS/6.0.\nX-Powered-By: ASP.NET.\nMS-Exchange-Permanent-URL: http://e1.exmx.net/exchange/yourname.yourdomain.com/-FlatUrlSpace-/122cda661de1da48936f9\n44bda4dde6e-3af8a8/122cda661de1da48936f944bda4dde6e-3f3383.\nLocation: http://e1.exmx.net/exchange/yourname.yourdomain.com/Cal2/CC1.1163646061548.0.eml.\nRepl-UID: <rid:122cda661de1da48936f944bda4dde6e0000003f3383>.\nContent-Type: text/html.\nContent-Length: 110.\nAllow: OPTIONS, TRACE, GET, HEAD, DELETE, PUT, COPY, MOVE, PROPFIND, PROPPATCH, SEARCH, SUBSCRIBE, UNSUBSCRIBE, PO\nLL, BDELETE, BCOPY, BMOVE, BPROPPATCH, BPROPFIND, LOCK, UNLOCK.\nResourceTag: <rt:122cda661de1da48936f944bda4dde6e0000003f3383122cda661de1da48936f944bda4dde6e0000003f4671>.\nGetETag: \"122cda661de1da48936f944bda4dde6e0000003f4671\".\nMS-WebStorage: 6.5.7638.\nCache-Control: no-cache.\n T 66.211.136.9:80 -> 10.0.1.95:59741 [AP]\n<body><h1>/exchange/yourname.yourdomain.com/Cal2/CC1.1163646061548.0.eml was created successfully</h1></body>.\n dav:/exchange/yourname@yourdomain.com/Cal2/> propget CC1.1163646061548.0.eml\n Fetching properties for `CC1.1163646061548.0.eml':\n textdescription = this is a description\n contentclass = urn:content-classes:appointment\n supportedlock = <lockentry><locktype><transaction><groupoperation></groupoperation></transaction></locktype><locks\n cope><local></local></lockscope></lockentry>\n permanenturl = http://e1.exmx.net/exchange/yourname@yourdomain.com/-FlatUrlSpace-/122cda661de1da48936f944bda4dde6e-\n 3af8a8/122cda661de1da48936f944bda4dde6e-3f3383\n getcontenttype = message/rfc822\n id = AQEAAAAAOvioAQAAAAA/M4MAAAAA\n mid = -8992774761696198655\n uid = E1+1382+1014+495066799@I1+1382+1014+6+495066799\n isfolder = 0\n resourcetype = \n method = PUBLISH\n getetag = \"122cda661de1da48936f944bda4dde6e0000003f4671\"\n lockdiscovery = \n outlookmessageclass = IPM.Appointment\n creationdate = 2006-11-16T03:00:16.549Z\n outlookmessageclass = IPM.Appointment\n creationdate = 2006-11-16T03:00:16.549Z\n ntsecuritydescriptor = CAAEAAAAAAABAC+MMAAAAEwAAAAAAAAAFAAAAAIAHAABAAAAARAUAL8PHwABAQAAAAAABQcAAAABBQAAAAAABRUAAAC\n nkePD6LEa8iIT/+gqDAAAAQUAAAAAAAUVAAAAp5Hjw+ixGvIiE//oAQIAAA==\n dtstamp = 2006-11-10T07:48:56.000Z\n lastmodified = 2006-11-16T03:00:16.565Z\n dtstart = 2006-11-22T19:30:00.000Z\n location = x44444 pc:6879\n duration = 3600\n htmldescription = <!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 3.2//EN\">\n <HTML>\n <HEAD>\n\n <META NAME=\"Generator\" CONTENT=\"MS Exchange Server version 6.5.7638.1\">\n <TITLE>this is a summary</TITLE>\n </HEAD>\n <BODY>\n <!-- Converted from text/plain format -->\n\n <P><FONT SIZE=2>this is a description</FONT>\n </P>\n\n </BODY>\n </HTML>\n ishidden = 0\n parentname = http://e1.exmx.net/exchange/yourname@yourdomain.com/Cal2/\n meetingstatus = TENTATIVE\n subject = this is a summary\n getcontentlength = 631\n normalizedsubject = this is a summary\n isstructureddocument = 0\n repl-uid = rid:122cda661de1da48936f944bda4dde6e0000003f3383\n timezoneid = 0\n displayname = CC1.1163646061548.0.eml\n href = http://e1.exmx.net/exchange/yourname@yourdomain.com/Cal2/CC1.1163646061548.0.eml\n nomodifyexceptions = 1\n patternend = 2006-11-22T20:30:00.000Z\n isreadonly = 0\n instancetype = 0\n uid = AQEAAAAAPzODAAAAAAAAAAAAAAAA\n getlastmodified = 2006-11-16T03:00:16.565Z\n created = 2006-11-16T03:00:16.549Z\n sensitivity = 0\n dtend = 2006-11-22T20:30:00.000Z\n hasattachment = 0\n iscollection = 0\n read = 1\n resourcetag = rt:122cda661de1da48936f944bda4dde6e0000003f3383122cda661de1da48936f944bda4dde6e0000003f4671\n patternstart = 2006-11-22T19:30:00.000Z\n priority = 0\n sequence = 0\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/88276", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
88,306
<p>I'm making a small web application in Seaside. I have a login component, and after the user logs in I want to send along a cookie when the next component renders itself. Is there a way to get at the object handling the response so I can add something to the headers it will output?</p> <p>I'm trying to avoid using WASession>>redirectWithCookies since it seems pretty kludgey to redirect only because I want to set a cookie.</p> <p>Is there another way that already exist to add a cookie that will go out on the next response?</p>
[ { "answer_id": 90695, "author": "Julian", "author_id": 11526, "author_profile": "https://Stackoverflow.com/users/11526", "pm_score": 4, "selected": true, "text": "self requestContext response addCookie: aCookie\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/88306", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2766176/" ]
88,311
<p>I'm currently generating an 8-character pseudo-random uppercase string for "A" .. "Z":</p> <pre><code>value = ""; 8.times{value &lt;&lt; (65 + rand(25)).chr} </code></pre> <p>but it doesn't look clean, and it can't be passed as an argument since it isn't a single statement. To get a mixed-case string "a" .. "z" plus "A" .. "Z", I changed it to:</p> <pre><code>value = ""; 8.times{value &lt;&lt; ((rand(2)==1?65:97) + rand(25)).chr} </code></pre> <p>but it looks like trash.</p> <p>Does anyone have a better method?</p>
[ { "answer_id": 88338, "author": "easeout", "author_id": 10906, "author_profile": "https://Stackoverflow.com/users/10906", "pm_score": 0, "selected": false, "text": "(0...8).collect { |n| value << (65 + rand(25)).chr }.join()\n" }, { "answer_id": 88341, "author": "Kent Fredric", "author_id": 15614, "author_profile": "https://Stackoverflow.com/users/15614", "pm_score": 11, "selected": true, "text": "(0...8).map { (65 + rand(26)).chr }.join\n (0...50).map { ('a'..'z').to_a[rand(26)] }.join\n o = [('a'..'z'), ('A'..'Z')].map(&:to_a).flatten\nstring = (0...50).map { o[rand(o.length)] }.join\n 50.times.map { (0...(rand(10))).map { ('a'..'z').to_a[rand(26)] }.join }.join(\" \")\n" }, { "answer_id": 88371, "author": "Purfideas", "author_id": 4615, "author_profile": "https://Stackoverflow.com/users/4615", "pm_score": -1, "selected": false, "text": " (1..8).map{|i| ('a'..'z').to_a[rand(26)]}.join\n" }, { "answer_id": 88422, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 4, "selected": false, "text": "require 'sha1'\nsrand\nseed = \"--#{rand(10000)}--#{Time.now}--\"\nDigest::SHA1.hexdigest(seed)[0,8]\n" }, { "answer_id": 88470, "author": "Carlos Villela", "author_id": 16944, "author_profile": "https://Stackoverflow.com/users/16944", "pm_score": 2, "selected": false, "text": "class String\n\n def self.random(length=10)\n ('a'..'z').sort_by {rand}[0,length].join\n end\n\nend\n" }, { "answer_id": 89042, "author": "Ryan Bigg", "author_id": 15245, "author_profile": "https://Stackoverflow.com/users/15245", "pm_score": 2, "selected": false, "text": "def generate_random_string(length=6)\n string = \"\"\n chars = (\"A\"..\"Z\").to_a\n length.times do\n string << chars[rand(chars.length-1)]\n end\n string\nend\n" }, { "answer_id": 89514, "author": "webmat", "author_id": 6349, "author_profile": "https://Stackoverflow.com/users/6349", "pm_score": 2, "selected": false, "text": "CHARS = ('a'..'z').to_a + ('A'..'Z').to_a\ndef rand_string(length=8)\n s=''\n length.times{ s << CHARS[rand(CHARS.length)] }\n s\nend\n" }, { "answer_id": 493230, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 7, "selected": false, "text": "# Generates a random string from a set of easily readable characters\ndef generate_activation_code(size = 6)\n charset = %w{ 2 3 4 6 7 9 A C D E F G H J K M N P Q R T V W X Y Z}\n (0...size).map{ charset.to_a[rand(charset.size)] }.join\nend\n" }, { "answer_id": 1117003, "author": "Travis Reeder", "author_id": 105562, "author_profile": "https://Stackoverflow.com/users/105562", "pm_score": 5, "selected": false, "text": "def random_string(length=10)\n chars = 'abcdefghjkmnpqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ0123456789'\n password = ''\n length.times { password << chars[rand(chars.size)] }\n password\nend\n" }, { "answer_id": 1619602, "author": "christopherstyles", "author_id": 131852, "author_profile": "https://Stackoverflow.com/users/131852", "pm_score": 10, "selected": false, "text": "require 'securerandom'\nrandom_string = SecureRandom.hex\n\n# outputs: 5b5cd0da3121fc53b4bc84d0c8af2e81 (i.e. 32 chars of 0..9, a..f)\n" }, { "answer_id": 2031464, "author": "user163365", "author_id": 163365, "author_profile": "https://Stackoverflow.com/users/163365", "pm_score": 3, "selected": false, "text": " rand(2**256).to_s(36)[0..7]\n ljust rand(2**256).to_s(36).ljust(8,'a')[0..7]\n" }, { "answer_id": 2908081, "author": "Nathan L Smith", "author_id": 161787, "author_profile": "https://Stackoverflow.com/users/161787", "pm_score": 0, "selected": false, "text": "`pwgen 8 1`.chomp\n" }, { "answer_id": 3326909, "author": "Ragmaanir", "author_id": 323733, "author_profile": "https://Stackoverflow.com/users/323733", "pm_score": 4, "selected": false, "text": "ALPHABET = ('a'..'z').to_a\n#=> [\"a\", \"b\", \"c\", \"d\", \"e\", \"f\", \"g\", \"h\", \"i\", \"j\", \"k\", \"l\", \"m\", \"n\", \"o\", \"p\", \"q\", \"r\", \"s\", \"t\", \"u\", \"v\", \"w\", \"x\", \"y\", \"z\"]\n\n10.times.map { ALPHABET.sample }.join\n#=> \"stkbssowre\"\n\n# or\n\n10.times.inject('') { |s| s + ALPHABET.sample }\n#=> \"fdgvacnxhc\"\n" }, { "answer_id": 3431889, "author": "erik", "author_id": 414025, "author_profile": "https://Stackoverflow.com/users/414025", "pm_score": 2, "selected": false, "text": "str = ''\n8.times {|i| str << ARRAY_OF_POSSIBLE_VALUES[rand(SIZE_OF_ARRAY_OF_POSSIBLE_VALUES)] }\n str" }, { "answer_id": 3572953, "author": "Christoffer Möller", "author_id": 431562, "author_profile": "https://Stackoverflow.com/users/431562", "pm_score": 8, "selected": false, "text": "string_length = 8\nrand(36**string_length).to_s(36)\n" }, { "answer_id": 5073878, "author": "Manuel A. Guilamo", "author_id": 627682, "author_profile": "https://Stackoverflow.com/users/627682", "pm_score": 2, "selected": false, "text": "def rand_name(len=9)\n ary = [('0'..'9').to_a, ('a'..'z').to_a, ('A'..'Z').to_a]\n name = ''\n\n len.times do\n name << ary.choice.choice\n end\n name\nend\n" }, { "answer_id": 5735905, "author": "Tim James", "author_id": 17055, "author_profile": "https://Stackoverflow.com/users/17055", "pm_score": 2, "selected": false, "text": "chars = [*('a'..'z'),*('0'..'9')].flatten\n Array.new(len) { chars.sample }.join\n" }, { "answer_id": 6412228, "author": "Nathan Long", "author_id": 4376, "author_profile": "https://Stackoverflow.com/users/4376", "pm_score": 3, "selected": false, "text": "characters = ('a'..'z').to_a + ('A'..'Z').to_a\n# Prior to 1.9, use .choice, not .sample\n(0..8).map{characters.sample}.join\n characters = ('a'..'z').to_a + ('A'..'Z').to_a + (0..9).to_a\n characters = ('A'..'F').to_a + (0..9).to_a\n characters = (32..126).to_a.pack('U*').chars.to_a\n" }, { "answer_id": 7173336, "author": "Evgenii", "author_id": 297131, "author_profile": "https://Stackoverflow.com/users/297131", "pm_score": 2, "selected": false, "text": "require \"securerandom\" def secure_random_string(length = 32, non_ambiguous = false)\n characters = ('a'..'z').to_a + ('A'..'Z').to_a + ('0'..'9').to_a\n\n %w{I O l 0 1}.each{ |ambiguous_character| \n characters.delete ambiguous_character \n } if non_ambiguous\n\n (0...length).map{\n characters[ActiveSupport::SecureRandom.random_number(characters.size)]\n }.join\nend\n" }, { "answer_id": 7222962, "author": "Travis Reeder", "author_id": 105562, "author_profile": "https://Stackoverflow.com/users/105562", "pm_score": 7, "selected": false, "text": "require 'securerandom'\np SecureRandom.urlsafe_base64(5) #=> \"UtM7aa8\"\np SecureRandom.urlsafe_base64 #=> \"UZLdOkzop70Ddx-IJR0ABg\"\np SecureRandom.urlsafe_base64(nil, true) #=> \"i0XQ-7gglIsHGV2_BNPrdQ==\"\n" }, { "answer_id": 7653318, "author": "eric", "author_id": 979198, "author_profile": "https://Stackoverflow.com/users/979198", "pm_score": 2, "selected": false, "text": "''.tap {|v| 4.times { v << ('a'..'z').to_a.sample} }\n" }, { "answer_id": 8730431, "author": "Shai Coleman", "author_id": 891862, "author_profile": "https://Stackoverflow.com/users/891862", "pm_score": 6, "selected": false, "text": "[*('A'..'Z')].sample(8).join\n ([*('A'..'Z'),*('0'..'9')]-%w(0 1 I O)).sample(8).join\n" }, { "answer_id": 9234645, "author": "peter", "author_id": 923315, "author_profile": "https://Stackoverflow.com/users/923315", "pm_score": 2, "selected": false, "text": "(('a'..'z').to_a + ('A'..'Z').to_a + (0..9).to_a).sample(8).join\n\n([*(48..57),*(65..90),*(97..122)]).sample(8).collect(&:chr)*\"\"\n ( ('a'..'z').to_a.sample(8) + ('A'..'Z').to_a.sample(8) + (0..9).to_a.sample(8) ).shuffle.join \n#=> \"Kc5zOGtM0H796QgPp8u2Sxo1\"\n" }, { "answer_id": 10220012, "author": "Teej", "author_id": 37532, "author_profile": "https://Stackoverflow.com/users/37532", "pm_score": 3, "selected": false, "text": "SecureRandom.base64(15).tr('+/=lIO0', 'pqrsxyz')\n" }, { "answer_id": 10292347, "author": "Chris Bloom", "author_id": 83743, "author_profile": "https://Stackoverflow.com/users/83743", "pm_score": 1, "selected": false, "text": "def random_password\n specials = ((32..47).to_a + (58..64).to_a + (91..96).to_a + (123..126).to_a).pack('U*').chars.to_a\n numbers = (0..9).to_a\n alpha = ('a'..'z').to_a + ('A'..'Z').to_a\n %w{i I l L 1 O o 0}.each{ |ambiguous_character| \n alpha.delete ambiguous_character \n }\n characters = (alpha + specials + numbers)\n password = Random.new.rand(8..18).times.map{characters.sample}\n password << specials.sample unless password.join =~ Regexp.new(Regexp.escape(specials.join))\n password << numbers.sample unless password.join =~ Regexp.new(Regexp.escape(numbers.join))\n password.shuffle.join\nend\n" }, { "answer_id": 10434882, "author": "tybro0103", "author_id": 202875, "author_profile": "https://Stackoverflow.com/users/202875", "pm_score": 2, "selected": false, "text": " def token(length=16)\n chars = [*('A'..'Z'), *('a'..'z'), *(0..9)]\n (0..length).map {chars.sample}.join\n end\n" }, { "answer_id": 10773250, "author": "pdu", "author_id": 92096, "author_profile": "https://Stackoverflow.com/users/92096", "pm_score": 3, "selected": false, "text": "def random_string(length = 8)\n rand(32**length).to_s(32)\nend\n" }, { "answer_id": 11313001, "author": "lzap", "author_id": 299204, "author_profile": "https://Stackoverflow.com/users/299204", "pm_score": 2, "selected": false, "text": "random_string = `openssl rand -base64 24`\n" }, { "answer_id": 11462624, "author": "LENZCOM", "author_id": 1055573, "author_profile": "https://Stackoverflow.com/users/1055573", "pm_score": 5, "selected": false, "text": "require 'securerandom'\nSecureRandom.urlsafe_base64(9)\n" }, { "answer_id": 12890596, "author": "Thaha kp", "author_id": 1465460, "author_profile": "https://Stackoverflow.com/users/1465460", "pm_score": 3, "selected": false, "text": "rand_password=('0'..'z').to_a.shuffle.first(8).join\n" }, { "answer_id": 15719632, "author": "pencil", "author_id": 933424, "author_profile": "https://Stackoverflow.com/users/933424", "pm_score": 3, "selected": false, "text": "rand length = 10\ncharacters = ('A'..'Z').to_a + ('a'..'z').to_a + ('0'..'9').to_a\n\npassword = SecureRandom.random_bytes(length).each_char.map do |char|\n characters[(char.ord % characters.length)]\nend.join\n" }, { "answer_id": 15789933, "author": "Ghazi", "author_id": 1114817, "author_profile": "https://Stackoverflow.com/users/1114817", "pm_score": 0, "selected": false, "text": "myStr = \"OID-\"\n begin; n = ((rand * 43) + 47).ceil; myStr << n.chr if !(58..64).include?(n); end while(myStr.length < 12)\n (rand * 43) + 47).ceil\n !(58..64).include?(n)\n while(myStr.length < 12)\n \"OID-XZ2J32XM\"\n" }, { "answer_id": 17596273, "author": "Srikanta Mahapatro", "author_id": 889340, "author_profile": "https://Stackoverflow.com/users/889340", "pm_score": 5, "selected": false, "text": "require 'securerandom'\nrandomstring = SecureRandom.hex(n)\n 2n 0-9 a-f" }, { "answer_id": 17949884, "author": "Abdo", "author_id": 226255, "author_profile": "https://Stackoverflow.com/users/226255", "pm_score": 0, "selected": false, "text": "class String\n # generate a random string of length n using current string as the source of characters\n def random(n)\n return \"\" if n <= 0\n (chars * (n / length + 1)).shuffle[0..n-1].join \n end\nend\n \"ATCG\".random(8) => \"CGTGAAGA\"\n \"AAAAATCG\".random(10) => \"CTGAAAAAGC\"\n" }, { "answer_id": 20272585, "author": "Josh", "author_id": 1193216, "author_profile": "https://Stackoverflow.com/users/1193216", "pm_score": 2, "selected": false, "text": "(:A..:Z).to_a.shuffle[0,8].join" }, { "answer_id": 20342630, "author": "Sibevin Wang", "author_id": 232710, "author_profile": "https://Stackoverflow.com/users/232710", "pm_score": 2, "selected": false, "text": "random_token" }, { "answer_id": 23310810, "author": "Automatico", "author_id": 741850, "author_profile": "https://Stackoverflow.com/users/741850", "pm_score": 0, "selected": false, "text": "Array.new(8).inject(\"\"){|r|r<<('0'..'z').to_a.shuffle[0]} # 57\n(1..8).inject(\"\"){|r|r<<('0'..'z').to_a.shuffle[0]} # 51\ne=\"\";8.times{e<<('0'..'z').to_a.shuffle[0]};e # 45\n(1..8).map{('0'..'z').to_a.shuffle[0]}.join # 43\n(1..8).map{rand(49..122).chr}.join # 34\n" }, { "answer_id": 25358706, "author": "lzap", "author_id": 299204, "author_profile": "https://Stackoverflow.com/users/299204", "pm_score": 2, "selected": false, "text": ">> require \"openssl\"\n>> OpenSSL::Random.random_bytes(20).unpack('H*').join\n=> \"2f3ff53dd712ba2303a573d9f9a8c1dbc1942d28\"\n" }, { "answer_id": 25456667, "author": "Tilo", "author_id": 677684, "author_profile": "https://Stackoverflow.com/users/677684", "pm_score": 3, "selected": false, "text": "String#random facets class String\n def self.random(len=32, character_set = [\"A\"..\"Z\", \"a\"..\"z\", \"0\"..\"9\"])\n characters = character_set.map { |i| i.to_a }.flatten\n characters_len = characters.length\n (0...len).map{ characters[rand(characters_len)] }.join\n end\nend\n" }, { "answer_id": 26107751, "author": "gr8scott06", "author_id": 2760406, "author_profile": "https://Stackoverflow.com/users/2760406", "pm_score": 4, "selected": false, "text": "Array.new(n){[*\"0\"..\"9\"].sample}.join n=8 Array.new(n){[*\"A\"..\"Z\", *\"0\"..\"9\"].sample}.join" }, { "answer_id": 27010181, "author": "Awais", "author_id": 2561638, "author_profile": "https://Stackoverflow.com/users/2561638", "pm_score": 4, "selected": false, "text": " random_string = ('0'..'z').to_a.shuffle.first(8).join\n random_password = ('0'..'z').to_a.shuffle.first(8).join\n" }, { "answer_id": 32656602, "author": "Alex Antonov", "author_id": 2926641, "author_profile": "https://Stackoverflow.com/users/2926641", "pm_score": 3, "selected": false, "text": "Faker::Lorem.characters(10) # => \"ang9cbhoa8\"" }, { "answer_id": 35601419, "author": "DDD", "author_id": 2665844, "author_profile": "https://Stackoverflow.com/users/2665844", "pm_score": 1, "selected": false, "text": "10.times do \n alphabet = ('a'..'z').to_a\n string += alpha[rand(alpha.length)]\nend\n" }, { "answer_id": 37333123, "author": "shiva kumar", "author_id": 2400485, "author_profile": "https://Stackoverflow.com/users/2400485", "pm_score": 1, "selected": false, "text": "(0...8).map { ([65, 97].sample + rand(26)).chr }.push(rand(99)).join\n" }, { "answer_id": 39246466, "author": "Minski", "author_id": 5308822, "author_profile": "https://Stackoverflow.com/users/5308822", "pm_score": 0, "selected": false, "text": "a='';8.times{a<<[*'a'..'z'].sample};p a\n 8.times.collect{[*'a'..'z'].sample}.join\n" }, { "answer_id": 48521297, "author": "Markus", "author_id": 590761, "author_profile": "https://Stackoverflow.com/users/590761", "pm_score": 7, "selected": false, "text": "SecureRandom.alphanumeric len = 8\nSecureRandom.alphanumeric(len)\n=> \"larHSsgL\"\n require 'benchmark'\nrequire 'securerandom'\n\nlen = 10\nn = 100_000\n\nBenchmark.bm(12) do |x|\n x.report('SecureRandom') { n.times { SecureRandom.alphanumeric(len) } }\n x.report('rand') do\n o = [('a'..'z'), ('A'..'Z'), (0..9)].map(&:to_a).flatten\n n.times { (0...len).map { o[rand(o.length)] }.join }\n end\nend\n user system total real\nSecureRandom 0.429442 0.002746 0.432188 ( 0.432705)\nrand 0.306650 0.000716 0.307366 ( 0.307745)\n rand SecureRandom" }, { "answer_id": 51750404, "author": "Lucas Andrade", "author_id": 7390929, "author_profile": "https://Stackoverflow.com/users/7390929", "pm_score": 1, "selected": false, "text": " def random_string(length=5)\n chars = 'abdefghjkmnpqrstuvwxyzABDEFGHJKLMNPQRSTUVWXYZ'\n numbers = '0123456789'\n random_s = ''\n (length/2).times { random_s << numbers[rand(numbers.size)] }\n (length - random_s.length).times { random_s << chars[rand(chars.size)] }\n random_s.split('').shuffle.join\n end\n random_string random_string" }, { "answer_id": 71507399, "author": "Tareq Saif", "author_id": 3981013, "author_profile": "https://Stackoverflow.com/users/3981013", "pm_score": 0, "selected": false, "text": "def generate_random_password(min_length, max_length)\n length = SecureRandom.random_number(max_length - min_length) + min_length\n character_sets = [ \n ('a'..'z').to_a,\n ('A'..'Z').to_a,\n ('0'..'9').to_a,\n \"~!@^&*()_-+=[]|:;<,>.?\".split('')\n ] \n retval = []\n # \n # Add one character from each set\n # \n character_sets.each do |character_set|\n character = character_set[SecureRandom.random_number(character_set.count)]\n retval.push character\n end \n # \n # Fill the rest of the password with a random character from a random set\n # \n i = character_sets.count - 1 \n while i < length\n character_set = character_sets[SecureRandom.random_number(character_sets.count)]\n character = character_set[SecureRandom.random_number(character_set.count)]\n retval.push character\n i += 1\n end\n retval.shuffle.join\n end\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/88311", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10157/" ]
88,325
<p>I have a class:</p> <pre><code>class MyClass: def __init__(self, foo): if foo != 1: raise Error("foo is not equal to 1!") </code></pre> <p>and a unit test that is supposed to make sure the incorrect arg passed to the constructor properly raises an error:</p> <pre><code>def testInsufficientArgs(self): foo = 0 self.assertRaises((Error), myClass = MyClass(Error, foo)) </code></pre> <p>But I get...</p> <pre><code>NameError: global name 'Error' is not defined </code></pre> <p>Why? Where should I be defining this Error object? I thought it was built-in as a default exception type, no?</p>
[ { "answer_id": 88346, "author": "Jerub", "author_id": 14648, "author_profile": "https://Stackoverflow.com/users/14648", "pm_score": 6, "selected": true, "text": "class MyClass:\n def __init__(self, foo):\n if foo != 1:\n raise ValueError(\"foo is not equal to 1!\")\n\nimport unittest\nclass TestFoo(unittest.TestCase):\n def testInsufficientArgs(self):\n foo = 0\n self.failUnlessRaises(ValueError, MyClass, foo)\n\nif __name__ == '__main__':\n unittest.main()\n .\n----------------------------------------------------------------------\nRan 1 test in 0.007s\n\nOK\n class TestFoo(unittest.TestCase):\n def failUnlessRaises(self, excClass, callableObj, *args, **kwargs):\n try:\n callableObj(*args, **kwargs)\n except excClass, excObj:\n return excObj # Actually return the exception object\n else:\n if hasattr(excClass,'__name__'): excName = excClass.__name__\n else: excName = str(excClass)\n raise self.failureException, \"%s not raised\" % excName\n\n def testInsufficientArgs(self):\n foo = 0\n excObj = self.failUnlessRaises(ValueError, MyClass, foo)\n self.failUnlessEqual(excObj[0], 'foo is not equal to 1!')\n" }, { "answer_id": 88369, "author": "Terhorst", "author_id": 8062, "author_profile": "https://Stackoverflow.com/users/8062", "pm_score": 3, "selected": false, "text": "class MyClass:\n def __init__(self, foo):\n if foo != 1:\n raise Exception(\"foo is not equal to 1!\")\n\nimport unittest\n\nclass Tests(unittest.TestCase):\n def testSufficientArgs(self):\n foo = 1\n MyClass(foo)\n\n def testInsufficientArgs(self):\n foo = 2\n self.assertRaises(Exception, MyClass, foo)\n\nif __name__ == '__main__':\n unittest.main()\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/88325", "https://Stackoverflow.com", "https://Stackoverflow.com/users/577/" ]
88,326
<p>Does <a href="http://elmah.github.io/" rel="nofollow noreferrer">ELMAH</a> logged exceptions even when they do not bubble up to the application? I'd like to pop up a message when an exception occurs and still log the exception. Currently I've been putting everything in try catch blocks and spitting out messages, but this gets tedious.</p>
[ { "answer_id": 841426, "author": "Michael La Voie", "author_id": 65843, "author_profile": "https://Stackoverflow.com/users/65843", "pm_score": 7, "selected": false, "text": "try\n{\n int i = 5;\n int j = 0;\n i = i / j; //Throws exception\n}\ncatch (Exception ex)\n{\n MyPersonalHandlingCode(ex);\n ErrorSignal.FromCurrentContext().Raise(ex); //ELMAH Signaling\n}\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/88326", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16891/" ]
88,343
<p>When I try to compile code on VS 2005 and it fails, the line which causes the error gets underlined blue, and mouse-hovering over it displays the error message. Fine, but you can't see object types or whatever, because Intellisense will show the error message, and not object info.</p> <p>In this image, I wanted to see what type <code>DateTime.Subtract()</code> returns, but VS insists on showing the error message:</p> <p><a href="http://img502.imageshack.us/img502/6962/vs2005errordl7.png" rel="nofollow noreferrer">alt text http://img502.imageshack.us/img502/6962/vs2005errordl7.png</a></p> <p>Does anyone know how to get the error message out of the way, <strong>once you've got enough of it</strong>?</p>
[ { "answer_id": 88459, "author": "André Chalella", "author_id": 4850, "author_profile": "https://Stackoverflow.com/users/4850", "pm_score": 0, "selected": false, "text": "View -> IntelliSense -> Quick Info Ctrl+K, Ctrl+I" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/88343", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4850/" ]
88,359
<p>While searching the interweb for a solution for my VB.net problems I often find helpful articles on a specific topic, but the code is C#. That is no big problem but it cost some time to convert it to VB manually. There are some sites that offer code converters from C# to VB and vice versa, but to fix all the flaws after the code-conversion is nearly as time-consuming as doing it by myself in the first place.</p> <p>Till now I am using <a href="http://labs.developerfusion.co.uk/convert/csharp-to-vb.aspx" rel="noreferrer">http://labs.developerfusion.co.uk/convert/csharp-to-vb.aspx</a></p> <p>Do you know something better?</p>
[ { "answer_id": 114152, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 4, "selected": false, "text": "public class FileSystemEventSubscription : EventSubscription\n{\n private FileSystemWatcher fileSystemWatcher;\n\n public FileSystemEventSubscription(IComparable queueName, \n Guid workflowInstanceId, FileSystemWatcher fileSystemWatcher) : base(queueName, workflowInstanceId)\n {\n this.fileSystemWatcher = fileSystemWatcher;\n }\n Public Class FileSystemEventSubscription\n Inherits EventSubscription \n Private myFileSystemWatcher As FileSystemWatcher\n Public Sub New(ByVal QueueName As IComparable, ByVal WorkflowInstanceID As Guid, ByVal Watcher As FileSystemWatcher)\n MyBase.New(QueueName, WorkflowInstanceID)\n Me.myFileSystemWatcher = Watcher\n End Sub\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/88359", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12336/" ]
88,361
<p>I have an Asp.Net repeater, which contains a textbox and a checkbox. I need to add client-side validation that verifies that when the checkbox is checked, the textbox can only accept a value of zero or blank.</p> <p>I would like to use one or more of Asp.Net's validator controls to accomplish this, to provide a consistent display for client side errors (server-side errors are handled by another subsystem).</p> <p>The Asp:CompareValidator doesn't seem to be flexible enough to perform this kind of complex comparison, so I'm left looking at the Asp:CustomValidator.</p> <p>The problem I'm running into is that there doesn't seem to be any way to pass custom information into the validation function. This is an issue because the ClientIds of the checkbox and the textbox are unknown to me at runtime (as they're part of a Repeater).</p> <p>So... My options seem to be:</p> <ol> <li>Pass the textbox and checkbox to the CustomValidator somehow (doesn't seem to be possible).</li> <li>Find the TextBox through JavaScript based on the arguments passed in by the CustomValidator. Is this even possible, what with the ClientId being ambiguous?</li> <li>Forget validation entirely, and emit custom JavaScript (allowing me to pass both ClientIds to a custom function).</li> </ol> <p>Any ideas on what might be a better way of implementing this?</p>
[ { "answer_id": 88386, "author": "Doug Moore", "author_id": 13179, "author_profile": "https://Stackoverflow.com/users/13179", "pm_score": 0, "selected": false, "text": "protected MyDataBound(object sender, RepeaterItemEventArgs e) {\n (CheckBox)cb = (CheckBox)e.Item.FindControl(\"myCheckboxName\");\n (TextBox)tb = (TextBox)e.Item.FindControl(\"myTextBox\");\n}\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/88361", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16911/" ]
88,381
<p>we have several <em>"production environments"</em> (three servers each, with the same version of our system. Each one has a SQL Server Database as production database). </p> <p>In one of this environment the <em>tempdb</em> transaction log starts to grow fast and infinitely, we can´t find why. Same version of SO, SQL Server, application. No changes in the environment.</p> <p>Someone know how to figure what´s happening ou how to fix this?</p>
[ { "answer_id": 88446, "author": "Nick Craver", "author_id": 13249, "author_profile": "https://Stackoverflow.com/users/13249", "pm_score": 0, "selected": false, "text": "DBCC OPENTRAN\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/88381", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
88,399
<p>I saw <a href="https://stackoverflow.com/questions/73319/duplicate-a-whole-line-in-vim#73357">this same question for VIM</a> and it has been something that I myself wanted to know how to do for Emacs. In ReSharper I use CTRL-D for this action. What is the least number of commands to perform this in Emacs?</p>
[ { "answer_id": 88468, "author": "Allen", "author_id": 6043, "author_profile": "https://Stackoverflow.com/users/6043", "pm_score": 2, "selected": false, "text": "kill-whole-line" }, { "answer_id": 88588, "author": "sverrejoh", "author_id": 473, "author_profile": "https://Stackoverflow.com/users/473", "pm_score": 2, "selected": false, "text": "C-a C-k C-k C-y C-y\n" }, { "answer_id": 88737, "author": "Chris Conway", "author_id": 1412, "author_profile": "https://Stackoverflow.com/users/1412", "pm_score": 8, "selected": true, "text": "C-a C-SPACE C-n M-w C-y\n C-a C-SPACE C-n M-w C-y C-a C-k C-k C-y C-y\n C-a C-k C-k C-y C-y C-d C-d delete-char C-c C-d .emacs (global-set-key \"\\C-c\\C-d\" \"\\C-a\\C- \\C-n\\M-w\\C-y\")\n C-c C-d" }, { "answer_id": 88828, "author": "Nate", "author_id": 17009, "author_profile": "https://Stackoverflow.com/users/17009", "pm_score": 7, "selected": false, "text": "(defun duplicate-line()\n (interactive)\n (move-beginning-of-line 1)\n (kill-line)\n (yank)\n (open-line 1)\n (next-line 1)\n (yank)\n)\n(global-set-key (kbd \"C-d\") 'duplicate-line)\n" }, { "answer_id": 167972, "author": "Darron", "author_id": 22704, "author_profile": "https://Stackoverflow.com/users/22704", "pm_score": 3, "selected": false, "text": "copy-from-above-command" }, { "answer_id": 551053, "author": "pw.", "author_id": 66574, "author_profile": "https://Stackoverflow.com/users/66574", "pm_score": 4, "selected": false, "text": " (open-line 1)\n (next-line 1)\n (newline)\n (defun duplicate-line()\n (interactive)\n (move-beginning-of-line 1)\n (kill-line)\n (yank)\n (newline)\n (yank)\n)\n(global-set-key (kbd \"C-d\") 'duplicate-line)\n" }, { "answer_id": 551290, "author": "polyglot", "author_id": 45383, "author_profile": "https://Stackoverflow.com/users/45383", "pm_score": 2, "selected": false, "text": "(setq kill-whole-line t)\n C-a go to beginning of line\nC-k kill-line (i.e. cut the line into clipboard)\nC-y yank (i.e. paste); the first time you get the killed line back; \n second time gives the duplicated line.\n" }, { "answer_id": 890279, "author": "Marius Andersen", "author_id": 110198, "author_profile": "https://Stackoverflow.com/users/110198", "pm_score": 2, "selected": false, "text": "(transient-mark-mode t)\n(defadvice kill-ring-save (before slick-copy activate compile)\n \"When called interactively with no active region, copy a single line instead.\"\n (interactive\n (if mark-active (list (region-beginning) (region-end))\n (message \"Copied line\")\n (list (line-beginning-position)\n (line-beginning-position 2)))))\n(defadvice kill-region (before slick-cut activate compile)\n \"When called interactively with no active region, kill a single line instead.\"\n (interactive\n (if mark-active (list (region-beginning) (region-end))\n (list (line-beginning-position)\n (line-beginning-position 2)))))\n .emacs M-w C-w C-a M-w C-y C-y C-y ..." }, { "answer_id": 959435, "author": "mk-fg", "author_id": 1646435, "author_profile": "https://Stackoverflow.com/users/1646435", "pm_score": 3, "selected": false, "text": "(defun duplicate-line ()\n \"Clone line at cursor, leaving the latter intact.\"\n (interactive)\n (save-excursion\n (let ((kill-read-only-ok t) deactivate-mark)\n (toggle-read-only 1)\n (kill-whole-line)\n (toggle-read-only 0)\n (yank))))\n" }, { "answer_id": 998472, "author": "pesche", "author_id": 3686, "author_profile": "https://Stackoverflow.com/users/3686", "pm_score": 6, "selected": false, "text": "(defun duplicate-line (arg)\n \"Duplicate current line, leaving point in lower line.\"\n (interactive \"*p\")\n\n ;; save the point for undo\n (setq buffer-undo-list (cons (point) buffer-undo-list))\n\n ;; local variables for start and end of line\n (let ((bol (save-excursion (beginning-of-line) (point)))\n eol)\n (save-excursion\n\n ;; don't use forward-line for this, because you would have\n ;; to check whether you are at the end of the buffer\n (end-of-line)\n (setq eol (point))\n\n ;; store the line and disable the recording of undo information\n (let ((line (buffer-substring bol eol))\n (buffer-undo-list t)\n (count arg))\n ;; insert the line arg times\n (while (> count 0)\n (newline) ;; because there is no newline in 'line'\n (insert line)\n (setq count (1- count)))\n )\n\n ;; create the undo information\n (setq buffer-undo-list (cons (cons eol (point)) buffer-undo-list)))\n ) ; end-of-let\n\n ;; put the point in the lowest line and return\n (next-line arg))\n (global-set-key (kbd \"C-d\") 'duplicate-line)\n" }, { "answer_id": 1062326, "author": "Joyer", "author_id": 126671, "author_profile": "https://Stackoverflow.com/users/126671", "pm_score": 2, "selected": false, "text": "duplicate-line (defun jr-duplicate-line ()\n \"EASY\"\n (interactive)\n (save-excursion\n (let ((line-text (buffer-substring-no-properties\n (line-beginning-position)\n (line-end-position))))\n (move-end-of-line 1)\n (newline)\n (insert line-text))))\n (global-set-key \"\\C-cd\" 'jr-duplicate-line)\n" }, { "answer_id": 3206650, "author": "Ray", "author_id": 4872, "author_profile": "https://Stackoverflow.com/users/4872", "pm_score": 6, "selected": false, "text": "kill-line C-k C-a C-k C-k C-y C-y kill-whole-line C-S-Backspace\nC-y\nC-y\n C-k C-k C-k" }, { "answer_id": 3208345, "author": "phils", "author_id": 324105, "author_profile": "https://Stackoverflow.com/users/324105", "pm_score": 2, "selected": false, "text": "(interactive \"*\") (defun duplicate-line ()\n \"Clone line at cursor, leaving the latter intact.\"\n (interactive \"*\")\n (save-excursion\n ;; The last line of the buffer cannot be killed\n ;; if it is empty. Instead, simply add a new line.\n (if (and (eobp) (bolp))\n (newline)\n ;; Otherwise kill the whole line, and yank it back.\n (let ((kill-read-only-ok t)\n deactivate-mark)\n (toggle-read-only 1)\n (kill-whole-line)\n (toggle-read-only 0)\n (yank)))))\n" }, { "answer_id": 3446738, "author": "Karthik", "author_id": 394835, "author_profile": "https://Stackoverflow.com/users/394835", "pm_score": 0, "selected": false, "text": "(defun duplicate-line (&optional arg)\n \"Duplicate it. With prefix ARG, duplicate ARG times.\"\n (interactive \"p\")\n (next-line \n (save-excursion \n (let ((beg (line-beginning-position))\n (end (line-end-position)))\n (copy-region-as-kill beg end)\n (dotimes (num arg arg)\n (end-of-line) (newline)\n (yank))))))\n (defun duplicate-line (&optional arg)\n \"Duplicate it. With prefix ARG, duplicate ARG times.\"\n (interactive \"p\")\n (save-excursion \n (let ((beg (line-beginning-position))\n (end \n (progn (forward-line (1- arg)) (line-end-position))))\n (copy-region-as-kill beg end)\n (end-of-line) (newline)\n (yank)))\n (next-line arg))\n (global-set-key (kbd \"C-S-d\") 'duplicate-line)" }, { "answer_id": 4717026, "author": "qmega", "author_id": 416571, "author_profile": "https://Stackoverflow.com/users/416571", "pm_score": 5, "selected": false, "text": "(defun duplicate-line-or-region (&optional n)\n \"Duplicate current line, or region if active.\nWith argument N, make N copies.\nWith negative N, comment out original line and use the absolute value.\"\n (interactive \"*p\")\n (let ((use-region (use-region-p)))\n (save-excursion\n (let ((text (if use-region ;Get region if active, otherwise line\n (buffer-substring (region-beginning) (region-end))\n (prog1 (thing-at-point 'line)\n (end-of-line)\n (if (< 0 (forward-line 1)) ;Go to beginning of next line, or make a new one\n (newline))))))\n (dotimes (i (abs (or n 1))) ;Insert N times, or once if not specified\n (insert text))))\n (if use-region nil ;Only if we're working with a line (not a region)\n (let ((pos (- (point) (line-beginning-position)))) ;Save column\n (if (> 0 n) ;Comment out original with negative arg\n (comment-region (line-beginning-position) (line-end-position)))\n (forward-line 1)\n (forward-char pos)))))\n C-c d (global-set-key [?\\C-c ?d] 'duplicate-line-or-region)\n C-c" }, { "answer_id": 12119106, "author": "WisdomFusion", "author_id": 191071, "author_profile": "https://Stackoverflow.com/users/191071", "pm_score": 0, "selected": false, "text": ";; http://www.emacswiki.org/emacs/WholeLineOrRegion#toc2\n;; cut, copy, yank\n(defadvice kill-ring-save (around slick-copy activate)\n \"When called interactively with no active region, copy a single line instead.\"\n (if (or (use-region-p) (not (called-interactively-p)))\n ad-do-it\n (kill-new (buffer-substring (line-beginning-position)\n (line-beginning-position 2))\n nil '(yank-line))\n (message \"Copied line\")))\n(defadvice kill-region (around slick-copy activate)\n \"When called interactively with no active region, kill a single line instead.\"\n (if (or (use-region-p) (not (called-interactively-p)))\n ad-do-it\n (kill-new (filter-buffer-substring (line-beginning-position)\n (line-beginning-position 2) t)\n nil '(yank-line))))\n(defun yank-line (string)\n \"Insert STRING above the current line.\"\n (beginning-of-line)\n (unless (= (elt string (1- (length string))) ?\\n)\n (save-excursion (insert \"\\n\")))\n (insert string))\n\n(global-set-key (kbd \"<f2>\") 'kill-region) ; cut.\n(global-set-key (kbd \"<f3>\") 'kill-ring-save) ; copy.\n(global-set-key (kbd \"<f4>\") 'yank) ; paste.\n" }, { "answer_id": 19916232, "author": "linbianxiaocao", "author_id": 2956795, "author_profile": "https://Stackoverflow.com/users/2956795", "pm_score": 0, "selected": false, "text": "C-a C-SPACE C-n M-w C-y\n" }, { "answer_id": 20248584, "author": "Louis Kottmann", "author_id": 677014, "author_profile": "https://Stackoverflow.com/users/677014", "pm_score": 2, "selected": false, "text": "M-w C-a RET C-y\n" }, { "answer_id": 24105783, "author": "kuanyui", "author_id": 1244729, "author_profile": "https://Stackoverflow.com/users/1244729", "pm_score": 1, "selected": false, "text": "(defun duplicate-line ()\n \"Duplicate current line.\"\n (interactive)\n (let ((text (buffer-substring-no-properties (point-at-bol) (point-at-eol)))\n (cur-col (current-column)))\n (end-of-line) (insert \"\\n\" text)\n (beginning-of-line) (right-char cur-col)))\n(global-set-key (kbd \"C-c d l\") 'duplicate-line)\n (defun duplicate-line ()\n \"Duplicate current line.\"\n (interactive)\n (let* ((text (buffer-substring-no-properties (point-at-bol) (point-at-eol)))\n (cur-col (length (buffer-substring-no-properties (point-at-bol) (point)))))\n (end-of-line) (insert \"\\n\" text)\n (beginning-of-line) (right-char cur-col)))\n(global-set-key (kbd \"C-c d l\") 'duplicate-line)\n" }, { "answer_id": 30977209, "author": "yPhil", "author_id": 1729094, "author_profile": "https://Stackoverflow.com/users/1729094", "pm_score": 2, "selected": false, "text": "(defadvice kill-ring-save (before slick-copy activate compile)\n \"When called interactively with no active region, COPY a single line instead.\"\n (interactive\n (if mark-active (list (region-beginning) (region-end))\n (message \"Copied line\")\n (list (line-beginning-position)\n (line-beginning-position 2)))))\n (defadvice kill-region (before slick-cut activate compile)\n \"When called interactively with no active region, KILL a single line instead.\"\n (interactive\n (if mark-active (list (region-beginning) (region-end))\n (message \"Killed line\")\n (list (line-beginning-position)\n (line-beginning-position 2)))))\n (defun move-line-up ()\n \"Move the current line up.\"\n (interactive)\n (transpose-lines 1)\n (forward-line -2)\n (indent-according-to-mode))\n\n(defun move-line-down ()\n \"Move the current line down.\"\n (interactive)\n (forward-line 1)\n (transpose-lines 1)\n (forward-line -1)\n (indent-according-to-mode))\n\n(global-set-key [(meta shift up)] 'move-line-up)\n(global-set-key [(meta shift down)] 'move-line-down)\n" }, { "answer_id": 38338217, "author": "user6581334", "author_id": 6581334, "author_profile": "https://Stackoverflow.com/users/6581334", "pm_score": 2, "selected": false, "text": "(defun duplicate-line ()\n \"Duplicate current line\"\n (interactive)\n (kill-whole-line)\n (yank)\n (yank))\n(global-set-key (kbd \"C-x M-d\") 'duplicate-line)\n" }, { "answer_id": 39643342, "author": "AesopHimself", "author_id": 3648760, "author_profile": "https://Stackoverflow.com/users/3648760", "pm_score": 2, "selected": false, "text": "(defun wrx/duplicate-line-or-region (beg end)\n \"Implements functionality of JetBrains' `Command-d' shortcut for `duplicate-line'.\n BEG & END correspond point & mark, smaller first\n `use-region-p' explained: \n http://emacs.stackexchange.com/questions/12334/elisp-for-applying-command-to-only-the-selected-region#answer-12335\"\n (interactive \"r\")\n (if (use-region-p)\n (wrx/duplicate-region-in-buffer beg end)\n (wrx/duplicate-line-in-buffer)))\n (defun wrx/duplicate-region-in-buffer (beg end)\n \"copy and duplicate context of current active region\n |------------------------+----------------------------|\n | before | after |\n |------------------------+----------------------------|\n | first <MARK>line here | first line here |\n | second item<POINT> now | second item<MARK>line here |\n | | second item<POINT> now |\n |------------------------+----------------------------|\n TODO: Acts funky when point < mark\"\n (set-mark-command nil)\n (insert (buffer-substring beg end))\n (setq deactivate-mark nil))\n (defun wrx/duplicate-line-in-buffer ()\n \"Duplicate current line, maintaining column position.\n |--------------------------+--------------------------|\n | before | after |\n |--------------------------+--------------------------|\n | lorem ipsum<POINT> dolor | lorem ipsum dolor |\n | | lorem ipsum<POINT> dolor |\n |--------------------------+--------------------------|\n TODO: Save history for `Cmd-Z'\n Context: \n http://stackoverflow.com/questions/88399/how-do-i-duplicate-a-whole-line-in-emacs#answer-551053\"\n (setq columns-over (current-column))\n (save-excursion\n (kill-whole-line)\n (yank)\n (yank))\n (let (v)\n (dotimes (n columns-over v)\n (right-char)\n (setq v (cons n v))))\n (next-line))\n (global-set-key (kbd \"M-D\") 'wrx/duplicate-line-or-region)\n" }, { "answer_id": 48330087, "author": "Dodgie", "author_id": 1851813, "author_profile": "https://Stackoverflow.com/users/1851813", "pm_score": 2, "selected": false, "text": "C-3 C-S-o (defun duplicate-lines (arg)\n (interactive \"P\")\n (let* ((arg (if arg arg 1))\n (beg (save-excursion (beginning-of-line) (point)))\n (end (save-excursion (end-of-line) (point)))\n (line (buffer-substring-no-properties beg end)))\n (save-excursion\n (end-of-line)\n (open-line arg)\n (setq num 0)\n (while (< num arg)\n (setq num (1+ num))\n (forward-line 1)\n (insert line))\n )))\n\n(global-set-key (kbd \"C-S-o\") 'duplicate-lines)\n" }, { "answer_id": 52565378, "author": "Andy", "author_id": 1028665, "author_profile": "https://Stackoverflow.com/users/1028665", "pm_score": 1, "selected": false, "text": "<C-S-backspace> C-/ <C-S-backspace> C-/" }, { "answer_id": 53670517, "author": "krsoni", "author_id": 3504244, "author_profile": "https://Stackoverflow.com/users/3504244", "pm_score": 1, "selected": false, "text": "fun duplicate-line ()\n (interactive)\n (let ((col (current-column)))\n (move-beginning-of-line 1)\n (kill-line)\n (yank)\n (newline)\n (yank)\n (move-to-column col)))\n" }, { "answer_id": 58221106, "author": "Dan Garland", "author_id": 875138, "author_profile": "https://Stackoverflow.com/users/875138", "pm_score": 2, "selected": false, "text": "duplicate-line-or-region SPC x l d \n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/88399", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4872/" ]
88,434
<p>I'm trying to build a better username/password field for my workplace and would like to be able to complain when they have their caps lock on.</p> <p>Is this possible? And if so I'd like to have it detected before the client types their first letter.</p> <p>Is there a non-platform specific way to do this?</p>
[ { "answer_id": 88456, "author": "Nick Craver", "author_id": 13249, "author_profile": "https://Stackoverflow.com/users/13249", "pm_score": 6, "selected": true, "text": "Toolkit.getDefaultToolkit().getLockingKeyState(KeyEvent.VK_CAPS_LOCK)\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/88434", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2443/" ]
88,448
<p>I have a public facing application deployed with Flex. I want to switch to using the cached framework (.swz) but need to know if for my user base this is an effective solution or not (most users will only visit the site once and its just not worth it).</p> <p>What I want to do is track whether or not a user has loaded the .swz/.swf file during that session - or if they are using a cached version they had previously downloaded from me or another site. If say 80% of users are downloading the framework .swz then i may as well embed the cutdown framework. But if 60% of users already have the framework I'd rather allow that cached version to be used.</p> <p>The best solution I have now is to look at the web server log and count the .swz file downloads vs. the number of times my main application .swf file is loaded. This is clumsy and a pain and I havent even been able to go to the effort of doing it yet.</p> <p>I cannot seem to find anything indicating what .swz or .swf files are loaded. I'd like to track against the current user session if i can determine this.</p>
[ { "answer_id": 90767, "author": "Seldaek", "author_id": 6512, "author_profile": "https://Stackoverflow.com/users/6512", "pm_score": 0, "selected": false, "text": "grep -c \\.swz web_log_dir/* \ngrep -c \\.swf web_log_dir/*\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/88448", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16940/" ]
88,454
<p>Most of the MVC samples I have seen pass an instance of the view to the controller like this</p> <pre><code>public class View { Controller controller = new Controller(this); } </code></pre> <p>Is there any advantage to passing a class which provides access to just the the properties and events the controller is interested in, like this:</p> <pre><code>public class UIWrapper { private TextBox textBox; public TextBox TextBox { get {return textBox;} } public UIWrapper(ref TextBox textBox) { this.textBox = textBox; } public class View { UIWrapper wrapper = new UIWrapper(this); Controller controller = new Controller(wrapper) } </code></pre>
[ { "answer_id": 90767, "author": "Seldaek", "author_id": 6512, "author_profile": "https://Stackoverflow.com/users/6512", "pm_score": 0, "selected": false, "text": "grep -c \\.swz web_log_dir/* \ngrep -c \\.swf web_log_dir/*\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/88454", "https://Stackoverflow.com", "https://Stackoverflow.com/users/35031/" ]
88,460
<p>I'm trying to use libvirt with virsh to manage my kvm/qemu vms. The problem I have is with getting it to work with public IPs. The server is running ubuntu 8.04.</p> <p>libvirt keeps trying to run it as:</p> <pre><code>/usr/bin/kvm -M pc -m 256 -smp 3 -monitor pty -no-acpi \ -drive file=/opt/virtual-machines/calculon/root.qcow2,if=ide,boot=on \ -net nic,vlan=0,model=virtio -net tap,fd=10,vlan=0 -usb -vnc 127.0.0.1:0 </code></pre> <p>Which boots, but does not have any network access (pings go nowhere). Running it without fd=10 makes it work right, with kvm creating the necessary TAP device for me and networking functioning inside the host. All the setup guides I've seen focus on setting up masquerading, while I just want a simple bridge and unfiltered access to the net (both the guests and host must use public IPs). </p> <p>Running ifconfig on the host gives this, the bridge is manually setup in my /etc/network/interfaces file. :</p> <pre><code>br0 Link encap:Ethernet HWaddr 00:1e:c9:3c:59:b8 inet addr:12.34.56.78 Bcast:12.34.56.79 Mask:255.255.255.240 inet6 addr: fe80::21e:c9ff:fe3c:59b8/64 Scope:Link UP BROADCAST RUNNING MULTICAST MTU:1500 Metric:1 RX packets:3359 errors:0 dropped:0 overruns:0 frame:0 TX packets:3025 errors:0 dropped:0 overruns:0 carrier:0 collisions:0 txqueuelen:0 RX bytes:180646 (176.4 KB) TX bytes:230908 (225.4 KB) eth0 Link encap:Ethernet HWaddr 00:1e:c9:3c:59:b8 inet6 addr: fe80::21e:c9ff:fe3c:59b8/64 Scope:Link UP BROADCAST RUNNING MULTICAST MTU:1500 Metric:1 RX packets:6088386 errors:0 dropped:0 overruns:0 frame:0 TX packets:3058 errors:0 dropped:0 overruns:0 carrier:0 collisions:0 txqueuelen:1000 RX bytes:680236624 (648.7 MB) TX bytes:261696 (255.5 KB) Interrupt:33 </code></pre> <p>Any help would be greatly appreciated.</p>
[ { "answer_id": 90689, "author": "AgentK", "author_id": 14868, "author_profile": "https://Stackoverflow.com/users/14868", "pm_score": 4, "selected": true, "text": "auto eth0\niface eth0 inet manual\n\nauto br0\niface br0 inet static\n address 192.168.0.10\n network 192.168.0.0\n netmask 255.255.255.0\n broadcast 192.168.0.255\n gateway 192.168.0.1\n bridge_ports eth0\n bridge_fd 9\n bridge_hello 2\n bridge_maxage 12\n bridge_stp off\n /usr/bin/kvm -M pc -no-kqemu -m 256 -smp 1 -monitor pty -boot c -hda \\\n /libvirt/apt.img -net nic,macaddr=00:16:3e:77:32:1d,vlan=0 -net \\\n tap,fd=11,script=,vlan=0 -usb -vnc 127.0.0.1:0\n <interface type='bridge'>\n <mac address='00:16:3e:77:32:1d'/>\n <source bridge='br0'/>\n</interface>\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/88460", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11105/" ]
88,471
<p>I have searched for such a plugin but haven't found any. I need a facility to "tag" my java files. Similar to tagging on stackoverflow.</p> <p>I want to be able to group my files based on projects/tasks I wam working on. Mylyn helps a little but it dynamically changes the context (list of resources associated with a task) based on various factors. </p> <p>I just want a basic tagging facility for all the files in my workspace.</p>
[ { "answer_id": 97820, "author": "Scott Stanchfield", "author_id": 12541, "author_profile": "https://Stackoverflow.com/users/12541", "pm_score": 0, "selected": false, "text": "public interface Observer {} // no required methods\n public class SomeClass implements Observer {...}\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/88471", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
88,473
<p>Does anybody know how to apply a "where in values" type condition using LINQ-to-Entities? I've tried the following but it doesn't work:</p> <pre><code>var values = new[] { "String1", "String2" }; // some string values var foo = model.entitySet.Where(e =&gt; values.Contains(e.Name)); </code></pre> <p>I believe this works in LINQ-to-SQL though? Any thoughts?</p>
[ { "answer_id": 88486, "author": "Aaron Powell", "author_id": 11388, "author_profile": "https://Stackoverflow.com/users/11388", "pm_score": 0, "selected": false, "text": "SELECT [t0].[col1]\nFROM [table] [t0]\nWHERE [col1] IN ( 'Value 1', 'Value 2')\n" }, { "answer_id": 88495, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "var results = from p in db.Products\n\n where p.Name == nameTextBox.Text\n\n select p;\n" }, { "answer_id": 88645, "author": "Michael Brown", "author_id": 14359, "author_profile": "https://Stackoverflow.com/users/14359", "pm_score": 4, "selected": false, "text": "var listOfIds=GetAListOfIds();\nvar context=CreateEntityFrameworkObjectContext();\nvar results = from item in context.Items\n where listOfIds.Contains(item.Category.Id)\n select item;\n//results contains the items with matching category Ids\n" }, { "answer_id": 2543363, "author": "Changgyu Oh", "author_id": 304851, "author_profile": "https://Stackoverflow.com/users/304851", "pm_score": 1, "selected": false, "text": "var ids = \"12, 34, 35\";\nusing (context = new Entites())\n{\n var selectedProducts = context.CreateQuery<Products>(\n String.Format(\"select value p from [Entities].Products as p \n where p.productId in {{{0}}}\", ids)).ToList();\n ...\n}\n" }, { "answer_id": 4759633, "author": "Lucian", "author_id": 158246, "author_profile": "https://Stackoverflow.com/users/158246", "pm_score": 1, "selected": false, "text": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Linq.Expressions;\nusing System.Data.Objects;\n\nnamespace Sample {\n public static class Extensions {\n public static IQueryable<T> ExtWhereIn<T, TValue>(this ObjectQuery<T> query,\n Expression<Func<T, TValue>> valueSelector,\n IEnumerable<TValue> values) {\n return query.Where(BuildContainsExpression<T, TValue>(valueSelector, values));\n }\n public static IQueryable<T> ExtWhereIn<T, TValue>(this IQueryable<T> query,\n Expression<Func<T, TValue>> valueSelector,\n IEnumerable<TValue> values) {\n return query.Where(BuildContainsExpression<T, TValue>(valueSelector, values));\n }\n private static Expression<Func<TElement, bool>> BuildContainsExpression<TElement, TValue>(\n Expression<Func<TElement, TValue>> valueSelector, IEnumerable<TValue> values) {\n if (null == valueSelector) { throw new ArgumentNullException(\"valueSelector\"); }\n if (null == values) { throw new ArgumentNullException(\"values\"); }\n ParameterExpression p = valueSelector.Parameters.Single();\n // p => valueSelector(p) == values[0] || valueSelector(p) == ...\n if (!values.Any()) {\n return e => false;\n }\n var equals = values.Select(value => (Expression)Expression.Equal(valueSelector.Body, Expression.Constant(value, typeof(TValue))));\n var body = equals.Aggregate<Expression>((accumulate, equal) => Expression.Or(accumulate, equal));\n return Expression.Lambda<Func<TElement, bool>>(body, p);\n }\n }\n class Program {\n static void Main(string[] args) {\n List<int> fullList = new List<int>();\n for (int i = 0; i < 20; i++) {\n fullList.Add(i);\n }\n\n List<int> filter = new List<int>();\n filter.Add(2);\n filter.Add(5);\n filter.Add(10);\n\n List<int> results = fullList.AsQueryable().ExtWhereIn<int, int>(item => item, filter).ToList();\n foreach (int result in results) {\n Console.WriteLine(result);\n }\n }\n } \n}\n class Product {\n public int Id { get; set; }\n /// ... other properties\n}\n\n\nList<Product> GetProducts(List<int> productIds) { \n using (MyEntities context = new MyEntities()) {\n return context.Products.ExtWhereIn<Product, int>(product => product.Id, productIds).ToList();\n }\n}\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/88473", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16948/" ]
88,476
<p>I'm a little hesitant to post this, as I'm not completely sure what I'm doing. Any help would be wonderful.</p> <p>I'm on a computer with a firewall/filter on it. I can download files without any difficulty. When I try to clone files from Github, though, the computer just hangs. Nothing happens. It creates a git file in the folder, but the key files don't get loaded in. For context, I'm working on a Rails app, trying to load in Restful Authentication.</p> <p>Have any of you dealt with this? Any suggestions for getting the clone to work? Disabling the firewall might be an option, but if I can do something without going through that process, I'd appreciate it.</p>
[ { "answer_id": 88492, "author": "Greg Hewgill", "author_id": 893, "author_profile": "https://Stackoverflow.com/users/893", "pm_score": 2, "selected": false, "text": "git://" }, { "answer_id": 2382585, "author": "rogerdpack", "author_id": 32453, "author_profile": "https://Stackoverflow.com/users/32453", "pm_score": 3, "selected": false, "text": "$ ssh username@some_host_not_firewalled -L9418:github.com:9418\n $ git clone git://github.com/jruby/jruby.git\n $ git clone git://localhost/jruby/jruby.git\n $ git config --global url.git://localhost/.insteadOf git://github.com/\n" }, { "answer_id": 34379154, "author": "Buddhi Kasun", "author_id": 4777170, "author_profile": "https://Stackoverflow.com/users/4777170", "pm_score": 0, "selected": false, "text": "git config --global url.\"https://\".insteadOf git://\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/88476", "https://Stackoverflow.com", "https://Stackoverflow.com/users/69299/" ]
88,481
<p>I see that Adobe AIR uses WebKit as its render and I see that WebKit (at least the most current build) has some SVG support. Does this mean (and has anyone specifically tried) that an Adobe AIR application could render SVG on an HTML page?</p>
[ { "answer_id": 227999, "author": "aaaidan", "author_id": 26331, "author_profile": "https://Stackoverflow.com/users/26331", "pm_score": 2, "selected": false, "text": "[Embed(source=\"assets/frog.svg\")]\n[Bindable]\npublic var SvgAsset:Class;\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/88481", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8256/" ]
88,485
<p>This is a follow up question to <a href="https://stackoverflow.com/questions/85815/how-to-tell-if-a-javascript-function-is-defined">This Question</a>. </p> <p>I like (and understand) the solution there. However, in the code I am working in, another way to solve the same problem is used:</p> <pre><code>function exist(sFN) { if(self[sFN]) return true; return false; } </code></pre> <p>It seems to work fine, although I don't understand how. Does it work? How? What are minuses of this approach? Should I switch to solution from the other question?</p>
[ { "answer_id": 88498, "author": "kch", "author_id": 13989, "author_profile": "https://Stackoverflow.com/users/13989", "pm_score": 2, "selected": false, "text": "typeof typeof(foobar) // -> undefined\ntypeof(alert) // -> function\n function isfun(sym) { return typeof(sym) } isfun(inexistent) typeof function isfun(identifier) {\n return typeof(window[identifier]) == 'function';\n}\n isfun('alert'); // -> true\nisfun('foobar'); // -> false\n false (function closure() { \n function enclosed() {}\n print(isfun('enclosed'))\n})()\n" }, { "answer_id": 88499, "author": "Nick Craver", "author_id": 13249, "author_profile": "https://Stackoverflow.com/users/13249", "pm_score": 3, "selected": false, "text": "function exist(sFN) {\n return (typeof sFN == 'function');\n}\n" }, { "answer_id": 88576, "author": "Tim Booker", "author_id": 10046, "author_profile": "https://Stackoverflow.com/users/10046", "pm_score": 0, "selected": false, "text": "function bob()\n{}\n\nif( typeof bob == \"function\" )\n alert( \"bob exists\" );\n\nif( typeof dave != \"function\" )\n alert( \"dave doesn't\" );\n" }, { "answer_id": 228703, "author": "Jrgns", "author_id": 6681, "author_profile": "https://Stackoverflow.com/users/6681", "pm_score": -1, "selected": false, "text": "if (window.my_func_name) {\n my_func_name('tester!');\n}\n if (window.opener.my_func_name) {\n my_func_name('tester!');\n}\n function function_exists(func_name) {\n var eval_string;\n if (window.opener) {\n eval_string = 'window.opener.' + func_name;\n } else {\n eval_string = 'window.' + func_name;\n }\n return eval(eval_string + ' ? true : false');\n}\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/88485", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2515/" ]
88,488
<p>Is there a way to get a <code>DrawingContext</code> (or something similar) for a <code>WriteableBitmap</code>? I.e. something to allow you to call simple <code>DrawLine</code>/<code>DrawRectangle</code>/etc kinds of methods, rather than manipulate the raw pixels directly.</p>
[ { "answer_id": 88531, "author": "user7116", "author_id": 7116, "author_profile": "https://Stackoverflow.com/users/7116", "pm_score": 3, "selected": false, "text": "DrawingVisual drawingVisual = new DrawingVisual();\nusing (DrawingContext drawingContext = drawingVisual.RenderOpen())\n{\n //\n // ... draw on the drawingContext\n //\n RenderTargetBitmap bmp = new RenderTargetBitmap(width, height, dpi, dpi, PixelFormats.Default);\n bmp.Render(drawingVisual);\n image.Source = bmp;\n}\n" }, { "answer_id": 797519, "author": "Danko Durbić", "author_id": 19241, "author_profile": "https://Stackoverflow.com/users/19241", "pm_score": 4, "selected": false, "text": "System.Drawing var wb = new WriteableBitmap( width, height, dpi, dpi, \n PixelFormats.Pbgra32, null );\nwb.Lock();\nvar bmp = new System.Drawing.Bitmap( wb.PixelWidth, wb.PixelHeight,\n wb.BackBufferStride, \n PixelFormat.Format32bppPArgb, \n wb.BackBuffer );\n\nGraphics g = System.Drawing.Graphics.FromImage( bmp ); // Good old Graphics\n\ng.DrawLine( ... ); // etc...\n\n// ...and finally:\ng.Dispose(); \nbmp.Dispose();\nwb.AddDirtyRect( ... );\nwb.Unlock(); \n" }, { "answer_id": 869767, "author": "Daniel Wolf", "author_id": 52041, "author_profile": "https://Stackoverflow.com/users/52041", "pm_score": 5, "selected": false, "text": "public static BitmapSource CreateBitmap(\n int width, int height, double dpi, Action<DrawingContext> render)\n{\n DrawingVisual drawingVisual = new DrawingVisual();\n using (DrawingContext drawingContext = drawingVisual.RenderOpen())\n {\n render(drawingContext);\n }\n RenderTargetBitmap bitmap = new RenderTargetBitmap(\n width, height, dpi, dpi, PixelFormats.Default);\n bitmap.Render(drawingVisual);\n\n return bitmap;\n}\n BitmapSource image = ImageTools.CreateBitmap(\n 320, 240, 96,\n drawingContext =>\n {\n drawingContext.DrawRectangle(\n Brushes.Green, null, new Rect(50, 50, 200, 100));\n drawingContext.DrawLine(\n new Pen(Brushes.White, 2), new Point(0, 0), new Point(320, 240));\n });\n" }, { "answer_id": 44424307, "author": "David Jeske", "author_id": 519568, "author_profile": "https://Stackoverflow.com/users/519568", "pm_score": 1, "selected": false, "text": "RenderTargetBitmap WriteableBitmap // create the backing store in a constructor\nvar backingStore = \n new RenderTargetBitmap(200,200,97,97,PixelFormats.Pbgra32);\nmyImage.Source = backingStore;\n\n// whenever you want to update the bitmap, do:\nvar drawingVisual = new DrawingVisual();\nvar drawingContext = drawingVisual.RenderOpen();\n{\n // your drawing commands go here\n drawingContext.DrawRectangle(\n Brushes.Red, new Pen(),\n new Rect(this.RenderSize));\n}\nRender(drawingContext);\ndrawingContext.Close();\nbackingStore.Render(drawingVisual);\n RenderTargetBitmap CompositionTarget.Rendering CompositionTarget.Rendering += MyRenderingHandler;\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/88488", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2495/" ]
88,489
<p><strong>Keep in mind that I'm not looking for a list of current browsers to support, I'm looking for logical ways to make that list, backed by some kind of hard statistics.</strong> </p> <p>Since it's been a while since my last web job, I decided to do this latest site up from scratch. Now I have to decide <em>again</em> what to support in terms of browsers. Certainly I have a list of what I'd like to support, but the decisions that went into that list seem to be a little arbitrary to me. Where can I go to get a reliable picture of browser usage and what seems to be a good point at which to cut off an old version of a browser from support?</p>
[ { "answer_id": 88538, "author": "Jim", "author_id": 8427, "author_profile": "https://Stackoverflow.com/users/8427", "pm_score": 6, "selected": true, "text": "alt" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/88489", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16398/" ]
88,490
<p>Is there a difference between just saying <code>throw;</code> and <code>throw ex;</code> assuming <code>ex</code> is the exception you're catching?</p>
[ { "answer_id": 88502, "author": "GEOCHET", "author_id": 5640, "author_profile": "https://Stackoverflow.com/users/5640", "pm_score": 6, "selected": true, "text": "throw ex; throw;" }, { "answer_id": 88577, "author": "Eric Schoonover", "author_id": 3957, "author_profile": "https://Stackoverflow.com/users/3957", "pm_score": 4, "selected": false, "text": "throw ex; using System;\n\nnamespace StackOverflowMess\n{\n class Program\n {\n static void TestMethod()\n {\n throw new NotImplementedException();\n }\n\n static void Main(string[] args)\n {\n try\n {\n //example showing the output of throw ex\n try\n {\n TestMethod();\n }\n catch (Exception ex)\n {\n throw ex;\n }\n }\n catch (Exception ex)\n {\n Console.WriteLine(ex.ToString());\n }\n\n Console.WriteLine();\n Console.WriteLine();\n\n try\n {\n //example showing the output of throw\n try\n {\n TestMethod();\n }\n catch (Exception ex)\n {\n throw;\n }\n }\n catch (Exception ex)\n {\n Console.WriteLine(ex.ToString());\n }\n\n Console.ReadLine();\n }\n }\n}\n System.NotImplementedException: The method or operation is not implemented. at StackOverflowMess.Program.Main(String[] args) in Program.cs:line 23 System.NotImplementedException: The method or operation is not implemented. at StackOverflowMess.Program.TestMethod() in Program.cs:line 9 at StackOverflowMess.Program.Main(String[] args) in Program.cs:line 43" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/88490", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16891/" ]
88,518
<p>I'm a complete perl novice, am running a perl script using perl 5.10 and getting this warning: </p> <pre><code>$* is no longer supported at migrate.pl line 380. </code></pre> <p>Can anyone describe what $* did and what the recommended replacement of it is now? Alternatively if you could point me to documentation that describes this that would be great.</p> <p>The script I'm running is to migrate a source code database from vss to svn and can be found here: <a href="http://www.x2systems.com/files/migrate.pl.txt" rel="noreferrer">http://www.x2systems.com/files/migrate.pl.txt</a></p> <p>The two snippets of code that use it are: </p> <pre><code> $* = 1; $/ = ':'; $cmd = $SSCMD . " Dir -I- \"$proj\""; $_ = `$cmd`; # what this next expression does is to merge wrapped lines like: # $/DeviceAuthority/src/com/eclyptic/networkdevicedomain/deviceinterrogator/excep # tion: # into: # $/DeviceAuthority/src/com/eclyptic/networkdevicedomain/deviceinterrogator/exception: s/\n((\w*\-*\.*\w*\/*)+\:)/$1/g; $* = 0; </code></pre> <p>and then some ways later on: </p> <pre><code> $cmd = $SSCMD . " get -GTM -W -I-Y -GL\"$localdir\" -V$version \"$file\" 2&gt;&amp;1"; $out = `$cmd`; # get rid of stupid VSS warning messages $* = 1; $out =~ s/\n?Project.*rebuilt\.//g; $out =~ s/\n?File.*rebuilt\.//g; $out =~ s/\n.*was moved out of this project.*rebuilt\.//g; $out =~ s/\nContinue anyway.*Y//g; $* = 0; </code></pre> <p>many thanks, </p> <ul> <li>Rory</li> </ul>
[ { "answer_id": 88528, "author": "Leon Timmermans", "author_id": 4727, "author_profile": "https://Stackoverflow.com/users/4727", "pm_score": 1, "selected": false, "text": "m s s/\\n?Project.*rebuilt\\.//msg\n" }, { "answer_id": 88540, "author": "Michael Carman", "author_id": 8233, "author_profile": "https://Stackoverflow.com/users/8233", "pm_score": 2, "selected": false, "text": "$* local" }, { "answer_id": 88544, "author": "Axeman", "author_id": 11289, "author_profile": "https://Stackoverflow.com/users/11289", "pm_score": 5, "selected": true, "text": " $haystack =~ m/.../sm;\n qr/(?ms-ix:$expr)/;\n s/\\n((\\w*\\-*\\.*\\w*\\/*)+\\:)/$1/gsm;\n" }, { "answer_id": 88578, "author": "Notitze", "author_id": 9411, "author_profile": "https://Stackoverflow.com/users/9411", "pm_score": 2, "selected": false, "text": "$* $* * ^ $ $* == 0 $* /s /m $* $* $* == 0 $*" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/88518", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8479/" ]
88,522
<p>I wanting to show prices for my products in my online store. I'm currently doing:</p> <pre><code>&lt;span class="ourprice"&gt; &lt;%=GetPrice().ToString("C")%&gt; &lt;/span&gt; </code></pre> <p>Where GetPrice() returns a decimal. So this currently returns a value e.g. "£12.00"</p> <p>I think the correct HTML for an output of "£12.00" is "<code>&amp;pound;12.00</code>", so although this is rendering fine in most browsers, some browsers (Mozilla) show this as $12.00. </p> <p>(The server is in the UK, with localisation is set appropriately in web.config).</p> <p>Is the below an improvement, or is there a better way?</p> <pre><code>&lt;span class="ourprice"&gt; &lt;%=GetPrice().ToString("C").Replace("£","&amp;pound;")%&gt; &lt;/span&gt; </code></pre>
[ { "answer_id": 88535, "author": "Nick Craver", "author_id": 13249, "author_profile": "https://Stackoverflow.com/users/13249", "pm_score": 2, "selected": false, "text": "<%=String.Format(\"{0:C}\",GetPrice())%>\n" }, { "answer_id": 88555, "author": "Claus Thomsen", "author_id": 15555, "author_profile": "https://Stackoverflow.com/users/15555", "pm_score": 2, "selected": false, "text": "GetPrice().ToString(\"C\", CultureInfo.CreateSpecificCulture(\"en-GB\"))\n" }, { "answer_id": 91463, "author": "martin", "author_id": 8421, "author_profile": "https://Stackoverflow.com/users/8421", "pm_score": 3, "selected": true, "text": "<globalization culture=\"auto:en-us\" uiCulture=\"auto:en-US\" />\n <globalization culture=\"us\" uiCulture=\"en-gb\" />\n <%@Page Culture=\"en-gb\" UICulture=\"en-gb\" ..etc... %>\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/88522", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11538/" ]
88,541
<p>I’ve been reading a few questions and answers regarding exceptions and their use. Seems to be a strong opinion that exceptions should be raised only for exception, unhandled cases. So that lead me to wondering how validation works with business objects.</p> <p>Lets say I have a business object with getters/setters for the properties on the object. Let’s say I need to validate that the value is between 10 and 20. This is a business rule so it belongs in my business object. So that seems to imply to me that the validation code goes in my setter. Now I have my UI databound to the properties of the data object. The user enters 5, so the rule needs to fail and the user is not allowed to move out of the textbox. . The UI is databound to the property so the setter is going to be called, rule checked and failed. If I raised an exception from my business object to say the rule failed, the UI would pick that up. But that seems to go against the preferred usage for exceptions. Given that it’s a setter, you aren’t really going to have a ‘result’ for the setter. If I set another flag on the object then that would imply the UI has to check that flag after each UI interaction.</p> <p>So how should the validation work?</p> <p>Edit: I've probably used an over-simplified example here. Something like the range check above could be handled easily by the UI but what if the valdation was more complicated, e.g. the business object calculates a number based on the input and if that calculated number is out of range it should be recjected. This is more complicated logic that should not be in th UI. </p> <p>There is also the consideration of further data entered based on a field already entered. e.g.I have to enter an item on the order to get certain informaion like stock on hand, current cost, etc. The user may require this information to make decisions on further entry (liek how many units to order) or it may be required in order for further validation to be done. Should a user be able to enter other fields if the item isn't valid? What would be the point?</p>
[ { "answer_id": 88733, "author": "Matt Howells", "author_id": 16881, "author_profile": "https://Stackoverflow.com/users/16881", "pm_score": 2, "selected": false, "text": "[MinValue(10), MaxValue(20)]\npublic int Value { get; set; }\n" }, { "answer_id": 88770, "author": "Rob Gray", "author_id": 5691, "author_profile": "https://Stackoverflow.com/users/5691", "pm_score": 2, "selected": false, "text": "using Microsoft.Practices.EnterpriseLibrary.Validation;\nusing Microsoft.Practices.EnterpriseLibrary.Validation.Validators;\npublic class Customer\n{\n [StringLengthValidator(0, 20)]\n public string CustomerName;\n\n public Customer(string customerName)\n {\n this.CustomerName = customerName;\n }\n}\n" }, { "answer_id": 133045, "author": "Mac", "author_id": 8696, "author_profile": "https://Stackoverflow.com/users/8696", "pm_score": 4, "selected": false, "text": "Name try/catch try/catch" }, { "answer_id": 398124, "author": "foson", "author_id": 22539, "author_profile": "https://Stackoverflow.com/users/22539", "pm_score": 2, "selected": false, "text": "AllowValidate EnableAllowFocusChange private void textBox1_Validating(object sender, CancelEventArgs e)\n {\n if (textBox1.Text != String.Empty)\n {\n errorProvider1.SetError(sender as Control, \"Can not be empty\");\n e.Cancel = true;\n }\n else\n {\n errorProvider1.SetError(sender as Control, \"\");\n }\n }\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/88541", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11355/" ]
88,546
<p>In Perl, a conditional can be expressed either as</p> <pre><code>if (condition) { do something } </code></pre> <p>or as</p> <pre><code>(condition) and do { do something } </code></pre> <p>Interestingly, the second way seems to be about 10% faster. Does anyone know why?</p>
[ { "answer_id": 88611, "author": "Leon Timmermans", "author_id": 4727, "author_profile": "https://Stackoverflow.com/users/4727", "pm_score": 4, "selected": false, "text": "LISTOP (0x8177a18) leave [1] \n OP (0x8176590) enter \n COP (0x8177a40) nextstate \n LISTOP (0x8177b20) scope \n OP (0x81779b8) null [174] \n UNOP (0x8177c40) dofile \n SVOP (0x8177b58) const [1] PV (0x81546e4) \"something\" \n LISTOP (0x8177b28) leave [1] \n OP (0x8176598) enter \n COP (0x8177a48) nextstate \n UNOP (0x8177980) null \n LISTOP (0x8177ca0) scope \n OP (0x81779c0) null [174] \n UNOP (0x8177c48) dofile \n SVOP (0x8177b60) const [1] PV (0x81546e4) \"something\"\n" }, { "answer_id": 88937, "author": "shelfoo", "author_id": 3444, "author_profile": "https://Stackoverflow.com/users/3444", "pm_score": 2, "selected": false, "text": "\nuse Benchmark;\n\ntimethese(10000000, {\n 'if' => '$m=5;if($m > 4){my $i=0;}',\n 'and' => '$m=5; $m > 4 and do {my $i =0}',\n});\n \nBenchmark: timing 10000000 iterations of Name1, Name2...\n if: 3 wallclock secs ( 2.94 usr + 0.01 sys = 2.95 CPU) @ 3389830.51/s (n=10000000)\n and: 3 wallclock secs ( 3.01 usr + 0.01 sys = 3.02 CPU) @ 3311258.28/s (n=10000000)\n" }, { "answer_id": 91147, "author": "ysth", "author_id": 17389, "author_profile": "https://Stackoverflow.com/users/17389", "pm_score": 4, "selected": false, "text": "$ perl -MO=Concise,-exec -e'($condition) and do { do something }'\n1 <0> enter \n2 <;> nextstate(main 2 -e:1) v\n3 <#> gvsv[*condition] s\n4 <|> and(other->5) vK/1\n5 <$> const[PV \"something\"] s/BARE\n6 <1> dofile vK/1\n7 <@> leave[1 ref] vKP/REFC\n-e syntax OK\n$ perl -MO=Concise,-exec -e'if ($condition) { do something }'\n1 <0> enter \n2 <;> nextstate(main 3 -e:1) v\n3 <#> gvsv[*condition] s\n4 <|> and(other->5) vK/1\n5 <$> const[PV \"something\"] s/BARE\n6 <1> dofile vK/1\n7 <@> leave[1 ref] vKP/REFC\n-e syntax OK\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/88546", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
88,554
<p>In <em>C++</em>, I can have take input like this: </p> <pre><code>cin &gt;&gt; a &gt;&gt; b &gt;&gt; c; </code></pre> <p>And <code>a</code> can be <code>int</code>, <code>b</code> can be <code>float</code>, and <code>c</code> can be whatever... How do I do the same in <em>python</em>?</p> <p><code>input()</code> and <code>raw_input()</code>, the way I'm using them, don't seem to be giving me the desired results.</p>
[ { "answer_id": 88587, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "input() int float >>> line = raw_input().split()\n>>> a = int(line[0])\n>>> b = float(line[1])\n>>> c = \" \".join(line[2:])\n try: ... except (ValueError, IndexError):" }, { "answer_id": 88714, "author": "S.Lott", "author_id": 10661, "author_profile": "https://Stackoverflow.com/users/10661", "pm_score": 2, "selected": false, "text": "import sys\ntokens= sys.stdin.read().split()\ntry:\n a= int(token[0])\n b= float(token[1])\nexcept ValueError, e:\n print e # handle the invalid input\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/88554", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10096/" ]
88,558
<p>I am making a game in C++ and am having problems with my derived class. I have a base class called GameScreen which has a vitrual void draw() function with no statements. I also have a derived class called MenuScreen which also has a virtual void draw() function and a derived class from MenuScreen called TestMenu which also has a void draw() function. In my program I have a list of GameScreens that I have a GameScreen iterator pass through calling each GameScreens draw() function.</p> <p>The issue is that I have placed a TestMenu object on the GameScreen list. Instead of the iterator calling the draw() function of TestMenu it is calling the draw() function of the GameScreen class. Does anyone know how I could call the draw() function of TestMenu instead of the one in GameScreen.</p> <p>Here is the function:</p> <pre><code>// Tell each screen to draw itself. //gsElement is a GameScreen iterator //gsScreens is a list of type GameScreen void Draw() { for (gsElement = gsScreens.begin(); gsElement != gsScreens.end(); gsElement++) { /*if (gsElement-&gt;ssState == Hidden) continue;*/ gsElement-&gt;Draw(); } } </code></pre> <p>Here are a copy of my classes:</p> <pre><code>class GameScreen { public: string strName; bool bIsPopup; bool bOtherScreenHasFocus; ScreenState ssState; //ScreenManager smScreenManager; GameScreen(string strName){ this-&gt;strName = strName; } //Determine if the screen should be drawn or not bool IsActive(){ return !bOtherScreenHasFocus &amp;&amp; (ssState == Active); } //------------------------------------ //Load graphics content for the screen //------------------------------------ virtual void LoadContent(){ } //------------------------------------ //Unload content for the screen //------------------------------------ virtual void UnloadContent(){ } //------------------------------------------------------------------------- //Update changes whether the screen should be updated or not and sets //whether the screen should be drawn or not. // //Input: // bOtherScreenHasFocus - is used set whether the screen should update // bCoveredByOtherScreen - is used to set whether the screen is drawn or not //------------------------------------------------------------------------- virtual void Update(bool bOtherScreenHasFocus, bool bCoveredByOtherScreen){ this-&gt;bOtherScreenHasFocus = bOtherScreenHasFocus; //if the screen is covered by another than change the screen state to hidden //else set the screen state to active if(bCoveredByOtherScreen){ ssState = Hidden; } else{ ssState = Active; } } //----------------------------------------------------------- //Takes input from the mouse and calls appropriate actions //----------------------------------------------------------- virtual void HandleInput(){ } //---------------------- //Draw content on screen //---------------------- virtual void Draw(){ } //-------------------------------------- //Deletes screen from the screen manager //-------------------------------------- void ExitScreen(){ //smScreenManager.RemoveScreen(*this); } }; class MenuScreen: public GameScreen{ public: vector &lt;BUTTON&gt; vbtnMenuEntries; MenuScreen(string strName):GameScreen(strName){ } virtual void Update(bool bOtherScreenHasFocus, bool bCoveredByOtherScreen){ GameScreen::Update(bOtherScreenHasFocus, bCoveredByOtherScreen); for(unsigned int i = 0; i &lt; vbtnMenuEntries.size(); i++){ vbtnMenuEntries[i].IsPressed(); } } virtual void Draw(){ GameScreen::Draw(); for(unsigned int i = 0; i &lt; vbtnMenuEntries.size(); i++) vbtnMenuEntries[i].Draw(); } }; class testMenu : public MenuScreen{ public: vector&lt;OBJECT&gt; test; //OBJECT background3(); // OBJECT testPic(512, 384, buttonHover.png, 100, 40, 100, 40); // BUTTON x(256, 384, buttonNormal.png, buttonHover.png, buttonPressed.png, 100, 40, test()); bool draw; testMenu():MenuScreen("testMenu"){ OBJECT background3(1, 1, 0, TEXT("background.png"), 1, 1, 1024, 768); OBJECT testPic(512, 384,0, TEXT("buttonHover.png"), 1, 1, 100, 40); test.push_back(background3); test.push_back(testPic); //background3.Init(int xLoc, int yLoc, int zLoc, LPCTSTR filePath, int Rows, int Cols, int Width, int Height) //test.push_back(background3); // vbtnMenuEntries.push_back(x); draw = false; } void Update(bool bOtherScreenHasFocus, bool bCoveredByOtherScreen){ MenuScreen::Update(bOtherScreenHasFocus, bCoveredByOtherScreen); //cout &lt;&lt; "X" &lt;&lt; endl; /*if(MouseLButton == true){ testMenu2 t; smManager.AddScreen(t); }*/ } void Draw(){ //background3.Draw(); test[0].Draw(); test[1].Draw(); MenuScreen::Draw(); ///*if(draw){*/ // testPic.Draw(); //} } /*void test(){ draw = true; }*/ }; </code></pre>
[ { "answer_id": 90612, "author": "Johann Gerell", "author_id": 6345, "author_profile": "https://Stackoverflow.com/users/6345", "pm_score": 1, "selected": false, "text": "std::vector<> #include <vector>\n#include <algorithm>\n\nstruct Base\n{\n virtual void Foo() = 0;\n virtual ~Base() { }\n};\n\nstruct Derived1 : public Base\n{\n void Foo() { }\n};\n\nstruct Derived2 : public Base\n{\n void Foo() { }\n};\n\nstruct delete_ptr\n{\n template <typename T>\n void operator()(T& p)\n {\n delete p;\n p = 0;\n }\n};\n\nint wmain(int, wchar_t*[])\n{\n std::vector<Base*> items;\n items.push_back(new Derived1);\n items.push_back(new Derived2);\n\n Base& first = items.front();\n first.Foo(); // Will boil down to Derived1::Foo().\n\n Base& last = items.back();\n last.Foo(); // Will boil down to Derived2::Foo().\n\n std::for_each(items.begin(), items.end(), delete_ptr())\n};\n" }, { "answer_id": 90634, "author": "Roger Lipscombe", "author_id": 8446, "author_profile": "https://Stackoverflow.com/users/8446", "pm_score": 0, "selected": false, "text": "#define DISALLOW_COPYING(X) \\\n private: \\\n X(const X &); \\\n const X& operator= (const X& x)\n class Foo {\n // ...\n DISALLOW_COPYING(Foo);\n};\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/88558", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
88,566
<p>In a custom module for drupal 4.7 I hacked together a node object and passed it to node_save($node) to create nodes. This hack appears to no longer work in drupal 6. While I'm sure this hack could be fixed I'm curious if there is a standard solution to create nodes without a form. In this case the data is pulled in from a custom feed on another website.</p>
[ { "answer_id": 88876, "author": "calebbrown", "author_id": 7007, "author_profile": "https://Stackoverflow.com/users/7007", "pm_score": 4, "selected": true, "text": "node_add() node_form() node_object_prepare()" }, { "answer_id": 90437, "author": "William OConnor - csevb10", "author_id": 10084, "author_profile": "https://Stackoverflow.com/users/10084", "pm_score": 4, "selected": false, "text": "\n$form_id = 'xxxx_node_form'; // where xxxx is the node type\n$form_state = array();\n$form_state['values']['type'] = 'xxxx'; // same as above\n$form_state['values']['title'] = 'My Node Title';\n// ... repeat for all fields that you need to save\n// this is required to get node form submits to work correctly\n$form_state['submit_handlers'] = array('node_form_submit');\n\n$node = new stdClass();\n// I don't believe anything is required here, though \n// fields did seem to be required in D5\n\ndrupal_execute($form_id, $form_state, $node);\n" }, { "answer_id": 454618, "author": "Eaton", "author_id": 19411, "author_profile": "https://Stackoverflow.com/users/19411", "pm_score": 3, "selected": false, "text": "$node = new stdClass();\n$node->type = 'story';\n$node->title = 'This is a title';\n$node->body = 'This is the body.';\n$node->teaser = 'This is the teaser.';\n$node->uid = 1;\n$node->status = 1;\n$node->promote = 1;\n\nnode_save($node);\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/88566", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10393/" ]
88,570
<p>Does anyone know if it's possible to use regex capture within Apache's DirectoryMatch directive? I'd like to do something like the following:</p> <pre><code>&lt;DirectoryMatch ^/home/www/(.*)&gt; AuthType Basic AuthName $1 AuthUserFile /etc/apache2/svn.passwd Require group $1 admin &lt;/DirectoryMatch&gt; </code></pre> <p>but so far I've had no success.</p> <p>Specifically, I'm trying to create a group-based HTTP Auth for individual directories/vhosts on a server in Apache 2.0. </p> <p>For example, Site A, pointing to /home/www/a will be available to all users in group admin and group a, site b at /home/www/b will be available to all users in group admin and group b, etc. I'd like to keep everything based on the directory name so I can easily script adding htpasswd users to the correct groups and automate this as much as possible, but other suggestions for solving the problem are certainly welcome.</p>
[ { "answer_id": 91535, "author": "innaM", "author_id": 7498, "author_profile": "https://Stackoverflow.com/users/7498", "pm_score": 3, "selected": true, "text": "<Perl>\nmy @groups = qw/ foo bar baz /;\nforeach ( @groups ) {\n push @PerlConfig, qq| <Directory /home/www/$_> blah </Directory> |;\n}\n</Perl>\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/88570", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16960/" ]
88,573
<p>In C++, you can specify that a function may or may not throw an exception by using an exception specifier. For example:</p> <pre><code>void foo() throw(); // guaranteed not to throw an exception void bar() throw(int); // may throw an exception of type int void baz() throw(...); // may throw an exception of some unspecified type </code></pre> <p>I'm doubtful about actually using them because of the following:</p> <ol> <li>The compiler doesn't really enforce exception specifiers in any rigorous way, so the benefits are not great. Ideally, you would like to get a compile error.</li> <li>If a function violates an exception specifier, I think the standard behaviour is to terminate the program.</li> <li>In VS.Net, it treats throw(X) as throw(...), so adherence to the standard is not strong.</li> </ol> <p>Do you think exception specifiers should be used?<br> Please answer with "yes" or "no" and provide some reasons to justify your answer.</p>
[ { "answer_id": 88599, "author": "Branan", "author_id": 13894, "author_profile": "https://Stackoverflow.com/users/13894", "pm_score": 2, "selected": false, "text": "throw()" }, { "answer_id": 88905, "author": "Christopher", "author_id": 3186, "author_profile": "https://Stackoverflow.com/users/3186", "pm_score": 8, "selected": true, "text": "template<class T>\nvoid f( T k )\n{\n T x( k );\n x.x();\n}\n x() virtual void open() throw( FileNotFound );\n virtual void open() throw( FileNotFound, SocketNotReady, InterprocessObjectNotImplemented, HardwareUnresponsive );\n throw( ... )\n int lib_f();\n\nvoid g() throw( k_too_small_exception )\n{ \n int k = lib_f();\n if( k < 0 ) throw k_too_small_exception();\n}\n g lib_f() std::terminate() Error e = open( \"bla.txt\" );\nif( e == FileNotFound )\n MessageUser( \"File bla.txt not found\" );\nif( e == AccessDenied )\n MessageUser( \"Failed to open bla.txt, because we don't have read rights ...\" );\nif( e != Success )\n MessageUser( \"Failed due to some other error, error code = \" + itoa( e ) );\n\ntry\n{\n std::vector<TObj> k( 1000 );\n // ...\n}\ncatch( const bad_alloc& b )\n{ \n MessageUser( \"out of memory, exiting process\" );\n throw;\n}\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/88573", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3146/" ]
88,582
<p>For a small project I have to parse pdf files and take a specific part of them (a simple chain of characters). I'd like to use python to do this and I've found several libraries that are capable of doing what I want in some ways.</p> <p>But now after a few researches, I'm wondering what is the real structure of a pdf file, does anyone know if there is a spec or some explanations anywhere online? I've found a link on adobe but it seems that it's a dead link :(</p>
[ { "answer_id": 57220079, "author": "keithchristian", "author_id": 7396580, "author_profile": "https://Stackoverflow.com/users/7396580", "pm_score": 0, "selected": false, "text": "pdfinfo -layout some_pdf_file.pdf\n some_pdf_file.txt grep -a --color=always \"\\\\\\\\[0-9][0-9][0-9]\" some_pdf_file.txt\n grep -ao \"\\\\\\\\[0-9][0-9][0-9]\" some_pdf_file.txt|sort|uniq\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/88582", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11544/" ]
88,613
<p>How do I tokenize the string:</p> <pre><code>&quot;2+24*48/32&quot; </code></pre> <p>Into a list:</p> <pre><code>['2', '+', '24', '*', '48', '/', '32'] </code></pre>
[ { "answer_id": 88639, "author": "Cristian", "author_id": 680, "author_profile": "https://Stackoverflow.com/users/680", "pm_score": 2, "selected": false, "text": ">>> import re\n>>> splitter = re.compile(r'([+*/])')\n>>> splitter.split(\"2+24*48/32\")\n" }, { "answer_id": 88663, "author": "readonly", "author_id": 4883, "author_profile": "https://Stackoverflow.com/users/4883", "pm_score": 5, "selected": false, "text": "split re import re\ndata = re.split(r'(\\D)', '2+24*48/32')\n" }, { "answer_id": 88783, "author": "Jerub", "author_id": 14648, "author_profile": "https://Stackoverflow.com/users/14648", "pm_score": 4, "selected": false, "text": "import re\n\npatterns = [\n ('number', re.compile('\\d+')),\n ('*', re.compile(r'\\*')),\n ('/', re.compile(r'\\/')),\n ('+', re.compile(r'\\+')),\n ('-', re.compile(r'\\-')),\n]\nwhitespace = re.compile('\\W+')\n\ndef tokenize(string):\n while string:\n\n # strip off whitespace\n m = whitespace.match(string)\n if m:\n string = string[m.end():]\n\n for tokentype, pattern in patterns:\n m = pattern.match(string)\n if m:\n yield tokentype, m.group(0)\n string = string[m.end():]\n\ndef parseNumber(tokens):\n tokentype, literal = tokens.pop(0)\n assert tokentype == 'number'\n return int(literal)\n\ndef parseMultiplication(tokens):\n product = parseNumber(tokens)\n while tokens and tokens[0][0] in ('*', '/'):\n tokentype, literal = tokens.pop(0)\n if tokentype == '*':\n product *= parseNumber(tokens)\n elif tokentype == '/':\n product /= parseNumber(tokens)\n else:\n raise ValueError(\"Parse Error, unexpected %s %s\" % (tokentype, literal))\n\n return product\n\ndef parseAddition(tokens):\n total = parseMultiplication(tokens)\n while tokens and tokens[0][0] in ('+', '-'):\n tokentype, literal = tokens.pop(0)\n if tokentype == '+':\n total += parseMultiplication(tokens)\n elif tokentype == '-':\n total -= parseMultiplication(tokens)\n else:\n raise ValueError(\"Parse Error, unexpected %s %s\" % (tokentype, literal))\n\n return total\n\ndef parse(tokens):\n tokenlist = list(tokens)\n returnvalue = parseAddition(tokenlist)\n if tokenlist:\n print 'Unconsumed data', tokenlist\n return returnvalue\n\ndef main():\n string = '2+24*48/32'\n for tokentype, literal in tokenize(string):\n print tokentype, literal\n\n print parse(tokenize(string))\n\nif __name__ == '__main__':\n main()\n" }, { "answer_id": 89003, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "splitter = re.compile(r'([\\D])'). \n digits operators" }, { "answer_id": 89534, "author": "molasses", "author_id": 11293, "author_profile": "https://Stackoverflow.com/users/11293", "pm_score": 4, "selected": false, "text": ">>> import re\n>>> re.findall(r'\\d+|\\D+', '2+24*48/32=10')\n\n['2', '+', '24', '*', '48', '/', '32', '=', '10']\n >>> re.findall(r'[0-9\\.]+|[^0-9\\.]+', '2+24*48/32=10.1')\n\n['2', '+', '24', '*', '48', '/', '32', '=', '10.1']\n" }, { "answer_id": 89666, "author": "habnabit", "author_id": 10999, "author_profile": "https://Stackoverflow.com/users/10999", "pm_score": 2, "selected": false, "text": "import operator, math\ncalc_operands = {\n '+': (2, operator.add),\n '-': (2, operator.sub),\n '*': (2, operator.mul),\n '/': (2, operator.truediv),\n '//': (2, operator.div),\n '%': (2, operator.mod),\n '^': (2, operator.pow),\n '**': (2, math.pow),\n 'abs': (1, operator.abs),\n 'ceil': (1, math.ceil),\n 'floor': (1, math.floor),\n 'round': (2, round),\n 'trunc': (1, int),\n 'log': (2, math.log),\n 'ln': (1, math.log),\n 'pi': (0, lambda: math.pi),\n 'e': (0, lambda: math.e),\n}\n\ndef calculate(inp):\n stack = []\n for tok in inp.split():\n if tok in self.calc_operands:\n n_pops, func = self.calc_operands[tok]\n args = [stack.pop() for x in xrange(n_pops)]\n args.reverse()\n stack.append(func(*args))\n elif '.' in tok:\n stack.append(float(tok))\n else:\n stack.append(int(tok))\n if not stack:\n raise ValueError('no items on the stack.')\n return stack.pop()\n if stack:\n raise ValueError('%d item(s) left on the stack.' % len(stack))\n\ncalculate('24 38 * 32 / 2 +')\n" }, { "answer_id": 111355, "author": "Glyph", "author_id": 13564, "author_profile": "https://Stackoverflow.com/users/13564", "pm_score": 6, "selected": false, "text": "tokenize from io import StringIO\nfrom tokenize import generate_tokens\n\nSTRING = 1\nprint(\n list(\n token[STRING]\n for token in generate_tokens(StringIO(\"2+24*48/32\").readline)\n if token[STRING]\n )\n)\n ['2', '+', '24', '*', '48', '/', '32']\n" }, { "answer_id": 8863507, "author": "jbchichoko", "author_id": 1126747, "author_profile": "https://Stackoverflow.com/users/1126747", "pm_score": 1, "selected": false, "text": ">>> import re\n>>> my_string = \"2+24*48/32\"\n>>> my_list = re.findall(r\"-?\\d+|\\S\", my_string)\n>>> print my_list\n\n['2', '+', '24', '*', '48', '/', '32']\n" }, { "answer_id": 72064350, "author": "Xinyue Zhang", "author_id": 18994381, "author_profile": "https://Stackoverflow.com/users/18994381", "pm_score": 0, "selected": false, "text": "import re\n \n \n# initializing string \ndata = \"2+24*48/32\"\n \n# printing original string \nprint(\"The original string is : \" + data) \n \n# Using re.findall() \n# Splitting characters in String \nres = re.findall(r\"[\\w']+\", data)\n \n# printing result \nprint(\"The list after performing split functionality : \" + str(res)) \n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/88613", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
88,615
<p>Given an arbitrary string, what is an efficient method of finding duplicate phrases? We can say that phrases must be longer than a certain length to be included.</p> <p>Ideally, you would end up with the number of occurrences for each phrase.</p>
[ { "answer_id": 88765, "author": "Sridhar Iyer", "author_id": 13820, "author_profile": "https://Stackoverflow.com/users/13820", "pm_score": 3, "selected": true, "text": "js" }, { "answer_id": 580135, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "Algo(A(i))\n{\n while i<>n\n {\n temp=A[i];\n if A[i]<>A[i+1] then\n { \n temp=A[i+1];\n i=i+1;\n Algo(A[i])\n }\n else if A[i]==A[i+1] then\n mark A[i] and A[i+1] as duplicates\n }\n}\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/88615", "https://Stackoverflow.com", "https://Stackoverflow.com/users/337/" ]
88,618
<p>We have a medium sized .js file that we include in our web framework that I am porting over to SharePoint. However, I'm not sure how to go about this or what the best practice is. This is for a framework solution that will be used by other client projects, so it's best for it to be self contained and deploy-able, rather than requiring manually deploying files to the webserver.</p> <p>My current thinking to put the JavaScript into an embedded resource and then use the script manager to write out the file. Does this seem reasonable? Or does anyone have any other recommendations?</p>
[ { "answer_id": 93475, "author": "andrew", "author_id": 17767, "author_profile": "https://Stackoverflow.com/users/17767", "pm_score": 0, "selected": false, "text": "<TemplateFiles>\n <TemplateFile Location=\"LAYOUTS\\somescript.js\" />\n</TemplateFiles>\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/88618", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1685/" ]