qid
int64
4
22.2M
question
stringlengths
18
48.3k
answers
list
date
stringlengths
10
10
metadata
list
249,372
<p>Given two integers <code>a</code> and <code>b</code>, how would I go about calculating the repeating decimal of <code>a / b</code>? This can be in any language; whatever it's easiest for you to express it in.</p>
[ { "answer_id": 251597, "author": "ShreevatsaR", "author_id": 4958, "author_profile": "https://Stackoverflow.com/users/4958", "pm_score": 3, "selected": false, "text": "a / b" }, { "answer_id": 15230863, "author": "Harit Vishwakarma", "author_id": 569161, "author_profile": "https://Stackoverflow.com/users/569161", "pm_score": 1, "selected": false, "text": "public static String divide(int a,int b,boolean decimalDone,boolean isMultiplied,String result){\n if(a<b){\n a=a*10;\n\n if(!decimalDone ) {result+=\".\";decimalDone=true;}\n else if(isMultiplied) result+=\"0\";\n isMultiplied=true;\n divide(a,b,decimalDone,isMultiplied,result);\n\n }\n else{\n result+=a/b;\n a=a%b;\n isMultiplied=false;\n divide(a,b,decimalDone,isMultiplied,result);\n }\n\n return result;\n }\n" }, { "answer_id": 31002479, "author": "Pigna", "author_id": 4551565, "author_profile": "https://Stackoverflow.com/users/4551565", "pm_score": 0, "selected": false, "text": "#you want to get a/b\nfrom fractions import Fraction:\nprint float(Fraction(a,b))\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/249372", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15055/" ]
249,374
<p>Is anyone familiar with this?</p> <blockquote> <p>Write a procedure that takes as inputs a procedure that computes f and a positive integer n and returns the procedure that computes the nth repeated application of f. The procedure should be able to be used as follows:</p> <pre><code>((repeated square 2) 5) 625 </code></pre> </blockquote> <p>I know that the following code I've created for the composition of functions will help make the solution simpler, but I'm not sure where to go from here:</p> <pre><code>(define (compose f g) (lambda (x) (f (g x)))) </code></pre>
[ { "answer_id": 249490, "author": "Matthias Benkard", "author_id": 15517, "author_profile": "https://Stackoverflow.com/users/15517", "pm_score": 1, "selected": false, "text": "((repeated square 3) 5)\n-> (square ((repeated square 2) 5))\n-> (square (square ((repeated square 1) 5)))\n-> (square (square (square ((repeated square 0) 5))))\n-> (square (square (square (identity 5))))\n" }, { "answer_id": 956173, "author": "Mark Probst", "author_id": 80410, "author_profile": "https://Stackoverflow.com/users/80410", "pm_score": 0, "selected": false, "text": "(define (repeated f n)\n (if (zero? n)\n identity\n (lambda (x) ((repeated f (- n 1)) (f x)))))\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/249374", "https://Stackoverflow.com", "https://Stackoverflow.com/users/30622/" ]
249,375
<p>How do you programmatically set a DataContext that specifies the selected item of a list? </p> <p>More simply, how do you reproduce this type of binding in code?</p> <pre><code>&lt;StackPanel&gt; &lt;ListBox Name="listBox1" /&gt; &lt;TextBox Name="textBox1" DataContext="{Binding ElementName=listBox1, Path=SelectedItem}" /&gt; &lt;/StackPanel&gt; </code></pre>
[ { "answer_id": 249378, "author": "Ty.", "author_id": 16948, "author_profile": "https://Stackoverflow.com/users/16948", "pm_score": 4, "selected": true, "text": "Binding binding = new Binding();\nbinding.ElementName = \"listBox1\";\nbinding.Path = new PropertyPath(\"SelectedItem\");\nbinding.Mode = BindingMode.OneWay;\ntxtMyTextBox.SetBinding(TextBox.TextProperty, binding);\n" }, { "answer_id": 249386, "author": "Toji", "author_id": 25968, "author_profile": "https://Stackoverflow.com/users/25968", "pm_score": 1, "selected": false, "text": "Binding b = new Binding();\nb.Path = new PropertyPath(ListBox.SelectedItemProperty);\nb.Source = listBox1;\ntextBox1.SetBinding(TextBox.DataContextProperty, b);\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/249375", "https://Stackoverflow.com", "https://Stackoverflow.com/users/25968/" ]
249,388
<p>I'm having trouble getting pictures supported with PIL - it throws me this:</p> <pre><code>IOError: decoder jpeg not available </code></pre> <p>I installed PIL from binary, not realizing I needed libjpeg.</p> <p>I installed libjpeg and freetype2 through fink. </p> <p>I tried to reinstall PIL using instructions from <a href="http://timhatch.com/" rel="nofollow noreferrer">http://timhatch.com/</a> (bottom of the page)</p> <ul> <li>Download PIL 1.1.6 source package and have the Developer Tools already installed</li> <li><p>Patch setup.py with this patch so it can find the Freetype you already have.</p> <p><code>patch -p0 &lt; leopard_freetype2.diff</code></p></li> <li>sudo apt-get install libjpeg if you have fink (otherwise, build by hand and adjust paths)</li> </ul> <p>But I'm still getting the same error. </p> <p>I'm on Leopard PPC. </p>
[ { "answer_id": 4533995, "author": "Walty Yeung", "author_id": 176423, "author_profile": "https://Stackoverflow.com/users/176423", "pm_score": 0, "selected": false, "text": "file /usr/local/lib/libjpeg.7.dylib \n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/249388", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20824/" ]
249,392
<p>How would I implement a binary search using just an array? </p>
[ { "answer_id": 249404, "author": "mmcdole", "author_id": 2635, "author_profile": "https://Stackoverflow.com/users/2635", "pm_score": 6, "selected": true, "text": "BinarySearch(A[0..N-1], value, low, high) { \n if (high < low) \n return -1 // not found \n mid = low + ((high - low) / 2) \n if (A[mid] > value) \n return BinarySearch(A, value, low, mid-1) \n else if (A[mid] < value) \n return BinarySearch(A, value, mid+1, high) \n else\n return mid // found\n }\n" }, { "answer_id": 255007, "author": "Jed", "author_id": 33208, "author_profile": "https://Stackoverflow.com/users/33208", "pm_score": 0, "selected": false, "text": "int bsearch_double(const double a[], int n, double v) {\n int low = 0, mid;\n while (n - low > 1) {\n mid = low + (n - low) / 2;\n if (v < a[mid]) n = mid;\n else low = mid;\n }\n return (low < n && a[low] == v) ? low : -1;\n}\n" }, { "answer_id": 39693211, "author": "Mohammad", "author_id": 5475941, "author_profile": "https://Stackoverflow.com/users/5475941", "pm_score": 0, "selected": false, "text": "import java.util.Arrays;\n\npublic class BinarySearchExample {\n\n //Find one occurrence\n public static int indexOf(int[] a, int key) {\n int lo = 0;\n int hi = a.length - 1;\n while (lo <= hi) {\n // Key is in a[lo..hi] or not present.\n int mid = lo + (hi - lo) / 2;\n if (key < a[mid]) hi = mid - 1;\n else if (key > a[mid]) lo = mid + 1;\n else return mid;\n }\n return -1;\n }\n\n //Find all occurrence\n public static void PrintIndicesForValue(int[] numbers, int target) {\n if (numbers == null)\n return;\n\n int low = 0, high = numbers.length - 1;\n // get the start index of target number\n int startIndex = -1;\n while (low <= high) {\n int mid = (high - low) / 2 + low;\n if (numbers[mid] > target) {\n high = mid - 1;\n } else if (numbers[mid] == target) {\n startIndex = mid;\n high = mid - 1;\n } else\n low = mid + 1;\n }\n\n // get the end index of target number\n int endIndex = -1;\n low = 0;\n high = numbers.length - 1;\n while (low <= high) {\n int mid = (high - low) / 2 + low;\n if (numbers[mid] > target) {\n high = mid - 1;\n } else if (numbers[mid] == target) {\n endIndex = mid;\n low = mid + 1;\n } else\n low = mid + 1;\n }\n\n if (startIndex != -1 && endIndex != -1){\n System.out.print(\"All: \");\n for(int i=0; i+startIndex<=endIndex;i++){\n if(i>0)\n System.out.print(',');\n System.out.print(i+startIndex);\n }\n }\n }\n\n public static void main(String[] args) {\n\n // read the integers from a file\n int[] arr = {23,34,12,24,266,1,3,66,78,93,22,24,25,27};\n Boolean[] arrFlag = new Boolean[arr.length];\n Arrays.fill(arrFlag,false);\n\n // sort the array\n Arrays.sort(arr);\n\n //Search\n System.out.print(\"Array: \");\n for(int i=0; i<arr.length; i++)\n if(i != arr.length-1){\n System.out.print(arr[i]+\",\");\n }else{\n System.out.print(arr[i]);\n }\n\n System.out.println(\"\\nOnly one: \"+indexOf(arr,24));\n PrintIndicesForValue(arr,24);\n\n }\n\n}\n" }, { "answer_id": 50189125, "author": "user7258708", "author_id": 7258708, "author_profile": "https://Stackoverflow.com/users/7258708", "pm_score": 0, "selected": false, "text": " /**\n * Simplistic BInary Search using Recursion\n * @param arr\n * @param low\n * @param high\n * @param num\n * @return int\n */\n public int binSearch(int []arr,int low,int high,int num)\n {\n int mid=low+high/2;\n if(num >arr[high] || num <arr[low])\n {\n return -1;\n }\n\n while(low<high)\n {\n if(num==arr[mid])\n {\n return mid;\n\n }\n else if(num<arr[mid])\n {\n return binSearch(arr,low,high-1, num);\n }\n\n else if(num>arr[mid])\n {\n return binSearch(arr,low+1,high, num);\n }\n\n }//end of while\n\n return -1;\n }\n\n public static void main(String args[])\n {\n int arr[]= {2,4,6,8,10};\n BinSearch s=new BinSearch();\n int n=s.binSearch(arr, 0, arr.length-1, 10);\n String result= n>1?\"Number found at \"+n:\"Number not found\";\n System.out.println(result);\n }\n}\n" }, { "answer_id": 50545530, "author": "Lior Elrom", "author_id": 1843451, "author_profile": "https://Stackoverflow.com/users/1843451", "pm_score": 2, "selected": false, "text": "function binarySearch (arr, val) {\n let start = 0;\n let end = arr.length - 1;\n let mid;\n\n while (start <= end) {\n mid = Math.floor((start + end) / 2);\n\n if (arr[mid] === val) {\n return mid;\n }\n if (val < arr[mid]) {\n end = mid - 1;\n } else {\n start = mid + 1;\n }\n }\n return -1;\n}\n" }, { "answer_id": 68149436, "author": "bhargav3vedi", "author_id": 6763678, "author_profile": "https://Stackoverflow.com/users/6763678", "pm_score": 0, "selected": false, "text": "def bin(search, h, l):\n mid = (h+l)//2\n if m[mid] == search:\n return mid\n else:\n if l == h:\n return -1\n elif search > m[mid]:\n l = mid+1\n return bin(search, h, l)\n elif search < m[mid]:\n h = mid-1\n return bin(search, h, l)\n \nm = [1,2,3,4,5,6,7,8]\ntot = len(m)\nprint(bin(10, len(m)-1, 0))\n" }, { "answer_id": 68322246, "author": "qulinxao", "author_id": 660391, "author_profile": "https://Stackoverflow.com/users/660391", "pm_score": 0, "selected": false, "text": "function search( nums, target){ \n for(let mid,look,p=[0,,nums.length-1]; p[0]<=p[2]; p[look+1]=mid-look){\n mid = (p[0] + p[2])>>>1\n look = Math.sign(nums[mid]-target)\n if(!look) \n return mid\n }\n return -1\n}\n" }, { "answer_id": 70013435, "author": "Niyousha Mohammadshafie", "author_id": 11705232, "author_profile": "https://Stackoverflow.com/users/11705232", "pm_score": 0, "selected": false, "text": "def binary_search(nums: List[int], target: int) -> int:\n n = len(nums) - 1\n left = 0\n right = n\n \n \n while left <= right:\n mid = left + (right - left) // 2\n if target == nums[mid]:\n return mid\n elif target < nums[mid]:\n right = mid - 1\n else:\n left = mid + 1\n \n \n return -1\n" }, { "answer_id": 72664752, "author": "Sanpreet", "author_id": 2557590, "author_profile": "https://Stackoverflow.com/users/2557590", "pm_score": 1, "selected": false, "text": "mid index" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/249392", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15055/" ]
249,423
<p>Can someone explain to me how XOR swapping of two variables with no temp variable works?</p> <pre><code>void xorSwap (int *x, int *y) { if (x != y) { *x ^= *y; *y ^= *x; *x ^= *y; } } </code></pre> <p>I understand WHAT it does, but can someone walk me through the logic of how it works? </p>
[ { "answer_id": 249427, "author": "VonC", "author_id": 6309, "author_profile": "https://Stackoverflow.com/users/6309", "pm_score": 4, "selected": false, "text": "tmp = x\nx = y\ny = tmp\n" }, { "answer_id": 249431, "author": "Greg Hewgill", "author_id": 893, "author_profile": "https://Stackoverflow.com/users/893", "pm_score": 8, "selected": true, "text": "x1 = x0 xor y0\ny2 = x1 xor y0\nx2 = x1 xor y2\n" }, { "answer_id": 249438, "author": "Matt J", "author_id": 18528, "author_profile": "https://Stackoverflow.com/users/18528", "pm_score": 5, "selected": false, "text": "int x = 10, y = 7;\n\ny = x + y; //x = 10, y = 17\nx = y - x; //x = 7, y = 17\ny = y - x; //x = 7, y = 10\n" }, { "answer_id": 249552, "author": "kenny", "author_id": 3225, "author_profile": "https://Stackoverflow.com/users/3225", "pm_score": 3, "selected": false, "text": "word1 ^= word2;\nword2 ^= word1;\nword1 ^= word2;\n\n\nword1 word2\n0101 1111\nafter 1st xor\n1010 1111\nafter 2nd xor\n1010 0101\nafter 3rd xor\n1111 0101\n" }, { "answer_id": 528594, "author": "Mike Dunlavey", "author_id": 23771, "author_profile": "https://Stackoverflow.com/users/23771", "pm_score": 4, "selected": false, "text": " // A,B = 1,2\nA = A+B // 3,2\nB = A-B // 3,1\nA = A-B // 2,1\n" }, { "answer_id": 528869, "author": "jheriko", "author_id": 17604, "author_profile": "https://Stackoverflow.com/users/17604", "pm_score": 2, "selected": false, "text": "a = a + b\nb = a - b ( = a + b - b once expanded)\na = a - b ( = a + b - a once expanded).\n" }, { "answer_id": 528946, "author": "plinth", "author_id": 20481, "author_profile": "https://Stackoverflow.com/users/20481", "pm_score": 6, "selected": false, "text": " x: |1|0|1|1| -> 8 + 2 + 1\n y: |0|1|0|1| -> 4 + 1\n" }, { "answer_id": 61323856, "author": "Sungfu Chiu", "author_id": 8408846, "author_profile": "https://Stackoverflow.com/users/8408846", "pm_score": 2, "selected": false, "text": "a = a XOR b\nb = a XOR b\na = a XOR b \n" }, { "answer_id": 65581923, "author": "LifelessG", "author_id": 12135716, "author_profile": "https://Stackoverflow.com/users/12135716", "pm_score": 0, "selected": false, "text": "A = 1100" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/249423", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2635/" ]
249,448
<p>I have a textbox with the <strong>Text</strong> property bound to a dataset column with the DataType set to System.DateTime.<br> The FormatString on the Binding is set to <strong>dd-MM-yyyy</strong>.</p> <p>When the user enters a date it attempts to convert it to a date but can come up with some strange values for a seemingly invalid date.</p> <p>For example:</p> <pre><code>textBox1.Text = "01-02-200"; </code></pre> <p>Should be an invalid date but it formats it as <strong>01-02-0200</strong>.</p> <p>Is there an easy way to catch these out-of-bounds values either through setting a valid range or overriding an event on the binding/textbox?</p>
[ { "answer_id": 249519, "author": "Joe", "author_id": 13087, "author_profile": "https://Stackoverflow.com/users/13087", "pm_score": 3, "selected": true, "text": "private void textBox1_Validating(object sender, CancelEventArgs e)\n{\n DateTime date;\n if (!DateTime.TryParseExact(textBox1.Text, \n \"dd-MM-yyyy\", \n CultureInfo.CurrentCulture, \n DateTimeStyles.None, \n out date))\n {\n MessageBox.Show(textBox1.Text + \" is not a valid date\");\n textBox1.Focus();\n e.Cancel = true;\n return;\n }\n if ((date < (DateTime) System.Data.SqlTypes.SqlDateTime.MinValue) ||\n (date > (DateTime) System.Data.SqlTypes.SqlDateTime.MaxValue))\n {\n MessageBox.Show(textBox1.Text + \" is out of range\");\n textBox1.Focus();\n e.Cancel = true;\n return;\n }\n}\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/249448", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4490/" ]
249,452
<p>How to add new item in existing string array in C#.net?</p> <p>I need to preserve the existing data.</p>
[ { "answer_id": 249455, "author": "Ed S.", "author_id": 1053, "author_profile": "https://Stackoverflow.com/users/1053", "pm_score": 7, "selected": false, "text": "List<string> ls = new List<string>();\nls.Add(\"Hello\");\n" }, { "answer_id": 249486, "author": "Ali Ersöz", "author_id": 4215, "author_profile": "https://Stackoverflow.com/users/4215", "pm_score": 7, "selected": false, "text": "Array.Resize(ref array, newsize);\narray[newsize - 1] = \"newvalue\"\n" }, { "answer_id": 249792, "author": "artur02", "author_id": 13937, "author_profile": "https://Stackoverflow.com/users/13937", "pm_score": 5, "selected": false, "text": "string[]" }, { "answer_id": 2787955, "author": "Dave Blake", "author_id": 335357, "author_profile": "https://Stackoverflow.com/users/335357", "pm_score": 0, "selected": false, "text": "private static string[] GetMergedArray(string[] originalArray, string[] newArray)\n {\n int startIndexForNewArray = originalArray.Length;\n Array.Resize<string>(ref originalArray, originalArray.Length + newArray.Length);\n newArray.CopyTo(originalArray, startIndexForNewArray);\n return originalArray;\n }\n" }, { "answer_id": 5780240, "author": "Gia Duong Duc Minh", "author_id": 701950, "author_profile": "https://Stackoverflow.com/users/701950", "pm_score": 2, "selected": false, "text": "string str = \"string \";\nList<string> li_str = new List<string>();\n for (int k = 0; k < 100; i++ )\n li_str.Add(str+k.ToString());\nstring[] arr_str = li_str.ToArray();\n" }, { "answer_id": 7116251, "author": "Stephen Chung", "author_id": 650891, "author_profile": "https://Stackoverflow.com/users/650891", "pm_score": 6, "selected": false, "text": "arr = (arr ?? Enumerable.Empty<string>()).Concat(new[] { newitem }).ToArray();\n" }, { "answer_id": 8616931, "author": "tmania", "author_id": 538280, "author_profile": "https://Stackoverflow.com/users/538280", "pm_score": 5, "selected": false, "text": " Array.Resize(ref youur_array_name, your_array_name.Length + 1);\n your_array_name[your_array_name.Length - 1] = \"new item\";\n" }, { "answer_id": 11035286, "author": "dblood", "author_id": 673545, "author_profile": "https://Stackoverflow.com/users/673545", "pm_score": 3, "selected": false, "text": "public static class CollectionHelper\n{\n public static IEnumerable<T> Add<T>(this IEnumerable<T> sequence, T item)\n {\n return (sequence ?? Enumerable.Empty<T>()).Concat(new[] { item });\n }\n\n public static T[] AddRangeToArray<T>(this T[] sequence, T[] items)\n {\n return (sequence ?? Enumerable.Empty<T>()).Concat(items).ToArray();\n }\n\n public static T[] AddToArray<T>(this T[] sequence, T item)\n {\n return Add(sequence, item).ToArray();\n }\n\n}\n" }, { "answer_id": 26710916, "author": "Suren", "author_id": 428061, "author_profile": "https://Stackoverflow.com/users/428061", "pm_score": 3, "selected": false, "text": "Add" }, { "answer_id": 36759482, "author": "Saif", "author_id": 5362552, "author_profile": "https://Stackoverflow.com/users/5362552", "pm_score": 0, "selected": false, "text": "public class CustomArrayList<T> \n { \n private T[] arr; private int count; \n\npublic int Count \n { \n get \n { \n return this.count; \n } \n } \n private const int INITIAL_CAPACITY = 4; \n\n public CustomArrayList(int capacity = INITIAL_CAPACITY) \n { \n this.arr = new T[capacity]; this.count = 0; \n } \n\n public void Add(T item) \n { \n GrowIfArrIsFull(); \n this.arr[this.count] = item; this.count++; \n } \n\npublic void Insert(int index, T item) \n{ \n if (index > this.count || index < 0) \n { \n throw new IndexOutOfRangeException( \"Invalid index: \" + index); \n } \n GrowIfArrIsFull(); \n Array.Copy(this.arr, index, this.arr, index + 1, this.count - index); \n this.arr[index] = item; this.count++; } \n\n private void GrowIfArrIsFull() \n { \n if (this.count + 1 > this.arr.Length) \n { \n T[] extendedArr = new T[this.arr.Length * 2]; \n Array.Copy(this.arr, extendedArr, this.count); \n this.arr = extendedArr; \n } \n }\n }\n}\n" }, { "answer_id": 37369110, "author": "stackuser83", "author_id": 832705, "author_profile": "https://Stackoverflow.com/users/832705", "pm_score": 3, "selected": false, "text": "Add" }, { "answer_id": 37695587, "author": "Grimace of Despair", "author_id": 281084, "author_profile": "https://Stackoverflow.com/users/281084", "pm_score": 5, "selected": false, "text": "myArray = new List<string>(myArray) { \"add this\" }.ToArray();\n" }, { "answer_id": 42800892, "author": "William", "author_id": 907734, "author_profile": "https://Stackoverflow.com/users/907734", "pm_score": 2, "selected": false, "text": "public static IEnumerable<TSource> Union<TSource>(this IEnumerable<TSource> source, TSource item)\n{\n return source.Union(new TSource[] { item });\n}\n" }, { "answer_id": 46234371, "author": "Adi_Pithwa", "author_id": 2298846, "author_profile": "https://Stackoverflow.com/users/2298846", "pm_score": 3, "selected": false, "text": "var tempList = originalArray.ToList();\ntempList.Add(newitem);\n" }, { "answer_id": 50772992, "author": "Walter Verhoeven", "author_id": 8000382, "author_profile": "https://Stackoverflow.com/users/8000382", "pm_score": 3, "selected": false, "text": "Array.Resize(ref myArray, myArray.Length + 1);\ndata[myArray.Length - 1] = Value;\n" }, { "answer_id": 60377314, "author": "0xced", "author_id": 21698, "author_profile": "https://Stackoverflow.com/users/21698", "pm_score": 3, "selected": false, "text": "Append<TSource>" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/249452", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
249,460
<p>On Windows Mobile, I am displaying my output in HTML. This includes lots of user-generated strings. Occasionally there are situations where a really large string is part of the output that has no whitespaces or punctuation. </p> <p>Unfortunately the Windows Mobile's HTML view (htmlview.dll, based on Pocket Internet Explorer) does not break these long words down so they fit on screen. Instead a horizontal scrollbar is added and the user has to scroll sideways to see the whole word. This also affects other output which now also is spread along this larger screen width.</p> <p>Is there any possibility to either make the htmlview behave differently, or to force the word to break? CSS can be used. Regarding the forcing: The &amp;shy; tag is ALWAYS inserting a "-" character and never causes a breaks, the &lt;WBR&gt; tag is not doing anything at all, &amp;8203; is output as &amp;8203:, empty tags like <B></B> also do nothing. Also it should be noted that this code is running on multiple screen sizes and due to other parts of the HTML output I am not 100% sure how much screen width I have left.</p> <p>P.S.: My app is compiled using the WM 5.0 SDK and is written in C++/Win32/MFC.</p>
[ { "answer_id": 249455, "author": "Ed S.", "author_id": 1053, "author_profile": "https://Stackoverflow.com/users/1053", "pm_score": 7, "selected": false, "text": "List<string> ls = new List<string>();\nls.Add(\"Hello\");\n" }, { "answer_id": 249486, "author": "Ali Ersöz", "author_id": 4215, "author_profile": "https://Stackoverflow.com/users/4215", "pm_score": 7, "selected": false, "text": "Array.Resize(ref array, newsize);\narray[newsize - 1] = \"newvalue\"\n" }, { "answer_id": 249792, "author": "artur02", "author_id": 13937, "author_profile": "https://Stackoverflow.com/users/13937", "pm_score": 5, "selected": false, "text": "string[]" }, { "answer_id": 2787955, "author": "Dave Blake", "author_id": 335357, "author_profile": "https://Stackoverflow.com/users/335357", "pm_score": 0, "selected": false, "text": "private static string[] GetMergedArray(string[] originalArray, string[] newArray)\n {\n int startIndexForNewArray = originalArray.Length;\n Array.Resize<string>(ref originalArray, originalArray.Length + newArray.Length);\n newArray.CopyTo(originalArray, startIndexForNewArray);\n return originalArray;\n }\n" }, { "answer_id": 5780240, "author": "Gia Duong Duc Minh", "author_id": 701950, "author_profile": "https://Stackoverflow.com/users/701950", "pm_score": 2, "selected": false, "text": "string str = \"string \";\nList<string> li_str = new List<string>();\n for (int k = 0; k < 100; i++ )\n li_str.Add(str+k.ToString());\nstring[] arr_str = li_str.ToArray();\n" }, { "answer_id": 7116251, "author": "Stephen Chung", "author_id": 650891, "author_profile": "https://Stackoverflow.com/users/650891", "pm_score": 6, "selected": false, "text": "arr = (arr ?? Enumerable.Empty<string>()).Concat(new[] { newitem }).ToArray();\n" }, { "answer_id": 8616931, "author": "tmania", "author_id": 538280, "author_profile": "https://Stackoverflow.com/users/538280", "pm_score": 5, "selected": false, "text": " Array.Resize(ref youur_array_name, your_array_name.Length + 1);\n your_array_name[your_array_name.Length - 1] = \"new item\";\n" }, { "answer_id": 11035286, "author": "dblood", "author_id": 673545, "author_profile": "https://Stackoverflow.com/users/673545", "pm_score": 3, "selected": false, "text": "public static class CollectionHelper\n{\n public static IEnumerable<T> Add<T>(this IEnumerable<T> sequence, T item)\n {\n return (sequence ?? Enumerable.Empty<T>()).Concat(new[] { item });\n }\n\n public static T[] AddRangeToArray<T>(this T[] sequence, T[] items)\n {\n return (sequence ?? Enumerable.Empty<T>()).Concat(items).ToArray();\n }\n\n public static T[] AddToArray<T>(this T[] sequence, T item)\n {\n return Add(sequence, item).ToArray();\n }\n\n}\n" }, { "answer_id": 26710916, "author": "Suren", "author_id": 428061, "author_profile": "https://Stackoverflow.com/users/428061", "pm_score": 3, "selected": false, "text": "Add" }, { "answer_id": 36759482, "author": "Saif", "author_id": 5362552, "author_profile": "https://Stackoverflow.com/users/5362552", "pm_score": 0, "selected": false, "text": "public class CustomArrayList<T> \n { \n private T[] arr; private int count; \n\npublic int Count \n { \n get \n { \n return this.count; \n } \n } \n private const int INITIAL_CAPACITY = 4; \n\n public CustomArrayList(int capacity = INITIAL_CAPACITY) \n { \n this.arr = new T[capacity]; this.count = 0; \n } \n\n public void Add(T item) \n { \n GrowIfArrIsFull(); \n this.arr[this.count] = item; this.count++; \n } \n\npublic void Insert(int index, T item) \n{ \n if (index > this.count || index < 0) \n { \n throw new IndexOutOfRangeException( \"Invalid index: \" + index); \n } \n GrowIfArrIsFull(); \n Array.Copy(this.arr, index, this.arr, index + 1, this.count - index); \n this.arr[index] = item; this.count++; } \n\n private void GrowIfArrIsFull() \n { \n if (this.count + 1 > this.arr.Length) \n { \n T[] extendedArr = new T[this.arr.Length * 2]; \n Array.Copy(this.arr, extendedArr, this.count); \n this.arr = extendedArr; \n } \n }\n }\n}\n" }, { "answer_id": 37369110, "author": "stackuser83", "author_id": 832705, "author_profile": "https://Stackoverflow.com/users/832705", "pm_score": 3, "selected": false, "text": "Add" }, { "answer_id": 37695587, "author": "Grimace of Despair", "author_id": 281084, "author_profile": "https://Stackoverflow.com/users/281084", "pm_score": 5, "selected": false, "text": "myArray = new List<string>(myArray) { \"add this\" }.ToArray();\n" }, { "answer_id": 42800892, "author": "William", "author_id": 907734, "author_profile": "https://Stackoverflow.com/users/907734", "pm_score": 2, "selected": false, "text": "public static IEnumerable<TSource> Union<TSource>(this IEnumerable<TSource> source, TSource item)\n{\n return source.Union(new TSource[] { item });\n}\n" }, { "answer_id": 46234371, "author": "Adi_Pithwa", "author_id": 2298846, "author_profile": "https://Stackoverflow.com/users/2298846", "pm_score": 3, "selected": false, "text": "var tempList = originalArray.ToList();\ntempList.Add(newitem);\n" }, { "answer_id": 50772992, "author": "Walter Verhoeven", "author_id": 8000382, "author_profile": "https://Stackoverflow.com/users/8000382", "pm_score": 3, "selected": false, "text": "Array.Resize(ref myArray, myArray.Length + 1);\ndata[myArray.Length - 1] = Value;\n" }, { "answer_id": 60377314, "author": "0xced", "author_id": 21698, "author_profile": "https://Stackoverflow.com/users/21698", "pm_score": 3, "selected": false, "text": "Append<TSource>" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/249460", "https://Stackoverflow.com", "https://Stackoverflow.com/users/27101/" ]
249,461
<p>I want to compute for month difference of 2 dates which will return a float value.</p> <p>example:</p> <p>date1='4/23/2008' date2='12/31/2008'</p> <p>that will be 7.y months. I want to find the y value. can someone give me the formula to make this in sql codes? tnx..</p>
[ { "answer_id": 249477, "author": "a2800276", "author_id": 27408, "author_profile": "https://Stackoverflow.com/users/27408", "pm_score": 1, "selected": false, "text": "to_date()" }, { "answer_id": 249481, "author": "Ali Ersöz", "author_id": 4215, "author_profile": "https://Stackoverflow.com/users/4215", "pm_score": 0, "selected": false, "text": "select cast(datediff(dd, date1, date2) as float) / 30\n" }, { "answer_id": 249511, "author": "Tomalak", "author_id": 18771, "author_profile": "https://Stackoverflow.com/users/18771", "pm_score": 1, "selected": false, "text": "DECLARE @d1 DATETIME\nDECLARE @d2 DATETIME\n\nSET @d1 = '2008-04-23'\nSET @d2 = '2008-12-31'\n\nSELECT CONVERT(FLOAT, DATEDIFF(mm, @d1, @d2)) + ROUND(CONVERT(FLOAT, DATEDIFF(dd, DATEADD(mm, DATEDIFF(mm, @d1, @d2), @d1), @d2) % 30) / 30, 1)\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/249461", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21963/" ]
249,467
<p>I've heard of "error" when using floating point variables. Now I'm trying to solve this puzzle and I think I'm getting some rounding/floating point error. So I'm finally going to figure out the basics of floating point error.</p> <p>What is a simple example of floating point/rounding error (preferably in C++) ?</p> <p>Edit: For example say I have an event that has probability p of succeeding. I do this event 10 times (p does not change and all trials are independent). What is the probability of exactly 2 successful trials? I have this coded as:</p> <pre><code>double p_2x_success = pow(1-p, (double)8) * pow(p, (double)2) * (double)choose(8, 2); </code></pre> <p>Is this an opportunity for floating point error?</p>
[ { "answer_id": 249498, "author": "Matthew Schinckel", "author_id": 188, "author_profile": "https://Stackoverflow.com/users/188", "pm_score": 4, "selected": false, "text": "Python 2.5.1 (r251:54863, Apr 15 2008, 22:57:26) \n[GCC 4.0.1 (Apple Inc. build 5465)] on darwin\nType \"help\", \"copyright\", \"credits\" or \"license\" for more information.\n>>> 0.1\n0.10000000000000001\n>>> \n" }, { "answer_id": 249526, "author": "SmacL", "author_id": 22564, "author_profile": "https://Stackoverflow.com/users/22564", "pm_score": 3, "selected": false, "text": "double d = 0;\nsscanf(\"90.1000\", \"%lf\", &d);\nprintf(\"%0.4f\", d);\n" }, { "answer_id": 249777, "author": "Motti", "author_id": 3848, "author_profile": "https://Stackoverflow.com/users/3848", "pm_score": 5, "selected": false, "text": " for(double d = 0; d != 0.3; d += 0.1); // never terminates \n" }, { "answer_id": 5694505, "author": "Agnius Vasiliauskas", "author_id": 380331, "author_profile": "https://Stackoverflow.com/users/380331", "pm_score": 6, "selected": false, "text": "f(k)" }, { "answer_id": 27529238, "author": "Rory O'Bryan", "author_id": 1347502, "author_profile": "https://Stackoverflow.com/users/1347502", "pm_score": 3, "selected": false, "text": " round(256.49999) == 256\nroundf(256.49999) == 257\n" }, { "answer_id": 53177677, "author": "Samuel Li", "author_id": 2108824, "author_profile": "https://Stackoverflow.com/users/2108824", "pm_score": 3, "selected": false, "text": "Python 2.7.10 (default, Oct 6 2017, 22:29:07) \n[GCC 4.2.1 Compatible Apple LLVM 9.0.0 (clang-900.0.31)] on darwin\nType \"help\", \"copyright\", \"credits\" or \"license\" for more information.\n>>> 0.1+0.2\n0.30000000000000004\n>>>\n" }, { "answer_id": 57495203, "author": "formiaczek", "author_id": 1266432, "author_profile": "https://Stackoverflow.com/users/1266432", "pm_score": 2, "selected": false, "text": "a = 10000000.1\nb = 1/10\nprint(a - b == 10000000)\nprint ('a:{0:.20f}\\nb:{1:.20f}'.format(a, b))\n" }, { "answer_id": 61917303, "author": "Danilo Pianini", "author_id": 1916413, "author_profile": "https://Stackoverflow.com/users/1916413", "pm_score": 3, "selected": false, "text": "0.2 + 0.1\n" }, { "answer_id": 67477450, "author": "x-yuri", "author_id": 52499, "author_profile": "https://Stackoverflow.com/users/52499", "pm_score": 0, "selected": false, "text": "sum = 0\n10_000.times do\n sum = sum + 0.0001\nend\nprint sum #=> 0.9999999999999062\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/249467", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22471/" ]
249,468
<p>I'm looking at stdint.h and given that it has uint16_t and uint_fast16_t, what is the use for uint_least16_t what might you want that couldn't be done equally well with one of the other two?</p>
[ { "answer_id": 249482, "author": "Michael Burr", "author_id": 12711, "author_profile": "https://Stackoverflow.com/users/12711", "pm_score": 5, "selected": true, "text": "unsigned char" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/249468", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10471/" ]
249,470
<p>What would be a simple implementation of a method to convert a String like "Hello there everyone" to "helloThereEveryone". In JavaME support for String and StringBuffer utility operations are quite limited.</p>
[ { "answer_id": 249512, "author": "PhiLho", "author_id": 15459, "author_profile": "https://Stackoverflow.com/users/15459", "pm_score": 3, "selected": true, "text": "String str = \"Hello, there, everyone?\";\n\nStringBuffer result = new StringBuffer(str.length());\nString strl = str.toLowerCase();\nboolean bMustCapitalize = false;\nfor (int i = 0; i < strl.length(); i++)\n{\n char c = strl.charAt(i);\n if (c >= 'a' && c <= 'z')\n {\n if (bMustCapitalize)\n {\n result.append(strl.substring(i, i+1).toUpperCase());\n bMustCapitalize = false;\n }\n else\n {\n result.append(c);\n }\n }\n else\n {\n bMustCapitalize = true;\n }\n}\nSystem.out.println(result);\n" }, { "answer_id": 10498249, "author": "RURANGIRWA Bailly", "author_id": 1381989, "author_profile": "https://Stackoverflow.com/users/1381989", "pm_score": -1, "selected": false, "text": "private String toCamelCase(String s) {\n StringBuffer sb = new StringBuffer();\n String[] x = s.replaceAll(\"[^A-Za-z]\", \" \").replaceAll(\"\\\\s+\", \" \")\n .trim().split(\" \");\n\n for (int i = 0; i < x.length; i++) {\n if (i == 0) {\n x[i] = x[i].toLowerCase();\n } else {\n String r = x[i].substring(1);\n x[i] = String.valueOf(x[i].charAt(0)).toUpperCase() + r;\n\n }\n sb.append(x[i]);\n }\n return sb.toString();\n}\n" }, { "answer_id": 11089164, "author": "Tibi", "author_id": 1464565, "author_profile": "https://Stackoverflow.com/users/1464565", "pm_score": -1, "selected": false, "text": "import org.apache.commons.lang.WordUtils;\n\nString camel = WordUtils.capitalizeFully('I WANT TO BE A CAMEL', new char[]{' '});\n\nreturn camel.replaceAll(\" \", \"\");\n" }, { "answer_id": 11433313, "author": "qoss", "author_id": 1517835, "author_profile": "https://Stackoverflow.com/users/1517835", "pm_score": -1, "selected": false, "text": " String camelCased = \"\";\n String[] tokens = inputString.split(\"\\\\s\");\n for (int i = 0; i < tokens.length; i++) {\n String token = tokens[i];\n camelCased = camelCased + token.substring(0, 1).toUpperCase() + token.substring(1, token.length());\n }\n return camelCased;\n" }, { "answer_id": 16310578, "author": "Cheeso", "author_id": 48082, "author_profile": "https://Stackoverflow.com/users/48082", "pm_score": 1, "selected": false, "text": "private static String toCamelCase(String s) {\n String result = \"\";\n String[] tokens = s.split(\"_\"); // or whatever the divider is\n for (int i = 0, L = tokens.length; i<L; i++) {\n String token = tokens[i];\n if (i==0) result = token.toLowerCase();\n else\n result += token.substring(0, 1).toUpperCase() +\n token.substring(1, token.length()).toLowerCase();\n }\n return result;\n}\n" }, { "answer_id": 33007028, "author": "HS Shin", "author_id": 4853250, "author_profile": "https://Stackoverflow.com/users/4853250", "pm_score": 0, "selected": false, "text": "public static String toCamel(String str) {\n String rtn = str;\n rtn = rtn.toLowerCase();\n Matcher m = Pattern.compile(\"_([a-z]{1})\").matcher(rtn);\n StringBuffer sb = new StringBuffer();\n while (m.find()) {\n m.appendReplacement(sb, m.group(1).toUpperCase());\n }\n m.appendTail(sb);\n rtn = sb.toString();\n return rtn;\n}\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/249470", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22012/" ]
249,489
<p>I hope someone will be able to answer my question.</p> <p>I have Subversion set up, served by Apache2+SSL, doing web development.</p> <p>I want a post-commit hook that runs svn update on my testing server, so when someone commits, it will automatically update the testing site. The hook doesn't work because the certificate is a self generated one and it's not trusted.</p> <p>I've tried to accept (p)ermanently, but it doesn't. </p> <p>Any ideas?</p>
[ { "answer_id": 6049056, "author": "ownking", "author_id": 275443, "author_profile": "https://Stackoverflow.com/users/275443", "pm_score": 0, "selected": false, "text": "svn co file:///path_to/your/repo\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/249489", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
249,499
<p>Evaluate:</p> <pre><code>((((lambda (x) (lambda (y) (lambda (x) (+ x y)))) 3) 4) 5) </code></pre> <p>This is what I did:</p> <ul> <li><p>evaluate <code>((((lambda (x) (lambda (y) (lambda (x) (+ x y)))) 3) 4) 5)</code></p> <ul> <li>evaluate <code>5 -&gt; 5</code></li> </ul></li> <li><p>evaluate <code>(((lambda (x) (lambda (y) (lambda (x) (+ x y)))) 3) 4)</code></p> <ul> <li>evaluate <code>4 -&gt; 4</code></li> </ul></li> <li><p>evaluate <code>((lambda (x) (lambda (y) (lambda (x) (+ x y)))) 3)</code></p> <ul> <li>evaluate <code>3 -&gt; 3</code></li> </ul></li> <li><p><code>(lambda (x) (lambda (y) (lambda (x) (+ x y))))</code> -> <code>(lambda (x) (lambda (y) (lambda (x) (+ x y))))</code></p></li> <li><p>apply <code>(lambda (x) (lambda (y) (lambda (x) (+ x y))))</code> to <code>3</code></p> <ul> <li><p>substitute <code>3</code> -> <code>x</code> in <code>(lambda (y) (lambda (x) (+ x y))</code></p></li> <li><p><code>(lambda (y) (lambda (x) (+ 3 y))</code></p></li> <li><p>evaluate <code>(lambda (y) (lambda (x) (+ 3 y)) -&gt; (lambda (y) (lambda (x) (+ 3 y))</code></p></li> <li><p><code>apply (lambda (y) (lambda (x) (+ 3 y))</code> to <code>4</code></p></li> <li><p>subsitute <code>4 -&gt; y</code> in <code>(lambda (y) (lambda (x) (+ 3 y))</code></p></li> <li><p><code>(lambda (y) (+ 3 4))</code></p></li> <li><p>evaluate <code>(lambda (y) (+ 3 4)) -&gt; (lambda (y) (7))</code></p> <ul> <li>subsitute <code>5</code> -> ?</li> </ul></li> </ul></li> </ul> <p>And then I'm stuck.</p>
[ { "answer_id": 249520, "author": "leppie", "author_id": 15541, "author_profile": "https://Stackoverflow.com/users/15541", "pm_score": 2, "selected": false, "text": "(define part1 (lambda (y) (lambda (x) (+ x y)))) ; basically an adder\n(define part2 (lambda (x) part1)) ; just return part1, x has no effect\n" }, { "answer_id": 249537, "author": "Matthias Benkard", "author_id": 15517, "author_profile": "https://Stackoverflow.com/users/15517", "pm_score": 1, "selected": false, "text": "-substitute 3 -> x in (lambda (y) (lambda (x) (+ x y))\n-(lambda (y) (lambda (x) (+ 3 y))\n" }, { "answer_id": 249539, "author": "mweerden", "author_id": 4285, "author_profile": "https://Stackoverflow.com/users/4285", "pm_score": 1, "selected": false, "text": "x" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/249499", "https://Stackoverflow.com", "https://Stackoverflow.com/users/30622/" ]
249,500
<p>OK, I have a somewhat complicated system in C++. In a nutshell, I need to add a method to a third party abstract base class. The third party also provides a ton of derived classes that also need the new functionality.</p> <p>I'm using a library that provides a standard Shape interface, as well as some common shapes.</p> <pre><code>class Shape { public: Shape(position); virtual ~Shape(); virtual position GetPosition() const; virtual void SetPosition(position); virtual double GetPerimeter() const = 0; private: ... }; class Square : public Shape { public: Square(position, side_length); ... }; class Circle, Rectangle, Hexagon, etc </code></pre> <p>Now, here's my problem. I want the Shape class to also include a GetArea() function. So it seems like I should just do a:</p> <pre><code>class ImprovedShape : public virtual Shape { virtual double GetArea() const = 0; }; class ImprovedSquare : public Square, public ImprovedShape { ... } </code></pre> <p>And then I go and make an ImprovedSquare that inherits from ImprovedShape and Square. Well, as you can see, I have now created the dreaded <a href="http://en.wikipedia.org/wiki/Diamond_problem" rel="nofollow noreferrer">diamond inheritance problem</a>. This would easily be fixed if the third party library used <a href="http://en.wikipedia.org/wiki/Virtual_inheritance" rel="nofollow noreferrer">virtual inheritance</a> for their Square, Circle, etc. However, getting them to do that isn't a reasonable option.</p> <p>So, what do you do when you need to add a little functionality to an interface defined in a library? Is there a good answer?</p> <p>Thanks!</p>
[ { "answer_id": 249666, "author": "Dave Hillier", "author_id": 1575281, "author_profile": "https://Stackoverflow.com/users/1575281", "pm_score": 3, "selected": false, "text": "class ImprovedShape : public virtual Shape\n{\n virtual double GetArea() const = 0;\n};\n" }, { "answer_id": 250443, "author": "twokats", "author_id": 24263, "author_profile": "https://Stackoverflow.com/users/24263", "pm_score": 1, "selected": false, "text": "ImprovedShape" }, { "answer_id": 256783, "author": "fizzer", "author_id": 18167, "author_profile": "https://Stackoverflow.com/users/18167", "pm_score": 1, "selected": false, "text": "GetArea()" }, { "answer_id": 256863, "author": "Pete Kirkham", "author_id": 1527, "author_profile": "https://Stackoverflow.com/users/1527", "pm_score": 1, "selected": false, "text": "#import <iostream>\n\nusing namespace std;\n\n// base types\nclass Shape {\n public:\n Shape () {}\n virtual ~Shape () { }\n virtual void DoShapyStuff () const = 0;\n};\n\nclass RectangularShape : public Shape {\n public:\n RectangularShape () { }\n\n virtual double GetHeight () const = 0 ;\n virtual double GetWidth () const = 0 ;\n};\n\nclass Square : public RectangularShape {\n public:\n Square () { }\n\n virtual void DoShapyStuff () const\n {\n cout << \"I\\'m a square.\" << endl;\n }\n\n virtual double GetHeight () const { return 10.0; }\n virtual double GetWidth () const { return 10.0; }\n};\n\nclass Rect : public RectangularShape {\n public:\n Rect () { }\n\n virtual void DoShapyStuff () const\n {\n cout << \"I\\'m a rectangle.\" << endl;\n }\n\n virtual double GetHeight () const { return 9.0; }\n virtual double GetWidth () const { return 16.0; }\n};\n\n// extension has a cast to Shape rather than extending Shape\nclass HasArea {\n public:\n virtual double GetArea () const = 0;\n virtual Shape& AsShape () = 0;\n virtual const Shape& AsShape () const = 0;\n\n operator Shape& ()\n {\n return AsShape();\n }\n\n operator const Shape& () const\n {\n return AsShape();\n }\n};\n\ntemplate<class S> struct AreaOf { };\n\n// you have to have the declaration before the ShapeWithArea \n// template if you want to use polymorphic behaviour, which \n// is a bit clunky\nstatic double GetArea (const RectangularShape& shape)\n{\n return shape.GetWidth() * shape.GetHeight();\n}\n\ntemplate <class S>\nclass ShapeWithArea : public S, public HasArea {\n public:\n virtual double GetArea () const\n {\n return ::GetArea(*this);\n }\n virtual Shape& AsShape () { return *this; }\n virtual const Shape& AsShape () const { return *this; }\n};\n\n// don't have to write two implementations of GetArea\n// as we use the GetArea for the super type\ntypedef ShapeWithArea<Square> ImprovedSquare;\ntypedef ShapeWithArea<Rect> ImprovedRect;\n\nvoid Demo (const HasArea& hasArea)\n{\n const Shape& shape(hasArea);\n shape.DoShapyStuff();\n cout << \"Area = \" << hasArea.GetArea() << endl;\n}\n\nint main ()\n{\n ImprovedSquare square;\n ImprovedRect rect;\n\n Demo(square);\n Demo(rect);\n\n return 0;\n}\n" }, { "answer_id": 301731, "author": "mstrobl", "author_id": 25965, "author_profile": "https://Stackoverflow.com/users/25965", "pm_score": 0, "selected": false, "text": "class ShapeWithArea : public Shape\n{\n protected:\n Shape* shape_;\n\n public:\n virtual ~ShapeWithArea();\n\n virtual position GetPosition() const { return shape_->GetPosition(); }\n virtual void SetPosition(position) { shape_->SetPosition(); }\n virtual double GetPerimeter() const { return shape_->GetPerimeter(); }\n\n ShapeWithArea (Shape* shape) : shape_(shape) {}\n\n virtual double getArea (void) const = 0;\n};\n" }, { "answer_id": 3823817, "author": "yasouser", "author_id": 338913, "author_profile": "https://Stackoverflow.com/users/338913", "pm_score": 1, "selected": false, "text": "template <class ShapeType, class AreaFunctor> \nint GetArea(const ShapeType& shape, AreaFunctor func);\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/249500", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3175/" ]
249,536
<p>FindBugs has found a potential bug in my code. But it is not a bug.</p> <p>Is it possible to mark this occurrence as 'not a bug' AND have it removed from the bug list?</p> <p>I have documented quite clearly why for each case it is not a bug.</p> <p>For example. A class implements the comparable interface. it has the compareTo method. I have however not overridden the equals method.</p> <p>FindBugs does not like this as the JavaDocs state that it is recommended that</p> <pre><code>(x.compareTo(y)==0) == (x.equals(y)) </code></pre> <p>Although in my case the above condition is and always will be true.</p>
[ { "answer_id": 249543, "author": "VonC", "author_id": 6309, "author_profile": "https://Stackoverflow.com/users/6309", "pm_score": 3, "selected": false, "text": "<Match>\n <Class name=\"com.foobar.MyClass\" />\n <Method name=\"myMethod\" />\n <Bug pattern=\"EQ_COMPARETO_USE_OBJECT_EQUALS\" />\n</Match>\n" }, { "answer_id": 249556, "author": "WMR", "author_id": 2844, "author_profile": "https://Stackoverflow.com/users/2844", "pm_score": 6, "selected": true, "text": "@edu.umd.cs.findbugs.annotations.SuppressWarnings(\n value=\"EQ_COMPARETO_USE_OBJECT_EQUALS\", \n justification=\"because I know better\")\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/249536", "https://Stackoverflow.com", "https://Stackoverflow.com/users/939/" ]
249,540
<p>How do I specify the username and password in order for my program to open a file for reading? The program that needs to access the file is running from an account that does not have read access to the folder the file is in. Program is written in C# and .NET 2, running under XP and file is on a Windows Server 2003 machine.</p>
[ { "answer_id": 249594, "author": "James Newton-King", "author_id": 11829, "author_profile": "https://Stackoverflow.com/users/11829", "pm_score": 4, "selected": false, "text": "using (new Impersonator(\"myUsername\", \"myDomainname\", \"myPassword\"))\n{\n string fileText = File.ReadAllText(\"c:\\test.txt\");\n Console.WriteLine(fileText);\n}\n" }, { "answer_id": 35492964, "author": "ΩmegaMan", "author_id": 285795, "author_profile": "https://Stackoverflow.com/users/285795", "pm_score": 3, "selected": false, "text": "using (Impersonation.LogonUser(\"{domain}\",\n \"{UserName}\", \n \"{Password}\", \n LogonType.Interactive))\n{\n var directory = @\"\\\\MyCorpServer.net\\alpha\\cars\";\n\n Assert.IsTrue(Directory.Exists(directory));\n}\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/249540", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
249,557
<blockquote> <p>If f is a numerical function and n is a positive integer, then we can form the nth repeated application of f, which is defined to be the function whose value at x is f(f(...(f(x))...)). For example, if f is the function x + 1, then the nth repeated application of f is the function x + n. If f is the operation of squaring a number, then the nth repeated application of f is the function that raises its argument to the 2^nth power. Write a procedure that takes as inputs a procedure that computes f and a positive integer n and returns the procedure that computes the nth repeated application of f. Your procedure should be able to be used as follows:</p> <pre><code>((repeated square 2) 5) 625 </code></pre> <p>You can use this to simplify the answer:</p> <pre><code> (define (compose f g) (lambda (x) (f (g x)))) </code></pre> </blockquote>
[ { "answer_id": 249564, "author": "Matthias Benkard", "author_id": 15517, "author_profile": "https://Stackoverflow.com/users/15517", "pm_score": 1, "selected": false, "text": "((repeated square 3) 5)\n-> (square ((repeated square 2) 5))\n-> (square (square ((repeated square 1) 5)))\n-> (square (square (square ((repeated square 0) 5))))\n-> (square (square (square (identity 5))))\n" }, { "answer_id": 824363, "author": "Maxim", "author_id": 11587, "author_profile": "https://Stackoverflow.com/users/11587", "pm_score": 2, "selected": false, "text": "(define (repeated f n)\n (if (= n 1)\n f\n (compose f (repeated f (- n 1)))))\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/249557", "https://Stackoverflow.com", "https://Stackoverflow.com/users/30622/" ]
249,567
<p>What would be the best way to avoid SQL injection on the C#.net platform.</p> <p>Please post an C# implementation if you have any.</p>
[ { "answer_id": 249582, "author": "Greg Beech", "author_id": 13552, "author_profile": "https://Stackoverflow.com/users/13552", "pm_score": 5, "selected": false, "text": "'" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/249567", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11135/" ]
249,570
<p>On a particular Debian server, iostat (and similar) report an unexpectedly high volume (in bytes) of disk writes going on. I am having trouble working out which process is doing these writes.</p> <p>Two interesting points:</p> <ol> <li><p>Tried turning off system services one at a time to no avail. Disk activity remains fairly constant and unexpectedly high.</p></li> <li><p>Despite the writing, do not seem to be consuming more overall space on the disk.</p></li> </ol> <p>Both of those make me think that the writing may be something that the kernel is doing, but I'm not swapping, so it's not clear to me what Linux might try to write.</p> <p>Could try out atop:</p> <p><a href="http://www.atcomputing.nl/Tools/atop/" rel="noreferrer">http://www.atcomputing.nl/Tools/atop/</a></p> <p>but would like to avoid patching my kernel.</p> <p>Any ideas on how to track this down?</p>
[ { "answer_id": 395362, "author": "Igor Pozgaj", "author_id": 19777, "author_profile": "https://Stackoverflow.com/users/19777", "pm_score": 2, "selected": false, "text": "CONFIG_TASKSTATS=y\nCONFIG_TASK_IO_ACCOUNTING=y\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/249570", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
249,573
<p>There is small system, where a database table as queue on MSSQL 2005. Several applications are writing to this table, and one application is reading and processing in a FIFO manner.</p> <p>I have to make it a little bit more advanced to be able to create a distributed system, where several processing application can run. The result should be that 2-10 processing application should be able to run and they should not interfere each other during work.</p> <p>My idea is to extend the queue table with a row showing that a process is already working on it. The processing application will first update the table with it's idetifyer, and then asks for the updated records.</p> <p>So something like this:</p> <pre><code>start transaction update top(10) queue set processing = 'myid' where processing is null select * from processing where processing = 'myid' end transaction </code></pre> <p>After processing, it sets the processing column of the table to something else, like 'done', or whatever.</p> <p>I have three questions about this approach.</p> <p>First: can this work in this form?</p> <p>Second: if it is working, is it effective? Do you have any other ideas to create such a distribution?</p> <p>Third: In MSSQL the locking is row based, but after an amount of rows are locked, the lock is extended to the whole table. So the second application cannot access it, until the first application does not release the transaction. How big can be the selection (top x) in order to not lock the whole table, only create row locks?</p>
[ { "answer_id": 249688, "author": "mjallday", "author_id": 6084, "author_profile": "https://Stackoverflow.com/users/6084", "pm_score": 1, "selected": false, "text": "update mytable with (rowlock) set x=y where a=b\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/249573", "https://Stackoverflow.com", "https://Stackoverflow.com/users/968/" ]
249,578
<p>I'm writing a bash script that needs to delete old files.</p> <p>It's currently implemented using :</p> <pre><code>find $LOCATION -name $REQUIRED_FILES -type f -mtime +1 -delete </code></pre> <p>This will delete of the files older than 1 day.</p> <p>However, what if I need a finer resolution that 1 day, say like 6 hours old? Is there a nice clean way to do it, like there is using find and -mtime?</p>
[ { "answer_id": 249584, "author": "GavinCattell", "author_id": 21644, "author_profile": "https://Stackoverflow.com/users/21644", "pm_score": 2, "selected": false, "text": "man find\n" }, { "answer_id": 249591, "author": "Paul Dixon", "author_id": 6521, "author_profile": "https://Stackoverflow.com/users/6521", "pm_score": 10, "selected": true, "text": "find" }, { "answer_id": 249608, "author": "xtofl", "author_id": 6610, "author_profile": "https://Stackoverflow.com/users/6610", "pm_score": 4, "selected": false, "text": "-newer file" }, { "answer_id": 2957262, "author": "Rajeev Rumale", "author_id": 356377, "author_profile": "https://Stackoverflow.com/users/356377", "pm_score": 1, "selected": false, "text": " Example 6 Selecting a File Using 24-hour Mode\n\n\n The descriptions of -atime, -ctime, and -mtime use the ter-\n minology n ``24-hour periods''. For example, a file accessed\n at 23:59 is selected by:\n\n\n example% find . -atime -1 -print\n\n\n\n\n at 00:01 the next day (less than 24 hours later, not more\n than one day ago). The midnight boundary between days has no\n effect on the 24-hour calculation.\n" }, { "answer_id": 40351544, "author": "Eragonz91", "author_id": 2690656, "author_profile": "https://Stackoverflow.com/users/2690656", "pm_score": 0, "selected": false, "text": "find $PATH -name $log_prefix\"*\"$log_ext -mmin +$num_mins -exec rm -f {} \\;" }, { "answer_id": 44522525, "author": "satyr0909", "author_id": 8154766, "author_profile": "https://Stackoverflow.com/users/8154766", "pm_score": 0, "selected": false, "text": "/etc/crontab" }, { "answer_id": 44837673, "author": "Malcolm Boekhoff", "author_id": 1388639, "author_profile": "https://Stackoverflow.com/users/1388639", "pm_score": 1, "selected": false, "text": "-mtime +(X * 0.041667)\n" }, { "answer_id": 48887660, "author": "Axel Ronsin", "author_id": 4213669, "author_profile": "https://Stackoverflow.com/users/4213669", "pm_score": 5, "selected": false, "text": "$ find /path/to/the/folder -name '*.*' -mmin +59 -delete > /dev/null\n" }, { "answer_id": 61247632, "author": "kbulgrien", "author_id": 856172, "author_profile": "https://Stackoverflow.com/users/856172", "pm_score": 1, "selected": false, "text": "find" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/249578", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13523/" ]
249,580
<p>What is the recommended practice? Should I add the my sub-folder under the fitnesse folder to version control? </p> <p><em>Context: working on a single developer rails pet project. I've my rails project under version-control (Subversion) however my fitnesse wiki pages lie under the fitnesse program folder.</em></p> <p>Fitnesse seems to have its own version-control... (I see numbered zips along with each of my wiki pages) Is it reliable? Where does it store the revisions?</p>
[ { "answer_id": 446230, "author": "Gishu", "author_id": 1695, "author_profile": "https://Stackoverflow.com/users/1695", "pm_score": 6, "selected": true, "text": "-d" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/249580", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1695/" ]
249,581
<p>I have checked with the <a href="http://en.wikipedia.org/wiki/Facade_pattern" rel="noreferrer">wikipedia article</a>, and it seems like it is missing the c++ version of a code example. I am not able to fully appreciate the Facade pattern without this, can you please help explain it to me using C++?</p>
[ { "answer_id": 249656, "author": "Dave Hillier", "author_id": 1575281, "author_profile": "https://Stackoverflow.com/users/1575281", "pm_score": 3, "selected": false, "text": "// \"Subsystem ClassA\" \n#include <iostream>\nclass SubSystemOne\n{\npublic:\n void MethodOne()\n {\n std::cout << \" SubSystemOne Method\" << std::endl;\n }\n}\n\n// Subsystem ClassB\" \n\nclass SubSystemTwo\n{\npublic:\n void MethodTwo()\n {\n std::cout << \" SubSystemTwo Method\" << std::endl;\n }\n}\n\n// Subsystem ClassC\" \n\nclass SubSystemThree\n{\npublic:\n void MethodThree()\n {\n std::cout << \" SubSystemThree Method\" << std::endl;\n }\n}\n\n// Subsystem ClassD\" \n\nclass SubSystemFour\n{\npublic:\n void MethodFour()\n {\n std::cout << \" SubSystemFour Method\" << std::endl;\n }\n}\n\n// \"Facade\" \n\nclass Facade\n{\n SubSystemOne one;\n SubSystemTwo two;\n SubSystemThree three;\n SubSystemFour four;\n\npublic:\n Facade()\n {\n }\n\n void MethodA()\n {\n std::cout << \"\\nMethodA() ---- \" << std::endl;\n one.MethodOne();\n two.MethodTwo();\n four.MethodFour();\n }\n void MethodB()\n {\n std::cout << \"\\nMethodB() ---- \" << std::endl;\n two.MethodTwo();\n three.MethodThree();\n }\n}\n\nint Main()\n{\n Facade facade = new Facade();\n\n facade.MethodA();\n facade.MethodB();\n\n return 0;\n}\n" }, { "answer_id": 249981, "author": "Gishu", "author_id": 1695, "author_profile": "https://Stackoverflow.com/users/1695", "pm_score": 6, "selected": true, "text": "sResource = LWCPPSimple::get(\"http://www.perl.org\")\n" }, { "answer_id": 249995, "author": "wasker", "author_id": 21952, "author_profile": "https://Stackoverflow.com/users/21952", "pm_score": 4, "selected": false, "text": "class Engine\n{\n\npublic:\n void Start() { }\n\n};\n\nclass Headlights\n{\n\npublic:\n void TurnOn() { }\n\n};\n\n// That's your facade.\nclass Car\n{\n\nprivate:\n Engine engine;\n Headlights headlights;\n\npublic:\n void TurnIgnitionKeyOn()\n {\n headlights.TurnOn();\n engine.Start();\n }\n\n};\n\nint Main(int argc, char *argv[])\n{\n // Consuming facade.\n Car car;\n car.TurnIgnitionKeyOn();\n\n return 0;\n}\n" }, { "answer_id": 2457357, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "class A {\n private B b; // Class A uses Class B, the \"interface\"\n public int f() { return b.g(); }\n};\n\nclass B {\n private C c; // class B uses class C, a \"subsystem\"\n private ... ...; // other subsystems can be added\n public int g() { c.h(); return c.i(); }\n};\n\nclass C { // a subsystem\n public void h() { ... }\n public int i() { return x; }\n};\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/249581", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22076/" ]
249,587
<p>I want to scale an image in C# with quality level as good as Photoshop does. Is there any C# image processing library available to do this thing?</p>
[ { "answer_id": 249601, "author": "Hallgrim", "author_id": 15454, "author_profile": "https://Stackoverflow.com/users/15454", "pm_score": 4, "selected": false, "text": "Bitmap original = ...\nBitmap scaled = new Bitmap(new Size(original.Width * 4, original.Height * 4));\nusing (Graphics graphics = Graphics.FromImage(scaled)) {\n graphics.DrawImage(original, new Rectangle(0, 0, scaled.Width, scaled.Height));\n}\n" }, { "answer_id": 353193, "author": "plinth", "author_id": 20481, "author_profile": "https://Stackoverflow.com/users/20481", "pm_score": 2, "selected": false, "text": "// BiCubic is one technique available in PhotoShop\nResampleCommand resampler = new ResampleCommand(newSize, ResampleMethod.BiCubic);\nAtalaImage newImage = resampler.Apply(oldImage).Image;\n" }, { "answer_id": 353222, "author": "Doctor Jones", "author_id": 39277, "author_profile": "https://Stackoverflow.com/users/39277", "pm_score": 9, "selected": true, "text": "using System;\nusing System.Collections.Generic;\nusing System.Drawing;\nusing System.Drawing.Imaging;\n\nnamespace DoctaJonez.Drawing.Imaging\n{\n /// <summary>\n /// Provides various image untilities, such as high quality resizing and the ability to save a JPEG.\n /// </summary>\n public static class ImageUtilities\n { \n /// <summary>\n /// A quick lookup for getting image encoders\n /// </summary>\n private static Dictionary<string, ImageCodecInfo> encoders = null;\n\n /// <summary>\n /// A lock to prevent concurrency issues loading the encoders.\n /// </summary>\n private static object encodersLock = new object();\n\n /// <summary>\n /// A quick lookup for getting image encoders\n /// </summary>\n public static Dictionary<string, ImageCodecInfo> Encoders\n {\n //get accessor that creates the dictionary on demand\n get\n {\n //if the quick lookup isn't initialised, initialise it\n if (encoders == null)\n {\n //protect against concurrency issues\n lock (encodersLock)\n {\n //check again, we might not have been the first person to acquire the lock (see the double checked lock pattern)\n if (encoders == null)\n {\n encoders = new Dictionary<string, ImageCodecInfo>();\n\n //get all the codecs\n foreach (ImageCodecInfo codec in ImageCodecInfo.GetImageEncoders())\n {\n //add each codec to the quick lookup\n encoders.Add(codec.MimeType.ToLower(), codec);\n }\n }\n }\n }\n\n //return the lookup\n return encoders;\n }\n }\n\n /// <summary>\n /// Resize the image to the specified width and height.\n /// </summary>\n /// <param name=\"image\">The image to resize.</param>\n /// <param name=\"width\">The width to resize to.</param>\n /// <param name=\"height\">The height to resize to.</param>\n /// <returns>The resized image.</returns>\n public static System.Drawing.Bitmap ResizeImage(System.Drawing.Image image, int width, int height)\n {\n //a holder for the result\n Bitmap result = new Bitmap(width, height);\n //set the resolutions the same to avoid cropping due to resolution differences\n result.SetResolution(image.HorizontalResolution, image.VerticalResolution);\n\n //use a graphics object to draw the resized image into the bitmap\n using (Graphics graphics = Graphics.FromImage(result))\n {\n //set the resize quality modes to high quality\n graphics.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;\n graphics.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;\n graphics.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;\n //draw the image into the target bitmap\n graphics.DrawImage(image, 0, 0, result.Width, result.Height);\n }\n\n //return the resulting bitmap\n return result;\n }\n\n /// <summary> \n /// Saves an image as a jpeg image, with the given quality \n /// </summary> \n /// <param name=\"path\">Path to which the image would be saved.</param> \n /// <param name=\"quality\">An integer from 0 to 100, with 100 being the \n /// highest quality</param> \n /// <exception cref=\"ArgumentOutOfRangeException\">\n /// An invalid value was entered for image quality.\n /// </exception>\n public static void SaveJpeg(string path, Image image, int quality)\n {\n //ensure the quality is within the correct range\n if ((quality < 0) || (quality > 100))\n {\n //create the error message\n string error = string.Format(\"Jpeg image quality must be between 0 and 100, with 100 being the highest quality. A value of {0} was specified.\", quality);\n //throw a helpful exception\n throw new ArgumentOutOfRangeException(error);\n }\n\n //create an encoder parameter for the image quality\n EncoderParameter qualityParam = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, quality);\n //get the jpeg codec\n ImageCodecInfo jpegCodec = GetEncoderInfo(\"image/jpeg\");\n\n //create a collection of all parameters that we will pass to the encoder\n EncoderParameters encoderParams = new EncoderParameters(1);\n //set the quality parameter for the codec\n encoderParams.Param[0] = qualityParam;\n //save the image using the codec and the parameters\n image.Save(path, jpegCodec, encoderParams);\n }\n\n /// <summary> \n /// Returns the image codec with the given mime type \n /// </summary> \n public static ImageCodecInfo GetEncoderInfo(string mimeType)\n {\n //do a case insensitive search for the mime type\n string lookupKey = mimeType.ToLower();\n\n //the codec to return, default to null\n ImageCodecInfo foundCodec = null;\n\n //if we have the encoder, get it to return\n if (Encoders.ContainsKey(lookupKey))\n {\n //pull the codec from the lookup\n foundCodec = Encoders[lookupKey];\n }\n\n return foundCodec;\n } \n }\n}\n" }, { "answer_id": 8646234, "author": "Leslie Marshall", "author_id": 1113505, "author_profile": "https://Stackoverflow.com/users/1113505", "pm_score": 2, "selected": false, "text": " public Image ResizeImage(Image source, RectangleF destinationBounds)\n {\n RectangleF sourceBounds = new RectangleF(0.0f,0.0f,(float)source.Width, (float)source.Height);\n RectangleF scaleBounds = new RectangleF();\n\n Image destinationImage = new Bitmap((int)destinationBounds.Width, (int)destinationBounds.Height);\n Graphics graph = Graphics.FromImage(destinationImage);\n graph.InterpolationMode =\n System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;\n\n // Fill with background color\n graph.FillRectangle(new SolidBrush(System.Drawing.Color.White), destinationBounds);\n\n float resizeRatio, sourceRatio;\n float scaleWidth, scaleHeight;\n\n sourceRatio = (float)source.Width / (float)source.Height;\n\n if (sourceRatio >= 1.0f)\n {\n //landscape\n resizeRatio = destinationBounds.Width / sourceBounds.Width;\n scaleWidth = destinationBounds.Width;\n scaleHeight = sourceBounds.Height * resizeRatio;\n float trimValue = destinationBounds.Height - scaleHeight;\n graph.DrawImage(source, 0, (trimValue / 2), destinationBounds.Width, scaleHeight);\n }\n else\n {\n //portrait\n resizeRatio = destinationBounds.Height/sourceBounds.Height;\n scaleWidth = sourceBounds.Width * resizeRatio;\n scaleHeight = destinationBounds.Height;\n float trimValue = destinationBounds.Width - scaleWidth;\n graph.DrawImage(source, (trimValue / 2), 0, scaleWidth, destinationBounds.Height);\n }\n\n return destinationImage;\n\n }\n" }, { "answer_id": 14278580, "author": "DareDevil", "author_id": 1147352, "author_profile": "https://Stackoverflow.com/users/1147352", "pm_score": 1, "selected": false, "text": "private static Bitmap ResizeBitmap(Bitmap srcbmp, int width, int height )\n{\n Bitmap newimage = new Bitmap(width, height);\n using (Graphics g = Graphics.FromImage(newimage))\n g.DrawImage(srcbmp, 0, 0, width, height);\n return newimage;\n}\n" }, { "answer_id": 25343437, "author": "bafsar", "author_id": 2374053, "author_profile": "https://Stackoverflow.com/users/2374053", "pm_score": 0, "selected": false, "text": "public static System.Drawing.Bitmap ResizeImage(System.Drawing.Image image, Size size)\n{\n return ResizeImage(image, size.Width, size.Height);\n}\n\n\npublic static Size GetProportionedSize(Image image, int maxWidth, int maxHeight, bool withProportion)\n{\n if (withProportion)\n {\n double sourceWidth = image.Width;\n double sourceHeight = image.Height;\n\n if (sourceWidth < maxWidth && sourceHeight < maxHeight)\n {\n maxWidth = (int)sourceWidth;\n maxHeight = (int)sourceHeight;\n }\n else\n {\n double aspect = sourceHeight / sourceWidth;\n\n if (sourceWidth < sourceHeight)\n {\n maxWidth = Convert.ToInt32(Math.Round((maxHeight / aspect), 0));\n }\n else\n {\n maxHeight = Convert.ToInt32(Math.Round((maxWidth * aspect), 0));\n }\n }\n }\n\n return new Size(maxWidth, maxHeight);\n}\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/249587", "https://Stackoverflow.com", "https://Stackoverflow.com/users/191/" ]
249,607
<p>I am using Visual C++ 2005 Express Edition and get the following linker errors:</p> <pre><code>19&gt;mylib1.lib(mylibsource1.obj) : error LNK2019: unresolved external symbol "__declspec(dllimport) public: void __thiscall std::exception::_Raise(void)const " (__imp_?_Raise@exception@std@@QBEXXZ) referenced in function "protected: static void __cdecl std::vector&lt;class mytype,class std::allocator&lt;class mytype&gt; &gt;::_Xlen(void)" (?_Xlen@?$vector@Vmytype@@V?$allocator@Vmytype@@@std@@@std@@KAXXZ) 19&gt;mylib2.lib(mylibsource2.obj) : error LNK2001: unresolved external symbol "__declspec(dllimport) public: void __thiscall std::exception::_Raise(void)const " (__imp_?_Raise@exception@std@@QBEXXZ) 19&gt;mylib1.lib(mylibsource1.obj) : error LNK2019: unresolved external symbol "__declspec(dllimport) public: __thiscall std::exception::exception(char const *,int)" (__imp_??0exception@std@@QAE@PBDH@Z) referenced in function "public: __thiscall std::logic_error::logic_error(class std::basic_string&lt;char,struct std::char_traits&lt;char&gt;,class std::allocator&lt;char&gt; &gt; const &amp;)" (??0logic_error@std@@QAE@ABV?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@1@@Z) 19&gt;mylib2.lib(mylibsource2.obj) : error LNK2001: unresolved external symbol "__declspec(dllimport) public: __thiscall std::exception::exception(char const *,int)" (__imp_??0exception@std@@QAE@PBDH@Z) </code></pre> <p>I turned off exceptions in generated code, and I am using before including the vector header file:</p> <pre><code>#define _HAS_EXCEPTIONS 0 </code></pre> <p>A few Google results turned up some stuff, but no "aha!" solutions that worked for me.</p> <p>EDIT:</p> <p>As noted "_HAS_EXCEPTIONS 0" doesn't turn off exceptions, per se. What it does is, at least in the vector header file, is call _Raise on an exception object instead of calling the C++ "throw". In my case, it can't link to the exception object's _Raise function since I am not including the correct library. What that library is, though, is not obvious.</p>
[ { "answer_id": 249685, "author": "MSalters", "author_id": 15416, "author_profile": "https://Stackoverflow.com/users/15416", "pm_score": 0, "selected": false, "text": "#define the _HAS_EXCEPTIONS 0" }, { "answer_id": 254069, "author": "Jim Buck", "author_id": 2666, "author_profile": "https://Stackoverflow.com/users/2666", "pm_score": 2, "selected": true, "text": "#define _STATIC_CPPLIB\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/249607", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2666/" ]
249,618
<p>Can anyone explain to me how to get the visual state manager to work with a WPF application? It's just been added to the new wpftoolkit. I installed it as told, but even the sample doesn't show the VSM. In silverlight it work, but not in WPF. If installed the latest Blend 2 and updated with the SP1. </p>
[ { "answer_id": 249833, "author": "Sorskoot", "author_id": 31722, "author_profile": "https://Stackoverflow.com/users/31722", "pm_score": 2, "selected": false, "text": "HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Expression\\Blend\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/249618", "https://Stackoverflow.com", "https://Stackoverflow.com/users/31722/" ]
249,637
<p>Let's suppose I have an applet running within a page in a browser. What happens when the browser is closed by the user?</p> <p>Is the applet notified so that it can perform some kind of close action on its side (closing connections opened to a server, cleaning static variables, ...)?</p> <p>Also, I assume the same behavior would apply for a page refresh or page navigation (instead of browser close). The browser remains opened but the applet is gone. Although when you close the browser you also close the JVM so I'm unsure at this point.</p> <p>Thanks, JB</p>
[ { "answer_id": 249643, "author": "keparo", "author_id": 19468, "author_profile": "https://Stackoverflow.com/users/19468", "pm_score": 3, "selected": true, "text": "public void finalize () {\n destroy();\n}\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/249637", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7218/" ]
249,655
<p>I work on a large project in Delphi 5. Today, after merging two branches of the app together, one of the hundreds of units, UnitMain (the main form's unit, would you guess) stopped recognizing the Application global.</p> <p>This is a rather bizarre problem - I could get the program to compile by defining Application: TApplication in UnitMain, and setting that to the Application from our .dpr project file, but that leads to an access violation, which isn't much of a surprise with Application being the special thing it is.</p> <p>I'm hoping someone has faced the same problem before, or knows enough of Delphi VCL's inner workings to help me out here.</p> <pre><code>unit UnitMain; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, Menus, ComCtrls, StdCtrls, cxButtons, ExtCtrls, IniFiles, ShellAPI, LMDControl, LMDBaseControl, LMDBaseGraphicControl, LMDGraphicControl, LMDScrollText, cxControls, cxContainer, cxListBox, Psock, NMFtp, db, DBTables, FileCtrl, Configs, cxHint, DSetFunc, OleCtrls, DsInformation, InterAppComm, ActnList, ADODB, OleServer, CRAXDRT_TLB; </code></pre> <p>The exact error is that the compiler does not recognize Application in this unit. For example, for a Application.ProcessMessages; call, the error is "Object or class type required". None of the other units has this problem.</p>
[ { "answer_id": 249669, "author": "Re0sless", "author_id": 2098, "author_profile": "https://Stackoverflow.com/users/2098", "pm_score": 2, "selected": false, "text": "unit MyUnit;\n\ninterface\n\nuses\n Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms;\n" }, { "answer_id": 249930, "author": "Mike Sutton", "author_id": 23008, "author_profile": "https://Stackoverflow.com/users/23008", "pm_score": 3, "selected": false, "text": "Forms.Application.ProcessMessages;\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/249655", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15477/" ]
249,657
<p>could someone provide working example (full maven plugin configuration) how to copy built jar file to a specific server(s) at the time of deploy phase?</p> <p>I have tried to look at wagon plugin, but it is hugely undocumented and I was not able to set it up. The build produces standard jar that is being deployed to Nexus, but I need to put the jar also to the test server automatically over local network (\someserver\testapp\bin).</p> <p>I will be grateful for any hints.</p> <p>Thank you</p>
[ { "answer_id": 250021, "author": "Petr Macek", "author_id": 15045, "author_profile": "https://Stackoverflow.com/users/15045", "pm_score": 3, "selected": false, "text": "<plugin>\n <groupId>org.apache.maven.plugins</groupId>\n <artifactId>maven-dependency-plugin</artifactId>\n <executions>\n <execution>\n <id>copy-to-ebs</id>\n <phase>deploy</phase>\n <goals>\n <goal>copy</goal>\n </goals>\n <configuration>\n <artifactItems>\n <artifactItem>\n <groupId>${project.groupId}</groupId>\n <artifactId>${project.artifactId}</artifactId>\n <version>${project.version}</version>\n <type>${project.packaging}</type>\n </artifactItem>\n </artifactItems>\n <outputDirectory>\\\\someserver\\somedirectory</outputDirectory>\n <stripVersion>true</stripVersion> \n </configuration>\n </execution> \n </executions>\n</plugin>\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/249657", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15045/" ]
249,664
<p>I found the discussion on <a href="https://stackoverflow.com/questions/105007/do-you-test-private-method">Do you test private method</a> informative.</p> <p>I have decided, that in some classes, I want to have protected methods, but test them. Some of these methods are static and short. Because most of the public methods make use of them, I will probably be able to safely remove the tests later. But for starting with a TDD approach and avoid debugging, I really want to test them.</p> <p>I thought of the following:</p> <ul> <li><a href="http://www.refactoring.com/catalog/replaceMethodWithMethodObject.html" rel="noreferrer">Method Object</a> as adviced in <a href="https://stackoverflow.com/questions/105007/do-you-test-private-method#105021">an answer</a> seems to be overkill for this.</li> <li>Start with public methods and when code coverage is given by higher level tests, turn them protected and remove the tests.</li> <li>Inherit a class with a testable interface making protected methods public</li> </ul> <p>Which is best practice? Is there anything else?</p> <p>It seems, that JUnit automatically changes protected methods to be public, but I did not have a deeper look at it. PHP does not allow this via <a href="http://php.net/language.oop5.reflection" rel="noreferrer">reflection</a>.</p>
[ { "answer_id": 249776, "author": "troelskn", "author_id": 18180, "author_profile": "https://Stackoverflow.com/users/18180", "pm_score": 6, "selected": false, "text": "class Foo {\n protected function stuff() {\n // secret stuff, you want to test\n }\n}\n\nclass SubFoo extends Foo {\n public function exposedStuff() {\n return $this->stuff();\n }\n}\n" }, { "answer_id": 254468, "author": "Michael Johnson", "author_id": 17688, "author_profile": "https://Stackoverflow.com/users/17688", "pm_score": 4, "selected": false, "text": "class ClassToTest\n{\n protected function testThisMethod()\n {\n // Implement stuff here\n }\n}\n" }, { "answer_id": 2790847, "author": "David Harkness", "author_id": 285873, "author_profile": "https://Stackoverflow.com/users/285873", "pm_score": 3, "selected": false, "text": "class Example {\n protected function getMessage() {\n return 'hello';\n }\n}\n" }, { "answer_id": 2798203, "author": "uckelman", "author_id": 181106, "author_profile": "https://Stackoverflow.com/users/181106", "pm_score": 10, "selected": true, "text": "protected static function getMethod($name) {\n $class = new ReflectionClass('MyClass');\n $method = $class->getMethod($name);\n $method->setAccessible(true);\n return $method;\n}\n\npublic function testFoo() {\n $foo = self::getMethod('foo');\n $obj = new MyClass();\n $foo->invokeArgs($obj, array(...));\n ...\n}\n" }, { "answer_id": 5671560, "author": "teastburn", "author_id": 224221, "author_profile": "https://Stackoverflow.com/users/224221", "pm_score": 5, "selected": false, "text": "class PHPUnitUtil {\n /**\n * Get a private or protected method for testing/documentation purposes.\n * How to use for MyClass->foo():\n * $cls = new MyClass();\n * $foo = PHPUnitUtil::getPrivateMethod($cls, 'foo');\n * $foo->invoke($cls, $...);\n * @param object $obj The instantiated instance of your class\n * @param string $name The name of your private/protected method\n * @return ReflectionMethod The method you asked for\n */\n public static function getPrivateMethod($obj, $name) {\n $class = new ReflectionClass($obj);\n $method = $class->getMethod($name);\n $method->setAccessible(true);\n return $method;\n }\n // ... some other functions\n}\n" }, { "answer_id": 8702347, "author": "robert.egginton", "author_id": 987484, "author_profile": "https://Stackoverflow.com/users/987484", "pm_score": 6, "selected": false, "text": "class PHPUnitUtil\n{\n public static function callMethod($obj, $name, array $args) {\n $class = new \\ReflectionClass($obj);\n $method = $class->getMethod($name);\n $method->setAccessible(true);\n return $method->invokeArgs($obj, $args);\n }\n}\n" }, { "answer_id": 70153700, "author": "AlexeyP0708", "author_id": 11903519, "author_profile": "https://Stackoverflow.com/users/11903519", "pm_score": 0, "selected": false, "text": " <?php\n class Helper{\n public static function sandbox(\\Closure $call,$target,?string $slaveClass=null,...$args)\n {\n $slaveClass=!empty($slaveClass)?$slaveClass:(is_string($target)?$target:get_class($target));\n $target=!is_string($target)?$target:null;\n $call=$call->bindTo($target,$slaveClass);\n return $call(...$args);\n }\n }\n class A{\n private $prop='bay';\n public function get()\n {\n return $this->prop; \n }\n \n }\n class B extends A{}\n $b=new B;\n $priv_prop=Helper::sandbox(function(...$args){\n return $this->prop;\n },$b,A::class);\n \n var_dump($priv_prop);// bay\n \n Helper::sandbox(function(...$args){\n $this->prop=$args[0];\n },$b,A::class,'hello');\n var_dump($b->get());// hello\n" }, { "answer_id": 70911711, "author": "Артем Вирский", "author_id": 13363316, "author_profile": "https://Stackoverflow.com/users/13363316", "pm_score": 0, "selected": false, "text": "<?php\n\nclass A\n{\n private string $value = 'Kolobol';\n private string $otherPrivateValue = 'I\\'m very private, like a some kind of password!';\n\n public function setValue(string $value): void\n {\n $this->value = $value;\n }\n\n private function getValue(): string\n {\n return $this->value . ': ' . $this->getVeryPrivate();\n }\n\n private function getVeryPrivate()\n {\n return $this->otherPrivateValue;\n }\n}\n\n$getPrivateProperty = function &(string $propName) {\n return $this->$propName;\n};\n\n$getPrivateMethod = function (string $methodName) {\n return Closure::fromCallable([$this, $methodName]);\n};\n\n$objA = new A;\n$getPrivateProperty = Closure::bind($getPrivateProperty, $objA, $objA);\n$getPrivateMethod = Closure::bind($getPrivateMethod, $objA, $objA);\n$privateByLink = &$getPrivateProperty('value');\n$privateMethod = $getPrivateMethod('getValue');\n\necho $privateByLink, PHP_EOL; // Kolobok\n\n$objA->setValue('Zmey-Gorynich');\necho $privateByLink, PHP_EOL; // Zmey-Gorynich\n\n$privateByLink = 'Alyonushka';\necho $privateMethod(); // Alyonushka: I'm very private, like a some kind of password!\n" }, { "answer_id": 71605134, "author": "Dan", "author_id": 6394404, "author_profile": "https://Stackoverflow.com/users/6394404", "pm_score": 0, "selected": false, "text": "class MethodInvoker\n{\n public function invoke($object, string $methodName, array $args=[]) {\n $privateMethod = $this->getMethod(get_class($object), $methodName);\n\n return $privateMethod->invokeArgs($object, $args);\n }\n\n private function getMethod(string $className, string $methodName) {\n $class = new \\ReflectionClass($className);\n \n $method = $class->getMethod($methodName);\n $method->setAccessible(true);\n \n return $method;\n }\n}\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/249664", "https://Stackoverflow.com", "https://Stackoverflow.com/users/32679/" ]
249,667
<p>Say you get a recordset like the following:</p> <pre><code>| ID | Foo | Bar | Red | |-----|------|------|------| | 1 | 100 | NULL | NULL | | 1 | NULL | 200 | NULL | | 1 | NULL | NULL | 300 | | 2 | 400 | NULL | NULL | | ... | ... | ... | ... | -- etc. </code></pre> <p>And you want:</p> <pre><code>| ID | Foo | Bar | Red | |-----|-----|-----|-----| | 1 | 100 | 200 | 300 | | 2 | 400 | ... | ... | | ... | ... | ... | ... | -- etc. </code></pre> <p>You could use something like:</p> <pre><code>SELECT ID, MAX(Foo) AS Foo, MAX(Bar) AS Bar, MAX(Red) AS Red FROM foobarred GROUP BY ID </code></pre> <hr> <p>Now, how might you accomplish similar when Foo, Bar, and Red are VARCHAR?</p> <pre><code>| ID | Foo | Bar | Red | |-----|----------|---------|---------| | 1 | 'Text1' | NULL | NULL | | 1 | NULL | 'Text2' | NULL | | 1 | NULL | NULL | 'Text3' | | 2 | 'Test4' | NULL | NULL | | ... | ... | ... | ... | -- etc. </code></pre> <p>To:</p> <pre><code>| ID | Foo | Bar | Red | |-----|----------|---------|---------| | 1 | 'Text1' | 'Text2' | 'Text3' | | 2 | 'Text4' | ... | ... | | ... | ... | ... | ... | -- etc. </code></pre> <hr> <p>Currently working primarily with SQL Server 2000; but have access to 2005 servers.</p>
[ { "answer_id": 249719, "author": "Eoin Campbell", "author_id": 30155, "author_profile": "https://Stackoverflow.com/users/30155", "pm_score": 1, "selected": true, "text": "CREATE TABLE Flatten (\n id int not null,\n foo Nvarchar(10) null,\n bar Nvarchar(10) null,\n red Nvarchar(10) null)\n\nINSERT INTO Flatten (ID, foo, bar, red) VALUES (1, 'Text1', null, null)\nINSERT INTO Flatten (ID, foo, bar, red) VALUES (1, null, 'Text2', null)\nINSERT INTO Flatten (ID, foo, bar, red) VALUES (1, null, null, 'Text3')\nINSERT INTO Flatten (ID, foo, bar, red) VALUES (2, 'Text4', null, null)\n\n\n\nSELECT \n ID, \n max(foo),\n max(bar),\n max(red)\nFROM\nFlatten\nGROUP BY ID\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/249667", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15031/" ]
249,671
<p>I have created the following style for a listbox that will have an image displayed next to some text:</p> <pre><code>&lt;Style x:Key="ImageListBoxStyle" TargetType="{x:Type ListBox}"&gt; &lt;Setter Property="SnapsToDevicePixels" Value="true"/&gt; &lt;Setter Property="BorderThickness" Value="1"/&gt; &lt;Setter Property="ScrollViewer.HorizontalScrollBarVisibility" Value="Auto"/&gt; &lt;Setter Property="ScrollViewer.VerticalScrollBarVisibility" Value="Auto"/&gt; &lt;Setter Property="ScrollViewer.CanContentScroll" Value="True"/&gt; &lt;Setter Property="ItemContainerStyle"&gt; &lt;Setter.Value&gt; &lt;!-- Simple ListBoxItem - This is used for each Item in a ListBox. The item's content is placed in the ContentPresenter --&gt; &lt;Style TargetType="{x:Type ListBoxItem}"&gt; &lt;Setter Property="SnapsToDevicePixels" Value="true"/&gt; &lt;Setter Property="OverridesDefaultStyle" Value="true"/&gt; &lt;Setter Property="VerticalContentAlignment" Value="Center"/&gt; &lt;Setter Property="Template"&gt; &lt;Setter.Value&gt; &lt;ControlTemplate TargetType="{x:Type ListBoxItem}"&gt; &lt;Grid SnapsToDevicePixels="true"&gt; &lt;Border x:Name="Border"&gt; &lt;Grid Height="40"&gt; &lt;Grid.ColumnDefinitions&gt; &lt;ColumnDefinition Width="Auto"/&gt; &lt;ColumnDefinition Width="*"/&gt; &lt;/Grid.ColumnDefinitions&gt; &lt;Image x:Name="DisplayImage" Source="{Binding Path=ThumbnailImage}" Height="30" Width="30" Grid.Column="0"/&gt; &lt;ContentPresenter x:Name="DisplayText" HorizontalAlignment="Stretch" VerticalAlignment="Center" Grid.Column="1"/&gt; &lt;!--&lt;ContentPresenter.Resources&gt; &lt;Style TargetType="{x:Type TextBlock}"&gt; &lt;Setter Property="Foreground" Value="Black"/&gt; &lt;/Style&gt; &lt;/ContentPresenter.Resources&gt;--&gt; &lt;!--Content="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType=ListBox}, Path=DisplayMemberPath, Converter={StaticResource myDisplayMemberConverter}}"--&gt; &lt;!--&lt;Label x:Name="Text" Content="{Binding Path=FullNameAndTitle}" Foreground="Black" VerticalAlignment="{TemplateBinding VerticalContentAlignment}" VerticalContentAlignment="Center" HorizontalAlignment="Stretch" Grid.Column="1" Height="40"/&gt;--&gt; &lt;/Grid&gt; &lt;/Border&gt; &lt;/Grid&gt; &lt;ControlTemplate.Triggers&gt; &lt;Trigger Property="IsSelected" Value="true"&gt; &lt;!--&lt;Setter Property="FontWeight" Value="Bold" TargetName="DisplayText"/&gt;--&gt; &lt;!--&lt;Setter Property="Style" Value="{StaticResource SelectedTextStyle}" TargetName="DisplayText"/&gt;--&gt; &lt;Setter Property="Background" Value="DarkBlue" TargetName="Border"/&gt; &lt;Setter Property="Width" Value="40" TargetName="DisplayImage"/&gt; &lt;Setter Property="Height" Value="40" TargetName="DisplayImage"/&gt; &lt;/Trigger&gt; &lt;/ControlTemplate.Triggers&gt; &lt;/ControlTemplate&gt; &lt;/Setter.Value&gt; &lt;/Setter&gt; &lt;/Style&gt; &lt;/Setter.Value&gt; &lt;/Setter&gt; &lt;Setter Property="Template"&gt; &lt;Setter.Value&gt; &lt;ControlTemplate TargetType="{x:Type ListBox}"&gt; &lt;Grid&gt; &lt;Border x:Name="Border" Background="{TemplateBinding Background}" BorderBrush="Black" BorderThickness="{TemplateBinding BorderThickness}"&gt; &lt;Grid&gt; &lt;ScrollViewer Margin="1,1,1,1" Focusable="false" Background="{TemplateBinding Background}" SnapsToDevicePixels="True"&gt; &lt;StackPanel IsItemsHost="true"/&gt; &lt;/ScrollViewer&gt; &lt;/Grid&gt; &lt;/Border&gt; &lt;/Grid&gt; &lt;ControlTemplate.Triggers&gt; &lt;Trigger Property="IsGrouping" Value="true"&gt; &lt;Setter Property="ScrollViewer.CanContentScroll" Value="false"/&gt; &lt;/Trigger&gt; &lt;/ControlTemplate.Triggers&gt; &lt;/ControlTemplate&gt; &lt;/Setter.Value&gt; &lt;/Setter&gt; &lt;/Style&gt; </code></pre> <p>I have to use the contentpresenter as I am filtering what is displayed (text wise) using the DisplayMemberPath of the ListBox itself.</p> <p>All I want to do is set the FontWeight to Bold and the Foreground to White when an item is selected in the ListBox.</p> <p>Has anyone encountered a problem like this? I have looked at some related questions but people have been able to use a TextBlock to get around their issues I can't unfortunately.</p> <p>Any info ppl can give will be appreciated.</p> <p>Cheers</p>
[ { "answer_id": 258612, "author": "Bijington", "author_id": 32348, "author_profile": "https://Stackoverflow.com/users/32348", "pm_score": 5, "selected": false, "text": "<Setter Property=\"FontWeight\" Value=\"Bold\"/>\n<Setter Property=\"Foreground\" Value=\"White\"/>\n" }, { "answer_id": 8247884, "author": "BrightShadow", "author_id": 1062610, "author_profile": "https://Stackoverflow.com/users/1062610", "pm_score": 7, "selected": true, "text": "ContentPresenter" }, { "answer_id": 8288929, "author": "Factor Mystic", "author_id": 1569, "author_profile": "https://Stackoverflow.com/users/1569", "pm_score": 4, "selected": false, "text": "<Setter TargetName=\"ctContentPresenter\" Property=\"TextBlock.Foreground\" Value=\"{StaticResource StyleForeColorBrush}\" />\n" }, { "answer_id": 22372284, "author": "Anatoly Ruchka", "author_id": 880709, "author_profile": "https://Stackoverflow.com/users/880709", "pm_score": 2, "selected": false, "text": " <Storyboard x:Key=\"Storyboard1\"> \n <ColorAnimationUsingKeyFrames Storyboard.TargetProperty=\"(TextBlock.Foreground).(SolidColorBrush.Color)\" Storyboard.TargetName=\"myContentPresenter\">\n <EasingColorKeyFrame KeyTime=\"0\" Value=\"Black\"/>\n <EasingColorKeyFrame KeyTime=\"0:0:0.2\" Value=\"White\"/>\n </ColorAnimationUsingKeyFrames> \n </Storyboard>\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/249671", "https://Stackoverflow.com", "https://Stackoverflow.com/users/32348/" ]
249,692
<p>I'm having difficulty parsing some JSON data returned from my server using jQuery.ajax()</p> <p>To perform the AJAX I'm using:</p> <pre><code>$.ajax({ url: myUrl, cache: false, dataType: "json", success: function(data){ ... }, error: function(e, xhr){ ... } }); </code></pre> <p>And if I return an array of items then it works fine:</p> <pre><code>[ { title: "One", key: "1" }, { title: "Two", key: "2" } ] </code></pre> <p>The success function is called and receives the correct object.</p> <p>However, when I'm trying to return a single object:</p> <pre><code>{ title: "One", key: "1" } </code></pre> <p>The error function is called and xhr contains 'parsererror'. I've tried wrapping the JSON in parenthesis on the server before sending it down the wire, but it makes no difference. Yet if I paste the content into a string in Javascript and then use the eval() function, it evaluates it perfectly.</p> <p>Any ideas what I'm doing wrong?</p> <p>Anthony</p>
[ { "answer_id": 249758, "author": "Tomalak", "author_id": 18771, "author_profile": "https://Stackoverflow.com/users/18771", "pm_score": 7, "selected": true, "text": "\"*/json\"" }, { "answer_id": 250245, "author": "Josh", "author_id": 2204759, "author_profile": "https://Stackoverflow.com/users/2204759", "pm_score": 5, "selected": false, "text": "var jsonMimeType = \"application/json;charset=UTF-8\";\n$.ajax({\n type: \"GET\",\n url: myURL,\n beforeSend: function(x) {\n if(x && x.overrideMimeType) {\n x.overrideMimeType(jsonMimeType);\n }\n },\n dataType: \"json\",\n success: function(data){\n // do stuff...\n }\n});\n" }, { "answer_id": 250309, "author": "David Alpert", "author_id": 8997, "author_profile": "https://Stackoverflow.com/users/8997", "pm_score": 1, "selected": false, "text": "[ { title: \"One\", key: \"1\" } ]\n" }, { "answer_id": 250328, "author": "bobince", "author_id": 18936, "author_profile": "https://Stackoverflow.com/users/18936", "pm_score": 2, "selected": false, "text": "{ title: \"One\", key: \"1\" }\n" }, { "answer_id": 251096, "author": "Ben Combee", "author_id": 1323, "author_profile": "https://Stackoverflow.com/users/1323", "pm_score": 6, "selected": false, "text": "{ \"title\": \"One\", \"key\": \"1\" }\n" }, { "answer_id": 327647, "author": "Jay", "author_id": 41690, "author_profile": "https://Stackoverflow.com/users/41690", "pm_score": 1, "selected": false, "text": "obj = new Object; obj = (data.obj);\n" }, { "answer_id": 350890, "author": "Andreas Grech", "author_id": 44084, "author_profile": "https://Stackoverflow.com/users/44084", "pm_score": 2, "selected": false, "text": "<webServices>\n <protocols>\n <add name=\"HttpGet\"/>\n <add name=\"HttpPost\"/>\n </protocols>\n</webServices>\n" }, { "answer_id": 2519983, "author": "John Mee", "author_id": 75033, "author_profile": "https://Stackoverflow.com/users/75033", "pm_score": 5, "selected": false, "text": "{\"who\": \"Hello World\"}\n" }, { "answer_id": 4465752, "author": "Jubair", "author_id": 354306, "author_profile": "https://Stackoverflow.com/users/354306", "pm_score": 3, "selected": false, "text": "eval('('+data+')')\n" }, { "answer_id": 4631253, "author": "Jonathon Hill", "author_id": 168815, "author_profile": "https://Stackoverflow.com/users/168815", "pm_score": 1, "selected": false, "text": "echo json_encode((object) array('result' => 'success'));\n" }, { "answer_id": 5838466, "author": "webwiseguys", "author_id": 731907, "author_profile": "https://Stackoverflow.com/users/731907", "pm_score": 0, "selected": false, "text": "var data = eval(\"(\" + data.responseText + \")\");\nconsole.log(data.count);\n" }, { "answer_id": 10044085, "author": "valir", "author_id": 783850, "author_profile": "https://Stackoverflow.com/users/783850", "pm_score": 1, "selected": false, "text": "$.ajax({\n url: url,\n data:datas,\n success:function(datas, textStatus, jqXHR){\n var returnedData = jQuery.parseJSON(datas.substr(datas.indexOf('{')));\n})};\n" }, { "answer_id": 10627793, "author": "Nezzy", "author_id": 704426, "author_profile": "https://Stackoverflow.com/users/704426", "pm_score": 3, "selected": false, "text": "response = '{\"name\":\"John\"}';\nvar obj = jQuery.parseJSON(response);\nalert( obj.name === \"John\" );\n" }, { "answer_id": 24885407, "author": "user2854865", "author_id": 2854865, "author_profile": "https://Stackoverflow.com/users/2854865", "pm_score": -1, "selected": false, "text": "$data = yourarray(); \njson_encode($data)\n" }, { "answer_id": 24978063, "author": "user3612872", "author_id": 3612872, "author_profile": "https://Stackoverflow.com/users/3612872", "pm_score": 2, "selected": false, "text": " <?php\n\n header('Content-type:application/json');\n\n ?>\n" }, { "answer_id": 40569157, "author": "IAM_AL_X", "author_id": 3552393, "author_profile": "https://Stackoverflow.com/users/3552393", "pm_score": 2, "selected": false, "text": "var myObj = { ...some..code..here... };\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/249692", "https://Stackoverflow.com", "https://Stackoverflow.com/users/366/" ]
249,701
<p>I have a header file x.h which is included by more than one *.c source files. This header file has some structure variables defined.</p> <p>I have put multiple inclusion prevention guard at the beginning of the header file as:</p> <pre><code>#ifndef X_H #define X_H ... .. //header file declarations and definitons. #endif//X_H </code></pre> <p>On building I get linker errors related to multiple definitions. I understand the problem.</p> <ol> <li><p>Won't a multiple inclusion prevention guard at the top of header file as I have, prevent multiple inclusions of the header file x.h and thereby avoid multiple definitions of the variables that are there in x.h?</p></li> <li><p><code>#pragma</code> once does not work on this particular compiler, so what is the solution? Someone had posted <a href="https://stackoverflow.com/questions/223771/repeated-multiple-definition-errors-from-including-same-header-in-multiple-cpps#223798">this</a> answer to a similar question. It doesn't seem to work for me. How does this solution work?</p></li> </ol>
[ { "answer_id": 249707, "author": "Greg Hewgill", "author_id": 893, "author_profile": "https://Stackoverflow.com/users/893", "pm_score": 2, "selected": false, "text": "extern" }, { "answer_id": 249745, "author": "Roddy", "author_id": 1737, "author_profile": "https://Stackoverflow.com/users/1737", "pm_score": 6, "selected": false, "text": "#ifndef X_H\n#define X_H\n\nint myFunc()\n{\n return 42; // Wrong! definition in header.\n}\n\nint myVar; // Wrong! definition in header.\n\n#endif\n" }, { "answer_id": 9576187, "author": "perreal", "author_id": 390913, "author_profile": "https://Stackoverflow.com/users/390913", "pm_score": 5, "selected": false, "text": "main.c" }, { "answer_id": 12531657, "author": "Michael", "author_id": 712014, "author_profile": "https://Stackoverflow.com/users/712014", "pm_score": 0, "selected": false, "text": "X_H" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/249701", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2759376/" ]
249,703
<p>I have some scripts that ought to have stopped running but hang around forever. Is there some way I can figure out what they're writing to STDOUT and STDERR in a readable way?</p> <p>I tried, for example, to do:</p> <pre><code>$ tail -f /proc/(pid)/fd/1 </code></pre> <p>but that doesn't really work. It was a long shot anyway.</p> <p>Any other ideas? </p> <p><code>strace</code> on its own is quite verbose and unreadable for seeing this.</p> <p>Note: I am <em>only</em> interested in their output, not in anything else. I'm capable of figuring out the other things on my own; this question is only focused on getting access to stdout and stderr of the running process <em>after</em> starting it.</p>
[ { "answer_id": 249932, "author": "Thomas Vander Stichele", "author_id": 2900, "author_profile": "https://Stackoverflow.com/users/2900", "pm_score": 6, "selected": false, "text": "creat" }, { "answer_id": 251429, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "strace" }, { "answer_id": 8685132, "author": "Jeff Ward", "author_id": 1026023, "author_profile": "https://Stackoverflow.com/users/1026023", "pm_score": 2, "selected": false, "text": "strace" }, { "answer_id": 11892574, "author": "Lari Hotari", "author_id": 166062, "author_profile": "https://Stackoverflow.com/users/166062", "pm_score": 3, "selected": false, "text": "PID=some_process_id\nsudo strace -f -e trace=write -e verbose=none -e write=1,2 -q -p $PID -o \"| grep '^ |' | cut -c11-60 | sed -e 's/ //g' | xxd -r -p\"\n" }, { "answer_id": 26363348, "author": "Jérôme Pouiller", "author_id": 301717, "author_profile": "https://Stackoverflow.com/users/301717", "pm_score": 2, "selected": false, "text": "reredirect -m FILE PID\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/249703", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2900/" ]
249,704
<p>Has anyone tested sorting with Selenium? I'd like to verify that sorting a table in different ways work (a-z, z-a, state, date, etc.). Any help would be very much appreciated.</p> <p>/Göran</p>
[ { "answer_id": 296686, "author": "krosenvold", "author_id": 23691, "author_profile": "https://Stackoverflow.com/users/23691", "pm_score": 0, "selected": false, "text": " //div[@id='sortResult']/div[1]/div (this'd be row 1 of the search result)\n //div[@id='sortResult']/div[2]/div ( row 2)\n" }, { "answer_id": 1964222, "author": "Dave Hunt", "author_id": 154975, "author_profile": "https://Stackoverflow.com/users/154975", "pm_score": 0, "selected": false, "text": "findElements" }, { "answer_id": 11112854, "author": "Ranadheer Reddy", "author_id": 1215594, "author_profile": "https://Stackoverflow.com/users/1215594", "pm_score": 2, "selected": false, "text": "string" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/249704", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
249,709
<p>How can i, in a bash script, execute a command when the user stops the script (with ctrl - c)?</p> <p>Currently, i have this:</p> <pre><code>afplay file.mp3 while true: do osascript -e "set volume 10" end </code></pre> <p>But i would like it to execute <code>killall afplay</code> when the user is finished with it, regardless if it is command-c or another keypress.</p>
[ { "answer_id": 249733, "author": "Vebjorn Ljosa", "author_id": 17498, "author_profile": "https://Stackoverflow.com/users/17498", "pm_score": 4, "selected": true, "text": "trap 'killall afplay' EXIT" }, { "answer_id": 249736, "author": "CesarB", "author_id": 28258, "author_profile": "https://Stackoverflow.com/users/28258", "pm_score": 2, "selected": false, "text": "trap" }, { "answer_id": 249741, "author": "Alnitak", "author_id": 6782, "author_profile": "https://Stackoverflow.com/users/6782", "pm_score": 2, "selected": false, "text": "trap" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/249709", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2592/" ]
249,718
<p>Already implemented performance boosters : - Get compatible image of GraphicsConfiguration to draw on - Enable OpenGL pipeline in 1.5: Not possible due to severe artifacts</p> <p>So far I am fine, the main profiled bottleneck of the program is drawing an image with several thousand tiles. Unfortunately it is not regular, else I simply could set pixels and scale them. I accerelated the image with VolatileImages and own rendering routines (ignore repaint and draw it itself with a timer). The result was pleasing and would suffice, BUT: Choosing a JMenu which hovers normally over the part of the image is severely disturbed because the JMenu is overdrawn. Inacceptable and the layout couldn't be changed.</p> <p>I tried the GLJPanel of JOGL, but there is no visible performance improvement. So is there a possibitlity to use VolatileImages (or other accerelated lightweighted components like GLCanvas) and still get normal JMenu display and if yes, how ? </p>
[ { "answer_id": 249920, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "import javax.swing.*;\nimport java.awt.*;\nimport java.awt.event.WindowAdapter;\nimport java.awt.event.WindowEvent;\nimport java.awt.image.BufferStrategy;\nimport java.awt.image.BufferedImage;\nimport java.awt.image.VolatileImage;\nimport java.io.File;\nimport java.io.IOException;\nimport java.util.Timer;\nimport java.util.TimerTask;\n\npublic final class FastDraw extends JFrame {\n\n private static final transient double NANO = 1.0e-9;\n private BufferStrategy bs;\n private BufferedImage frontImg;\n private BufferedImage backImg;\n private int PIC_WIDTH,\n PIC_HEIGHT;\n private Timer timer;\n\n public FastDraw() {\n timer = new Timer(true);\n JMenu menu = new JMenu(\"Dummy\");\n menu.add(new JMenuItem(\"Display me !\"));\n menu.add(new JMenuItem(\"Display me, too !\"));\n JMenuBar menuBar = new JMenuBar();\n menuBar.add(menu);\n setJMenuBar(menuBar);\n setIgnoreRepaint(true);\n setVisible(true);\n\n addWindowListener(new WindowAdapter() {\n public void windowClosing(WindowEvent evt) {\n super.windowClosing(evt);\n timer.cancel();\n dispose();\n System.exit(0);\n }\n });\n\n try {\n backImg = javax.imageio.ImageIO.read(new File(<insert a jpg picture here>));\n frontImg = javax.imageio.ImageIO.read(<here, too>));\n }\n catch (IOException e) {\n System.out.println(e.getMessage());\n }\n\n PIC_WIDTH = backImg.getWidth();\n PIC_HEIGHT = backImg.getHeight();\n setSize(PIC_WIDTH, PIC_HEIGHT);\n\n createBufferStrategy(1); // Double buffering\n bs = getBufferStrategy();\n timer.schedule(new Drawer(),0,20);\n\n }\n\n public static void main(String[] args) {\n new FastDraw();\n }\n\n private class Drawer extends TimerTask {\n private VolatileImage img;\n\n public void run() {\n long begin = System.nanoTime();\n Graphics2D g = (Graphics2D) bs.getDrawGraphics();\n GraphicsConfiguration gc = g.getDeviceConfiguration();\n\n if (img == null)\n img = gc.createCompatibleVolatileImage(PIC_WIDTH, PIC_HEIGHT);\n\n Graphics2D g2 = img.createGraphics();\n\n do {\n int valStatus = img.validate(gc);\n\n if (valStatus == VolatileImage.IMAGE_OK)\n g2.drawImage(backImg,0,0,null);\n else {\n g.drawImage(frontImg, 0, 0, null);\n }\n // volatile image is ready\n g.drawImage(img,0,50,null);\n bs.show();\n } while (img.contentsLost());\n }\n }\n}\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/249718", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
249,720
<p>I'm using the Lengauer and Tarjan algorithm with path compression to calculate the dominator tree for a graph where there are millions of nodes. The algorithm is quite complex and I have to admit I haven't taken the time to fully understand it, I'm just using it. Now I have a need to calculate the dominator trees of the direct children of the root node and possibly recurse down the graph to a certain depth repeating this operation. I.e. when I calculate the dominator tree for a child of the root node I want to pretend that the root node has been removed from the graph.</p> <p>My question is whether there is an efficient solution to this that makes use of immediate dominator information already calculated in the initial dominator tree for the root node? In other words I don't want to start from scratch for each of the children because the whole process is quite time consuming.</p> <p>Naively it seems it must be possible since there will be plenty of nodes deep down in the graph that have idoms just a little way above them and are unaffected by changes at the top of the graph.</p> <p>BTW just as aside: it's bizarre that the subject of dominator trees is "owned" by compiler people and there is no mention of it in books on classic graph theory. The application I'm using it for - my FindRoots java heap analyzer - is not related to compiler theory.</p> <p>Clarification: I'm talking about directed graphs here. The "root" I refer to is actually the node with the greatest reachability. I've updated the text above replacing references to "tree" with "graph". I tend to think of them as trees because the shape is <em>mainly</em> tree-like. The graph is actually of the objects in a java heap and as you can imagine is reasonably hierarchical. I have found the dominator tree useful when doing OOM leak analysis because what you are interested in is "what keeps this object alive?" and the answer ultimately is its dominator. Dominator trees allow you to &lt;ahem&gt; see the wood rather than the trees. But sometimes lots of junk floats to the top of the tree so you have a root with thousands of children directly below it. For such cases I would like to experiment with calculating the dominator trees rooted at each of the direct children (in the original graph) of the root and then maybe go to the next level down and so on. (I'm trying not to worry about the possibility of back links for the time being :)</p>
[ { "answer_id": 252927, "author": "jfs", "author_id": 4279, "author_profile": "https://Stackoverflow.com/users/4279", "pm_score": 4, "selected": true, "text": "boost::lengauer_tarjan_dominator_tree_without_dfs" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/249720", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15379/" ]
249,721
<blockquote> <p><strong>Possible Duplicate:</strong><br> <a href="https://stackoverflow.com/questions/249760/how-to-convert-unix-timestamp-to-datetime-and-vice-versa">How to convert UNIX timestamp to DateTime and vice versa?</a> </p> </blockquote> <p>I've got the following class:</p> <pre><code>[DataContractAttribute] public class TestClass { [DataMemberAttribute] public DateTime MyDateTime { get; set; } } </code></pre> <p>Here's the JSON:</p> <pre><code>{ "MyDateTime":"1221818565" } </code></pre> <p>The JSON is being returned from a PHP webservice.</p> <p>What I need to do, is convert that epoch string into a valid C# DateTime. What's the best way of doing this?</p> <p>I can do this:</p> <pre><code>[IgnoreDataMemberAttribute] public DateTime MyDateTime { get; set; } [DataMemberAttribute(Name = "MyDateTime")] public Int32 MyDateTimeTicks { get { return this.MyDateTime.Convert(...); } set { this.Created = new DateTime(...); } } </code></pre> <p>But the trouble with this is, the MyDateTimeTicks is public (changing it to private causes an exception in the serialization process)</p>
[ { "answer_id": 251804, "author": "Dan Esparza", "author_id": 19020, "author_profile": "https://Stackoverflow.com/users/19020", "pm_score": 2, "selected": false, "text": "new System.DateTime(1970, 1, 1, 0, 0, 0, 0).AddSeconds(1221818565);\n" }, { "answer_id": 251845, "author": "ageektrapped", "author_id": 631, "author_profile": "https://Stackoverflow.com/users/631", "pm_score": 1, "selected": false, "text": "DateTime unixEpoch = new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc);\nDateTime dotnetTime = unixEpoch.AddSeconds(Convert.ToDouble(ticks));\n" }, { "answer_id": 252301, "author": "TheSoftwareJedi", "author_id": 18941, "author_profile": "https://Stackoverflow.com/users/18941", "pm_score": 5, "selected": true, "text": "[DataContract]\npublic class TestClass\n{\n\n private static readonly DateTime unixEpoch = new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc);\n\n [IgnoreDataMember]\n public DateTime MyDateTime { get; set; }\n\n [DataMember(Name = \"MyDateTime\")]\n private int MyDateTimeTicks\n {\n get { return (int)(this.MyDateTime - unixEpoch).TotalSeconds; }\n set { this.MyDateTime = unixEpoch.AddSeconds(Convert.ToInt32(value)); }\n }\n\n}\n" }, { "answer_id": 5023900, "author": "Jeremy", "author_id": 267411, "author_profile": "https://Stackoverflow.com/users/267411", "pm_score": 2, "selected": false, "text": "unixEpoch.AddMilliseconds(Int64.Parse(date));" }, { "answer_id": 11887882, "author": "yossi", "author_id": 1588164, "author_profile": "https://Stackoverflow.com/users/1588164", "pm_score": 3, "selected": false, "text": "private DateTime ConvertJsonStringToDateTime(string jsonTime)\n {\n if (!string.IsNullOrEmpty(jsonTime) && jsonTime.IndexOf(\"Date\") > -1)\n {\n string milis = jsonTime.Substring(jsonTime.IndexOf(\"(\") + 1);\n string sign = milis.IndexOf(\"+\") > -1 ? \"+\" : \"-\";\n string hours = milis.Substring(milis.IndexOf(sign));\n milis = milis.Substring(0, milis.IndexOf(sign));\n hours = hours.Substring(0, hours.IndexOf(\")\"));\n return new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc).AddMilliseconds(Convert.ToInt64(milis)).AddHours(Convert.ToInt64(hours) / 100); \n }\n\n return DateTime.Now;\n }\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/249721", "https://Stackoverflow.com", "https://Stackoverflow.com/users/986/" ]
249,724
<p>How can I customise the Site Actions menu to remove or rename 'standard' menu items? Where are the site actions menu items defined? </p>
[ { "answer_id": 257789, "author": "Lachlan Wetherall", "author_id": 32701, "author_profile": "https://Stackoverflow.com/users/32701", "pm_score": 2, "selected": false, "text": "ConfigMenu=\"Delete\"" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/249724", "https://Stackoverflow.com", "https://Stackoverflow.com/users/32701/" ]
249,729
<p>I am writing a Jython script to sort a list of URLs.</p> <p>I have a list that looks like this:</p> <p><a href="http://www.domain.com/folder1/folder2/|,1" rel="nofollow noreferrer">http://www.domain.com/folder1/folder2/|,1</a><br /> <a href="http://www.domain.com/folder1/|,1" rel="nofollow noreferrer">http://www.domain.com/folder1/|,1</a><br /> <a href="http://www.domain.com/folder1/folder2/folder3/|,1" rel="nofollow noreferrer">http://www.domain.com/folder1/folder2/folder3/|,1</a><br /> <a href="http://www.domain.com/folder1/|,1" rel="nofollow noreferrer">http://www.domain.com/folder1/|,1</a><br /> <a href="http://www.domain.com/folder1/folder2/|,1" rel="nofollow noreferrer">http://www.domain.com/folder1/folder2/|,1</a><br /> <a href="http://www.domain.com/folder1/folder2/|,1" rel="nofollow noreferrer">http://www.domain.com/folder1/folder2/|,1</a><br /> <a href="http://www.domain.com/folder1/folder2/folder3/|,1" rel="nofollow noreferrer">http://www.domain.com/folder1/folder2/folder3/|,1</a><br /></p> <p>The pipe and the comma separates the path from the amount of files that are under that path. Is it possible some how use Jython to order the URLs by length, so it would end up look like the below list:</p> <p><a href="http://www.domain.com/folder1/|,1" rel="nofollow noreferrer">http://www.domain.com/folder1/|,1</a><br /> <a href="http://www.domain.com/folder1/|,1" rel="nofollow noreferrer">http://www.domain.com/folder1/|,1</a><br /> <a href="http://www.domain.com/folder1/folder2/|,1" rel="nofollow noreferrer">http://www.domain.com/folder1/folder2/|,1</a><br /> <a href="http://www.domain.com/folder1/folder2/|,1" rel="nofollow noreferrer">http://www.domain.com/folder1/folder2/|,1</a><br /> <a href="http://www.domain.com/folder1/folder2/|,1" rel="nofollow noreferrer">http://www.domain.com/folder1/folder2/|,1</a><br /> <a href="http://www.domain.com/folder1/folder2/folder3/|,1" rel="nofollow noreferrer">http://www.domain.com/folder1/folder2/folder3/|,1</a><br /> <a href="http://www.domain.com/folder1/folder2/folder3/|,1" rel="nofollow noreferrer">http://www.domain.com/folder1/folder2/folder3/|,1</a><br /></p> <p>Hope you guys get what I mean, any help would be appreciated. Cheers</p>
[ { "answer_id": 249754, "author": "bobince", "author_id": 18936, "author_profile": "https://Stackoverflow.com/users/18936", "pm_score": 3, "selected": true, "text": "urls.sort(lambda a, b: cmp(len(a), len(b)))\n" }, { "answer_id": 249766, "author": "gimel", "author_id": 6491, "author_profile": "https://Stackoverflow.com/users/6491", "pm_score": 1, "selected": false, "text": "mylist.sort(key=len)\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/249729", "https://Stackoverflow.com", "https://Stackoverflow.com/users/30786/" ]
249,760
<p>There is this example code, but then it starts talking about millisecond / nanosecond problems.</p> <p>The same question is on MSDN, <em><a href="https://learn.microsoft.com/archive/blogs/brada/seconds-since-the-unix-epoch-in-c" rel="noreferrer">Seconds since the Unix epoch in C#</a></em>.</p> <p>This is what I've got so far:</p> <pre><code>public Double CreatedEpoch { get { DateTime epoch = new DateTime(1970, 1, 1, 0, 0, 0, 0).ToLocalTime(); TimeSpan span = (this.Created.ToLocalTime() - epoch); return span.TotalSeconds; } set { DateTime epoch = new DateTime(1970, 1, 1, 0, 0, 0, 0).ToLocalTime(); this.Created = epoch.AddSeconds(value); } } </code></pre>
[ { "answer_id": 250400, "author": "ScottCher", "author_id": 24179, "author_profile": "https://Stackoverflow.com/users/24179", "pm_score": 11, "selected": true, "text": "public static DateTime UnixTimeStampToDateTime( double unixTimeStamp )\n{\n // Unix timestamp is seconds past epoch\n DateTime dateTime = new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc);\n dateTime = dateTime.AddSeconds( unixTimeStamp ).ToLocalTime();\n return dateTime;\n}\n" }, { "answer_id": 5641328, "author": "n8CodeGuru", "author_id": 311864, "author_profile": "https://Stackoverflow.com/users/311864", "pm_score": 3, "selected": false, "text": "DateTime date = new DateTime(2011, 4, 1, 12, 0, 0, 0);\nDateTime epoch = new DateTime(1970, 1, 1, 0, 0, 0, 0);\nTimeSpan span = (date - epoch);\ndouble unixTime =span.TotalSeconds;\n" }, { "answer_id": 7596509, "author": "Dmitry Fedorkov", "author_id": 934618, "author_profile": "https://Stackoverflow.com/users/934618", "pm_score": 8, "selected": false, "text": "public static double DateTimeToUnixTimestamp(DateTime dateTime)\n{\n return (TimeZoneInfo.ConvertTimeToUtc(dateTime) - \n new DateTime(1970, 1, 1, 0, 0, 0, 0, System.DateTimeKind.Utc)).TotalSeconds;\n}\n" }, { "answer_id": 10147471, "author": "gl051", "author_id": 1226576, "author_profile": "https://Stackoverflow.com/users/1226576", "pm_score": 6, "selected": false, "text": "TimeSpan span = (DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0,DateTimeKind.Utc));\ndouble unixTime = span.TotalSeconds;\n" }, { "answer_id": 12770507, "author": "Chris Thoman", "author_id": 918685, "author_profile": "https://Stackoverflow.com/users/918685", "pm_score": 4, "selected": false, "text": "static readonly DateTime UnixEpoch = new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc);\nstatic readonly double MaxUnixSeconds = (DateTime.MaxValue - UnixEpoch).TotalSeconds;\n\npublic static DateTime UnixTimeStampToDateTime(double unixTimeStamp)\n{\n return unixTimeStamp > MaxUnixSeconds\n ? UnixEpoch.AddMilliseconds(unixTimeStamp)\n : UnixEpoch.AddSeconds(unixTimeStamp);\n}\n" }, { "answer_id": 20796273, "author": "i3arnon", "author_id": 885318, "author_profile": "https://Stackoverflow.com/users/885318", "pm_score": 2, "selected": false, "text": "UNIX time" }, { "answer_id": 24906105, "author": "Felix Keil", "author_id": 3703372, "author_profile": "https://Stackoverflow.com/users/3703372", "pm_score": 5, "selected": false, "text": "public static DateTime UnixTimestampToDateTime(double unixTime)\n{\n DateTime unixStart = new DateTime(1970, 1, 1, 0, 0, 0, 0, System.DateTimeKind.Utc);\n long unixTimeStampInTicks = (long) (unixTime * TimeSpan.TicksPerSecond);\n return new DateTime(unixStart.Ticks + unixTimeStampInTicks, System.DateTimeKind.Utc);\n}\n" }, { "answer_id": 25270450, "author": "Hot Licks", "author_id": 581994, "author_profile": "https://Stackoverflow.com/users/581994", "pm_score": 2, "selected": false, "text": "DateTime unixEpoch = DateTime.ParseExact(\"1970-01-01\", \"yyyy-MM-dd\", System.Globalization.CultureInfo.InvariantCulture);\nDateTime convertedTime = unixEpoch.AddMilliseconds(unixTimeInMillisconds);\n" }, { "answer_id": 26225744, "author": "i3arnon", "author_id": 885318, "author_profile": "https://Stackoverflow.com/users/885318", "pm_score": 9, "selected": false, "text": "DateTimeOffset" }, { "answer_id": 29908680, "author": "orad", "author_id": 450913, "author_profile": "https://Stackoverflow.com/users/450913", "pm_score": 4, "selected": false, "text": "public static class EpochTimeExtensions\n{\n /// <summary>\n /// Converts the given date value to epoch time.\n /// </summary>\n public static long ToEpochTime(this DateTime dateTime)\n {\n var date = dateTime.ToUniversalTime();\n var ticks = date.Ticks - new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc).Ticks;\n var ts = ticks / TimeSpan.TicksPerSecond;\n return ts;\n }\n\n /// <summary>\n /// Converts the given date value to epoch time.\n /// </summary>\n public static long ToEpochTime(this DateTimeOffset dateTime)\n {\n var date = dateTime.ToUniversalTime();\n var ticks = date.Ticks - new DateTimeOffset(1970, 1, 1, 0, 0, 0, TimeSpan.Zero).Ticks;\n var ts = ticks / TimeSpan.TicksPerSecond;\n return ts;\n }\n\n /// <summary>\n /// Converts the given epoch time to a <see cref=\"DateTime\"/> with <see cref=\"DateTimeKind.Utc\"/> kind.\n /// </summary>\n public static DateTime ToDateTimeFromEpoch(this long intDate)\n {\n var timeInTicks = intDate * TimeSpan.TicksPerSecond;\n return new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc).AddTicks(timeInTicks);\n }\n\n /// <summary>\n /// Converts the given epoch time to a UTC <see cref=\"DateTimeOffset\"/>.\n /// </summary>\n public static DateTimeOffset ToDateTimeOffsetFromEpoch(this long intDate)\n {\n var timeInTicks = intDate * TimeSpan.TicksPerSecond;\n return new DateTimeOffset(1970, 1, 1, 0, 0, 0, TimeSpan.Zero).AddTicks(timeInTicks);\n }\n}\n" }, { "answer_id": 30518793, "author": "superlogical", "author_id": 52360, "author_profile": "https://Stackoverflow.com/users/52360", "pm_score": -1, "selected": false, "text": "public static class UnixDateTime\n{\n public static DateTimeOffset FromUnixTimeSeconds(long seconds)\n {\n if (seconds < -62135596800L || seconds > 253402300799L)\n throw new ArgumentOutOfRangeException(\"seconds\", seconds, \"\");\n\n return new DateTimeOffset(seconds * 10000000L + 621355968000000000L, TimeSpan.Zero);\n }\n\n public static DateTimeOffset FromUnixTimeMilliseconds(long milliseconds)\n {\n if (milliseconds < -62135596800000L || milliseconds > 253402300799999L)\n throw new ArgumentOutOfRangeException(\"milliseconds\", milliseconds, \"\");\n\n return new DateTimeOffset(milliseconds * 10000L + 621355968000000000L, TimeSpan.Zero);\n }\n\n public static long ToUnixTimeSeconds(this DateTimeOffset utcDateTime)\n {\n return utcDateTime.Ticks / 10000000L - 62135596800L;\n }\n\n public static long ToUnixTimeMilliseconds(this DateTimeOffset utcDateTime)\n {\n return utcDateTime.Ticks / 10000L - 62135596800000L;\n }\n\n [Test]\n public void UnixSeconds()\n {\n DateTime utcNow = DateTime.UtcNow;\n DateTimeOffset utcNowOffset = new DateTimeOffset(utcNow);\n\n long unixTimestampInSeconds = utcNowOffset.ToUnixTimeSeconds();\n\n DateTimeOffset utcNowOffsetTest = UnixDateTime.FromUnixTimeSeconds(unixTimestampInSeconds);\n\n Assert.AreEqual(utcNowOffset.Year, utcNowOffsetTest.Year);\n Assert.AreEqual(utcNowOffset.Month, utcNowOffsetTest.Month);\n Assert.AreEqual(utcNowOffset.Date, utcNowOffsetTest.Date);\n Assert.AreEqual(utcNowOffset.Hour, utcNowOffsetTest.Hour);\n Assert.AreEqual(utcNowOffset.Minute, utcNowOffsetTest.Minute);\n Assert.AreEqual(utcNowOffset.Second, utcNowOffsetTest.Second);\n }\n\n [Test]\n public void UnixMilliseconds()\n {\n DateTime utcNow = DateTime.UtcNow;\n DateTimeOffset utcNowOffset = new DateTimeOffset(utcNow);\n\n long unixTimestampInMilliseconds = utcNowOffset.ToUnixTimeMilliseconds();\n\n DateTimeOffset utcNowOffsetTest = UnixDateTime.FromUnixTimeMilliseconds(unixTimestampInMilliseconds);\n\n Assert.AreEqual(utcNowOffset.Year, utcNowOffsetTest.Year);\n Assert.AreEqual(utcNowOffset.Month, utcNowOffsetTest.Month);\n Assert.AreEqual(utcNowOffset.Date, utcNowOffsetTest.Date);\n Assert.AreEqual(utcNowOffset.Hour, utcNowOffsetTest.Hour);\n Assert.AreEqual(utcNowOffset.Minute, utcNowOffsetTest.Minute);\n Assert.AreEqual(utcNowOffset.Second, utcNowOffsetTest.Second);\n Assert.AreEqual(utcNowOffset.Millisecond, utcNowOffsetTest.Millisecond);\n }\n}\n" }, { "answer_id": 31588322, "author": "Fred", "author_id": 2470524, "author_profile": "https://Stackoverflow.com/users/2470524", "pm_score": 4, "selected": false, "text": "static DateTimeOffset FromUnixTimeSeconds(long seconds)\nstatic DateTimeOffset FromUnixTimeMilliseconds(long milliseconds)\nlong DateTimeOffset.ToUnixTimeSeconds()\nlong DateTimeOffset.ToUnixTimeMilliseconds()\n" }, { "answer_id": 50904674, "author": "madan", "author_id": 1251980, "author_profile": "https://Stackoverflow.com/users/1251980", "pm_score": 1, "selected": false, "text": "public static class UnixTime\n {\n private static readonly DateTime Epoch = new DateTime(1970, 1, 1, 0, 0, 0, 0);\n\n public static DateTime UnixTimeToDateTime(double unixTimeStamp)\n {\n return Epoch.AddSeconds(unixTimeStamp).ToUniversalTime();\n }\n }\n" }, { "answer_id": 53248007, "author": "mesut", "author_id": 1334979, "author_profile": "https://Stackoverflow.com/users/1334979", "pm_score": 3, "selected": false, "text": "var dt = DateTime.Now; \nvar unixTime = ((DateTimeOffset)dt).ToUnixTimeSeconds();\n" }, { "answer_id": 54722681, "author": "Yang Zhang", "author_id": 1982524, "author_profile": "https://Stackoverflow.com/users/1982524", "pm_score": 3, "selected": false, "text": "var dateTime = DateTimeOffset.FromUnixTimeSeconds(unixDateTime).DateTime;\n" }, { "answer_id": 57790748, "author": "Riyaz Hameed", "author_id": 1570636, "author_profile": "https://Stackoverflow.com/users/1570636", "pm_score": 3, "selected": false, "text": "public static class DateTimeExtensions\n{\n public static DateTime FromUnixTimeStampToDateTime(this string unixTimeStamp)\n {\n\n return DateTimeOffset.FromUnixTimeSeconds(long.Parse(unixTimeStamp)).UtcDateTime;\n }\n}\n" }, { "answer_id": 57974399, "author": "AMieres", "author_id": 4550898, "author_profile": "https://Stackoverflow.com/users/4550898", "pm_score": 3, "selected": false, "text": "System.DateTimeOffset.Now.ToUnixTimeSeconds()\n" }, { "answer_id": 61380874, "author": "Ramil Aliyev", "author_id": 8810311, "author_profile": "https://Stackoverflow.com/users/8810311", "pm_score": 5, "selected": false, "text": "var dateTime1 = DateTime.Now;\n" }, { "answer_id": 68662817, "author": "Nilufar Makhmudova", "author_id": 3480038, "author_profile": "https://Stackoverflow.com/users/3480038", "pm_score": 4, "selected": false, "text": "DateTime.UnixEpoch.AddMilliseconds(millis)\n" }, { "answer_id": 69231326, "author": "Brendan Sluke", "author_id": 7660196, "author_profile": "https://Stackoverflow.com/users/7660196", "pm_score": 3, "selected": false, "text": "DateTime.UnixEpoch.AddSeconds(unixTimeInSeconds)\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/249760", "https://Stackoverflow.com", "https://Stackoverflow.com/users/986/" ]
249,775
<p>Say I have an input file, and a target directory. How do I determine if the input file is on the same hard-drive (or partition) as the target directory?</p> <p>What I want to do is the copy a file if it's on a different, but move it if it's the same. For example:</p> <pre><code>target_directory = "/Volumes/externalDrive/something/" input_foldername, input_filename = os.path.split(input_file) if same_partition(input_foldername, target_directory): copy(input_file, target_directory) else: move(input_file, target_directory) </code></pre>
[ { "answer_id": 249796, "author": "CesarB", "author_id": 28258, "author_profile": "https://Stackoverflow.com/users/28258", "pm_score": 5, "selected": true, "text": "stat()" }, { "answer_id": 250149, "author": "Brian", "author_id": 9493, "author_profile": "https://Stackoverflow.com/users/9493", "pm_score": 2, "selected": false, "text": "OSError" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/249775", "https://Stackoverflow.com", "https://Stackoverflow.com/users/745/" ]
249,779
<p>I'm using a <code>BindingList&lt;T&gt;</code> in my Windows Forms that contains a list of "<code>IComparable&lt;Contact&gt;</code>" Contact-objects. Now I'd like the user to be able to sort by any column displayed in the grid.</p> <p>There is a way described on MSDN online which shows how to implement a custom collection based on <code>BindingList&lt;T&gt;</code> which allows sorting. But isn't there a Sort-event or something that could be caught in the DataGridView (or, even nicer, on the BindingSource) to sort the underlying collection using custom code?</p> <p>I don't really like the way described by MSDN. The other way I could easily apply a LINQ query to the collection.</p>
[ { "answer_id": 281324, "author": "Matthias Meid", "author_id": 17713, "author_profile": "https://Stackoverflow.com/users/17713", "pm_score": 5, "selected": false, "text": "BindingList<T>" }, { "answer_id": 1178144, "author": "Sorin Comanescu", "author_id": 117290, "author_profile": "https://Stackoverflow.com/users/117290", "pm_score": 6, "selected": true, "text": "protected abstract Comparison<T> GetComparer(PropertyDescriptor prop);\n" }, { "answer_id": 3687781, "author": "Dan Koster", "author_id": 444685, "author_profile": "https://Stackoverflow.com/users/444685", "pm_score": 2, "selected": false, "text": "class SortableBindingList<T> : BindingList<T>\n{\n public SortableBindingList(IList<T> list) : base(list) { }\n\n public void Sort() { sort(null, null); }\n public void Sort(IComparer<T> p_Comparer) { sort(p_Comparer, null); }\n public void Sort(Comparison<T> p_Comparison) { sort(null, p_Comparison); }\n\n private void sort(IComparer<T> p_Comparer, Comparison<T> p_Comparison)\n {\n if(typeof(T).GetInterface(typeof(IComparable).Name) != null)\n {\n bool originalValue = this.RaiseListChangedEvents;\n this.RaiseListChangedEvents = false;\n try\n {\n List<T> items = (List<T>)this.Items;\n if(p_Comparison != null) items.Sort(p_Comparison);\n else items.Sort(p_Comparer);\n }\n finally\n {\n this.RaiseListChangedEvents = originalValue;\n }\n }\n }\n}\n" }, { "answer_id": 20406268, "author": "Scott Chamberlain", "author_id": 80274, "author_profile": "https://Stackoverflow.com/users/80274", "pm_score": 2, "selected": false, "text": "IList<T>" }, { "answer_id": 28520948, "author": "Ravi M Patel", "author_id": 3317709, "author_profile": "https://Stackoverflow.com/users/3317709", "pm_score": 3, "selected": false, "text": "BindingList<T>" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/249779", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17713/" ]
249,780
<p>I have a really simple search form with the following</p> <ul> <li>Label ("Search")</li> <li>Textbox (fixed width)</li> <li>Submit button</li> <li>"Advanced" link</li> </ul> <p>Label, textbox and submit are all on one horizontal line and centered. Now I would like my advanced link to be under the submit button.</p> <p>Any ideas?</p>
[ { "answer_id": 249790, "author": "Greg", "author_id": 24181, "author_profile": "https://Stackoverflow.com/users/24181", "pm_score": 3, "selected": true, "text": " Search [xxxxxxxxxxxxxxxx] [Submit]\n Advanced\n" }, { "answer_id": 249812, "author": "Norbert B.", "author_id": 2605840, "author_profile": "https://Stackoverflow.com/users/2605840", "pm_score": 0, "selected": false, "text": "<style type=\"text/css\">\n #searchpanel\n {\n width: <displaywidth of controls>px;\n text-align: center;\n }\n\n #button\n {\n text-align: right;\n }\n</style>\n<div =\"searchpanel\">\n <label for=\"textbox\">Search</label><input type=\"text\" id=\"textbox\" />\n <input type=\"submit\" value=\"Search\" />\n</div>\n<div id=\"button\">\n <a href=\"#\">Advanced</a>\n</div>\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/249780", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11333/" ]
249,785
<p>Simply moving the file to <code>~/.Trash/</code> will not work, as if the file os on an external drive, it will move the file to the main system drive..</p> <p>Also, there are other conditions, like files on external drives get moved to <code>/Volumes/.Trash/501/</code> (or whatever the current user's ID is)</p> <p>Given a file or folder path, what is the correct way to determine the trash folder? I imagine the language is pretty irrelevant, but I intend to use Python</p>
[ { "answer_id": 251566, "author": "Dave Dribin", "author_id": 26825, "author_profile": "https://Stackoverflow.com/users/26825", "pm_score": 4, "selected": true, "text": "url = NSURL.fileURLWithPath(path)\nfinder = SBApplication.applicationWithBundleIdentifier(\"com.apple.Finder\")\nitem = finder.items.objectAtLocation(url)\nitem.delete\n" }, { "answer_id": 252920, "author": "dbr", "author_id": 745, "author_profile": "https://Stackoverflow.com/users/745", "pm_score": 3, "selected": false, "text": "def get_trash_path(input_file):\n path, file = os.path.split(input_file)\n if path.startswith(\"/Volumes/\"):\n # /Volumes/driveName/.Trashes/<uid>\n s = path.split(os.path.sep)\n # s[2] is drive name ([0] is empty, [1] is Volumes)\n trash_path = os.path.join(\"/Volumes\", s[2], \".Trashes\", str(os.getuid()))\n if not os.path.isdir(trash_path):\n raise IOError(\"Volume appears to be a network drive (%s could not be found)\" % (trash_path))\n else:\n trash_path = os.path.join(os.getenv(\"HOME\"), \".Trash\")\n return trash_path\n" }, { "answer_id": 3654566, "author": "tig", "author_id": 96823, "author_profile": "https://Stackoverflow.com/users/96823", "pm_score": 1, "selected": false, "text": "Appscript.app('Finder').items[MacTypes::Alias.path(path)].delete\n" }, { "answer_id": 5012645, "author": "Ashley Clark", "author_id": 4556, "author_profile": "https://Stackoverflow.com/users/4556", "pm_score": 2, "selected": false, "text": "from AppKit import NSWorkspace, NSWorkspaceRecycleOperation\n\nsource = \"path holding files\"\nfiles = [\"file1\", \"file2\"]\n\nws = NSWorkspace.sharedWorkspace()\nws.performFileOperation_source_destination_files_tag_(NSWorkspaceRecycleOperation, source, \"\", files, None)\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/249785", "https://Stackoverflow.com", "https://Stackoverflow.com/users/745/" ]
249,786
<p>I'm at a client doing some quick fixes to their access application. It was a while I had a go with access, but I'm recovering quickly. However, I've discovered an interesting problem:</p> <p>For some reports, I get a "Record is deleted" error. I've checked the reports, and it seems like there's a problem with one table. When opening that table, I find a record where all columns are marked "#deleted". So obviously, this row seems to be the culprit. However, when I try to delete that row, nothing really happens. If I re-open the table, the row still exists. </p> <p>Is there a corruption in the db? How can I remove this record for good?</p> <p><strong>Edit:</strong> It's a MS2000-version</p> <p><strong>Solution:</strong> Simply compress/repair did not work. I converted the database to the 2003 file format instead, which did the trick. I've marked the first answer suggesting compress/repair, since it pointed me in the right direction. Thanks!</p>
[ { "answer_id": 252357, "author": "David-W-Fenton", "author_id": 9787, "author_profile": "https://Stackoverflow.com/users/9787", "pm_score": 2, "selected": false, "text": " Me!txtMyMemo = Me!MyMemo\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/249786", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17436/" ]
249,791
<p>How do I get the substring <code>" It's big \"problem "</code> using a regular expression?</p> <pre><code>s = ' function(){ return " It\'s big \"problem "; }'; </code></pre>
[ { "answer_id": 249804, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 4, "selected": false, "text": "/([\"\\']).*?(?<!\\\\)(\\\\\\\\)*\\1/is\n" }, { "answer_id": 249937, "author": "PhiLho", "author_id": 15459, "author_profile": "https://Stackoverflow.com/users/15459", "pm_score": 8, "selected": false, "text": "/\"(?:[^\"\\\\]|\\\\.)*\"/\n" }, { "answer_id": 1016356, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 5, "selected": false, "text": "\\\"(\\\\.|[^\\\"])*\\\"\n" }, { "answer_id": 4448207, "author": "Tosh Afanasiev", "author_id": 543106, "author_profile": "https://Stackoverflow.com/users/543106", "pm_score": 3, "selected": false, "text": "\"(?:\\\\\"|.)*?\"\n" }, { "answer_id": 10786066, "author": "Guy Bedford", "author_id": 1292590, "author_profile": "https://Stackoverflow.com/users/1292590", "pm_score": 5, "selected": false, "text": "/\"([^\"\\\\]*(\\\\.[^\"\\\\]*)*)\"/\n" }, { "answer_id": 15936558, "author": "user2267983", "author_id": 2267983, "author_profile": "https://Stackoverflow.com/users/2267983", "pm_score": 0, "selected": false, "text": "\\\"((\\\\\\\")|[^\\\\])*\\\"\n" }, { "answer_id": 20352652, "author": "Rvanlaak", "author_id": 1794894, "author_profile": "https://Stackoverflow.com/users/1794894", "pm_score": 0, "selected": false, "text": "/\"([^\"\\\\]{50,}(\\\\.[^\"\\\\]*)*)\"|\\'[^\\'\\\\]{50,}(\\\\.[^\\'\\\\]*)*\\'|“[^”\\\\]{50,}(\\\\.[^“\\\\]*)*”/ \n" }, { "answer_id": 25954054, "author": "Petter Thowsen", "author_id": 1303805, "author_profile": "https://Stackoverflow.com/users/1303805", "pm_score": -1, "selected": false, "text": "\"(([^\"\\\\]?(\\\\\\\\)?)|(\\\\\")+)+\"\n" }, { "answer_id": 30737232, "author": "Marc-André Poulin", "author_id": 3208143, "author_profile": "https://Stackoverflow.com/users/3208143", "pm_score": 4, "selected": false, "text": "\"(?:[^\"\\\\]*(?:\\\\.)?)*\"" }, { "answer_id": 33617839, "author": "ack", "author_id": 588561, "author_profile": "https://Stackoverflow.com/users/588561", "pm_score": 3, "selected": false, "text": "/\"(?:[^\"\\\\]++|\\\\.)*+\"/\n" }, { "answer_id": 43597014, "author": "Vadim Sayfi", "author_id": 7915886, "author_profile": "https://Stackoverflow.com/users/7915886", "pm_score": 3, "selected": false, "text": "\"(.*?[^\\\\])??((\\\\\\\\)+)?+\"\n" }, { "answer_id": 48165319, "author": "scagood", "author_id": 3533202, "author_profile": "https://Stackoverflow.com/users/3533202", "pm_score": 2, "selected": false, "text": "String \\\"this \"should\" NOT match\\\" and \"this \\\"should\\\" match\"" }, { "answer_id": 49291272, "author": "Bigger", "author_id": 1447087, "author_profile": "https://Stackoverflow.com/users/1447087", "pm_score": 0, "selected": false, "text": " line = line.replace(\"\\\\\\\"\",\"\\'\"); // Replace escaped quotes with something easier to handle\n line = line.replaceAll(\"\\\"([^\\\"]*)\\\"\",\"\\\"x\\\"\"); // Simple is beautiful\n" }, { "answer_id": 62857781, "author": "Aramis NSR", "author_id": 10499624, "author_profile": "https://Stackoverflow.com/users/10499624", "pm_score": 0, "selected": false, "text": "String s = \"\\\"en_usa\\\":[^\\\\,\\\\}]+\";\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/249791", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
249,794
<p>I'me looking for a function that would receive a time and would round it to the next/previous hour / half-hour / quarter / minute.</p>
[ { "answer_id": 249828, "author": "IAdapter", "author_id": 30453, "author_profile": "https://Stackoverflow.com/users/30453", "pm_score": 6, "selected": true, "text": "CREATE FUNCTION [dbo].[RoundTime] (@Time datetime, @RoundTo float)\nRETURNS datetime\nAS\nBEGIN\n DECLARE @RoundedTime smalldatetime\n DECLARE @Multiplier float\n\n SET @Multiplier= 24.0/@RoundTo\n\n SET @RoundedTime= ROUND(CAST(CAST(CONVERT(varchar,@Time,121) AS datetime) AS float) * @Multiplier,0)/@Multiplier\n\n RETURN @RoundedTime\nEND\n\n\n\nselect dbo.roundtime('13:15',0.5)\n" }, { "answer_id": 3176740, "author": "Kevin", "author_id": 383318, "author_profile": "https://Stackoverflow.com/users/383318", "pm_score": 3, "selected": false, "text": "convert(smalldatetime,ROUND(cast(TDatalog.Time as float) * (24/.25),0)/(24/.25)) AS RoundedTime\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/249794", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1842864/" ]
249,797
<p>I'm currently using the ActiveRecord-based session store for my Rails app and I have a background process which clears out inactive sessions every 30 minutes.</p> <p>I'd like to switch to Rails' new cookie-based session store but how do I set the expiry time of the session to 30 minutes, as opposed to the default 'at end of session' value?</p>
[ { "answer_id": 249966, "author": "Codebeef", "author_id": 12037, "author_profile": "https://Stackoverflow.com/users/12037", "pm_score": -1, "selected": false, "text": "session :session_key => 'my_session_key'\nsession :session_expires => 1.day.from_now\n" }, { "answer_id": 251123, "author": "Daniel Beardsley", "author_id": 13216, "author_profile": "https://Stackoverflow.com/users/13216", "pm_score": 3, "selected": false, "text": "session :session_expires => 1.day.from_now\n" }, { "answer_id": 3351506, "author": "Graeme Mathieson", "author_id": 341874, "author_profile": "https://Stackoverflow.com/users/341874", "pm_score": 5, "selected": true, "text": "config.action_controller.session = {\n :key => 'whatever',\n :secret => 'nottellingyou',\n :expire_after => 30.minutes\n}\n" }, { "answer_id": 14544511, "author": "n8vision", "author_id": 1701350, "author_profile": "https://Stackoverflow.com/users/1701350", "pm_score": 2, "selected": false, "text": " class ApplicationController < ActionController::Base\n\n after_filter :short_session\n\n ...\n\n def short_session\n request.session_options = request.session_options.dup\n request.session_options[:expire_after] = 1.minute\n request.session_options.freeze\n end\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/249797", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1174/" ]
249,819
<p>I have the following sql query for transforming data but is it possible to save the value of the int in some variable to avoid casting multiple times?</p> <pre><code>update prospekts set sni_kod = case when cast(sni_kod as int) &gt;= 1000 and cast(sni_kod as int) &lt;= 1499 or cast(sni_kod as int) &gt;= 1600 and cast(sni_kod as int) &lt;= 2439 then '1' when cast(sni_kod as int) &gt;= 7000 and cast(sni_kod as int) &lt;= 7499 then 'W' else sni_kod end </code></pre> <p>There are a lot more when-cases in the script, just showing the first one. I cannot use anything other than a simple text-script.</p> <p><strong>Update</strong> Using SQL Server 2000</p> <p>Thanks</p> <p>Anders</p>
[ { "answer_id": 249836, "author": "Dave Markle", "author_id": 24995, "author_profile": "https://Stackoverflow.com/users/24995", "pm_score": 1, "selected": false, "text": "With xxx AS (\n i_sni_kod = cast(sni_kod as int)\n ...)\nUPDATE prospekts set sni_kod = case \n when i_sni_kod >= 100 ...\n" }, { "answer_id": 249841, "author": "Tony Andrews", "author_id": 18747, "author_profile": "https://Stackoverflow.com/users/18747", "pm_score": 0, "selected": false, "text": "update (select prospekts.*, cast(sni_kod as int) sni_kod_int from prospekts)\nset sni_kod = case\nwhen \n sni_kod_int >= 1000 and sni_kod_int <= 1499 \n or sni_kod_int >= 1600 and sni_kod_int <= 2439\nthen 1\nelse\n sni_kod\nend\n" }, { "answer_id": 249965, "author": "Chris Shaffer", "author_id": 6744, "author_profile": "https://Stackoverflow.com/users/6744", "pm_score": 0, "selected": false, "text": "update prospekts set sni_kod = 1\nfrom prospekts\n join (select prospekts.primarykey, cast(prospekts.sni_kod as int) as sni_kod_int from prospekts) p2 on prospekts.primarykey = p2.primarykey\nWHERE (p2.sni_kod_int >=1000 and p2.sni_kod_int <= 1499)\n or (p2.sni_kod_int >=1600 and p2.sni_kod_int <= 2439)\n" }, { "answer_id": 250017, "author": "Tony Andrews", "author_id": 18747, "author_profile": "https://Stackoverflow.com/users/18747", "pm_score": 2, "selected": false, "text": "update prospekts set sni_kod = case\nwhen \n xxx >= 1000 and xxx <= 1499 \n or xxx >= 1600 and xxx <= 2439\nthen '1'\nwhen \n xxx >= 7000 and xxx <= 7499 \nthen 'W'\nelse\n sni_kod\nend\n" }, { "answer_id": 250099, "author": "Timothy Khouri", "author_id": 11917, "author_profile": "https://Stackoverflow.com/users/11917", "pm_score": 2, "selected": false, "text": "SELECT CONVERT(INT, '123'), CONVERT(INT, '123')\n" }, { "answer_id": 250102, "author": "Kevin Fairchild", "author_id": 3743, "author_profile": "https://Stackoverflow.com/users/3743", "pm_score": 3, "selected": true, "text": "UPDATE prospekts SET sni_kod = \n CASE\n WHEN ISNUMERIC(@sni_kod)=1 THEN\n CASE \n WHEN cast(@sni_kod as int) BETWEEN 1000 AND 1499 OR cast(@sni_kod as int) BETWEEN 1600 AND 2439 THEN '1'\n WHEN cast(@sni_kod as int) BETWEEN 7000 AND 7499 THEN 'W'\n ELSE @sni_kod\n END\n ELSE @sni_kod\n END\n" }, { "answer_id": 251272, "author": "Amy B", "author_id": 8155, "author_profile": "https://Stackoverflow.com/users/8155", "pm_score": 0, "selected": false, "text": "DECLARE @MyTable TABLE\n(\n theKey int identity(1,1) PRIMARY KEY,\n theValue varchar(30)\n)\n------ \nINSERT INTO @MyTable SELECT '1'\nINSERT INTO @MyTable SELECT '2'\nINSERT INTO @MyTable SELECT '3'\n------\n\nUPDATE sub\nSET theValue =\n CASE\n WHEN convertedvalue % 2 = 0 THEN 'even'\n ELSE theValue\n END\nFROM\n(\n SELECT\n CASE\n WHEN Isnumeric(theValue) = 1\n THEN convert(int, theValue)\n ELSE null\n END as convertedValue, *\n FROM @MyTable mt\n) as sub\n------\nSELECT *\nFROM @MyTable\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/249819", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22092/" ]
249,847
<p>I am wondering how to use NUnit correctly. First, I created a separate test project that uses my main project as reference. But in that case, I am not able to test private methods. My guess was that I need to include my test code into my main code?! - That doesn't seem to be the correct way to do it. (I dislike the idea of shipping code with tests in it.)</p> <p>How do you test private methods with NUnit?</p>
[ { "answer_id": 9035421, "author": "user1039513", "author_id": 1039513, "author_profile": "https://Stackoverflow.com/users/1039513", "pm_score": 6, "selected": false, "text": "private MethodInfo GetMethod(string methodName)\n{\n if (string.IsNullOrWhiteSpace(methodName))\n Assert.Fail(\"methodName cannot be null or whitespace\");\n\n var method = this.objectUnderTest.GetType()\n .GetMethod(methodName, BindingFlags.NonPublic | BindingFlags.Instance);\n\n if (method == null)\n Assert.Fail(string.Format(\"{0} method not found\", methodName));\n\n return method;\n}\n" }, { "answer_id": 25929073, "author": "Stuart Wood", "author_id": 430967, "author_profile": "https://Stackoverflow.com/users/430967", "pm_score": 3, "selected": false, "text": "#if DEBUG\n\n...test code...\n\n#endif\n" }, { "answer_id": 37552616, "author": "Furgalicious", "author_id": 6406025, "author_profile": "https://Stackoverflow.com/users/6406025", "pm_score": 1, "selected": false, "text": "assembly: InternalsVisibleTo(\"NAMESPACE\")" }, { "answer_id": 40397247, "author": "Maxim Kitsenko", "author_id": 3607337, "author_profile": "https://Stackoverflow.com/users/3607337", "pm_score": 2, "selected": false, "text": "public class SomeClass\n{\n protected int SomeMethod() {}\n}\n[TestFixture]\npublic class TestClass : SomeClass{\n \n protected void SomeMethod2() {}\n [Test]\n public void SomeMethodTest() { SomeMethod2(); }\n}\n" }, { "answer_id": 63776259, "author": "Rohim Chou", "author_id": 8140473, "author_profile": "https://Stackoverflow.com/users/8140473", "pm_score": 1, "selected": false, "text": "class Foo \n{\n private int Sum(int num1, int num2)\n {\n return num1 + num2;\n }\n}\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/249847", "https://Stackoverflow.com", "https://Stackoverflow.com/users/32726/" ]
249,860
<p>How can i restrict adding controls in Panel in C# window controls? I have to restrict user to add controls in a panel at design time.</p>
[ { "answer_id": 249934, "author": "Rune Grimstad", "author_id": 30366, "author_profile": "https://Stackoverflow.com/users/30366", "pm_score": 1, "selected": false, "text": "class MyPanel : Panel\n{\n\n public MyPanel()\n { }\n\n protected override void OnControlAdded(ControlEventArgs e)\n {\n base.OnControlAdded(e);\n\n if (!(e.Control is Label))\n {\n MessageBox.Show(\"control \" + e.Control.Name + \" is not a label but a \" + e.Control.GetType().ToString());\n Controls.Remove(e.Control);\n }\n\n }\n\n}\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/249860", "https://Stackoverflow.com", "https://Stackoverflow.com/users/31159/" ]
249,865
<p>We're seeing the error message ORA-00936 Missing Expression for the following SQL:</p> <p>Note that this is just a cut-down version of a much bigger SQL so rewriting it to a inner join or similar is not really in the scope of this:</p> <p>This is the SQL that fails:</p> <pre><code>select (select count(*) from gt_roster where ROS_ROSTERPLAN_ID = RPL_ID) from gt_rosterplan where RPL_ID = 432065061 </code></pre> <p>What I've tried: * Extracting the innermost SQL and substituting the ID from the outer SQL gives me the number 12. * Aliasing both the sub-query, and the count(*) individually and both at the same time does not change the outcome (ie. still an error)</p> <p>What else do I need to look at?</p> <p>The above are only tables, no views, RPL_ID is primary key of gt_rosterplan, and ROS_ROSTERPLAN_ID is a foreign key to this column, there is basically no magic or hidden information here.</p> <hr> <p><strong>Edit:</strong> In response to answer, no, you do not need the aliases here as the columns are uniquely named across the tables.</p> <hr> <p><strong>Solved:</strong> The problem was that the client was running the wrong client driver version, 9.2.0.1, and there are known problems with that version.</p>
[ { "answer_id": 249915, "author": "Tony Andrews", "author_id": 18747, "author_profile": "https://Stackoverflow.com/users/18747", "pm_score": 2, "selected": true, "text": "SQL> select (select count(*) from emp2 where empdeptno = deptno)\n 2 from dept\n 3 where deptno=10\n 4 /\n\n(SELECTCOUNT(*)FROMEMP2WHEREEMPDEPTNO=DEPTNO)\n---------------------------------------------\n 3\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/249865", "https://Stackoverflow.com", "https://Stackoverflow.com/users/267/" ]
249,866
<p>I'm creating a <code>Path</code> in <em>Silverlight</em>, and adding elements to it on mouse events. But, although the elements are there in memory, the screen doesn't get updated until something else causes a screen repaint to happen.</p> <p>Here's the relevant code - I'm responding to a mouse event, and I keep a class member of the path I'm editing.</p> <pre><code>Path path = null; private void LayoutRoot_MouseLeftButtonDown(object sender, MouseButtonEventArgs e) { Point thisPoint = e.GetPosition(LayoutRoot); if (path == null) { CreateNewPath(thisPoint); path.LayoutUpdated += new EventHandler(path_LayoutUpdated); } else { path.AddLineElement(thisPoint); } } private void CreateNewPath(Point startPoint) { path = new Path(); PathGeometry geometry = new PathGeometry(); path.Data = geometry; PathFigureCollection figures = new PathFigureCollection(); geometry.Figures = figures; PathFigure figure = new PathFigure(); figures.Add(figure); figure.StartPoint = startPoint; figure.Segments = new PathSegmentCollection(); path.Stroke = new SolidColorBrush(Colors.Red); path.StrokeThickness = 2; path.Stretch = Stretch.None; LayoutRoot.Children.Add(path); } </code></pre> <p><code>AddLineElement</code> is an extension method for the path class just to simplify:</p> <pre><code>public static class PathHelper { public static void AddLineElement(this Path thePath, Point newPoint) { PathGeometry geometry = thePath.Data as PathGeometry; geometry.Figures[0].Segments.Add(new LineSegment { Point = newPoint }); } } </code></pre> <p>This is the minimum needed to reproduce the problem. If you run this code in a full WPF app it all works as expected. Mouse clicks add line elements which appear immediately. However, in <em>Silverlight</em> it's a different matter. The clicks appear to do nothing, even though stepping through the code shows that the data is getting added. But if you click a few times, then resize the browser, for example, the path elements appear. If you happen to have a button on the page as well, and move the mouse over, the path will appear.</p> <p>I've tried all the obvious things, like calling <code>InvalidateMeasure</code> and <code>InvalidateArrange</code> on the <code>Path</code> (and on the parent grid) to no avail. </p> <p>The only workaround I've got is to change a property on the path then change it back, which seems to be enough to get the rendering engine to draw the new path elements. I use <code>Opacity</code>. You have to set it to a different value, otherwise (I presume) the <code>PropertyChanged</code> event won't fire. It's a kludge, though.</p> <p>Has anyone else played with paths in this way? I guess if I were putting other graphical elements on screen at the same time this wouldn't be an issue, so it's probably not something which will affect may people, but it would be good to know if there's a more correct way to do it.</p>
[ { "answer_id": 250873, "author": "Bryant", "author_id": 10893, "author_profile": "https://Stackoverflow.com/users/10893", "pm_score": 0, "selected": false, "text": "<UserControl x:Class=\"SilverlightTesting.Page\"\n xmlns=\"http://schemas.microsoft.com/winfx/2006/xaml/presentation\" \n xmlns:x=\"http://schemas.microsoft.com/winfx/2006/xaml\" \n Width=\"400\" Height=\"300\">\n <Canvas x:Name=\"LayoutRoot\" Background=\"White\" Width=\"400\" Height=\"300\" MouseLeftButtonDown=\"LayoutRoot_MouseLeftButtonDown\"/>\n</UserControl>\n" }, { "answer_id": 852122, "author": "Conceptdev", "author_id": 25673, "author_profile": "https://Stackoverflow.com/users/25673", "pm_score": 1, "selected": false, "text": "using System.Windows.Controls;\nusing System.Windows.Input;\nusing System.Windows.Media;\nusing Microsoft.VirtualEarth.MapControl;\n\nnamespace MapInfo\n{\n public partial class Page : UserControl\n {\n /// <summary>\n /// Sample drawing a polyline on a Virtual Earth map\n /// </summary>\n public Page()\n {\n InitializeComponent();\n VEMap.MouseLeftButtonUp += new MouseButtonEventHandler(VEMap_MouseLeftButtonDown);\n VEMap.MouseLeave += new MouseEventHandler(VEMap_MouseLeave);\n }\n\n MapPolyline polyline = null;\n\n /// <summary>\n /// Ends drawing the current polyline\n /// </summary>\n void VEMap_MouseLeave(object sender, MouseEventArgs e)\n {\n polyline = null;\n }\n /// <summary>\n /// Start or add-to a polyline\n /// </summary>\n private void VEMap_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)\n {\n Map m = (Map)sender;\n\n Location l = m.ViewportPointToLocation(e.GetPosition(m));\n\n if (polyline == null)\n {\n CreateNewPolyline(l);\n }\n else\n {\n polyline.Locations.Add(l);\n }\n }\n /// <summary>\n /// Create a new MapPolyline\n /// </summary>\n /// <param name=\"startPoint\">starting Location</param>\n private void CreateNewPolyline(Location startPoint)\n {\n polyline = new MapPolyline();\n polyline.Stroke = new SolidColorBrush(Colors.Red);\n polyline.StrokeThickness = 2;\n var lc = new LocationCollection();\n lc.Add(startPoint);\n polyline.Locations = lc;\n VEMap.Children.Add(polyline);\n }\n }\n}\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/249866", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6483/" ]
249,867
<p>I was wondering if in Java I would get any odd behaviour if I synchronise twice on the same object?</p> <p>The scenario is as follows</p> <pre><code>pulbic class SillyClassName { object moo; ... public void method1(){ synchronized(moo) { .... method2(); .... } } public void method2(){ synchronized(moo) { doStuff(); } } } </code></pre> <p>Both methods use the object and are synchronised on it. Will the second method when called by the first method stop because it's locked?</p> <p>I don't think so because it's the same thread but I'm unsure of any other odd results that might occur.</p>
[ { "answer_id": 249888, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "synchronized" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/249867", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20400/" ]
249,868
<p>I'd like to have a page in php that normally displays information based on the GET request sent to it. However, I'd like for it to also be able to process certain POST requests. So, how can I tell if any data was sent by POST so I can act on it?</p>
[ { "answer_id": 249873, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 6, "selected": true, "text": "$_SERVER['REQUEST_METHOD']" }, { "answer_id": 249879, "author": "moo", "author_id": 23107, "author_profile": "https://Stackoverflow.com/users/23107", "pm_score": -1, "selected": false, "text": "!empty($_POST)\n" }, { "answer_id": 249880, "author": "Philip Morton", "author_id": 21709, "author_profile": "https://Stackoverflow.com/users/21709", "pm_score": 2, "selected": false, "text": "$_SERVER['REQUEST_METHOD']" }, { "answer_id": 249885, "author": "Noah Goodrich", "author_id": 20178, "author_profile": "https://Stackoverflow.com/users/20178", "pm_score": 3, "selected": false, "text": "if($_SERVER['REQUEST_METHOD'] === 'post')\n{\n // Do one thing\n}\nelseif($_SERVER['REQUEST_METHOD'] === 'get')\n{\n // Do another thing\n}\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/249868", "https://Stackoverflow.com", "https://Stackoverflow.com/users/25680/" ]
249,878
<p>If it said "oneword", then I could write "#oneword", but what do I write when there is a space in the word?</p>
[ { "answer_id": 249887, "author": "Philip Morton", "author_id": 21709, "author_profile": "https://Stackoverflow.com/users/21709", "pm_score": 5, "selected": false, "text": "<p class=\"one two\">lalala</p>\n\n.one {\n color: black;\n}\n\n.two {\n font-weight: bold;\n} \n" }, { "answer_id": 249976, "author": "Ryan Rodemoyer", "author_id": 1444511, "author_profile": "https://Stackoverflow.com/users/1444511", "pm_score": 3, "selected": false, "text": "#two-words { font-family: arial; }\n.center { text-align: center; }\n.bold { font-weight: bold; }\n\n<div id=\"two-words\" class=\"center bold\">STUFF HERE</div>\n" }, { "answer_id": 12096290, "author": "Nuc134rB0t", "author_id": 1620416, "author_profile": "https://Stackoverflow.com/users/1620416", "pm_score": -1, "selected": false, "text": "id=\"two words\"" }, { "answer_id": 68804817, "author": "user16680381", "author_id": 16680381, "author_profile": "https://Stackoverflow.com/users/16680381", "pm_score": -1, "selected": false, "text": "#two\\ words {\n\n}\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/249878", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9328/" ]
249,883
<p>I have two XML files with two different XSD schemas and different namespaces. They have both an identical substructure. And now i need to copy that node (and all childs) from one XML document to the other one. </p> <p>Clone would do, if the namespaces were the same. Is there a nice way to do it? (The substructure will change later on - but will be kept identical.)</p>
[ { "answer_id": 250057, "author": "Tomalak", "author_id": 18771, "author_profile": "https://Stackoverflow.com/users/18771", "pm_score": 3, "selected": true, "text": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<test xmlns=\"http://tempuri.org/ns_old\">\n <child attrib=\"value\">text</child>\n</test>\n" }, { "answer_id": 251661, "author": "steve", "author_id": 32103, "author_profile": "https://Stackoverflow.com/users/32103", "pm_score": 0, "selected": false, "text": "Private Shared Sub CopyElement(ByVal FromE As Xml.XmlElement, ByVal ToE As Xml.XmlElement)\n CopyElement(FromE, ToE, Nothing)\nEnd Sub\nPrivate Shared Sub CopyElement(ByVal FromE As Xml.XmlElement, ByVal ToE As Xml.XmlElement, ByVal overAttr As Xml.XmlAttributeCollection)\n Dim NewE As Xml.XmlElement\n Dim e As Xml.XmlElement\n NewE = ToE.OwnerDocument.CreateElement(FromE.Name)\n\n CopyAttributes(FromE, NewE)\n If Not overAttr Is Nothing Then\n OverrideAttributes(overAttr, NewE)\n End If\n For Each e In FromE\n CopyElement(e, NewE, overAttr)\n Next\n ToE.AppendChild(NewE)\n\n\nEnd Sub\nPrivate Shared Sub CopyAttributes(ByVal FromE As Xml.XmlElement, ByVal ToE As Xml.XmlElement)\n Dim a As Xml.XmlAttribute\n For Each a In FromE.Attributes\n ToE.SetAttribute(a.Name, a.Value)\n Next\nEnd Sub\nPrivate Shared Sub OverrideAttributes(ByVal AC As Xml.XmlAttributeCollection, ByVal E As Xml.XmlElement)\n Dim a As Xml.XmlAttribute\n For Each a In AC\n If Not E.Attributes.ItemOf(a.Name) Is Nothing Then\n E.SetAttribute(a.Name, a.Value)\n End If\n Next\nEnd Sub\n" }, { "answer_id": 531434, "author": "zhaorufei", "author_id": 64469, "author_profile": "https://Stackoverflow.com/users/64469", "pm_score": 0, "selected": false, "text": "public static void RunSnippet()\n" }, { "answer_id": 11391690, "author": "Kanika", "author_id": 1511452, "author_profile": "https://Stackoverflow.com/users/1511452", "pm_score": 0, "selected": false, "text": "InnerXML" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/249883", "https://Stackoverflow.com", "https://Stackoverflow.com/users/32726/" ]
249,901
<p>What is the equivalent to web controls in frameworks other than ASP.Net?</p> <p>Specifically I'd like to know about Java, PHP and Ruby on Rails.</p> <p>What are the relative merits/faults of each of these frameworks for web development?</p> <p>I've had some exposure to ASP.Net and have been asked to look into developing an app that will have configurable controls on it. I know how I'd do this in ASP.Net, but it's to run on a linux box and in my experience Mono is not mature/stable when running ASP.Net.</p> <p><strong>Clarification</strong></p> <p>Basicly what I mean by webcontrols is a set of reusable componenet that I can initialize with various values.</p> <p>So if for example I want to have a reusable component which draws a graph of some kind on the page. and i want to lay out several of these to graph different things.</p>
[ { "answer_id": 249949, "author": "Jon Limjap", "author_id": 372, "author_profile": "https://Stackoverflow.com/users/372", "pm_score": 1, "selected": false, "text": "<input>" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/249901", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20400/" ]
249,916
<p>The <code>java.net.InetAddress.GetByName(String host)</code> method can only return <code>A</code> records so to lookup other record types I need to be able to send DNS queries using the <code>dnsjava</code> library.</p> <p>However that normally relies on being able to parse <code>/etc/resolv.conf</code> or similar to find the DNS server addresses and that doesn't work on Android.</p> <p>The current DNS settings on Android can apparently only be obtained from within a shell by using the <code>getprop</code> command.</p> <p>Can anyone tell me how to get those settings from Java other than by spawning a shell with <code>Runtime.exec()</code> and parsing the output from <code>getprop</code>?</p>
[ { "answer_id": 385806, "author": "Eugene Yokota", "author_id": 3827, "author_profile": "https://Stackoverflow.com/users/3827", "pm_score": 3, "selected": false, "text": "WiFiManager wifi = (WifiManager) getSystemService(WIFI_SERVICE); \nDhcpInfo info = wifi.getDhcpInfo(); \n" }, { "answer_id": 518952, "author": "Lawrence Dol", "author_id": 8946, "author_profile": "https://Stackoverflow.com/users/8946", "pm_score": 5, "selected": true, "text": "/etc/resolv.conf" }, { "answer_id": 46368989, "author": "Uddhav P. Gautam", "author_id": 7232295, "author_profile": "https://Stackoverflow.com/users/7232295", "pm_score": 1, "selected": false, "text": "<uses-permission android:name=\"android.permission.INTERNET\" />\n<uses-permission android:name=\"android.permission.ACCESS_NETWORK_STATE\" />\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/249916", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6782/" ]
249,926
<pre><code>&lt;a id="lblShowTimings" runat="server" title='&lt;%# Eval("SHOW_Name") %&gt;' onclick='PopulateTicketDiv(&lt;%#Eval("SHOW_ID") %&gt;)'&gt; &lt;-- this is the problem %#Eval("SHOW_Time") %&gt; &lt;/a&gt; </code></pre> <p>Can Eval be passed as an argument to a javascript function? If so whats the syntax?</p>
[ { "answer_id": 249986, "author": "tvanfosson", "author_id": 12950, "author_profile": "https://Stackoverflow.com/users/12950", "pm_score": 6, "selected": true, "text": "onclick='<%# \"PopulateTicketDiv(\" +Eval(\"SHOW_ID\") + \" );\" %>'\n" }, { "answer_id": 250004, "author": "Rob Stevenson-Leggett", "author_id": 4950, "author_profile": "https://Stackoverflow.com/users/4950", "pm_score": 2, "selected": false, "text": "<script type=\"javascript\">\n //Pollute the global namespace\n var ticketDivID = <%= SHOW_ID %>\n</script>\n\n<a id=\"lblShowTimings\" runat=\"server\" title='<%# Eval(\"SHOW_Name\") %>' onclick='PopulateTicketDiv(ticketDivID)'> <%#Eval(\"SHOW_Time\") %></a>\n" }, { "answer_id": 5893726, "author": "Rohan ", "author_id": 739340, "author_profile": "https://Stackoverflow.com/users/739340", "pm_score": 5, "selected": false, "text": "OnClientClick='<%# String.Format(\"javascript:return displayDeleteWarning(\\\"{0}\\\")\", Eval(\"ItemName\").ToString()) %>' \n" }, { "answer_id": 20137061, "author": "Aruna", "author_id": 2047527, "author_profile": "https://Stackoverflow.com/users/2047527", "pm_score": 2, "selected": false, "text": "<asp:ImageButton \n ID=\"Imagebutton1\" runat=\"server\"\n ImageUrl=\"../../common/images/pencil.gif\" \n OnClientClick='<%# String.Format(\"EditBankAccount(\\\"{0}\\\");\", Eval(\"BankAccountID\")) %>'\n OnClick=\"ImgBankAccountsDGEdit_Click\"/>\n" }, { "answer_id": 64317023, "author": "sushil suthar", "author_id": 4195533, "author_profile": "https://Stackoverflow.com/users/4195533", "pm_score": 0, "selected": false, "text": "<asp:CheckBox onclick='<%# \"ToggleByPassValidationRules(\" + \"\\\"\" + Eval(\"Name\") + \"\\\"\" + \");\" %>' ID=\"chkIsRuleActive\" runat=\"server\" Enabled=\"false\" />\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/249926", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17447/" ]
249,927
<p>How can I restart(recycle) IIS Application Pool from C# (.net 2)?</p> <p>Appreciate if you post sample code?</p>
[ { "answer_id": 249942, "author": "dove", "author_id": 30913, "author_profile": "https://Stackoverflow.com/users/30913", "pm_score": 7, "selected": true, "text": "// Gets the application pool collection from the server.\n[ModuleServiceMethod(PassThrough = true)]\npublic ArrayList GetApplicationPoolCollection()\n{\n // Use an ArrayList to transfer objects to the client.\n ArrayList arrayOfApplicationBags = new ArrayList();\n\n ServerManager serverManager = new ServerManager();\n ApplicationPoolCollection applicationPoolCollection = serverManager.ApplicationPools;\n foreach (ApplicationPool applicationPool in applicationPoolCollection)\n {\n PropertyBag applicationPoolBag = new PropertyBag();\n applicationPoolBag[ServerManagerDemoGlobals.ApplicationPoolArray] = applicationPool;\n arrayOfApplicationBags.Add(applicationPoolBag);\n // If the applicationPool is stopped, restart it.\n if (applicationPool.State == ObjectState.Stopped)\n {\n applicationPool.Start();\n }\n\n }\n\n // CommitChanges to persist the changes to the ApplicationHost.config.\n serverManager.CommitChanges();\n return arrayOfApplicationBags;\n}\n" }, { "answer_id": 333380, "author": "Wolf5", "author_id": 37643, "author_profile": "https://Stackoverflow.com/users/37643", "pm_score": 3, "selected": false, "text": " /// <summary>\n /// Get a list of available Application Pools\n /// </summary>\n /// <returns></returns>\n public static List<string> HentAppPools() {\n\n List<string> list = new List<string>();\n DirectoryEntry W3SVC = new DirectoryEntry(\"IIS://LocalHost/w3svc\", \"\", \"\");\n\n foreach (DirectoryEntry Site in W3SVC.Children) {\n if (Site.Name == \"AppPools\") {\n foreach (DirectoryEntry child in Site.Children) {\n list.Add(child.Name);\n }\n }\n }\n return list;\n }\n\n /// <summary>\n /// Recycle an application pool\n /// </summary>\n /// <param name=\"IIsApplicationPool\"></param>\n public static void RecycleAppPool(string IIsApplicationPool) {\n ManagementScope scope = new ManagementScope(@\"\\\\localhost\\root\\MicrosoftIISv2\");\n scope.Connect();\n ManagementObject appPool = new ManagementObject(scope, new ManagementPath(\"IIsApplicationPool.Name='W3SVC/AppPools/\" + IIsApplicationPool + \"'\"), null);\n\n appPool.InvokeMethod(\"Recycle\", null, null);\n }\n" }, { "answer_id": 496357, "author": "Ricardo Nolde", "author_id": 36272, "author_profile": "https://Stackoverflow.com/users/36272", "pm_score": 3, "selected": false, "text": "using System.DirectoryServices;\n\n...\n\nvoid Recycle(string appPool)\n{\n string appPoolPath = \"IIS://localhost/W3SVC/AppPools/\" + appPool;\n\n using (DirectoryEntry appPoolEntry = new DirectoryEntry(appPoolPath))\n {\n appPoolEntry.Invoke(\"Recycle\", null);\n appPoolEntry.Close();\n }\n}\n" }, { "answer_id": 1081902, "author": "Nathan Ridley", "author_id": 98389, "author_profile": "https://Stackoverflow.com/users/98389", "pm_score": 6, "selected": false, "text": "HttpRuntime.UnloadAppDomain();\n" }, { "answer_id": 18585661, "author": "Simply G.", "author_id": 381122, "author_profile": "https://Stackoverflow.com/users/381122", "pm_score": 2, "selected": false, "text": "ExecuteDosCommand(@\"c:\\Windows\\System32\\inetsrv\\appcmd recycle apppool \" + appPool);\n" }, { "answer_id": 28553422, "author": "Spazmoose", "author_id": 312147, "author_profile": "https://Stackoverflow.com/users/312147", "pm_score": 3, "selected": false, "text": "public static void RecycleApplicationPool(string serverName, string appPoolName)\n{\n if (!string.IsNullOrEmpty(serverName) && !string.IsNullOrEmpty(appPoolName))\n {\n try\n {\n using (ServerManager manager = ServerManager.OpenRemote(serverName))\n {\n ApplicationPool appPool = manager.ApplicationPools.FirstOrDefault(ap => ap.Name == appPoolName);\n\n //Don't bother trying to recycle if we don't have an app pool\n if (appPool != null)\n {\n //Get the current state of the app pool\n bool appPoolRunning = appPool.State == ObjectState.Started || appPool.State == ObjectState.Starting;\n bool appPoolStopped = appPool.State == ObjectState.Stopped || appPool.State == ObjectState.Stopping;\n\n //The app pool is running, so stop it first.\n if (appPoolRunning)\n {\n //Wait for the app to finish before trying to stop\n while (appPool.State == ObjectState.Starting) { System.Threading.Thread.Sleep(1000); }\n\n //Stop the app if it isn't already stopped\n if (appPool.State != ObjectState.Stopped)\n {\n appPool.Stop();\n }\n appPoolStopped = true;\n }\n\n //Only try restart the app pool if it was running in the first place, because there may be a reason it was not started.\n if (appPoolStopped && appPoolRunning)\n {\n //Wait for the app to finish before trying to start\n while (appPool.State == ObjectState.Stopping) { System.Threading.Thread.Sleep(1000); }\n\n //Start the app\n appPool.Start();\n }\n }\n else\n {\n throw new Exception(string.Format(\"An Application Pool does not exist with the name {0}.{1}\", serverName, appPoolName));\n }\n }\n }\n catch (Exception ex)\n {\n throw new Exception(string.Format(\"Unable to restart the application pools for {0}.{1}\", serverName, appPoolName), ex.InnerException);\n }\n }\n}\n" }, { "answer_id": 34154221, "author": "Fred", "author_id": 1442180, "author_profile": "https://Stackoverflow.com/users/1442180", "pm_score": 2, "selected": false, "text": "System.Web.HttpRuntime.UnloadAppDomain()\n" }, { "answer_id": 53431386, "author": "Kaarthikeyan", "author_id": 2092251, "author_profile": "https://Stackoverflow.com/users/2092251", "pm_score": 3, "selected": false, "text": "using Microsoft.Web.Administration;\n" }, { "answer_id": 57077950, "author": "Alex from Jitbit", "author_id": 56621, "author_profile": "https://Stackoverflow.com/users/56621", "pm_score": 0, "selected": false, "text": "System.Web.Hosting.HostingEnvironment.InitiateShutdown();\n" }, { "answer_id": 72033862, "author": "phillhutt", "author_id": 2585195, "author_profile": "https://Stackoverflow.com/users/2585195", "pm_score": 0, "selected": false, "text": "using (var serverManager = new ServerManager())\n{\n foreach (var appPool in serverManager.ApplicationPools)\n {\n appPool.Recycle();\n }\n}\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/249927", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
249,928
<p>I have an executable that is started by a windows service, this program will be run on a customers machine and will need to connect to a remote share to perform a particular task. This share is specified by the customer via a UI, so we do not know this in advance meaning it can't be "hard-coded", or the share mapped in advance.</p> <p>Previously we required the customer to log on to their machine and run the executable on log-on , but we have always wanted to allow our program to run within a service and not require a log-in, primarily to make it easier for the customer and prevent any accidental log-outs shutting down our software. So this also means we don't know what local user accounts exist on a customers machine, so we have to start the service using the local system account.</p> <p>We now have, as mentioned above, a wrapper service to start the executable and perform various tasks. This appears to work fine in most cases and accesses the underlying network fine - our software's purpose mainly involves capturing packets etc.</p> <p>However, when the software tries to connect to a windows share (UNC name) it cannot connect. Whereas if the executable was started manually it connects fine.</p> <p>The suggestions I have generally seen to resolve these kind of issues appear to all say use a user account as the system account cannot access network shares, but in our case this isn't possible. Is there any other way we could get this to work?</p> <p><strong>Edit: I forgot to mention that this application could (and most commonly will be) run on Win2K not XP, and I think I'm right in saying that the Local Network account is not available before XP?</strong></p>
[ { "answer_id": 249951, "author": "Treb", "author_id": 22114, "author_profile": "https://Stackoverflow.com/users/22114", "pm_score": 0, "selected": false, "text": "cmd.exe" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/249928", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15297/" ]
249,968
<p>I have written a web app in PHP which makes use of Ajax requests (made using YUI.util.Connect.asyncRequest).</p> <p>Most of the time, this works fine. The request is sent with an <strong>X-Requested-With</strong> value of <strong>XMLHttpRequest</strong>. My PHP controller code uses apache_request_headers() to check whether an incoming request is Ajax or not and all works well.</p> <p>But not always. Intermittently, I'm getting a situation where the Ajax request is sent (and Firebug confirms for me that the headers on the request include an X-Requested-With of XMLHttpRequest) but apache_request_headers() is not returning that header in its list.</p> <p>The output from when I var_dump the apache_request_headers() is as follows (note the lack of X-</p> <pre><code>'Host' =&gt; string 'peterh.labs.example.com' (length=26) 'User-Agent' =&gt; string 'Mozilla/5.0 (X11; U; Linux i686; en-GB; rv:1.9.0.3) Gecko/2008101315 Ubuntu/8.10 (intrepid) Firefox/3.0.3' (length=105) 'Accept' =&gt; string 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8' (length=63) 'Accept-Language' =&gt; string 'en-gb,en;q=0.5' (length=14) 'Accept-Encoding' =&gt; string 'gzip,deflate' (length=12) 'Accept-Charset' =&gt; string 'ISO-8859-1,utf-8;q=0.7,*;q=0.7' (length=30) 'Keep-Alive' =&gt; string '300' (length=3) 'Connection' =&gt; string 'keep-alive' (length=10) 'Referer' =&gt; string 'http://peterh.labs.example.com/qmail/' (length=40) 'Cookie' =&gt; string 'WORKFLOW_SESSION=55f9aff2051746851de453c1f776ad10745354f6' (length=57) 'Pragma' =&gt; string 'no-cache' (length=8) 'Cache-Control' =&gt; string 'no-cache' (length=8) </code></pre> <p>But Firebug tells me:</p> <pre><code>Request Headers: Host peterh.labs.example.com User-Agent Mozilla/5.0 (X11; U; Linux i686; en-GB; rv:1.9.0.3) Gecko/2008101315 Ubuntu/8.10 (intrepid) Firefox/3.0.3 Accept text/html,application/xhtml+xml,application/xml;q=0.9,**;q=0.8 Accept-Language en-gb,en;q=0.5 Accept-Encoding gzip,deflate Accept-Charset ISO-8859-1,utf-8;q=0.7,*;q=0.7 Keep-Alive 300 Connection keep-alive X-Requested-With XMLHttpRequest Referer http://peterh.labs.example.com/qmail/ Cookie WORKFLOW_SESSION=55f9aff2051746851de453c1f776ad10745354f6 </code></pre> <p>This mismatch is (apparently) intermittent when executing the same code. But I don't believe in "intermittent" when it comes to software! Help!</p>
[ { "answer_id": 250242, "author": "Till", "author_id": 2859, "author_profile": "https://Stackoverflow.com/users/2859", "pm_score": 0, "selected": false, "text": "$_SERVER" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/249968", "https://Stackoverflow.com", "https://Stackoverflow.com/users/24106/" ]
249,971
<p>Having some Geometry data and a Transform how can the transform be applied to the Geometry to get a new Geometry with it's data transformed ?</p> <p>Ex: I Have a Path object that has it's Path.Data set to a PathGeometry object, I want to tranform <strong>the points</strong> of the PathGeometry object <strong>in place</strong> using a transform, and not apply a transform to the PathGeometry that will be used at render time.</p> <p>P.S. I know that the Transform class has a method <code>Point Transform.Transform(Point p)</code> that can be used to transform a Point but...is there a way to transform a arbitrary geometry at once?</p> <p>Edit: See my repply for a currently found <a href="https://stackoverflow.com/questions/249971/wpf-how-to-apply-a-generaltransform-to-a-geometry-data-and-return-the-new-geome#250913">solution</a></p>
[ { "answer_id": 250587, "author": "Todd White", "author_id": 30833, "author_profile": "https://Stackoverflow.com/users/30833", "pm_score": 5, "selected": true, "text": "PathGeometry geometry = new PathGeometry();\ngeometry.Figures.Add(new PathFigure(new Point(10, 10), new PathSegment[] { new LineSegment(new Point(10, 20), true), new LineSegment(new Point(20, 20), true) }, true));\nScaleTransform transform = new ScaleTransform(2, 2);\nPathGeometry geometryTransformed = Geometry.Combine(geometry, geometry, GeometryCombineMode.Intersect, transform);\n" }, { "answer_id": 250913, "author": "Pop Catalin", "author_id": 4685, "author_profile": "https://Stackoverflow.com/users/4685", "pm_score": 4, "selected": false, "text": "PathGeometry geometryTransformed = Geometry.Combine(Geometry.Empty, geometry, GeometryCombineMode.Union, transform);\n" }, { "answer_id": 1504510, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "pathgeometry.Transform = transform;\nPathGeometry transformed = PathGeometry.CreateFromGeometry(pathgeometry);\n" }, { "answer_id": 7515015, "author": "Snowbear", "author_id": 570357, "author_profile": "https://Stackoverflow.com/users/570357", "pm_score": 2, "selected": false, "text": "Geometry inputGeometry = new PathGeometry();\nvar inputGeometryClone = inputGeometry.Clone(); // we need a clone since in order to\n // apply a Transform and geometry might be readonly\ninputGeometryClone.Transform = new TranslateTransform(); // applying some transform to it\nvar result = inputGeometryClone.GetFlattenedPathGeometry();\n" }, { "answer_id": 13960034, "author": "Curtis", "author_id": 981187, "author_profile": "https://Stackoverflow.com/users/981187", "pm_score": 3, "selected": false, "text": "var geometry = new PathGeometry();\ngeometry.Figures.Add(new PathFigure(new Point(10, 10), new PathSegment[] { new LineSegment(new Point(10, 20), true), new LineSegment(new Point(20, 20), true) }, true));\ngeometry.Transform = new ScaleTransform(2, 2);\n\nvar transformedGeometry = new PathGeometry ();\n// this copies the transformed figures one by one into the new geometry\ntransformedGeometry.AddGeometry (geometry); \n" }, { "answer_id": 27507885, "author": "rpaulin56", "author_id": 2794352, "author_profile": "https://Stackoverflow.com/users/2794352", "pm_score": 2, "selected": false, "text": "public static class GeometryHelper\n{\npublic static PointCollection TransformPoints(PointCollection pc, Transform t)\n{\n PointCollection tp = new PointCollection(pc.Count);\n foreach (Point p in pc)\n tp.Add(t.Transform(p));\n return tp;\n}\npublic static PathGeometry TransformedGeometry(PathGeometry g, Transform t)\n{\n Matrix m = t.Value;\n double scaleX = Math.Sqrt(m.M11 * m.M11 + m.M21 * m.M21);\n double scaleY = (m.M11 * m.M22 - m.M12 * m.M21) / scaleX;\n PathGeometry ng = g.Clone();\n foreach (PathFigure f in ng.Figures)\n {\n f.StartPoint = t.Transform(f.StartPoint);\n foreach (PathSegment s in f.Segments)\n {\n if (s is LineSegment)\n (s as LineSegment).Point = t.Transform((s as LineSegment).Point);\n else if (s is PolyLineSegment)\n (s as PolyLineSegment).Points = TransformPoints((s as PolyLineSegment).Points, t);\n else if (s is BezierSegment)\n {\n (s as BezierSegment).Point1 = t.Transform((s as BezierSegment).Point1);\n (s as BezierSegment).Point2 = t.Transform((s as BezierSegment).Point2);\n (s as BezierSegment).Point3 = t.Transform((s as BezierSegment).Point3);\n }\n else if (s is PolyBezierSegment)\n (s as PolyBezierSegment).Points = TransformPoints((s as PolyBezierSegment).Points, t);\n else if (s is QuadraticBezierSegment)\n {\n (s as QuadraticBezierSegment).Point1 = t.Transform((s as QuadraticBezierSegment).Point1);\n (s as QuadraticBezierSegment).Point2 = t.Transform((s as QuadraticBezierSegment).Point2);\n }\n else if (s is PolyQuadraticBezierSegment)\n (s as PolyQuadraticBezierSegment).Points = TransformPoints((s as PolyQuadraticBezierSegment).Points, t);\n else if (s is ArcSegment)\n {\n ArcSegment a = s as ArcSegment;\n a.Point = t.Transform(a.Point);\n a.Size = new Size(a.Size.Width * scaleX, a.Size.Height * scaleY); // NEVER TRIED\n }\n }\n }\n return ng;\n}\n}\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/249971", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4685/" ]
249,979
<p>In the below code snippet can i replace char * to const char * and remove the strdup() function call and directly take the optarg value set by getopt()? I am advised to use const char * to skip the strdup function usage. Appreciate the help in advance.</p> <pre><code>/* Code Snippet */ char *dir = NULL; char *bld = NULL; int chr; while ( ( chr = getopt( argc, argv, "d:a:b:f:" ) ) != -1 ) { switch ( chr ) { case 'd': //Directory parameter dir = strdup( optarg ); if (dir == NULL) { /*Error*/ } case 'b': //Build parameter bld = strdup( optarg ); if (bld == NULL) { /*Error*/ } ...other code... } } </code></pre> <p>I really don't understand the need for doing so.</p> <p>Edit: Thanks for the answers. It was really helpful. I modified the code to const char * and skipped the strdup call.</p> <p>Thanks, Liju</p>
[ { "answer_id": 250587, "author": "Todd White", "author_id": 30833, "author_profile": "https://Stackoverflow.com/users/30833", "pm_score": 5, "selected": true, "text": "PathGeometry geometry = new PathGeometry();\ngeometry.Figures.Add(new PathFigure(new Point(10, 10), new PathSegment[] { new LineSegment(new Point(10, 20), true), new LineSegment(new Point(20, 20), true) }, true));\nScaleTransform transform = new ScaleTransform(2, 2);\nPathGeometry geometryTransformed = Geometry.Combine(geometry, geometry, GeometryCombineMode.Intersect, transform);\n" }, { "answer_id": 250913, "author": "Pop Catalin", "author_id": 4685, "author_profile": "https://Stackoverflow.com/users/4685", "pm_score": 4, "selected": false, "text": "PathGeometry geometryTransformed = Geometry.Combine(Geometry.Empty, geometry, GeometryCombineMode.Union, transform);\n" }, { "answer_id": 1504510, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "pathgeometry.Transform = transform;\nPathGeometry transformed = PathGeometry.CreateFromGeometry(pathgeometry);\n" }, { "answer_id": 7515015, "author": "Snowbear", "author_id": 570357, "author_profile": "https://Stackoverflow.com/users/570357", "pm_score": 2, "selected": false, "text": "Geometry inputGeometry = new PathGeometry();\nvar inputGeometryClone = inputGeometry.Clone(); // we need a clone since in order to\n // apply a Transform and geometry might be readonly\ninputGeometryClone.Transform = new TranslateTransform(); // applying some transform to it\nvar result = inputGeometryClone.GetFlattenedPathGeometry();\n" }, { "answer_id": 13960034, "author": "Curtis", "author_id": 981187, "author_profile": "https://Stackoverflow.com/users/981187", "pm_score": 3, "selected": false, "text": "var geometry = new PathGeometry();\ngeometry.Figures.Add(new PathFigure(new Point(10, 10), new PathSegment[] { new LineSegment(new Point(10, 20), true), new LineSegment(new Point(20, 20), true) }, true));\ngeometry.Transform = new ScaleTransform(2, 2);\n\nvar transformedGeometry = new PathGeometry ();\n// this copies the transformed figures one by one into the new geometry\ntransformedGeometry.AddGeometry (geometry); \n" }, { "answer_id": 27507885, "author": "rpaulin56", "author_id": 2794352, "author_profile": "https://Stackoverflow.com/users/2794352", "pm_score": 2, "selected": false, "text": "public static class GeometryHelper\n{\npublic static PointCollection TransformPoints(PointCollection pc, Transform t)\n{\n PointCollection tp = new PointCollection(pc.Count);\n foreach (Point p in pc)\n tp.Add(t.Transform(p));\n return tp;\n}\npublic static PathGeometry TransformedGeometry(PathGeometry g, Transform t)\n{\n Matrix m = t.Value;\n double scaleX = Math.Sqrt(m.M11 * m.M11 + m.M21 * m.M21);\n double scaleY = (m.M11 * m.M22 - m.M12 * m.M21) / scaleX;\n PathGeometry ng = g.Clone();\n foreach (PathFigure f in ng.Figures)\n {\n f.StartPoint = t.Transform(f.StartPoint);\n foreach (PathSegment s in f.Segments)\n {\n if (s is LineSegment)\n (s as LineSegment).Point = t.Transform((s as LineSegment).Point);\n else if (s is PolyLineSegment)\n (s as PolyLineSegment).Points = TransformPoints((s as PolyLineSegment).Points, t);\n else if (s is BezierSegment)\n {\n (s as BezierSegment).Point1 = t.Transform((s as BezierSegment).Point1);\n (s as BezierSegment).Point2 = t.Transform((s as BezierSegment).Point2);\n (s as BezierSegment).Point3 = t.Transform((s as BezierSegment).Point3);\n }\n else if (s is PolyBezierSegment)\n (s as PolyBezierSegment).Points = TransformPoints((s as PolyBezierSegment).Points, t);\n else if (s is QuadraticBezierSegment)\n {\n (s as QuadraticBezierSegment).Point1 = t.Transform((s as QuadraticBezierSegment).Point1);\n (s as QuadraticBezierSegment).Point2 = t.Transform((s as QuadraticBezierSegment).Point2);\n }\n else if (s is PolyQuadraticBezierSegment)\n (s as PolyQuadraticBezierSegment).Points = TransformPoints((s as PolyQuadraticBezierSegment).Points, t);\n else if (s is ArcSegment)\n {\n ArcSegment a = s as ArcSegment;\n a.Point = t.Transform(a.Point);\n a.Size = new Size(a.Size.Width * scaleX, a.Size.Height * scaleY); // NEVER TRIED\n }\n }\n }\n return ng;\n}\n}\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/249979", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18657/" ]
249,987
<p>We'd like to start our bug numbers to something other than 1 for a new Bugzilla installation. Is there a way to do this?</p>
[ { "answer_id": 250130, "author": "Richard Morgan", "author_id": 2258, "author_profile": "https://Stackoverflow.com/users/2258", "pm_score": 3, "selected": false, "text": "ALTER TABLE bugs AUTO_INCREMENT = 100;\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/249987", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2258/" ]
249,991
<p>I am trying to read a custom (non-standard) CSS property, set in a stylesheet (not the inline style attribute) and get its value. Take this CSS for example:</p> <pre><code>#someElement { foo: 'bar'; } </code></pre> <p>I have managed to get its value with the currentStyle property in IE7:</p> <pre><code>var element = document.getElementById('someElement'); var val = element.currentStyle.foo; </code></pre> <p>But currentStyle is MS-specific. So I tried getComputedStyle() in Firefox 3 and Safari 3:</p> <pre><code>var val = getComputedStyle(element,null).foo; </code></pre> <p>...and it returns undefined. <strong>Does anyone know a cross-browser way of retreiving a custom CSS property value?</strong></p> <p><em>(As you might have noticed, this isn't valid CSS. But it should work as long as the value follows the correct syntax. A better property name would be "-myNameSpace-foo" or something.)</em></p>
[ { "answer_id": 265566, "author": "scunliffe", "author_id": 6144, "author_profile": "https://Stackoverflow.com/users/6144", "pm_score": 2, "selected": false, "text": "var firstSS = document.styleSheets[0];\nvar firstSSRule = firstSS.rules[0];\nif(typeof(firstSSRule.style.bar) != 'undefined'){\n alert('value of [foo] is: ' + firstSSRule.style.bar);\n} else {\n alert('does not have [foo] property');\n}\n" }, { "answer_id": 11599944, "author": "Esailija", "author_id": 995876, "author_profile": "https://Stackoverflow.com/users/995876", "pm_score": 4, "selected": false, "text": ":after" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/249991", "https://Stackoverflow.com", "https://Stackoverflow.com/users/27741/" ]
249,994
<p>I have a dump of a windows service i made. The exception is that my code can't move a file (for some reason). Now, in my code there's a number of places where i move files around the filesystem. So, using Windbg, i'm trying to see the code where the exception occurs.</p> <p>here's my !clrstack dump..</p> <pre><code>0:016&gt; !clrstack -p OS Thread Id: 0xdf8 (16) Child-SP RetAddr Call Site 0000000019edea70 0000064278a15e4f System.IO.__Error.WinIOError(Int32, System.String) PARAMETERS: errorCode = &lt;no data&gt; maybeFullPath = &lt;no data&gt; 0000000019edead0 0000064280181ce5 System.IO.File.Move(System.String, System.String) PARAMETERS: sourceFileName = &lt;no data&gt; destFileName = &lt;no data&gt; 0000000019edeb50 0000064280196532 MyClass.Foo.DoSomeStuffInHere(System.String) PARAMETERS: this = 0x0000000000c30aa8 filePathAndName = 0x0000000000d1aad0 </code></pre> <p>now, this helps a lot...</p> <pre><code>0:016&gt; !do 0x0000000000d1aad0 Name: System.String MethodTable: 00000642784365e8 EEClass: 000006427803e4f0 Size: 88(0x58) bytes (C:\WINDOWS\assembly\GAC_64\mscorlib\2.0.0.0__b77a5c561934e089\mscorlib.dll) String: C:\BlahBlahFolder\FooFolder\4469.jpg Fields: -snipped- </code></pre> <p>So i've figured out the file which failed to be moved. kewl. But i just want to see the code in this method MyClass.Foo.DoSomeStuffInHere(System.String) which calls File.Move(..). That method has lots of File.Move .. so i could put try / catches / debug / trace information .. but i'm hoping to be more efficient by using Windbg to help find this problem.</p> <p>Any thoughts?</p>
[ { "answer_id": 265566, "author": "scunliffe", "author_id": 6144, "author_profile": "https://Stackoverflow.com/users/6144", "pm_score": 2, "selected": false, "text": "var firstSS = document.styleSheets[0];\nvar firstSSRule = firstSS.rules[0];\nif(typeof(firstSSRule.style.bar) != 'undefined'){\n alert('value of [foo] is: ' + firstSSRule.style.bar);\n} else {\n alert('does not have [foo] property');\n}\n" }, { "answer_id": 11599944, "author": "Esailija", "author_id": 995876, "author_profile": "https://Stackoverflow.com/users/995876", "pm_score": 4, "selected": false, "text": ":after" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/249994", "https://Stackoverflow.com", "https://Stackoverflow.com/users/30674/" ]
250,000
<p>We all know that alerts are bad. If you didn't know it read <a href="http://www.codinghorror.com/blog/archives/000114.html" rel="nofollow noreferrer">this</a></p> <p>Alerts are used to communicate with the user. So if we don't use them what is a good alternative? </p> <p>I'd like to get a nice list of good alternatives to choose from when implementing something that requires user communications.</p> <p>I'll give one myself as an example and for everyone to use:</p> <p><strong>Case:</strong> we need to validate user input before we can proceed.</p> <p><strong>Solution:</strong> instead of showing an alert box when user clicks ok/next/submit show a clearly styled (eg. red on a white bg) "frame" around/next to the user input that has the invalid input with an informative text on what is wrong. To make it easier on the user the input in question should gain focus and if necessary moved back into view.</p>
[ { "answer_id": 250181, "author": "John Rudy", "author_id": 14048, "author_profile": "https://Stackoverflow.com/users/14048", "pm_score": 0, "selected": false, "text": "Text" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/250000", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22673/" ]
250,001
<p>Can someone define what exactly 'POCO' means? I am encountering the term more and more often, and I'm wondering if it is only about plain classes or it means something more?</p>
[ { "answer_id": 250006, "author": "David Mohundro", "author_id": 4570, "author_profile": "https://Stackoverflow.com/users/4570", "pm_score": 9, "selected": true, "text": "public class Person\n{\n public string Name { get; set; }\n\n public int Age { get; set; }\n}\n" }, { "answer_id": 38254006, "author": "Viking jonsson", "author_id": 4038542, "author_profile": "https://Stackoverflow.com/users/4038542", "pm_score": 5, "selected": false, "text": "class Fruit \n{\n public Fruit() { }\n\n public Fruit(string name, double weight, int quantity) \n {\n Name = name;\n Weight = weight;\n Quantity = quantity;\n }\n\n public string Name { get; set; }\n public double Weight { get; set; }\n public int Quantity { get; set; }\n\n public override string ToString() \n {\n return $\"{Name.ToUpper()} ({Weight}oz): {Quantity}\";\n }\n}\n" }, { "answer_id": 59906232, "author": "Mohammad Kamel", "author_id": 3227593, "author_profile": "https://Stackoverflow.com/users/3227593", "pm_score": 0, "selected": false, "text": "public class Customer\n{\n public int Id { get; set; }\n\n public string Name { get; set; }\n}\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/250001", "https://Stackoverflow.com", "https://Stackoverflow.com/users/30726/" ]
250,033
<p>C++: Since a struct is a class with everything "public", are default -ctors created and called?</p> <p>The reason I ask is to understand the overhead, if any, that C++ may have over C, when structs are used. An opinion I have heard is that classes have some overhead that structs don't, in C++, but I question this.</p>
[ { "answer_id": 250426, "author": "Steve Jessop", "author_id": 13005, "author_profile": "https://Stackoverflow.com/users/13005", "pm_score": 4, "selected": false, "text": "struct sPOD {\n int foo;\n float bar;\n char baz[23];\n};\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/250033", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
250,037
<p>I have a gridview and I need to sort its elements when the user clicks on the header.<br> Its datasource is a List object.</p> <p>The aspx is defined this way :</p> <pre><code>&lt;asp:GridView ID="grdHeader" AllowSorting="true" AllowPaging="false" AutoGenerateColumns="false" Width="780" runat="server" OnSorting="grdHeader_OnSorting" EnableViewState="true"&gt; &lt;Columns&gt; &lt;asp:BoundField DataField="Entitycode" HeaderText="Entity" SortExpression="Entitycode" /&gt; &lt;asp:BoundField DataField="Statusname" HeaderText="Status" SortExpression="Statusname" /&gt; &lt;asp:BoundField DataField="Username" HeaderText="User" SortExpression="Username" /&gt; &lt;/Columns&gt; &lt;/asp:GridView&gt; </code></pre> <p>The code behind is defined this way :<br> First load :</p> <pre><code>protected void btnSearch_Click(object sender, EventArgs e) { List&lt;V_ReportPeriodStatusEntity&gt; items = GetPeriodStatusesForScreenSelection(); this.grdHeader.DataSource = items; this.grdHeader.DataBind(); } </code></pre> <p>when the user clicks on headers :</p> <pre><code>protected void grdHeader_OnSorting(object sender, GridViewSortEventArgs e) { List&lt;V_ReportPeriodStatusEntity&gt; items = GetPeriodStatusesForScreenSelection(); items.Sort(new Helpers.GenericComparer&lt;V_ReportPeriodStatusEntity&gt;(e.SortExpression, e.SortDirection)); grdHeader.DataSource = items; grdHeader.DataBind(); } </code></pre> <p>My problem is that e.SortDirection is always set to Ascending.<br> I have webpage with a similar code and it works well, e.SortDirection alternates between Ascending and Descending.</p> <p>What did I do wrong ?</p>
[ { "answer_id": 250571, "author": "Michael DeLorenzo", "author_id": 1383003, "author_profile": "https://Stackoverflow.com/users/1383003", "pm_score": 1, "selected": false, "text": "List<V_ReportPeriodStatusEntity> items = GetPeriodStatusesForScreenSelection();" }, { "answer_id": 300872, "author": "djuth", "author_id": 38787, "author_profile": "https://Stackoverflow.com/users/38787", "pm_score": 1, "selected": false, "text": "protected void SetPageSort(GridViewSortEventArgs e)\n{\n if (e.SortExpression == SortExpression)\n {\n if (SortDirection == \"ASC\")\n {\n SortDirection = \"DESC\";\n }\n else\n {\n SortDirection = \"ASC\";\n }\n }\n else\n {\n SortDirection = \"ASC\";\n SortExpression = e.SortExpression;\n }\n}\n" }, { "answer_id": 399880, "author": "Sander", "author_id": 2928, "author_profile": "https://Stackoverflow.com/users/2928", "pm_score": 4, "selected": false, "text": " protected void OnSortingResults(object sender, GridViewSortEventArgs e)\n {\n // If we're toggling sort on the same column, we simply toggle the direction. Otherwise, ASC it is.\n // e.SortDirection is useless and unreliable (only works with SQL data source).\n if (_sortBy == e.SortExpression)\n _sortDirection = _sortDirection == SortDirection.Descending ? SortDirection.Ascending : SortDirection.Descending;\n else\n _sortDirection = SortDirection.Ascending;\n\n _sortBy = e.SortExpression;\n\n BindResults();\n }\n" }, { "answer_id": 415759, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 6, "selected": true, "text": "DataTable sourceTable = GridAttendence.DataSource as DataTable;\nDataView view = new DataView(sourceTable);\nstring[] sortData = ViewState[\"sortExpression\"].ToString().Trim().Split(' ');\nif (e.SortExpression == sortData[0])\n{\n if (sortData[1] == \"ASC\")\n {\n view.Sort = e.SortExpression + \" \" + \"DESC\";\n this.ViewState[\"sortExpression\"] = e.SortExpression + \" \" + \"DESC\";\n }\n else\n {\n view.Sort = e.SortExpression + \" \" + \"ASC\";\n this.ViewState[\"sortExpression\"] = e.SortExpression + \" \" + \"ASC\";\n }\n}\nelse\n{\n view.Sort = e.SortExpression + \" \" + \"ASC\";\n this.ViewState[\"sortExpression\"] = e.SortExpression + \" \" + \"ASC\";\n}\n" }, { "answer_id": 590830, "author": "rjzii", "author_id": 1185, "author_profile": "https://Stackoverflow.com/users/1185", "pm_score": 3, "selected": false, "text": "void DataGrid_Sorting(object sender, GridViewSortEventArgs e)\n{\n if (e.SortExpression == (string)ViewState[\"SortColumn\"])\n {\n // We are resorting the same column, so flip the sort direction\n e.SortDirection = \n ((SortDirection)ViewState[\"SortColumnDirection\"] == SortDirection.Ascending) ? \n SortDirection.Descending : SortDirection.Ascending;\n }\n // Apply the sort\n this._data.DefaultView.Sort = e.SortExpression +\n (string)((e.SortDirection == SortDirection.Ascending) ? \" ASC\" : \" DESC\");\n ViewState[\"SortColumn\"] = e.SortExpression;\n ViewState[\"SortColumnDirection\"] = e.SortDirection;\n}\n" }, { "answer_id": 812389, "author": "maxbeaudoin", "author_id": 79152, "author_profile": "https://Stackoverflow.com/users/79152", "pm_score": 4, "selected": false, "text": "protected SortDirection GetSortDirection(string column)\n{\n SortDirection nextDir = SortDirection.Ascending; // Default next sort expression behaviour.\n if (ViewState[\"sort\"] != null && ViewState[\"sort\"].ToString() == column)\n { // Exists... DESC.\n nextDir = SortDirection.Descending;\n ViewState[\"sort\"] = null;\n }\n else\n { // Doesn't exists, set ViewState.\n ViewState[\"sort\"] = column;\n }\n return nextDir;\n}\n" }, { "answer_id": 1298329, "author": "rwo", "author_id": 154001, "author_profile": "https://Stackoverflow.com/users/154001", "pm_score": 6, "selected": false, "text": "private void GridViewSortDirection(GridView g, GridViewSortEventArgs e, out SortDirection d, out string f)\n{\n f = e.SortExpression;\n d = e.SortDirection;\n\n //Check if GridView control has required Attributes\n if (g.Attributes[\"CurrentSortField\"] != null && g.Attributes[\"CurrentSortDir\"] != null)\n {\n if (f == g.Attributes[\"CurrentSortField\"])\n {\n d = SortDirection.Descending;\n if (g.Attributes[\"CurrentSortDir\"] == \"ASC\")\n {\n d = SortDirection.Ascending;\n }\n }\n\n g.Attributes[\"CurrentSortField\"] = f;\n g.Attributes[\"CurrentSortDir\"] = (d == SortDirection.Ascending ? \"DESC\" : \"ASC\");\n }\n\n}\n" }, { "answer_id": 1684595, "author": "Daver", "author_id": 68095, "author_profile": "https://Stackoverflow.com/users/68095", "pm_score": 0, "selected": false, "text": "Dim lquery = From s In listToMap\n Select s\n Order By s.ACCT_Active Descending, s.ACCT_Name\n" }, { "answer_id": 6477999, "author": "in4man_1", "author_id": 812365, "author_profile": "https://Stackoverflow.com/users/812365", "pm_score": 2, "selected": false, "text": "protected void SetPageSort(GridViewSortEventArgs e) \n { \n if (e.SortExpression == SortExpression) \n { \n if (SortDirection == \"ASC\") \n { \n SortDirection = \"DESC\"; \n } \n else \n { \n SortDirection = \"ASC\"; \n } \n } \n else \n {\n if (SortDirection == \"ASC\")\n {\n SortDirection = \"DESC\";\n }\n else\n {\n SortDirection = \"ASC\";\n } \n SortExpression = e.SortExpression; \n } \n } \n protected void gridView_Sorting(object sender, GridViewSortEventArgs e)\n {\n SetPageSort(e); \n" }, { "answer_id": 8510356, "author": "Basil", "author_id": 1098540, "author_profile": "https://Stackoverflow.com/users/1098540", "pm_score": 0, "selected": false, "text": "void dg_SortCommand(object source, DataGridSortCommandEventArgs e)\n{\n DataGrid dg = (DataGrid) source;\n string sortField = dg.Attributes[\"sortField\"];\n List < SubreportSummary > data = (List < SubreportSummary > ) dg.DataSource;\n string field = e.SortExpression.Split(' ')[0];\n string sort = \"ASC\";\n if (sortField != null)\n {\n sort = sortField.Split(' ')[0] == field ? (sortField.Split(' ')[1] == \"DESC\" ? \"ASC\" : \"DESC\") : \"ASC\";\n }\n dg.Attributes[\"sortField\"] = field + \" \" + sort;\n data.Sort(new GenericComparer < SubreportSummary > (field, sort, null));\n dg.DataSource = data;\n dg.DataBind();\n}\n" }, { "answer_id": 10426852, "author": "AVIK GHOSH", "author_id": 1371819, "author_profile": "https://Stackoverflow.com/users/1371819", "pm_score": 2, "selected": false, "text": " <asp:GridView ID=\"GridView1\" runat=\"server\" AutoGenerateColumns=\"false\" AllowSorting=\"True\" \n onsorting=\"GridView1_Sorting\" EnableViewState=\"true\">\n <Columns><asp:BoundField DataField=\"bookid\" HeaderText=\"BOOK ID\" SortExpression=\"bookid\" />\n <asp:BoundField DataField=\"bookname\" HeaderText=\"BOOK NAME\" />\n <asp:BoundField DataField=\"writer\" HeaderText=\"WRITER\" />\n <asp:BoundField DataField=\"totalbook\" HeaderText=\"TOTAL BOOK\" SortExpression=\"totalbook\" />\n <asp:BoundField DataField=\"availablebook\" HeaderText=\"AVAILABLE BOOK\" />\n//gridview code on page load under ispostback false//after that.\n\n\n\nprotected void Page_Load(object sender, EventArgs e)\n {\n if (!IsPostBack)\n {\n string query = \"SELECT * FROM book\";\n DataTable DT = new DataTable();\n SqlDataAdapter DA = new SqlDataAdapter(query, sqlCon);\n DA.Fill(DT);\n\n\n GridView1.DataSource = DT;\n GridView1.DataBind();\n }\n }\n\n protected void GridView1_Sorting(object sender, GridViewSortEventArgs e)\n {\n\n string query = \"SELECT * FROM book\";\n DataTable DT = new DataTable();\n SqlDataAdapter DA = new SqlDataAdapter(query, sqlCon);\n DA.Fill(DT);\n\n GridView1.DataSource = DT;\n GridView1.DataBind();\n\n if (DT != null)\n {\n\n DataView dataView = new DataView(DT);\n dataView.Sort = e.SortExpression + \" \" + ConvertSortDirectionToSql(e.SortDirection);\n\n\n GridView1.DataSource = dataView;\n GridView1.DataBind();\n }\n }\n\n private string GridViewSortDirection\n {\n get { return ViewState[\"SortDirection\"] as string ?? \"DESC\"; }\n set { ViewState[\"SortDirection\"] = value; }\n }\n\n private string ConvertSortDirectionToSql(SortDirection sortDirection)\n {\n switch (GridViewSortDirection)\n {\n case \"ASC\":\n GridViewSortDirection = \"DESC\";\n break;\n\n case \"DESC\":\n GridViewSortDirection = \"ASC\";\n break;\n }\n\n return GridViewSortDirection;\n }\n}\n" }, { "answer_id": 13504318, "author": "Dave Lucre", "author_id": 1219999, "author_profile": "https://Stackoverflow.com/users/1219999", "pm_score": 2, "selected": false, "text": "private DataTable DataTable1;\nprotected void Page_Load(object sender, EventArgs e)\n{\n DataTable1 = GetDataFromDatabase();\n this.GridView1.DataSource = DataTable1.DefaultView;\n this.GridView1.DataBind();\n}\n" }, { "answer_id": 15334800, "author": "Amrit Jain", "author_id": 2075104, "author_profile": "https://Stackoverflow.com/users/2075104", "pm_score": 1, "selected": false, "text": "<asp:BoundField DataField=\"DealCRMID\" HeaderText=\"Opportunity ID\"\n SortExpression=\"DealCRMID\"/>\n<asp:BoundField DataField=\"DealCustomerName\" HeaderText=\"Customer\" \n SortExpression=\"DealCustomerName\"/>\n<asp:BoundField DataField=\"SLCode\" HeaderText=\"Practice\" \n SortExpression=\"SLCode\"/>\n" }, { "answer_id": 17226727, "author": "Ali", "author_id": 1634697, "author_profile": "https://Stackoverflow.com/users/1634697", "pm_score": 1, "selected": false, "text": "protected void grdHeader_OnSorting(object sender, GridViewSortEventArgs e)\n{\n List<V_ReportPeriodStatusEntity> items = GetPeriodStatusesForScreenSelection();\n items.Sort = e.SortExpression + \" \" + ConvertSortDirectionToSql(e);\n grdHeader.DataSource = items;\n grdHeader.DataBind();\n}\n\nprivate string ConvertSortDirectionToSql(GridViewSortEventArgs e)\n{\n ViewState[e.SortExpression] = ViewState[e.SortExpression] ?? \"ASC\";\n ViewState[e.SortExpression] = (ViewState[e.SortExpression].ToString() == \"ASC\") ? \"DESC\" : \"ASC\";\n return ViewState[e.SortExpression].ToString();\n}\n" }, { "answer_id": 20188834, "author": "Arijus Gilbrantas", "author_id": 1110126, "author_profile": "https://Stackoverflow.com/users/1110126", "pm_score": 2, "selected": false, "text": "DataTable dt = GetData();\n\n SortDirection sd;\n string f;\n GridViewSortDirection(gvProductBreakdown, e, out sd, out f);\n dt.DefaultView.Sort = sd == SortDirection.Ascending ? f + \" asc\" : f + \" desc\";\n gvProductBreakdown.DataSource = dt;\n gvProductBreakdown.DataBind();\n" }, { "answer_id": 21892323, "author": "PrzemG", "author_id": 3195498, "author_profile": "https://Stackoverflow.com/users/3195498", "pm_score": 2, "selected": false, "text": " protected void gvItems_Sorting(object sender, GridViewSortEventArgs e)\n {\n GridView grid = sender as GridView; // get reference to grid\n SortDirection currentSortDirection = SortDirection.Ascending; // default order\n\n // get column index by SortExpression\n int columnIndex = grid.Columns.IndexOf(grid.Columns.OfType<DataControlField>()\n .First(x => x.SortExpression == e.SortExpression));\n\n // sort only if grid has more than 1 row\n if (grid.Rows.Count > 1)\n {\n // get cells\n TableCell firstCell = grid.Rows[0].Cells[columnIndex];\n TableCell lastCell = grid.Rows[grid.Rows.Count - 1].Cells[columnIndex];\n\n // if field type of the cell is 'TemplateField' Text property is always empty.\n // Below assumes that value is binded to Label control in 'TemplateField'.\n string firstCellValue = firstCell.Controls.Count == 0 ? firstCell.Text : ((Label)firstCell.Controls[1]).Text;\n string lastCellValue = lastCell.Controls.Count == 0 ? lastCell.Text : ((Label)lastCell.Controls[1]).Text;\n\n DateTime tmpDate;\n decimal tmpDecimal;\n\n // try to determinate cell type to ensure correct ordering\n // by date or number\n if (DateTime.TryParse(firstCellValue, out tmpDate)) // sort as DateTime\n {\n currentSortDirection = \n DateTime.Compare(Convert.ToDateTime(firstCellValue), \n Convert.ToDateTime(lastCellValue)) < 0 ? \n SortDirection.Ascending : SortDirection.Descending;\n }\n else if (Decimal.TryParse(firstCellValue, out tmpDecimal)) // sort as any numeric type\n {\n currentSortDirection = Decimal.Compare(Convert.ToDecimal(firstCellValue), \n Convert.ToDecimal(lastCellValue)) < 0 ? \n SortDirection.Ascending : SortDirection.Descending;\n }\n else // sort as string\n {\n currentSortDirection = string.CompareOrdinal(firstCellValue, lastCellValue) < 0 ? \n SortDirection.Ascending : SortDirection.Descending;\n }\n }\n\n // then bind GridView using correct sorting direction (in this example I use Linq)\n if (currentSortDirection == SortDirection.Descending)\n {\n grid.DataSource = myItems.OrderBy(x => x.GetType().GetProperty(e.SortExpression).GetValue(x, null));\n }\n else\n {\n grid.DataSource = myItems.OrderByDescending(x => x.GetType().GetProperty(e.SortExpression).GetValue(x, null));\n }\n\n grid.DataBind();\n }\n" }, { "answer_id": 23375917, "author": "mcfea", "author_id": 984463, "author_profile": "https://Stackoverflow.com/users/984463", "pm_score": 1, "selected": false, "text": "Private Sub DataGrid1_SortCommand(ByVal source As Object, ByVal e As DataGridSortCommandEventArgs) Handles grid1.SortCommand\n Dim dataView As DataView = CType(SqlDataSource1.Select(DataSourceSelectArguments.Empty), DataView)\n dataView.Sort = e.SortExpression + dataView.FieldSortDirection(Session, e.SortExpression)\n\n grid1.DataSourceID = Nothing\n grid1.DataSource = dataView\n grid1.DataBind()\n\nEnd Sub\n" }, { "answer_id": 25312200, "author": "Barry McDermid", "author_id": 403198, "author_profile": "https://Stackoverflow.com/users/403198", "pm_score": 0, "selected": false, "text": " // Make sure you have sortable: true on the relevant column names or \n // nothing happens as I found!!\n var columns = [\n { name: \"FileName\", id: \"FileName\", field: \"FileName\", width: 95, selectable: true, sortable: true },\n { name: \"Type\", id: \"DocumentType\", field: \"DocumentType\", minWidth: 105, width: 120, maxWidth: 120, selectable: true, sortable: true },\n { name: \"ScanDate\", id: \"ScanDate\", field: \"ScanDate\", width: 90, selectable: true, sortable: true }, ];\n" }, { "answer_id": 25657044, "author": "AdamE", "author_id": 796858, "author_profile": "https://Stackoverflow.com/users/796858", "pm_score": 3, "selected": false, "text": "<asp:HiddenField ID=\"hfSortExpression\" runat=\"server\" Value=\"LastName\" />\n<asp:HiddenField ID=\"hfSortDirection\" runat=\"server\" Value=\"Ascending\" />\n" }, { "answer_id": 26285465, "author": "PCPGMR", "author_id": 323650, "author_profile": "https://Stackoverflow.com/users/323650", "pm_score": 1, "selected": false, "text": " dgvCoaches.DataSource = dsCoaches.Tables[0];\n ViewState[\"AllCoaches\"] = dsCoaches.Tables[0];\n dgvCoaches.DataBind();\n" }, { "answer_id": 41749085, "author": "Bert", "author_id": 7442666, "author_profile": "https://Stackoverflow.com/users/7442666", "pm_score": -1, "selected": false, "text": "Protected Sub grTicketHistory_Sorting(sender As Object, e As GridViewSortEventArgs) Handles grTicketHistory.Sorting\n\n Dim dt As DataTable = Session(\"historytable\")\n If Session(\"SortDirection\" & e.SortExpression) = \"ASC\" Then\n Session(\"SortDirection\" & e.SortExpression) = \"DESC\"\n Else\n Session(\"SortDirection\" & e.SortExpression) = \"ASC\"\n End If\n dt.DefaultView.Sort = e.SortExpression & \" \" & Session(\"SortDirection\" & e.SortExpression)\n grTicketHistory.DataSource = dt\n grTicketHistory.DataBind()\n\nEnd Sub\n" }, { "answer_id": 42719613, "author": "Rasmus W", "author_id": 4243762, "author_profile": "https://Stackoverflow.com/users/4243762", "pm_score": 0, "selected": false, "text": " protected void GridView1_Sorting(object sender, GridViewSortEventArgs e)\n {\n if (ViewState[\"sortExpression\"] == null || ViewState[\"sortExpression\"].ToString() != e.SortExpression.ToString())\n MyDataTable.DefaultView.Sort = e.SortExpression + \" ASC\";\n else\n {\n if (ViewState[\"SortDirection\"].ToString() == \"Ascending\")\n MyDataTable.DefaultView.Sort = e.SortExpression = e.SortExpression + \" DESC\";\n else\n MyDataTable.DefaultView.Sort = e.SortExpression + \" ASC\";\n }\n\n GridView1.DataSource = MyDataTable;\n GridView1.DataBind();\n\n ViewState[\"sortExpression\"] = e.SortExpression;\n ViewState[\"SortDirection\"] = e.SortDirection;\n }\n" }, { "answer_id": 54828533, "author": "Isaac Byrne", "author_id": 5115866, "author_profile": "https://Stackoverflow.com/users/5115866", "pm_score": 1, "selected": false, "text": " // ==================================================\n // SortByDirection\n // ==================================================\n public SortDirection SortByDirection\n {\n get\n {\n if (ViewState[\"SortByDirection\"] == null)\n {\n ViewState[\"SortByDirection\"] = SortDirection.Ascending;\n }\n\n return (SortDirection)Enum.Parse(typeof(SortDirection), ViewState[\"SortByDirection\"].ToString());\n }\n set { ViewState[\"SortByDirection\"] = value; }\n }\n" }, { "answer_id": 58069201, "author": "Tomas", "author_id": 12109550, "author_profile": "https://Stackoverflow.com/users/12109550", "pm_score": 0, "selected": false, "text": "protected void gv_Sorting(object sender, GridViewSortEventArgs e)\n{\n DataTable dataTable = (DataTable)Cache[\"GridData\"];\n\n if (dataTable != null)\n {\n DataView dataView = new DataView(dataTable);\n string Field1 = e.SortExpression;\n string whichWay = \"ASC\";\n if (HttpContext.Current.Session[Field1] != null)\n {\n whichWay = HttpContext.Current.Session[Field1].ToString();\n if (whichWay == \"ASC\")\n whichWay = \"DESC\";\n else\n whichWay = \"ASC\"; \n }\n\n HttpContext.Current.Session[Field1] = whichWay;\n dataView.Sort = Field1 + \" \" + whichWay; \n gv.DataSource = dataView;\n gv.DataBind();\n }\n}\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/250037", "https://Stackoverflow.com", "https://Stackoverflow.com/users/28544/" ]
250,055
<p>I'd like to warn users when they <strong>try to close a browser window</strong> if they <strong>didn't save</strong> the changes they made in the web form.</p> <p>I'm using ASP.NET 3.5 (with ASP.NET Ajax).</p> <p>Is there a common solution which I could easily implement?</p> <p><em>EDIT: maybe my question wasn't clear:</em> I am specifically looking for a way which integrates gracefully in the <strong>ASP.NET</strong> Server Controls methodology.</p>
[ { "answer_id": 250078, "author": "Anders", "author_id": 25515, "author_profile": "https://Stackoverflow.com/users/25515", "pm_score": 0, "selected": false, "text": "<body onunload=\"onPageUnload();\">" }, { "answer_id": 250086, "author": "Eoin Campbell", "author_id": 30155, "author_profile": "https://Stackoverflow.com/users/30155", "pm_score": 2, "selected": false, "text": "window.onbeforeunload\n" }, { "answer_id": 250311, "author": "aemkei", "author_id": 28150, "author_profile": "https://Stackoverflow.com/users/28150", "pm_score": 2, "selected": false, "text": "window.onbeforeunload" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/250055", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6461/" ]
250,062
<p>I have been hearing a lot about Ruby and possibly even Javascript being "true" object oriented languages as opposed to C++ and C# which are class oriented (or template based) languages. What is meant by true OO and what are the advantages of this over the class/template approach?</p>
[ { "answer_id": 250098, "author": "Firas Assaad", "author_id": 23153, "author_profile": "https://Stackoverflow.com/users/23153", "pm_score": 5, "selected": true, "text": "1.to_s" }, { "answer_id": 277066, "author": "Johannes Schaub - litb", "author_id": 34509, "author_profile": "https://Stackoverflow.com/users/34509", "pm_score": 1, "selected": false, "text": "typedef struct foo_ {\n T1 (*getA)(foo * self);\n void (*setA)(foo * self, T1 a_);\n\n/* private: */\n T1 a_;\n} foo;\n\nT1 foo_getA(foo * self) {\n return self->a_;\n}\n\nvoid foo_setA(foo * self, T1 a_) {\n self->a_ = a_;\n}\n\nfoo * foo_create() {\n foo * f = malloc(sizeof(foo));\n f->getA = foo_getA;\n f->setA = foo_setA;\n return f;\n}\n\nvoid foo_destroy(foo * f) {\n free (f);\n}\n\nvoid doSomething(T1 a) {\n foo * f = foo_create();\n f->setA(f, a);\n foo_destroy(f);\n}\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/250062", "https://Stackoverflow.com", "https://Stackoverflow.com/users/31188/" ]
250,082
<p>I have a makefile template to compile a single DLL (for a plugin system). The makefile of the user looks like this:</p> <pre><code>EXTRA_SRCS=file1 file2 include makefile.in </code></pre> <p>In the <code>makefile.in</code> I have:</p> <pre><code>plugin.dll: plugin.os $(patsubst %,%.os,$(EXTRA_SRCS)) </code></pre> <p>Where <code>plugin.os</code> is the main C++ file to be compiled. Btw, the files ending is <code>.os</code> are the object files compiled for shared library (i.e. using the <code>-fpic</code> option with <code>gcc</code>)</p> <p>Now, the problem is that the extra sources will probably (but not necessarily) be header files. Ideally I would like to add them as dependencies for the target <code>plugin.os</code> and the <code>file.cpp</code>, but only if they exist.</p> <p>The method should work for both windows and linux, or at least be adaptable to each. However, I only use the GNU version of make.</p>
[ { "answer_id": 250163, "author": "JesperE", "author_id": 13051, "author_profile": "https://Stackoverflow.com/users/13051", "pm_score": 5, "selected": true, "text": "$(wildcard *.h)\n" }, { "answer_id": 250795, "author": "m0j0", "author_id": 31319, "author_profile": "https://Stackoverflow.com/users/31319", "pm_score": 3, "selected": false, "text": "%.d: %.c\n gcc $(INCS) $(CFLAGS) -MM $< -MF $@\n\n%.d: %.cpp\n g++ $(INCS) $(CXXFLAGS) -MM $< -MF $@\n" }, { "answer_id": 250831, "author": "ephemient", "author_id": 20713, "author_profile": "https://Stackoverflow.com/users/20713", "pm_score": 2, "selected": false, "text": "$(filter $(wildcard *.h),$(HEADER_FILES))\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/250082", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7136/" ]
250,096
<p>I'm trying to code opposite action to this:</p> <pre><code>std::ostream outs; // properly initialized of course std::set&lt;int&gt; my_set; // ditto outs &lt;&lt; my_set.size(); std::copy( my_set.begin(), my_set.end(), std::ostream_iterator&lt;int&gt;( outs ) ); </code></pre> <p>it should be something like this:</p> <pre><code>std::istream ins; std::set&lt;int&gt;::size_type size; ins &gt;&gt; size; std::copy( std::istream_iterator&lt;int&gt;( ins ), std::istream_iterator&lt;int&gt;( ins ) ???, std::inserter( my_set, my_set.end() ) ); </code></pre> <p>But I'm stuck with the 'end' iterator -- input interators can't use std::advance and neither I can use two streams with the same source...</p> <p>Is there any elegant way how to solve this? Of course I can use for loop, but maybe there's something nicer :)</p>
[ { "answer_id": 250380, "author": "Dominik Grabiec", "author_id": 3719, "author_profile": "https://Stackoverflow.com/users/3719", "pm_score": 2, "selected": false, "text": "std::istream ins;\nstd::set<int> my_set;\nstd::vector<int> my_vec;\n\nstruct read_functor\n{\n read_functor(std::istream& stream) :\n m_stream(stream)\n {\n }\n\n int operator()\n {\n int temp;\n m_stream >> temp;\n return temp;\n }\nprivate:\n std::istream& m_stream;\n};\n\nstd::set<int>::size_type size;\nins >> size;\nmy_vec.reserve(size);\n\nstd::generate_n(my_vec.begin(), size, read_functor(ins));\nmy_set.insert(my_vec.begin(), my_vec.end());\n" }, { "answer_id": 250745, "author": "Martin York", "author_id": 14065, "author_profile": "https://Stackoverflow.com/users/14065", "pm_score": 3, "selected": true, "text": "#include <set>\n#include <iterator>\n#include <algorithm>\n#include <iostream>\n\n\ntemplate<typename T>\nstruct CountIter: public std::istream_iterator<T>\n{\n CountIter(size_t c)\n :std::istream_iterator<T>()\n ,count(c)\n {}\n CountIter(std::istream& str)\n :std::istream_iterator<T>(str)\n ,count(0)\n {}\n\n bool operator!=(CountIter const& rhs) const\n {\n return (count != rhs.count) && (dynamic_cast<std::istream_iterator<T> const&>(*this) != rhs);\n }\n T operator*()\n {\n ++count;\n return std::istream_iterator<T>::operator*();\n }\n\n private:\n size_t count;\n};\n\nint main()\n{\n std::set<int> x;\n\n //std::copy(std::istream_iterator<int>(std::cin),std::istream_iterator<int>(),std::inserter(x,x.end()));\n std::copy(\n CountIter<int>(std::cin),\n CountIter<int>(5),\n std::inserter(x,x.end())\n );\n}\n" }, { "answer_id": 252834, "author": "Dean Michael", "author_id": 11274, "author_profile": "https://Stackoverflow.com/users/11274", "pm_score": 1, "selected": false, "text": "istream ins;\nset<int>::size_type size;\nset<int> new_set;\nins >> size;\nostream_iterator<int> ins_iter(ins);\n\nfor_each(counting_iterator<int>(0), counting_iterator<int>(size),\n [&new_set, &ins_iter](int n) { new_set.insert(*ins_iter++); }\n);\n" }, { "answer_id": 360344, "author": "Jeffrey Martinez", "author_id": 29703, "author_profile": "https://Stackoverflow.com/users/29703", "pm_score": 2, "selected": false, "text": "std::copy( std::istream_iterator<int>(ins),\n std::istream_iterator<int>(),\n std::inserter(my_set, my_set.end())\n );\n" }, { "answer_id": 5569467, "author": "jnyanez", "author_id": 695213, "author_profile": "https://Stackoverflow.com/users/695213", "pm_score": 1, "selected": false, "text": "my_set.insert(std::istream_iterator<int>(ins), std::istream_iterator<int>());\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/250096", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21009/" ]
250,134
<p>What is the difference between <code>int *a[3]</code> and <code>int (*a)[3]</code>?</p>
[ { "answer_id": 250164, "author": "Robert Gamble", "author_id": 25222, "author_profile": "https://Stackoverflow.com/users/25222", "pm_score": 4, "selected": false, "text": "int a[3]" }, { "answer_id": 250174, "author": "CAdaker", "author_id": 30579, "author_profile": "https://Stackoverflow.com/users/30579", "pm_score": 3, "selected": false, "text": "int *a[3]\n" }, { "answer_id": 250183, "author": "bltxd", "author_id": 11892, "author_profile": "https://Stackoverflow.com/users/11892", "pm_score": 3, "selected": false, "text": "#include <iostream>\n\ntemplate < class T > void describe(T& )\n{\n // With msvc, use __FUNCSIG__ instead\n std::cout << __PRETTY_FUNCTION__ << std::endl;\n}\n\nint main(int argc, char* argv[])\n{\n int *a[3];\n describe(a);\n\n int (*b)[3];\n describe(b);\n\n return EXIT_SUCCESS;\n}\n" }, { "answer_id": 250856, "author": "FreeMemory", "author_id": 2132, "author_profile": "https://Stackoverflow.com/users/2132", "pm_score": 3, "selected": false, "text": "cdecl" }, { "answer_id": 1145127, "author": "daveslab", "author_id": 99971, "author_profile": "https://Stackoverflow.com/users/99971", "pm_score": 2, "selected": false, "text": ")" }, { "answer_id": 59641539, "author": "Guruprasad", "author_id": 4693394, "author_profile": "https://Stackoverflow.com/users/4693394", "pm_score": -1, "selected": false, "text": "int *a[3]" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/250134", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
250,137
<p>I have the following legacy code:</p> <pre><code>public class MyLegacyClass { private static final String jndiName = "java:comp/env/jdbc/LegacyDataSource" public static SomeLegacyClass doSomeLegacyStuff(SomeOtherLegacyClass legacyObj) { // do stuff using jndiName } } </code></pre> <p>This class is working in a J2EE-Container.</p> <p>Now I would like to test the class outside of the container.</p> <p>What is the best strategy? Refactoring is basically allowed.</p> <p>Accessing the LegacyDataSource is allowed (the test does not have to be a "pure" unit-test).</p> <p>EDIT: Introducing additional runtime-frameworks is not allowed.</p>
[ { "answer_id": 250272, "author": "David Santamaria", "author_id": 24097, "author_profile": "https://Stackoverflow.com/users/24097", "pm_score": 1, "selected": false, "text": "DataSource datasource = (DataSource)initialContext.lookup(DATASOURCE_CONTEXT);\n" }, { "answer_id": 250635, "author": "Scott Bale", "author_id": 2495576, "author_profile": "https://Stackoverflow.com/users/2495576", "pm_score": 4, "selected": true, "text": "public class MyLegacyClass {\n\n private static Strategy strategy = new JNDIStrategy();\n\n public static SomeLegacyClass doSomeLegacyStuff(SomeOtherLegacyClass legacyObj) {\n // legacy logic\n SomeLegacyClass result = strategy.doSomeStuff(legacyObj);\n // more legacy logic\n return result;\n }\n\n static void setStrategy(Strategy strategy){\n MyLegacyClass.strategy = strategy;\n }\n\n}\n\ninterface Strategy{\n public SomeLegacyClass doSomeStuff(SomeOtherLegacyClass legacyObj);\n}\n\nclass JNDIStrategy implements Strategy {\n private static final String jndiName = \"java:comp/env/jdbc/LegacyDataSource\";\n\n public SomeLegacyClass doSomeStuff(SomeOtherLegacyClass legacyObj) {\n // do stuff using jndiName\n }\n}\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/250137", "https://Stackoverflow.com", "https://Stackoverflow.com/users/32749/" ]
250,151
<p>When I see Lua, the only thing I ever read is "great for embedding", "fast", "lightweight" and more often than anything else: "World of Warcraft" or in short "WoW".</p> <p>Why is it limited to embedding the whole thing into another application? Why not write general-purpose scripts like you do with Python or Perl?</p> <p>Lua seems to be doing great in aspects like speed and memory-usage (The fastest scripting language afaik) so why is it that I never see Lua being used as a "Desktop scripting-language" to automate tasks? For example:</p> <ul> <li>Renaming a bunch of files</li> <li>Download some files from the web</li> <li>Webscraping</li> </ul> <p>Is it the lack of the standard library?</p>
[ { "answer_id": 326660, "author": "Norman Ramsey", "author_id": 41661, "author_profile": "https://Stackoverflow.com/users/41661", "pm_score": 3, "selected": false, "text": "osutil" }, { "answer_id": 1537777, "author": "Arthur Reutenauer", "author_id": 46495, "author_profile": "https://Stackoverflow.com/users/46495", "pm_score": 2, "selected": false, "text": "luatex" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/250151", "https://Stackoverflow.com", "https://Stackoverflow.com/users/32756/" ]
250,157
<p>When you have a complex property, should you instantiate it or leave it to the user to instantiate it?</p> <p>For example (C#)</p> <p>A)</p> <pre><code> class Xyz{ List&lt;String&gt; Names {get; set;} } </code></pre> <p>When I try to use, I have to set it.</p> <pre><code>... Xyz xyz = new Xyz(); xyz.Name = new List&lt;String&gt;(); xyz.Name.Add("foo"); ... </code></pre> <p>Where as if I modify the code</p> <p>B)</p> <pre><code> class Xyz{ public Xyz(){ Names = new List&lt;String&gt;(); } List&lt;String&gt; Names {get; } } </code></pre> <p>which in this case, I can make the List read-only.</p> <p>Another scenario might arise, I suppose where you would intentionally not want to set it. For example in</p> <p>C)</p> <pre><code> class Xyz{ String Name {get; set;} } </code></pre> <p>I would thing it bad practice to initialize.</p> <p>Are there some rules of thumb for such scenarios?</p>
[ { "answer_id": 250193, "author": "kͩeͣmͮpͥ ͩ", "author_id": 26479, "author_profile": "https://Stackoverflow.com/users/26479", "pm_score": 2, "selected": false, "text": "class XYZ \n{\n public XYZ () { Names = new List<string>(); }\n public List<string> Names { get; private set; }\n}\n" }, { "answer_id": 250199, "author": "Morgan Cheng", "author_id": 26349, "author_profile": "https://Stackoverflow.com/users/26349", "pm_score": 1, "selected": false, "text": "class Xyz\n{\n public Xyz(string name)\n {\n this.Name = name;\n }\n String Name \n {\n get; \n private set;\n }\n}\n" }, { "answer_id": 250204, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "public bool IsValid(object input){\n foreach(var validator in this.Validators)\n if(!validator.IsValid(input)\n return false;\n return true;\n}\n" }, { "answer_id": 250339, "author": "James Curran", "author_id": 12725, "author_profile": "https://Stackoverflow.com/users/12725", "pm_score": 2, "selected": false, "text": "MyClass myc = new MyClass();\nmyc.SomeProp = 5;\nmyc.DoSomething();\n" }, { "answer_id": 3431143, "author": "Jerod Houghtelling", "author_id": 373521, "author_profile": "https://Stackoverflow.com/users/373521", "pm_score": 0, "selected": false, "text": "public class Xyz\n{\n private List<String> _names = new List<String>(); // could also set in constructor\n\n public IEnumerable<String> Names\n {\n get\n {\n return _names;\n }\n }\n\n public void AddName( string name )\n {\n _names.Add( name );\n }\n}\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/250157", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2017/" ]
250,166
<p>I have an application that I'm trying to wrap into a jar for easier deployment. The application compiles and runs fine (in a Windows cmd window) when run as a set of classes reachable from the CLASSPATH. But when I jar up my classes and try to run it with java 1.6 in the same cmd window, I start getting exceptions:</p> <pre><code>C:\dev\myapp\src\common\datagen&gt;C:/apps/jdk1.6.0_07/bin/java.exe -classpath C:\myapp\libs\commons -logging-1.1.jar -server -jar DataGen.jar Exception in thread "main" java.lang.NoClassDefFoundError: org/apache/commons/logging/LogFactory at com.example.myapp.fomc.common.datagen.DataGenerationTest.&lt;clinit&gt;(Unknown Source) Caused by: java.lang.ClassNotFoundException: org.apache.commons.logging.LogFactory at java.net.URLClassLoader$1.run(URLClassLoader.java:200) at java.security.AccessController.doPrivileged(Native Method) at java.net.URLClassLoader.findClass(URLClassLoader.java:188) at java.lang.ClassLoader.loadClass(ClassLoader.java:306) at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:276) at java.lang.ClassLoader.loadClass(ClassLoader.java:251) at java.lang.ClassLoader.loadClassInternal(ClassLoader.java:319) ... 1 more </code></pre> <p>The funny thing is, the offending LogFactory seems to be in commons-logging-1.1.jar, which is in the class path specified. The jar file (yep, it's really there):</p> <pre><code>C:\dev\myapp\src\common\datagen&gt;dir C:\myapp\libs\commons-logging-1.1.jar Volume in drive C is Local Disk Volume Serial Number is ECCD-A6A7 Directory of C:\myapp\libs 12/11/2007 11:46 AM 52,915 commons-logging-1.1.jar 1 File(s) 52,915 bytes 0 Dir(s) 10,956,947,456 bytes free </code></pre> <p>The contents of the commons-logging-1.1.jar file:</p> <pre><code>C:\dev\myapp\src\common\datagen&gt;jar -tf C:\myapp\libs\commons-logging-1.1.jar META-INF/ META-INF/MANIFEST.MF org/ org/apache/ org/apache/commons/ org/apache/commons/logging/ org/apache/commons/logging/impl/ META-INF/LICENSE.txt META-INF/NOTICE.txt org/apache/commons/logging/Log.class org/apache/commons/logging/LogConfigurationException.class org/apache/commons/logging/LogFactory$1.class org/apache/commons/logging/LogFactory$2.class org/apache/commons/logging/LogFactory$3.class org/apache/commons/logging/LogFactory$4.class org/apache/commons/logging/LogFactory$5.class org/apache/commons/logging/LogFactory.class ... (more classes in commons-logging-1.1 ...) </code></pre> <p>Yep, commons-logging has the LogFactory class. And finally, the contents of my jar's manifest:</p> <pre><code>Manifest-Version: 1.0 Ant-Version: Apache Ant 1.6.5 Created-By: 10.0-b23 (Sun Microsystems Inc.) Main-Class: com.example.myapp.fomc.common.datagen.DataGenerationTest Class-Path: commons-logging-1.1.jar commons-lang.jar antlr.jar toplink .jar GroboTestingJUnit-1.2.1-core.jar junit.jar </code></pre> <p>This has stumped me, and any coworkers I've bugged for more than a day now. Just to cull the answers, for now at least, third party solutions to this are probably out due to licensing restrictions and company policies (e.g.: tools for creating exe's or packaging up jars). The ultimate goal is to create a jar that can be copied from my development Windows box to a Linux server (with any dependent jars) and used to populate a database (so classpaths may wind up being different between development and deployment environments). Any clues to this mystery would be greatly appreciated!</p>
[ { "answer_id": 8838405, "author": "g_tom", "author_id": 1145934, "author_profile": "https://Stackoverflow.com/users/1145934", "pm_score": 5, "selected": false, "text": "-jar" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/250166", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13140/" ]
250,175
<p>When writing my own auto updater, is there a general framework that I should be following?</p> <p>A while ago I was reading up on how one should create a 'boot strapper' that will load first before the main application (since a running appilation can't be updated due to file locks etc.)</p> <p>So any tips/best practices for this?</p>
[ { "answer_id": 1220670, "author": "Cheeso", "author_id": 48082, "author_profile": "https://Stackoverflow.com/users/48082", "pm_score": 1, "selected": false, "text": " _Updater = new AppUpdater.SimpleAppUpdater(_MyManifestUrl);\n _Updater.Startup(App.CommandLineArgs);\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/250175", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
250,189
<p>I'm currently installing and configuring an open source project on a test server. I've been well trained to use source control, and I want to make sure everything I do is managed properly (both for me, the sole dev/admin, and for future maintaners). The open source project is available as a source download or by svn checkout.</p> <p>I want to have my own source controlled version of the project. I don't intend to be changing the (java servlet) code much (if at all), but there are configurations, XML files, XSL, CSS, etc. all involved that I definitely want to be source controlled.</p> <p>Should I go ahead and just make my own local repository of all of the source code? Should I try to only control the files that I need to change? In that case I would want the directory structure to match, so I could do checkouts directly to the build directories.</p>
[ { "answer_id": 1220670, "author": "Cheeso", "author_id": 48082, "author_profile": "https://Stackoverflow.com/users/48082", "pm_score": 1, "selected": false, "text": " _Updater = new AppUpdater.SimpleAppUpdater(_MyManifestUrl);\n _Updater.Startup(App.CommandLineArgs);\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/250189", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8092/" ]
250,191
<p>I have a menu of product brands that I want to split over 4 columns. So if I have 39 brands, then I want the maximum item count for each column to be 10 (with a single gap in the last column. Here's how I'm calculating the item count for a column (using C#):</p> <pre><code>int ItemCount = Convert.ToInt32(Math.Ceiling(Convert.ToDecimal(BrandCount) / 4m)); </code></pre> <p>All that conversion seems really ugly to me. Is there a better way to do math on integers in C#?</p>
[ { "answer_id": 250205, "author": "GavinCattell", "author_id": 21644, "author_profile": "https://Stackoverflow.com/users/21644", "pm_score": 3, "selected": false, "text": "ItemCount = BrandCount / 4;\nif (BrandCount%4 > 0) ItemCount++;\n" }, { "answer_id": 250206, "author": "kͩeͣmͮpͥ ͩ", "author_id": 26479, "author_profile": "https://Stackoverflow.com/users/26479", "pm_score": 5, "selected": true, "text": "int ItemCount = (int) Math.Ceiling( (decimal)BrandCount / 4m );\n" }, { "answer_id": 250211, "author": "John Rudy", "author_id": 14048, "author_profile": "https://Stackoverflow.com/users/14048", "pm_score": 2, "selected": false, "text": "BrandCount" }, { "answer_id": 250266, "author": "Motti", "author_id": 3848, "author_profile": "https://Stackoverflow.com/users/3848", "pm_score": 4, "selected": false, "text": "int ItemCount = (BrandCount+3)/4;\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/250191", "https://Stackoverflow.com", "https://Stackoverflow.com/users/203/" ]
250,197
<p>I am attempting to compose a style sheet that, given an XML input (obviously) and a parameter that specifies a "target", will produce a list of commands that match that target. Here is the style sheet as written:</p> <pre><code>&lt;?xml version="1.0"?&gt; &lt;xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0"&gt; &lt;xsl:param name="target" select="cora_cmd"/&gt; &lt;xsl:output method="xml" indent="yes"/&gt; &lt;xsl:template match="command/program"&gt; &lt;xsl:if test="@name=$target"&gt; &lt;xsl:message terminate="no"&gt;found match &lt;xsl:value-of select="$target"/&gt; &lt;/xsl:message&gt; &lt;xi:include xmlns:xi="http://www.w3.org/2003/XInclude"&gt; &lt;xsl:attribute name="href"&gt;&lt;xsl:value-of select="../@help"/&gt;&lt;/xsl:attribute&gt; &lt;/xi:include&gt; &lt;/xsl:if&gt; &lt;/xsl:template&gt; &lt;/xsl:stylesheet&gt; </code></pre> <p>I am invoking xsltproc to execute this style sheet as follows:</p> <pre><code>xsltproc --param target cora_cmd gen-commands.xsl commands.xml </code></pre> <p>The problem that I am encountering is that the parameter value for target does not seem to get set. At least the name that comes from the message appears to be an empty string and the test for xsl:if always fails. I am certain that this is due to some bone-headed mistake on my part but I've yet to recognise it. Does anybody know what I've done wrong?</p>
[ { "answer_id": 250337, "author": "Tim C", "author_id": 7585, "author_profile": "https://Stackoverflow.com/users/7585", "pm_score": 6, "selected": true, "text": "xsltproc --stringparam target cora_cmd gen-commands.xsl commands.xml\n" }, { "answer_id": 259119, "author": "ChuckB", "author_id": 28605, "author_profile": "https://Stackoverflow.com/users/28605", "pm_score": 3, "selected": false, "text": "@select" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/250197", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19674/" ]
250,207
<p>How to host the WCF service in windows service?</p> <p>Thanks Sekar</p>
[ { "answer_id": 250231, "author": "John Sibly", "author_id": 1078, "author_profile": "https://Stackoverflow.com/users/1078", "pm_score": 3, "selected": false, "text": " [RunInstaller(true)]\n public class ProjectInstaller : Installer\n {\n }\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/250207", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
250,209
<p>I'm relatively new to the Python world, but this seems very straight forward.</p> <p>Google is yelling at me that this code needs to be optimized:</p> <pre><code>class AddLinks(webapp.RequestHandler): def post(self): # Hash the textarea input to generate pseudo-unique value hash = md5.new(self.request.get('links')).hexdigest() # Seperate the input by line allLinks = self.request.get('links').splitlines() # For each line in the input, add to the database for x in allLinks: newGroup = LinkGrouping() newGroup.reference = hash newGroup.link = x newGroup.put() # testing vs live #baseURL = 'http://localhost:8080' baseURL = 'http://linkabyss.appspot.com' # Build template parameters template_values = { 'all_links': allLinks, 'base_url': baseURL, 'reference': hash, } # Output the template path = os.path.join(os.path.dirname(__file__), 'addLinks.html') self.response.out.write(template.render(path, template_values)) </code></pre> <p>The dashboard is telling me that this is using a ton of CPU.</p> <p>Where should I look for improvements?</p>
[ { "answer_id": 250294, "author": "monkut", "author_id": 24718, "author_profile": "https://Stackoverflow.com/users/24718", "pm_score": 2, "selected": false, "text": "unsplitlinks = self.request.get('links')\n" }, { "answer_id": 250322, "author": "Andre Bossard", "author_id": 21027, "author_profile": "https://Stackoverflow.com/users/21027", "pm_score": 2, "selected": false, "text": "self.request.get('links')" }, { "answer_id": 250395, "author": "Nick Johnson", "author_id": 12030, "author_profile": "https://Stackoverflow.com/users/12030", "pm_score": 4, "selected": true, "text": "# For each line in the input, add to the database\ngroups = []\nfor x in allLinks:\n newGroup = LinkGrouping()\n newGroup.reference = hash\n newGroup.link = x\n groups.append(newGroup)\ndb.put(groups)\n" }, { "answer_id": 250465, "author": "databyss", "author_id": 9094, "author_profile": "https://Stackoverflow.com/users/9094", "pm_score": 0, "selected": false, "text": "SELECT * FROM LinkGrouping WHERE links.contains('http://www.google.com')\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/250209", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9094/" ]
250,214
<p>I am updating a VBA program (excel). At startup the program checks if it can find a directory which is on the office file server using:</p> <pre><code>FileSystemObject.FolderExists("\\servername\path") </code></pre> <p>If this is not found the program switches to offline mode and saves its output to the local hard disk (for later transfer), instead of directly to the fileserver. </p> <p>This works OK, It's very quick if the computer can reach the path, however it can sometimes take a while (up to one minute) for the call to FolderExists to complete/time-out, especially if there is a network connection open but the required path does not exist (i.e. we are connected to some other LAN).</p> <p>My Question(s):</p> <ol> <li><p>is there a quicker/better way to check for the existence of a network path using VBA?</p></li> <li><p>is there a way to have the user cancel the search done by FolderExists() when (s)he knows it cannot succeed because they're not in the office. I.e. is there some way to prematurely exit FolderExists() (or any other function call for that matter)</p></li> </ol> <p>I want the solution to have as little user input as possible, which is why the check is done automatically, rather than just asking the user if (s)he's in the office or not in the first place.</p>
[ { "answer_id": 11306581, "author": "Rob Gibson", "author_id": 1498067, "author_profile": "https://Stackoverflow.com/users/1498067", "pm_score": 0, "selected": false, "text": "Dir" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/250214", "https://Stackoverflow.com", "https://Stackoverflow.com/users/32763/" ]
250,216
<p>Is there a good way to determine if a person has a popup blocker enabled? I need to maintain a web application that unfortunately has tons of popups throughout it and I need to check if the user has popup blockers enabled.</p> <p>The only way I've found to do this is to open a window from javascript, check to see if it's open to determine if a blocker is enabled and then close it right away.</p> <p>This is slightly annoying since users who do not have it enabled see a small flash on the screen as the window opens and closes right away.</p> <p>Are there any other non-obtrusive methods for accomplishing this?</p>
[ { "answer_id": 250267, "author": "Andre Bossard", "author_id": 21027, "author_profile": "https://Stackoverflow.com/users/21027", "pm_score": 4, "selected": true, "text": "var mine = window.open('','','width=1,height=1,left=0,top=0,scrollbars=no');\nif(mine)\n var popUpsBlocked = false\nelse\n var popUpsBlocked = true\nmine.close()\n" }, { "answer_id": 250715, "author": "Jonny Buchanan", "author_id": 6760, "author_profile": "https://Stackoverflow.com/users/6760", "pm_score": 2, "selected": false, "text": "Window" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/250216", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2849/" ]
250,228
<p>I have a page with many forms on it. could be 1..200. None of these forms have buttons and they are built programatically. I am using jquery to submit all the forms that are checked.</p> <pre><code> function FakeName() { $("input:checked").parent("form").submit(); } </code></pre> <p>My forms look like:</p> <pre><code> &lt;form name="FakeForm&lt;%=i%&gt;" action="javascript:void%200" onSubmit="processRow(&lt;%=i%&gt;)" method="post" style="margin:0px;"&gt; &lt;input type="checkbox" name="FakeNameCheck" value="FakeNameCheck"/&gt; &lt;input type="hidden" name="FakeNum" value="&lt;%= FakeNum%&gt;"/&gt; &lt;input type="hidden" name="FakeId" value="&lt;%=FakeIdr%&gt;"/&gt; &lt;input type="hidden" name="FakeAmt" value="&lt;%=FakeAmount%&gt;"/&gt; &lt;input type="hidden" name="FakeTrans" value="FakeTrans"/&gt; &lt;/form&gt; </code></pre> <p>Note: action is set to "javascript:void%200" so that it posts to a fake page. I want to handle my own posting in processRow.</p> <p>OnSubmit never gets called and therefore ProcessRow never gets called. </p> <p>Obviously all the names of the functions and variables have been changed to protect their identity :D</p> <p>How can I get a function in each form to fire when I call submit programmatically.</p>
[ { "answer_id": 250259, "author": "Gareth", "author_id": 31582, "author_profile": "https://Stackoverflow.com/users/31582", "pm_score": 3, "selected": true, "text": "onsubmit" }, { "answer_id": 250315, "author": "Brian G", "author_id": 3208, "author_profile": "https://Stackoverflow.com/users/3208", "pm_score": 0, "selected": false, "text": "<form name=\"FakeForm<%=i%>\" action=\"javascript:processRow(<%=i%>)\" method=\"post\" style=\"margin:0px;\">\n <input type=\"checkbox\" name=\"FakeNameCheck\" value=\"FakeNameCheck\"/>\n <input type=\"hidden\" name=\"FakeNum\" value=\"<%= FakeNum%>\"/>\n <input type=\"hidden\" name=\"FakeId\" value=\"<%=FakeIdr%>\"/>\n <input type=\"hidden\" name=\"FakeAmt\" value=\"<%=FakeAmount%>\"/>\n <input type=\"hidden\" name=\"FakeTrans\" value=\"FakeTrans\"/>\n </form>\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/250228", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3208/" ]
250,238
<p>We have a git project which has quite a big history.</p> <p>Specifically, early in the project there were quite a lot of binary resource files in the project, these have now been removed as they're effectively external resources.</p> <p>However, the size of our repository is >200MB (the total checkout is currently ~20MB) due to having these files previously committed.</p> <p>What we'd like to do is "collapse" the history so that the repository appears to have been created from a later revision than it was. For example</p> <pre><code>1-----2-----3-----4-----+---+---+ \ / +-----+---+---+ </code></pre> <ol> <li>Repository created</li> <li>Large set of binary files added</li> <li>Large set of binary files removed</li> <li>New intended 'start' of repository</li> </ol> <p>So effectively we want to lose the project history before a certain point. At this point there is only one branch, so there's no complication with trying to deal with multiple start points etc. However we don't want to lose all of the history and start a new repository with the current version.</p> <p>Is this possible, or are we doomed to have a bloated repository forever?</p>
[ { "answer_id": 250365, "author": "JesperE", "author_id": 13051, "author_profile": "https://Stackoverflow.com/users/13051", "pm_score": 3, "selected": false, "text": "git-fast-export" }, { "answer_id": 251252, "author": "Pat Notz", "author_id": 825, "author_profile": "https://Stackoverflow.com/users/825", "pm_score": 4, "selected": false, "text": "git-filter-branch" }, { "answer_id": 251927, "author": "Paul", "author_id": 23356, "author_profile": "https://Stackoverflow.com/users/23356", "pm_score": 8, "selected": true, "text": "$ git log --stat # list all commits and commit messages \n" }, { "answer_id": 475931, "author": "davitenio", "author_id": 50765, "author_profile": "https://Stackoverflow.com/users/50765", "pm_score": 5, "selected": false, "text": "git filter-branch" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/250238", "https://Stackoverflow.com", "https://Stackoverflow.com/users/31582/" ]
250,244
<p>I have a simple application with the following code:</p> <pre><code> FileInfo[] files = (new DirectoryInfo(initialDirectory)).GetFiles(); List&lt;Thread&gt; threads = new List&lt;Thread&gt;(files.Length); foreach (FileInfo f in files) { Thread t = new Thread(delegate() { Console.WriteLine(f.FullName); }); threads.Add(t); } foreach (Thread t in threads) t.Start(); </code></pre> <p>Lets say in 'I=initialDirectory' directory I have 3 files. This application should then create 3 threads, with each thread printing off one of the file names; however, instead each thread will print off the name of the last file in the 'files' array.</p> <p>Why is this? Why is the current file 'f' variable not getting setup in the anonymous method correctly?</p>
[ { "answer_id": 250249, "author": "Stewart Johnson", "author_id": 6408, "author_profile": "https://Stackoverflow.com/users/6408", "pm_score": 5, "selected": true, "text": "f" }, { "answer_id": 250260, "author": "Joel Coehoorn", "author_id": 3043, "author_profile": "https://Stackoverflow.com/users/3043", "pm_score": 1, "selected": false, "text": "f.FullName" }, { "answer_id": 251043, "author": "Charles Bretana", "author_id": 32632, "author_profile": "https://Stackoverflow.com/users/32632", "pm_score": 0, "selected": false, "text": "foreach (FileInfo f in files)\n { \n string filName = f.FullName;\n Thread t = new Thread(delegate() \n { Console.WriteLine(filName); }); \n t.Start();\n }\n" }, { "answer_id": 251723, "author": "user22367", "author_id": 22367, "author_profile": "https://Stackoverflow.com/users/22367", "pm_score": 0, "selected": false, "text": " Thread t = new Thread(delegate()\n {\n string name = f.Name;\n Console.WriteLine(name);\n });\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/250244", "https://Stackoverflow.com", "https://Stackoverflow.com/users/30006/" ]
250,256
<p>I have problem in some JavaScript that I am writing where the Switch statement does not seem to be working as expected.</p> <pre><code>switch (msg.ResultType) { case 0: $('#txtConsole').val("Some Val 0"); break; case 1: $('#txtConsole').val("Some Val 1"); break; case 2: $('#txtConsole').text("Some Val 2"); break; } </code></pre> <p>The ResultType is an integer value 0-2 and I can see that in FireBug. In all cases, the switch transfers control to the final break statement which means all the logic is completely skipped. What am I missing?</p>
[ { "answer_id": 250279, "author": "Joel Coehoorn", "author_id": 3043, "author_profile": "https://Stackoverflow.com/users/3043", "pm_score": 2, "selected": false, "text": "switch (msg.ResultType-0) {\n case 0:\n $('#txtConsole').val(\"Some Val 0\");\n break;\n case 1:\n $('#txtConsole').val(\"Some Val 1\");\n break;\n case 2:\n $('#txtConsole').text(\"Some Val 2\");\n break;\n}\n" }, { "answer_id": 18312257, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": " msg.ResultType | 0 \n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/250256", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4820/" ]
250,271
<p>How can I get the start and end positions of all matches using the <code>re</code> module? For example given the pattern <code>r'[a-z]'</code> and the string <code>'a1b2c3d4'</code> I'd want to get the positions where it finds each letter. Ideally, I'd like to get the text of the match back too.</p>
[ { "answer_id": 250303, "author": "Peter Hoffmann", "author_id": 720, "author_profile": "https://Stackoverflow.com/users/720", "pm_score": 9, "selected": true, "text": "import re\np = re.compile(\"[a-z]\")\nfor m in p.finditer('a1b2c3d4'):\n print(m.start(), m.group())\n" }, { "answer_id": 250306, "author": "gone", "author_id": 26880, "author_profile": "https://Stackoverflow.com/users/26880", "pm_score": 6, "selected": false, "text": ">>> p = re.compile('[a-z]+')\n>>> print p.match('::: message')\nNone\n>>> m = p.search('::: message') ; print m\n<re.MatchObject instance at 80c9650>\n>>> m.group()\n'message'\n>>> m.span()\n(4, 11)\n" }, { "answer_id": 44927208, "author": "Rams Here", "author_id": 8259376, "author_profile": "https://Stackoverflow.com/users/8259376", "pm_score": 5, "selected": false, "text": "from re import finditer\nfor match in finditer(\"pattern\", \"string\"):\n print(match.span(), match.group())\n" }, { "answer_id": 57167463, "author": "StevenWernerCS", "author_id": 3390659, "author_profile": "https://Stackoverflow.com/users/3390659", "pm_score": 4, "selected": false, "text": "regex_with_3_groups=r\"([a-z])([0-9]+)([A-Z])\"\nfor match in re.finditer(regex_with_3_groups, string):\n for idx in range(0, 4):\n print(match.span(idx), match.group(idx))\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/250271", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13009/" ]
250,283
<p>What's the most pythonic way to scp a file in Python? The only route I'm aware of is </p> <pre><code>os.system('scp "%s" "%s:%s"' % (localfile, remotehost, remotefile) ) </code></pre> <p>which is a hack, and which doesn't work outside Linux-like systems, and which needs help from the Pexpect module to avoid password prompts unless you already have passwordless SSH set up to the remote host.</p> <p>I'm aware of Twisted's <code>conch</code>, but I'd prefer to avoid implementing scp myself via low-level ssh modules.</p> <p>I'm aware of <code>paramiko</code>, a Python module that supports SSH and SFTP; but it doesn't support SCP.</p> <p>Background: I'm connecting to a router which doesn't support SFTP but does support SSH/SCP, so SFTP isn't an option.</p> <p><strong>EDIT</strong>: This is a duplicate of <a href="https://stackoverflow.com/questions/68335/how-do-i-copy-a-file-to-a-remote-server-in-python-using-scp-or-ssh">How to copy a file to a remote server in Python using SCP or SSH?</a>. <strong>However</strong>, that question doesn't give an scp-specific answer that deals with keys from within Python. I'm hoping for a way to run code kind of like</p> <pre><code>import scp client = scp.Client(host=host, user=user, keyfile=keyfile) # or client = scp.Client(host=host, user=user) client.use_system_keys() # or client = scp.Client(host=host, user=user, password=password) # and then client.transfer('/etc/local/filename', '/etc/remote/filename') </code></pre>
[ { "answer_id": 250786, "author": "Pat Notz", "author_id": 825, "author_profile": "https://Stackoverflow.com/users/825", "pm_score": 4, "selected": false, "text": "# This connects to the openbsd ftp site and\n# downloads the recursive directory listing.\nimport pexpect\nchild = pexpect.spawn ('ftp ftp.openbsd.org')\nchild.expect ('Name .*: ')\nchild.sendline ('anonymous')\nchild.expect ('Password:')\nchild.sendline ('noah@example.com')\nchild.expect ('ftp> ')\nchild.sendline ('cd pub')\nchild.expect('ftp> ')\nchild.sendline ('get ls-lR.gz')\nchild.expect('ftp> ')\nchild.sendline ('bye')\n" }, { "answer_id": 4282261, "author": "Tom Shen", "author_id": 259855, "author_profile": "https://Stackoverflow.com/users/259855", "pm_score": 7, "selected": false, "text": "import paramiko\nfrom scp import SCPClient\n\ndef createSSHClient(server, port, user, password):\n client = paramiko.SSHClient()\n client.load_system_host_keys()\n client.set_missing_host_key_policy(paramiko.AutoAddPolicy())\n client.connect(server, port, user, password)\n return client\n\nssh = createSSHClient(server, port, user, password)\nscp = SCPClient(ssh.get_transport())\n" }, { "answer_id": 8247987, "author": "user443854", "author_id": 443854, "author_profile": "https://Stackoverflow.com/users/443854", "pm_score": 3, "selected": false, "text": "from fabric import Connection\n\nwith Connection(host=\"hostname\", \n user=\"admin\", \n connect_kwargs={\"key_filename\": \"/home/myuser/.ssh/private.key\"}\n ) as c:\n c.get('/foo/bar/file.txt', '/tmp/')\n" }, { "answer_id": 24049247, "author": "user178047", "author_id": 2345251, "author_profile": "https://Stackoverflow.com/users/2345251", "pm_score": 2, "selected": false, "text": "sshpass -p password scp -o User=username -o StrictHostKeyChecking=no src dst:/path\n" }, { "answer_id": 24587238, "author": "smheidrich", "author_id": 2748899, "author_profile": "https://Stackoverflow.com/users/2748899", "pm_score": 2, "selected": false, "text": "import plumbum\nr = plumbum.machines.SshMachine(\"example.net\")\n # this will use your ssh config as `ssh` from shell\n # depending on your config, you might also need additional\n # params, eg: `user=\"username\", keyfile=\".ssh/some_key\"`\nfro = plumbum.local.path(\"some_file\")\nto = r.path(\"/path/to/destination/\")\nplumbum.path.utils.copy(fro, to)\n" }, { "answer_id": 38556344, "author": "Maviles", "author_id": 2653486, "author_profile": "https://Stackoverflow.com/users/2653486", "pm_score": 4, "selected": false, "text": "from paramiko import SSHClient\nfrom scp import SCPClient\n\nssh = SSHClient()\nssh.load_system_host_keys()\nssh.connect('example.com')\n\nwith SCPClient(ssh.get_transport()) as scp:\n scp.put('test.txt', 'test2.txt')\n scp.get('test2.txt')\n" }, { "answer_id": 42094822, "author": "user7529863", "author_id": 7529863, "author_profile": "https://Stackoverflow.com/users/7529863", "pm_score": 3, "selected": false, "text": "from subprocess import call\n\ncmd = \"scp user1@host1:files user2@host2:files\"\ncall(cmd.split(\" \"))\n" }, { "answer_id": 50423406, "author": "Loïc", "author_id": 3322400, "author_profile": "https://Stackoverflow.com/users/3322400", "pm_score": 3, "selected": false, "text": "AsyncSSH" }, { "answer_id": 59855568, "author": "shrikkanth roxor", "author_id": 10835077, "author_profile": "https://Stackoverflow.com/users/10835077", "pm_score": 3, "selected": false, "text": "import paramiko\n\nclient = paramiko.SSHClient()\nclient.set_missing_host_key_policy(paramiko.AutoAddPolicy())\n\nclient.connect('<IP Address>', username='<User Name>',password='' ,key_filename='<.PEM File path')\n\n#Setup sftp connection and transmit this script \nprint (\"copying\")\n\nsftp = client.open_sftp() \nsftp.put(<Source>, <Destination>)\n\n\nsftp.close()\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/250283", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4105/" ]