qid int64 4 19.1M | question stringlengths 18 48.3k | answers list | date stringlengths 10 10 | metadata list |
|---|---|---|---|---|
320,142 | <p>Can someone illustrate what really is the difference between the two?</p>
| [
{
"answer_id": 320171,
"author": "Vinko Vrsalovic",
"author_id": 5190,
"author_profile": "https://Stackoverflow.com/users/5190",
"pm_score": 4,
"selected": false,
"text": "|------------------------|\n| (------) |\n| (ClassA) |\n| (------) |\n| (-----------) |\n| ((Singleton)) |\n| (-----------) |\n| (---------) | \n| ((Factory)) |\n| (---------) |\n| |\n| |\n|------------------------|\n\nLegend:\n |---| Framework\n (---) Class\n () Design Pattern\n"
}
] | 2008/11/26 | [
"https://Stackoverflow.com/questions/320142",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16488/"
] |
320,148 | <p>I have a xml file like this:</p>
<pre><code><customer>
<field1 />
<field2 />
<field3>
<item1 />
</field3>
<field3>
<item1 />
</field3>
</customer>
</code></pre>
<p>field* can appear in any order and only field3 can appear more than once.</p>
<p>How can I create a XSD file to validate this?</p>
<p>Thank you!</p>
| [
{
"answer_id": 320363,
"author": "AJ.",
"author_id": 7211,
"author_profile": "https://Stackoverflow.com/users/7211",
"pm_score": 2,
"selected": false,
"text": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<xs:schema xmlns:xs=\"http://www.w3.org/2001/XMLSchema\">\n <xs:element name=\"customer\" type=\"customerType\"/>\n <xs:complexType name=\"customerType\">\n <xs:sequence>\n <xs:element name=\"field1\" minOccurs=\"1\" maxOccurs=\"1\">\n </xs:element>\n <xs:element name=\"field2\" minOccurs=\"1\" maxOccurs=\"1\">\n </xs:element>\n <xs:element name=\"field3\" type=\"field3Type\"\n minOccurs=\"1\" maxOccurs=\"unbounded\"/>\n </xs:sequence>\n </xs:complexType>\n <xs:complexType name=\"field3Type\">\n <xs:sequence>\n <xs:element name=\"item1\">\n </xs:element>\n </xs:sequence>\n </xs:complexType>\n</xs:schema>\n"
},
{
"answer_id": 323917,
"author": "gizmo",
"author_id": 9396,
"author_profile": "https://Stackoverflow.com/users/9396",
"pm_score": 0,
"selected": false,
"text": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<schema xmlns=\"http://www.w3.org/2001/XMLSchema\" targetNamespace=\"http://www.example.org/NewXMLSchema\"\nxmlns:tns=\"http://www.example.org/NewXMLSchema\" elementFormDefault=\"qualified\">\n\n <element name=\"customer\" type=\"tns:customerType\"/>\n <complexType name=\"customerType\">\n <sequence>\n <element>\n <complexType>\n <all>\n <element>\n <complexType>\n <sequence>\n <element ref=\"tns:field3\" maxOccurs=\"unbounded\"/>\n <element ref=\"tns:field1\" maxOccurs=\"1\"/>\n </sequence>\n </complexType>\n </element>\n <element>\n <complexType>\n <sequence>\n <element ref=\"tns:field3\" maxOccurs=\"unbounded\"/>\n <element ref=\"tns:field2\" maxOccurs=\"1\"/>\n </sequence>\n </complexType>\n </element>\n <element>\n <complexType>\n <sequence>\n <element ref=\"tns:field3\" maxOccurs=\"unbounded\"/>\n <element ref=\"tns:field4\" maxOccurs=\"1\"/>\n </sequence>\n </complexType>\n </element>\n </all>\n </complexType>\n </element>\n <element ref=\"tns:field3\" maxOccurs=\"unbounded\" />\n </sequence>\n </complexType>\n <complexType name=\"field1Container\"/>\n <complexType name=\"field2Container\"/>\n <complexType name=\"field3Type\">\n <sequence>\n <element name=\"item1\"/>\n </sequence>\n </complexType>\n <complexType name=\"field4Container\"/>\n <element name=\"field3\" type=\"tns:field3Type\"/>\n <element name=\"field1\"/>\n <element name=\"field2\"/>\n <element name=\"field4\"/>\n</schema>\n"
}
] | 2008/11/26 | [
"https://Stackoverflow.com/questions/320148",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/26079/"
] |
320,158 | <p>I've created a workflow/flowchart style designer for something. At the moment it is using relatively simple Bezier curve lines to connect up the various end points of the "blocks" on the workflow.</p>
<p>However I would like something a bit more intuitive for the user. I want the lines to avoid obstacles like other blocks (rectangles) and possibly other lines too.</p>
<p>I prefer the bezier splines rather than polylines because they are prettier and seem to fit in better with the designer in general. But am willing to compromise if they are much harder to accomplish.</p>
<p>I know there is a whole load of science behind this. I've looked into things like Graphviz, Microsoft's GLEE and their commericial AGL (automatic graph layout) library.</p>
<p>GLEE seems to barely be production worthy. And their commercial alternative is, well, a commercial alternative... it's quite expensive.</p>
<p>Graphviz doesn't seem to have been ported to .NET in any way.</p>
<p>I have seen a polyline implementation used by Windows Workflow Foundation for its "freeform designer". And this works, just, but it is not really of production grade appearance.</p>
<p>I'm surprised there isn't some plug'n'play .NET library for this type of thing? Something like:</p>
<p>Point[] RoutePolyline(Point begin, Point end, Rectangle[] rectObstacles, Point[] lineObstacles);</p>
| [
{
"answer_id": 320363,
"author": "AJ.",
"author_id": 7211,
"author_profile": "https://Stackoverflow.com/users/7211",
"pm_score": 2,
"selected": false,
"text": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<xs:schema xmlns:xs=\"http://www.w3.org/2001/XMLSchema\">\n <xs:element name=\"customer\" type=\"customerType\"/>\n <xs:complexType name=\"customerType\">\n <xs:sequence>\n <xs:element name=\"field1\" minOccurs=\"1\" maxOccurs=\"1\">\n </xs:element>\n <xs:element name=\"field2\" minOccurs=\"1\" maxOccurs=\"1\">\n </xs:element>\n <xs:element name=\"field3\" type=\"field3Type\"\n minOccurs=\"1\" maxOccurs=\"unbounded\"/>\n </xs:sequence>\n </xs:complexType>\n <xs:complexType name=\"field3Type\">\n <xs:sequence>\n <xs:element name=\"item1\">\n </xs:element>\n </xs:sequence>\n </xs:complexType>\n</xs:schema>\n"
},
{
"answer_id": 323917,
"author": "gizmo",
"author_id": 9396,
"author_profile": "https://Stackoverflow.com/users/9396",
"pm_score": 0,
"selected": false,
"text": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<schema xmlns=\"http://www.w3.org/2001/XMLSchema\" targetNamespace=\"http://www.example.org/NewXMLSchema\"\nxmlns:tns=\"http://www.example.org/NewXMLSchema\" elementFormDefault=\"qualified\">\n\n <element name=\"customer\" type=\"tns:customerType\"/>\n <complexType name=\"customerType\">\n <sequence>\n <element>\n <complexType>\n <all>\n <element>\n <complexType>\n <sequence>\n <element ref=\"tns:field3\" maxOccurs=\"unbounded\"/>\n <element ref=\"tns:field1\" maxOccurs=\"1\"/>\n </sequence>\n </complexType>\n </element>\n <element>\n <complexType>\n <sequence>\n <element ref=\"tns:field3\" maxOccurs=\"unbounded\"/>\n <element ref=\"tns:field2\" maxOccurs=\"1\"/>\n </sequence>\n </complexType>\n </element>\n <element>\n <complexType>\n <sequence>\n <element ref=\"tns:field3\" maxOccurs=\"unbounded\"/>\n <element ref=\"tns:field4\" maxOccurs=\"1\"/>\n </sequence>\n </complexType>\n </element>\n </all>\n </complexType>\n </element>\n <element ref=\"tns:field3\" maxOccurs=\"unbounded\" />\n </sequence>\n </complexType>\n <complexType name=\"field1Container\"/>\n <complexType name=\"field2Container\"/>\n <complexType name=\"field3Type\">\n <sequence>\n <element name=\"item1\"/>\n </sequence>\n </complexType>\n <complexType name=\"field4Container\"/>\n <element name=\"field3\" type=\"tns:field3Type\"/>\n <element name=\"field1\"/>\n <element name=\"field2\"/>\n <element name=\"field4\"/>\n</schema>\n"
}
] | 2008/11/26 | [
"https://Stackoverflow.com/questions/320158",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/40963/"
] |
320,170 | <p>Does anyone have a good algorithm for taking an ordered list of integers, i.e.:<br>
[1, 3, 6, 7, 8, 10, 11, 13, 14, 17, 19, 23, 25, 27, 28]</p>
<p>into a given number of evenly sized ordered sublists, i.e. for 4 it will be:<br>
[1, 3, 6] [7, 8, 10, 11] [13, 14, 17, 19] [23, 25, 27, 28]</p>
<p>The requirement being that each of the sublists are ordered and as similar in size as possible. </p>
| [
{
"answer_id": 320180,
"author": "Nicolai",
"author_id": 20962,
"author_profile": "https://Stackoverflow.com/users/20962",
"pm_score": 1,
"selected": false,
"text": "private static void splitOrderedDurationsIntoIntervals(Integer[] durations, List<Integer[]> intervals, int numberOfInterals) {\n int middle = durations.length / 2;\n Integer[] lowerHalf = Arrays.copyOfRange(durations, 0, middle);\n Integer[] upperHalf = Arrays.copyOfRange(durations, middle, durations.length);\n if (lowerHalf.length > upperHalf.length) {\n intervals.add(lowerHalf);\n intervals.add(upperHalf);\n } else {\n intervals.add(upperHalf);\n intervals.add(lowerHalf);\n }\n if (intervals.size() < numberOfIntervals) {\n int largestElementLength = intervals.get(0).length;\n if (largestElementLength > 1) {\n Integer[] duration = intervals.remove(0);\n splitOrderedDurationsIntoIntervals(duration, intervals);\n }\n }\n}\n"
},
{
"answer_id": 320188,
"author": "Magnar",
"author_id": 1123,
"author_profile": "https://Stackoverflow.com/users/1123",
"pm_score": 4,
"selected": true,
"text": " private static List<Integer[]> splitOrderedDurationsIntoIntervals(Integer[] durations, int numberOfIntervals) {\n\n int sizeOfSmallSublists = durations.length / numberOfIntervals;\n int sizeOfLargeSublists = sizeOfSmallSublists + 1;\n int numberOfLargeSublists = durations.length % numberOfIntervals;\n int numberOfSmallSublists = numberOfIntervals - numberOfLargeSublists;\n\n List<Integer[]> sublists = new ArrayList(numberOfIntervals);\n int numberOfElementsHandled = 0;\n for (int i = 0; i < numberOfIntervals; i++) {\n int size = i < numberOfSmallSublists ? sizeOfSmallSublists : sizeOfLargeSublists;\n Integer[] sublist = new Integer[size];\n System.arraycopy(durations, numberOfElementsHandled, sublist, 0, size);\n sublists.add(sublist);\n numberOfElementsHandled += size;\n }\n return sublists;\n}\n"
},
{
"answer_id": 320214,
"author": "Simon",
"author_id": 24039,
"author_profile": "https://Stackoverflow.com/users/24039",
"pm_score": 0,
"selected": false,
"text": "private static void splitOrderedDurationsIntoIntervals(Integer[] durations, List<Integer[]> intervals, int numberOfInterals) {\n\n int num_per_interval = Math.floor(durations.length / numberOfInterals);\n int i;\n int idx;\n\n // make sure you have somewhere to put the results\n for (i = 0; i < numberOfInterals; i++) intervals[i] = new Integer[];\n\n // run once through the list and put them in the right sub-list\n for (i = 0; i < durations.length; i++)\n {\n idx = Math.floor(i / num_per_interval);\n intervals[idx].add(durations[i]);\n }\n}\n"
},
{
"answer_id": 320218,
"author": "boutta",
"author_id": 15108,
"author_profile": "https://Stackoverflow.com/users/15108",
"pm_score": 0,
"selected": false,
"text": "public static void splitList(List<Integer> startList, List<List<Integer>> resultList, \n int subListNumber) {\n final int subListSize = startList.size() / subListNumber;\n int index = 0;\n int stopIndex = subListSize;\n for (int i = subListNumber; i > 0; i--) {\n resultList.add(new ArrayList<Integer>(startList.subList(index, stopIndex)));\n index = stopIndex;\n stopIndex =\n (index + subListSize > startList.size()) ? startList.size() : index + subListSize;\n }\n}\n"
},
{
"answer_id": 320240,
"author": "Rob",
"author_id": 34224,
"author_profile": "https://Stackoverflow.com/users/34224",
"pm_score": 0,
"selected": false,
"text": "\npublic static int[][] divide(int[] initialList, int sublistCount)\n {\n if (initialList == null)\n throw new NullPointerException(\"initialList\");\n if (sublistCount < 1)\n throw new IllegalArgumentException(\"sublistCount must be greater than 0.\");\n\n // without remainder, length / # lists will always be the minimum \n // number of items in a given subset\n int min = initialList.length / sublistCount;\n // without remainer, this algorithm determines the maximum number \n // of items in a given subset. example: in a 15-item sample, \n // with 4 subsets, we get a min of 3 (15 / 4 = 3r3), and \n // 15 + 3 - 1 = 17. 17 / 4 = 4r1.\n // in a 16-item sample, min = 4, and 16 + 4 - 1 = 19. 19 / 4 = 4r3.\n // The -1 is required in samples in which the max and min are the same.\n int max = (initialList.length + min - 1) / sublistCount;\n // this is the meat and potatoes of the algorithm. here we determine\n // how many lists have the min count and the max count. we start out \n // with all at max and work our way down.\n int sublistsHandledByMax = sublistCount;\n int sublistsHandledByMin = 0;\n while ((sublistsHandledByMax * max) + (sublistsHandledByMin * min)\n != initialList.length)\n {\n sublistsHandledByMax--;\n sublistsHandledByMin++;\n }\n\n // now we copy the items into their new sublists.\n int[][] items = new int[sublistCount][];\n int currentInputIndex = 0;\n for (int listIndex = 0; listIndex < sublistCount; listIndex++)\n {\n if (listIndex < sublistsHandledByMin)\n items[listIndex] = new int[min];\n else\n items[listIndex] = new int[max];\n\n // there's probably a better way to do array copies now.\n // it's been a while since I did Java :)\n System.arraycopy(initialList, currentInputIndex, items[listIndex], 0, items[listIndex].length);\n currentInputIndex += items[listIndex].length;\n }\n\n return items;\n }\n"
}
] | 2008/11/26 | [
"https://Stackoverflow.com/questions/320170",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20962/"
] |
320,178 | <p>I want to build an Axis2 client (I'm only accessing a remote web service, I'm <em>not</em> implementing one!) with Maven2 and I don't want to add 21MB of JARs to my project. What do I have to put in my pom.xml to compile the code when I've converted the WSDL with ADB?</p>
| [
{
"answer_id": 321599,
"author": "Alex",
"author_id": 30859,
"author_profile": "https://Stackoverflow.com/users/30859",
"pm_score": 5,
"selected": true,
"text": " <dependency>\n <groupId>org.apache.axis2</groupId>\n <artifactId>axis2-kernel</artifactId>\n <version>1.4.1</version>\n </dependency>\n <dependency>\n <groupId>org.apache.axis2</groupId>\n <artifactId>axis2-adb</artifactId>\n <version>1.4.1</version>\n </dependency>\n"
},
{
"answer_id": 1981676,
"author": "Luís Duarte",
"author_id": 210490,
"author_profile": "https://Stackoverflow.com/users/210490",
"pm_score": 1,
"selected": false,
"text": "<dependency>\n <groupId>org.apache.axis2</groupId>\n <artifactId>axis2-adb</artifactId>\n <version>1.5.1</version>\n</dependency>\n"
},
{
"answer_id": 2564423,
"author": "Mark O'Connor",
"author_id": 256618,
"author_profile": "https://Stackoverflow.com/users/256618",
"pm_score": 1,
"selected": false,
"text": "@Grapes([\n @Grab(group='org.apache.axis2', module='axis2-kernel', version='1.5.1'),\n @Grab(group='org.apache.axis2', module='axis2-adb', version='1.5.1'),\n @Grab(group='org.apache.axis2', module='axis2-transport-local', version='1.5.1'),\n @Grab(group='org.apache.axis2', module='axis2-transport-http', version='1.5.1'),\n])\n"
},
{
"answer_id": 5709307,
"author": "Renaud",
"author_id": 125617,
"author_profile": "https://Stackoverflow.com/users/125617",
"pm_score": 4,
"selected": false,
"text": "<dependency>\n <groupId>org.apache.axis2</groupId>\n <artifactId>axis2-adb</artifactId>\n <version>1.5.4</version>\n</dependency>\n<dependency>\n <groupId>org.apache.axis2</groupId>\n <artifactId>axis2-transport-local</artifactId>\n <version>1.5.4</version>\n</dependency>\n<dependency>\n <groupId>org.apache.axis2</groupId>\n <artifactId>axis2-transport-http</artifactId>\n <version>1.5.4</version>\n</dependency>\n"
},
{
"answer_id": 13748844,
"author": "chrisjleu",
"author_id": 196533,
"author_profile": "https://Stackoverflow.com/users/196533",
"pm_score": 3,
"selected": false,
"text": " <dependency>\n <groupId>org.apache.axis2</groupId>\n <artifactId>axis2-kernel</artifactId>\n <version>1.6.2</version>\n </dependency>\n <dependency>\n <groupId>org.apache.axis2</groupId>\n <artifactId>axis2-adb</artifactId>\n <version>1.6.2</version>\n </dependency>\n <dependency>\n <groupId>org.apache.axis2</groupId>\n <artifactId>axis2-transport-http</artifactId>\n <version>1.6.2</version>\n </dependency>\n <dependency>\n <groupId>org.apache.axis2</groupId>\n <artifactId>axis2-transport-local</artifactId>\n <version>1.6.2</version>\n </dependency>\n <dependency>\n <groupId>org.apache.axis2</groupId>\n <artifactId>axis2-xmlbeans</artifactId>\n <version>1.6.2</version>\n </dependency>\n"
},
{
"answer_id": 32620423,
"author": "IvanRF",
"author_id": 1718678,
"author_profile": "https://Stackoverflow.com/users/1718678",
"pm_score": 0,
"selected": false,
"text": "dependencies {\n\n ext.compileEx = { lib, exModules, exGroups ->\n compile (lib) {\n exModules.each { exclude module : \"$it\" }\n exGroups.each { exclude group: \"$it\" }\n }\n }\n\n List axisExModules = [ 'axiom-compat', 'jaxen', 'apache-mime4j-core' ]\n List axisExGroups = [ 'javax.servlet', 'commons-fileupload', 'org.apache.woden',\n 'javax.ws.rs', 'org.apache.geronimo.specs', 'org.codehaus.woodstox' ]\n compileEx ('org.apache.axis2:axis2-adb:1.6.3', axisExModules, axisExGroups)\n compileEx ('org.apache.axis2:axis2-transport-local:1.6.3', axisExModules, axisExGroups)\n compileEx ('org.apache.axis2:axis2-transport-http:1.6.3', axisExModules, axisExGroups)\n\n}\n"
}
] | 2008/11/26 | [
"https://Stackoverflow.com/questions/320178",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/34088/"
] |
320,184 | <p>Ever since switching from TABLE-layout to DIV-layout, one common problem remains:</p>
<p><strong>PROBLEM</strong>: you fill your DIV with dynamic text and inevitably there is a super-long word that extends over the edge of your div column and makes your site look unprofessional.</p>
<p><strong>RETRO-WHINING</strong>: This <em>never</em> happened with table layouts. A table cell will always nicely expand to the width of the longest word. </p>
<p><strong>SEVERITY</strong>: I see this problem on even the most major sites, especially on German sites where even common words such as "speed limit" are very long ("Geschwindigkeitsbegrenzung"). </p>
<p>Does anyone have a workable solution to this?</p>
| [
{
"answer_id": 320196,
"author": "Oli",
"author_id": 12870,
"author_profile": "https://Stackoverflow.com/users/12870",
"pm_score": 5,
"selected": false,
"text": "overflow:scroll overflow:hidden word-wrap: break-word overflow overflow:hidden div overflow:auto overflow:scroll overflow:hidden"
},
{
"answer_id": 320197,
"author": "VonC",
"author_id": 6309,
"author_profile": "https://Stackoverflow.com/users/6309",
"pm_score": 4,
"selected": false,
"text": "word-wrap: break-word <wbr> <wbr>"
},
{
"answer_id": 320231,
"author": "Kornel",
"author_id": 27009,
"author_profile": "https://Stackoverflow.com/users/27009",
"pm_score": 8,
"selected": true,
"text": "­ averyvery­longword\n /([^\\s-]{5})([^\\s-]{5})/ → $1­$2\n <wbr> <wbr> averyvery<wbr>longword\n ​ ​ hyphens: auto div.breaking {\n hyphens: auto;\n}\n <table> display:table div.breaking {\n display: table-cell;\n}\n overflow white-space: pre-wrap"
},
{
"answer_id": 320365,
"author": "alexmeia",
"author_id": 36587,
"author_profile": "https://Stackoverflow.com/users/36587",
"pm_score": 2,
"selected": false,
"text": "word-wrap: break-word;\n overflow: hidden;\n <a>"
},
{
"answer_id": 320406,
"author": "Snaky Love",
"author_id": 40960,
"author_profile": "https://Stackoverflow.com/users/40960",
"pm_score": 2,
"selected": false,
"text": "p {\n -webkit-hyphens: auto;\n -moz-hyphens: auto;\n hyphens: auto;\n}\n"
},
{
"answer_id": 703024,
"author": "John Gietzen",
"author_id": 57986,
"author_profile": "https://Stackoverflow.com/users/57986",
"pm_score": 1,
"selected": false,
"text": "overflow : auto"
},
{
"answer_id": 703425,
"author": "Neil Monroe",
"author_id": 64240,
"author_profile": "https://Stackoverflow.com/users/64240",
"pm_score": 5,
"selected": false,
"text": ".word-break {\n /* The following styles prevent unbroken strings from breaking the layout */\n width: 300px; /* set to whatever width you need */\n overflow: auto;\n white-space: -moz-pre-wrap; /* Mozilla */\n white-space: -hp-pre-wrap; /* HP printers */\n white-space: -o-pre-wrap; /* Opera 7 */\n white-space: -pre-wrap; /* Opera 4-6 */\n white-space: pre-wrap; /* CSS 2.1 */\n white-space: pre-line; /* CSS 3 (and 2.1 as well, actually) */\n word-wrap: break-word; /* IE */\n -moz-binding: url('xbl.xml#wordwrap'); /* Firefox (using XBL) */\n}\n <?xml version=\"1.0\" encoding=\"utf-8\"?>\n<bindings xmlns=\"http://www.mozilla.org/xbl\" \n xmlns:html=\"http://www.w3.org/1999/xhtml\">\n <!--\n More information on XBL:\n http://developer.mozilla.org/en/docs/XBL:XBL_1.0_Reference\n\n Example of implementing the CSS 'word-wrap' feature:\n http://blog.stchur.com/2007/02/22/emulating-css-word-wrap-for-mozillafirefox/\n -->\n <binding id=\"wordwrap\" applyauthorstyles=\"false\">\n <implementation>\n <constructor>\n //<![CDATA[\n var elem = this;\n\n doWrap();\n elem.addEventListener('overflow', doWrap, false);\n\n function doWrap() {\n var walker = document.createTreeWalker(elem, NodeFilter.SHOW_TEXT, null, false);\n while (walker.nextNode()) {\n var node = walker.currentNode;\n node.nodeValue = node.nodeValue.split('').join(String.fromCharCode('8203'));\n }\n }\n //]]>\n </constructor>\n </implementation>\n </binding>\n</bindings>\n"
},
{
"answer_id": 890888,
"author": "Dan Brown",
"author_id": 119941,
"author_profile": "https://Stackoverflow.com/users/119941",
"pm_score": 1,
"selected": false,
"text": " <style type=\"text/css\">\n .cell {\n float: left;\n width: 100px;\n border: 1px solid;\n line-height: 1em;\n }\n </style>\n\n <div class=\"cell\">TopLeft</div>\n <div class=\"cell\">TopMiddlePlusSomeOtherTextWhichMakesItToLong</div>\n <div class=\"cell\">TopRight</div>\n <br/>\n <div class=\"cell\">BottomLeft</div>\n <div class=\"cell\">BottomMiddle</div>\n <div class=\"cell\">bottomRight</div>\n <style type=\"text/css\">\n .column {\n float: left;\n min-width: 100px;\n }\n .cell2 {\n border: 1px solid;\n line-height: 1em;\n }\n </style>\n\n <div class=\"column\">\n <div class=\"cell2\">TopLeft</div>\n <div class=\"cell2\">BottomLeft</div>\n </div>\n <div class=\"column\">\n <div class=\"cell2\">TopMiddlePlusSomeOtherTextWhichMakesItToLong</div>\n <div class=\"cell2\">BottomMiddle</div>\n </div>\n <div class=\"column\">\n <div class=\"cell2\">TopRight</div>\n <div class=\"cell2\">bottomRight</div>\n </div>\n <br/>\n"
},
{
"answer_id": 3442805,
"author": "sanimalp",
"author_id": 309592,
"author_profile": "https://Stackoverflow.com/users/309592",
"pm_score": 4,
"selected": false,
"text": "word-break:break-all;"
},
{
"answer_id": 3561148,
"author": "Zac Imboden",
"author_id": 398517,
"author_profile": "https://Stackoverflow.com/users/398517",
"pm_score": 3,
"selected": false,
"text": "word-wrap: break-word;\n #consumeralerts_leftcol{\n float:left;\n width: 250px;\n margin-bottom:10px;\n word-wrap: break-word;\n}\n"
},
{
"answer_id": 4668882,
"author": "Remo",
"author_id": 572699,
"author_profile": "https://Stackoverflow.com/users/572699",
"pm_score": 5,
"selected": false,
"text": ".word_wrap\n{\n white-space: pre-wrap; /* css-3 */\n white-space: -moz-pre-wrap; /* Mozilla, since 1999 */\n white-space: -pre-wrap; /* Opera 4-6 */\n white-space: -o-pre-wrap; /* Opera 7 */\n word-wrap: break-word; /* Internet Explorer 5.5+ */\n}\n"
},
{
"answer_id": 6298738,
"author": "enigment",
"author_id": 736006,
"author_profile": "https://Stackoverflow.com/users/736006",
"pm_score": 2,
"selected": false,
"text": "'abcde12345678901234'.replace(/([^\\s-]{5})([^\\s-]{5})/g, '$1­$2')\n abcde­12345678901234\n .replace(/([^\\s-]{5})(?=[^\\s-])/g, '$1­')\n abcde­12345­67890­1234\n"
},
{
"answer_id": 6508168,
"author": "enigment",
"author_id": 736006,
"author_profile": "https://Stackoverflow.com/users/736006",
"pm_score": 2,
"selected": false,
"text": "makeWrappable = function(str, position)\n{\n if (!str)\n return '';\n position = position || 15; // default to breaking after 15 chars\n // matches every requested number of chars that's not whitespace or one of the special chars defined below\n var longRunsRegex = cachedRegex('([^\\\\s\\\\.\\/\\\\,_@\\\\|-]{' + position + '})(?=[^\\\\s\\\\.\\/\\\\,_@\\\\|-])', 'g');\n return str\n .replace(longRunsRegex, '$1​') // put a zero-width space every requested number of chars that's not whitespace or a special char\n .replace(makeWrappable.SPECIAL_CHARS_REGEX, '$1​'); // and one after special chars we want to allow breaking after\n};\nmakeWrappable.SPECIAL_CHARS_REGEX = /([\\.\\/\\\\,_@\\|-])/g; // period, forward slash, backslash, comma, underscore, @, |, hyphen\n\n\ncachedRegex = function(reString, reFlags)\n{\n var key = reString + (reFlags ? ':::' + reFlags : '');\n if (!cachedRegex.cache[key])\n cachedRegex.cache[key] = new RegExp(reString, reFlags);\n return cachedRegex.cache[key];\n};\ncachedRegex.cache = {};\n makeWrappable('12345678901234567890 12345678901234567890 1234567890/1234567890')\n var longRunsRegex = cachedRegex('([^&\\\\s\\\\.\\/\\\\,_@\\\\|-]{' + position + '})(?=[^&\\\\s\\\\.\\/\\\\,_@\\\\|-])', 'g');\n"
},
{
"answer_id": 11510593,
"author": "mpen",
"author_id": 65387,
"author_profile": "https://Stackoverflow.com/users/65387",
"pm_score": 3,
"selected": false,
"text": ".pre {\n font-weight: 500;\n font-family: Courier New, monospace;\n white-space: pre-wrap;\n word-wrap: break-word;\n word-break: break-all;\n -webkit-hyphens: auto;\n -moz-hyphens: auto;\n hyphens: auto;\n}\n white-space pre"
},
{
"answer_id": 15242604,
"author": "Jacob",
"author_id": 1918669,
"author_profile": "https://Stackoverflow.com/users/1918669",
"pm_score": 3,
"selected": false,
"text": "display:table;\nword-break:break-all;\n"
},
{
"answer_id": 16883124,
"author": "Olofu Mark",
"author_id": 2055028,
"author_profile": "https://Stackoverflow.com/users/2055028",
"pm_score": 0,
"selected": false,
"text": "display: inline;"
},
{
"answer_id": 17625070,
"author": "DoctorFox",
"author_id": 1317550,
"author_profile": "https://Stackoverflow.com/users/1317550",
"pm_score": 2,
"selected": false,
"text": "-ms-word-break: break-all;\n word-break: break-all;\n\n /* Non standard for webkit */\n word-break: break-word;\n\n-webkit-hyphens: auto;\n -moz-hyphens: auto;\n hyphens: auto;\n"
},
{
"answer_id": 19084692,
"author": "hharnisc",
"author_id": 1031205,
"author_profile": "https://Stackoverflow.com/users/1031205",
"pm_score": -1,
"selected": false,
"text": " String.prototype.shyBreakString = function(maxLength) {\n var shystring = [];\n _.each(this.split(' '), function(word){\n shystring.push(_.chop(word, maxLength).join('­'));\n });\n return shystring.join(' ');\n };\n"
},
{
"answer_id": 23686809,
"author": "Kishan Subhash",
"author_id": 3109971,
"author_profile": "https://Stackoverflow.com/users/3109971",
"pm_score": 0,
"selected": false,
"text": "css word-wrap: break-word;"
},
{
"answer_id": 24158056,
"author": "jacobsvensson",
"author_id": 3419295,
"author_profile": "https://Stackoverflow.com/users/3419295",
"pm_score": 1,
"selected": false,
"text": " -moz-white-space: pre-wrap;\nwhite-space: pre-wrap; \n hyphens: auto;\n -ms-word-break: break-all;\n -ms-word-wrap: break-all;\n -webkit-word-break: break-word;\n -webkit-word-wrap: break-word;\nword-break: break-word;\nword-wrap: break-word;\n -webkit-hyphens: auto;\n -moz-hyphens: auto;\n -ms-hyphens: auto;\nhyphens: auto;\n"
},
{
"answer_id": 27044441,
"author": "microbians",
"author_id": 2075819,
"author_profile": "https://Stackoverflow.com/users/2075819",
"pm_score": 2,
"selected": false,
"text": "p {\n overflow-wrap: break-word;\n}\n\n\n@-moz-document url-prefix() { \n p {\n white-space: -moz-pre-wrap;\n word-wrap: break-word;\n }\n}\n"
},
{
"answer_id": 34651154,
"author": "Jay Patel",
"author_id": 1286507,
"author_profile": "https://Stackoverflow.com/users/1286507",
"pm_score": 2,
"selected": false,
"text": "word-wrap: break-word;\noverflow-wrap: break-word;\nword-break: break-all;\n"
},
{
"answer_id": 47313377,
"author": "Jack",
"author_id": 1255427,
"author_profile": "https://Stackoverflow.com/users/1255427",
"pm_score": -1,
"selected": false,
"text": "­ /**\n * Add line-break to text x characters in\n * @param string $text \n * @param integer $characters_in \n * @return string \n */\nfunction line_break_text($text, $characters_in = 10) {\n\n $split = explode(' ', $text);\n\n if ( ! empty($split)) {\n\n foreach ($split as $key => $var) {\n\n if ( strlen($var) > $characters_in ) {\n\n $split[$key] = substr_replace($var, '­', $characters_in, 0);\n\n }\n\n }\n\n }\n\n return implode(' ', $split);\n\n}\n"
}
] | 2008/11/26 | [
"https://Stackoverflow.com/questions/320184",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4639/"
] |
320,189 | <p>I would like to build a web application on Castle MonoRail, I was wondering how can we use an action with extension and another action without extension? How can HTML helper generator url for us?</p>
<p>Ex: </p>
<ul>
<li><a href="http://mysite.com/Products/list" rel="nofollow noreferrer">http://mysite.com/Products/list</a></li>
<li><a href="http://mysite.com/Products/abc.castle" rel="nofollow noreferrer">http://mysite.com/Products/abc.castle</a></li>
</ul>
| [
{
"answer_id": 390569,
"author": "c.sokun",
"author_id": 15396,
"author_profile": "https://Stackoverflow.com/users/15396",
"pm_score": 0,
"selected": false,
"text": "/<controller>/<action>.castle \n"
}
] | 2008/11/26 | [
"https://Stackoverflow.com/questions/320189",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/35700/"
] |
320,194 | <p>In Ruby on Rails, how to add foreign key constraint in migration?</p>
| [
{
"answer_id": 320457,
"author": "Jeroen Heijmans",
"author_id": 30748,
"author_profile": "https://Stackoverflow.com/users/30748",
"pm_score": 3,
"selected": true,
"text": " class MakeJoinUnique < ActiveRecord::Migration\n def self.up\n execute \"ALTER TABLE `pages_linked_pages` ADD UNIQUE `page_id_linked_page_id` (`page_id`,`linked_page_id`)\"\n end\n\n def self.down\n execute \"ALTER TABLE `pages_linked_pages` DROP INDEX `page_id_linked_page_id`\"\n end\n end\n"
},
{
"answer_id": 7075216,
"author": "noloman",
"author_id": 257948,
"author_profile": "https://Stackoverflow.com/users/257948",
"pm_score": 0,
"selected": false,
"text": "Products User add_index :products, :user_id"
}
] | 2008/11/26 | [
"https://Stackoverflow.com/questions/320194",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/40236/"
] |
320,204 | <p>I have a <code>JFrame</code> that contains a "display" <code>JPanel</code> with <code>JTextField</code> and a "control" <code>JPanel</code> with buttons that should access the contents of the display <code>JPanel</code>. I think my problem is related on how to use the observer pattern, which in principle I understand. You need to place listeners and update messages, but I don't have a clue where to put these, how to get access from one panel to the other and maybe if necessary to introduce a "datamodel" class. For example, I want to access the contents of the <code>JTextField</code> from the control panel and I use an anonymous action listener as follows:</p>
<pre><code>JButton openfile = new JButton("Convert file");
openfile.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
openButtonPressed();
}
});
</code></pre>
| [
{
"answer_id": 320384,
"author": "Tom Hawtin - tackline",
"author_id": 4725,
"author_profile": "https://Stackoverflow.com/users/4725",
"pm_score": 1,
"selected": false,
"text": "JFrame JPanel Document"
},
{
"answer_id": 325281,
"author": "OscarRyz",
"author_id": 20654,
"author_profile": "https://Stackoverflow.com/users/20654",
"pm_score": 2,
"selected": true,
"text": "class App { // this is the mediator\n\n // GUI components.\n private JFrame frame;\n private JTextField name;\n private JTextField count;\n private JTextField date;\n // Result is displayed here.\n private JTextArea textArea;\n\n // Fired by this button.\n private JButton go;\n\n private ActionListener actionListener;\n\n\n public App(){\n actionListener = new ActionListener(){\n public void actionPerformed( ActionEvent e ){\n okButtonPressed();\n }\n };\n }\n\n private void okButtonPressed(){\n // template is an object irrelevant to this code.\n template.setData( getData() );\n textArea.setText( template.getTransformedData() );\n }\n\n\n public void initialize(){\n\n frame = new JFrame(\"Code challenge v0.1\");\n frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );\n\n name = new JTextField();\n count = new JTextField();\n date = new JTextField();\n textArea = new JTextArea();\n go = new JButton(\"Go\");\n go.addActionListener( actionListener ); // prepare the button.\n\n layoutComponents(); // a lot of panels are created here. Irrelevant.\n }\n}\n"
}
] | 2008/11/26 | [
"https://Stackoverflow.com/questions/320204",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/39444/"
] |
320,222 | <p>as a follow up on my <a href="https://stackoverflow.com/questions/318208/cast-to-combined-generic">previous question</a>
Having a function with combined generic bounds such as:</p>
<pre><code><T extends Foo & Bar> void doStuff(T argument) {
//do stuff wich should only be done if arguments is both foo and bar
}
</code></pre>
<p>Because this is not castable from a unspecified object, you need to have knowledge of some object which actually implements these interfaces. it seems to me that needing to know the specific type of the object argument to pass to <code>doStuff(T a)</code> is a violation of Demeter's law.</p>
<p>The function doesn't specify the need to know the actual class (there could be many different ones), and i really don't want to know it as knowing this class increases the dependency in my code base.</p>
<p>is using these bounds an anti pattern? and if so how should one best avoid it?</p>
<p>the case scenario involved one interface specifying the object is persistent and the other specified object having a related entity. the <code>doStuff(T a)</code> function in this case persisted the related entity when it was persisted. however nonpersistent entities can also have a related entity, but should not be processed by the <code>doStuff(T a)</code> function</p>
| [
{
"answer_id": 320262,
"author": "Frank Grimm",
"author_id": 903,
"author_profile": "https://Stackoverflow.com/users/903",
"pm_score": 2,
"selected": false,
"text": "<T extends Number & Comparable<T>> T max(Collection<T> numbers)\n"
},
{
"answer_id": 320318,
"author": "Miserable Variable",
"author_id": 18573,
"author_profile": "https://Stackoverflow.com/users/18573",
"pm_score": 2,
"selected": false,
"text": "T<? extends Foo & Bar> void doStuff(T argument) \n T<? extends Foo> void doStuff(T argument) \n void doStuff(T argument) \n"
}
] | 2008/11/26 | [
"https://Stackoverflow.com/questions/320222",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15355/"
] |
320,232 | <p>Is there a way to ensure all created subprocess are dead at exit time of a Python program? By subprocess I mean those created with subprocess.Popen().</p>
<p>If not, should I iterate over all of the issuing kills and then kills -9? anything cleaner?</p>
| [
{
"answer_id": 320286,
"author": "ddaa",
"author_id": 11549,
"author_profile": "https://Stackoverflow.com/users/11549",
"pm_score": 2,
"selected": false,
"text": "subprocess._cleanup()\nprint subprocess._active == []\n"
},
{
"answer_id": 320290,
"author": "S.Lott",
"author_id": 10661,
"author_profile": "https://Stackoverflow.com/users/10661",
"pm_score": 4,
"selected": false,
"text": "subprocess.Popen.wait() os.kill( PID, 9 ) os.kill"
},
{
"answer_id": 320712,
"author": "monkut",
"author_id": 24718,
"author_profile": "https://Stackoverflow.com/users/24718",
"pm_score": 7,
"selected": true,
"text": ">>> import atexit\n>>> import sys\n>>> import time\n>>> \n>>> \n>>>\n>>> def cleanup():\n... timeout_sec = 5\n... for p in all_processes: # list of your processes\n... p_sec = 0\n... for second in range(timeout_sec):\n... if p.poll() == None:\n... time.sleep(1)\n... p_sec += 1\n... if p_sec >= timeout_sec:\n... p.kill() # supported from python 2.6\n... print 'cleaned up!'\n...\n>>>\n>>> atexit.register(cleanup)\n>>>\n>>> sys.exit()\ncleaned up!\n def win_kill(pid):\n '''kill a process by specified PID in windows'''\n import win32api\n import win32con\n\n hProc = None\n try:\n hProc = win32api.OpenProcess(win32con.PROCESS_TERMINATE, 0, pid)\n win32api.TerminateProcess(hProc, 0)\n except Exception:\n return False\n finally:\n if hProc != None:\n hProc.Close()\n\n return True\n"
},
{
"answer_id": 322317,
"author": "orip",
"author_id": 37020,
"author_profile": "https://Stackoverflow.com/users/37020",
"pm_score": 6,
"selected": false,
"text": "if __name__ == \"__main__\":\n os.setpgrp() # create new process group, become its leader\n try:\n # some code\n finally:\n os.killpg(0, signal.SIGKILL) # kill all processes in my group\n kill kill -9 kill -9"
},
{
"answer_id": 22582659,
"author": "berdario",
"author_id": 293735,
"author_profile": "https://Stackoverflow.com/users/293735",
"pm_score": 3,
"selected": false,
"text": "p=subprocess.Popen(your_command, preexec_fn=os.setsid)\nos.killpg(os.getpgid(p.pid), 15)\n setsid os.killpg"
},
{
"answer_id": 27295927,
"author": "Carl D'Halluin",
"author_id": 361547,
"author_profile": "https://Stackoverflow.com/users/361547",
"pm_score": 3,
"selected": false,
"text": "subprocess.Popen([\"sleep\", \"100\"], preexec_fn=lambda: prctl.set_pdeathsig(signal.SIGKILL))\n"
},
{
"answer_id": 27831932,
"author": "Malcolm Handley",
"author_id": 1623531,
"author_profile": "https://Stackoverflow.com/users/1623531",
"pm_score": 3,
"selected": false,
"text": "class CleanChildProcesses:\n def __enter__(self):\n os.setpgrp() # create new process group, become its leader\n def __exit__(self, type, value, traceback):\n try:\n os.killpg(0, signal.SIGINT) # kill all processes in my group\n except KeyboardInterrupt:\n # SIGINT is delievered to this process as well as the child processes.\n # Ignore it so that the existing exception, if any, is returned. This\n # leaves us with a clean exit code if there was no exception.\n pass\n with CleanChildProcesses():\n # Do your work here\n"
},
{
"answer_id": 41381814,
"author": "matanmarkind",
"author_id": 7223291,
"author_profile": "https://Stackoverflow.com/users/7223291",
"pm_score": 2,
"selected": false,
"text": "import os, signal, time\n\nclass CleanChildProcesses:\n \"\"\"\n with CleanChildProcesses():\n Do work here\n \"\"\"\n def __init__(self, time_to_die=5, foreground=False):\n self.time_to_die = time_to_die # how long to give children to die before SIGKILL\n self.foreground = foreground # If user wants to receive Ctrl-C\n self.is_foreground = False\n self.SIGNALS = (signal.SIGHUP, signal.SIGTERM, signal.SIGABRT, signal.SIGALRM, signal.SIGPIPE)\n self.is_stopped = True # only call stop once (catch signal xor exiting 'with')\n\n def _run_as_foreground(self):\n if not self.foreground:\n return False\n try:\n fd = os.open(os.ctermid(), os.O_RDWR)\n except OSError:\n # Happens if process not run from terminal (tty, pty)\n return False\n\n os.close(fd)\n return True\n\n def _signal_hdlr(self, sig, framte):\n self.__exit__(None, None, None)\n\n def start(self):\n self.is_stopped = False\n \"\"\"\n When running out of remote shell, SIGHUP is only sent to the session\n leader normally, the remote shell, so we need to make sure we are sent \n SIGHUP. This also allows us not to kill ourselves with SIGKILL.\n - A process group is called orphaned when the parent of every member is \n either in the process group or outside the session. In particular, \n the process group of the session leader is always orphaned.\n - If termination of a process causes a process group to become orphaned, \n and some member is stopped, then all are sent first SIGHUP and then \n SIGCONT.\n consider: prctl.set_pdeathsig(signal.SIGTERM)\n \"\"\"\n self.childpid = os.fork() # return 0 in the child branch, and the childpid in the parent branch\n if self.childpid == 0:\n try:\n os.setpgrp() # create new process group, become its leader\n os.kill(os.getpid(), signal.SIGSTOP) # child fork stops itself\n finally:\n os._exit(0) # shut down without going to __exit__\n\n os.waitpid(self.childpid, os.WUNTRACED) # wait until child stopped after it created the process group\n os.setpgid(0, self.childpid) # join child's group\n\n if self._run_as_foreground():\n hdlr = signal.signal(signal.SIGTTOU, signal.SIG_IGN) # ignore since would cause this process to stop\n self.controlling_terminal = os.open(os.ctermid(), os.O_RDWR)\n self.orig_fore_pg = os.tcgetpgrp(self.controlling_terminal) # sends SIGTTOU to this process\n os.tcsetpgrp(self.controlling_terminal, self.childpid)\n signal.signal(signal.SIGTTOU, hdlr)\n self.is_foreground = True\n\n self.exit_signals = dict((s, signal.signal(s, self._signal_hdlr))\n for s in self.SIGNALS) \n\n def stop(self):\n try:\n for s in self.SIGNALS:\n #don't get interrupted while cleaning everything up\n signal.signal(s, signal.SIG_IGN)\n\n self.is_stopped = True\n\n if self.is_foreground:\n os.tcsetpgrp(self.controlling_terminal, self.orig_fore_pg)\n os.close(self.controlling_terminal)\n self.is_foreground = False\n\n try:\n os.kill(self.childpid, signal.SIGCONT)\n except OSError:\n \"\"\"\n can occur if process finished and one of:\n - was reaped by another process\n - if parent explicitly ignored SIGCHLD\n signal.signal(signal.SIGCHLD, signal.SIG_IGN)\n - parent has the SA_NOCLDWAIT flag set \n \"\"\"\n pass\n\n os.setpgrp() # leave the child's process group so I won't get signals\n try:\n os.killpg(self.childpid, signal.SIGINT)\n time.sleep(self.time_to_die) # let processes end gracefully\n os.killpg(self.childpid, signal.SIGKILL) # In case process gets stuck while dying\n os.waitpid(self.childpid, 0) # reap Zombie child process\n except OSError as e:\n pass\n finally:\n for s, hdlr in self.exit_signals.iteritems():\n signal.signal(s, hdlr) # reset default handlers\n\n def __enter__(self):\n if self.is_stopped:\n self.start()\n\n def __exit__(self, exit_type, value, traceback):\n if not self.is_stopped:\n self.stop()\n"
},
{
"answer_id": 43152455,
"author": "Patrick",
"author_id": 1737332,
"author_profile": "https://Stackoverflow.com/users/1737332",
"pm_score": 3,
"selected": false,
"text": "def _set_pdeathsig(sig=signal.SIGTERM):\n \"\"\"help function to ensure once parent process exits, its childrent processes will automatically die\n \"\"\"\n def callable():\n libc = ctypes.CDLL(\"libc.so.6\")\n return libc.prctl(1, sig)\n return callable\n\n\nsubprocess.Popen(your_command, preexec_fn=_set_pdeathsig(signal.SIGTERM)) \n"
},
{
"answer_id": 52778653,
"author": "waszil",
"author_id": 1169220,
"author_profile": "https://Stackoverflow.com/users/1169220",
"pm_score": 0,
"selected": false,
"text": "subalive from subalive import SubAliveMaster\n\n# start subprocess with alive keeping\nSubAliveMaster(<path to your slave script>)\n\n# do your stuff\n# ...\n from subalive import SubAliveSlave\n\n# start alive checking\nSubAliveSlave()\n\n# do your stuff\n# ...\n"
},
{
"answer_id": 72214707,
"author": "Sopel",
"author_id": 3763139,
"author_profile": "https://Stackoverflow.com/users/3763139",
"pm_score": 0,
"selected": false,
"text": "import subprocess\nimport sys\nimport os\n\ndef terminate_process_on_exit(process):\n if sys.platform == \"win32\":\n try:\n # Or provide this script normally. \n # Here just to make it somewhat self-contained.\n # see https://stackoverflow.com/a/22559493/3763139\n # see https://superuser.com/a/1299350/388191\n with open('.process_watchdog_helper.bat', 'x') as file:\n file.write(\"\"\":waitforpid\ntasklist /nh /fi \"pid eq %1\" 2>nul | find \"%1\" >nul\nif %ERRORLEVEL%==0 (\n timeout /t 5 /nobreak >nul\n goto :waitforpid\n) else (\n wmic process where processid=\"%2\" call terminate >nul\n)\"\"\")\n except:\n pass\n \n # After this spawns we're pretty safe. There is a race, but we do what we can.\n subprocess.Popen(\n ['.process_watchdog_helper.bat', str(os.getpid()), str(process.pid)],\n stdout=subprocess.DEVNULL,\n stderr=subprocess.DEVNULL\n )\n\n# example\nclass DummyProcess:\n def __init__(self, pid):\n self.pid = pid\nset_terminate_when_this_process_dies(DummyProcess(7516))\n"
}
] | 2008/11/26 | [
"https://Stackoverflow.com/questions/320232",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6068/"
] |
320,250 | <p>I am trying to return the minimum and maximum prices for a villa booking system. I have a look up table that stores the price for each week for each villa. </p>
<p>I am using the min and max functions to do this within the select but I'm having lots of problems. Can anyone explain where i'm going wrong? Heres the sp</p>
<pre><code>ALTER PROCEDURE spVillaGet
-- Add the parameters for the stored procedure here
@accomodationTypeFK int = null,
@regionFK int = null,
@arrivalDate datetime = null,
@numberOfNights int = null,
@sleeps int = null,
@priceFloor money = null,
@priceCeil money = null
</code></pre>
<p>AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;</p>
<pre><code>-- Insert statements for procedure here
SELECT tblVillas.name,
tblVillas.introduction,
tblVillas.italian_introduction,
tblVillas.uk_content,
tblVillas.italian_content,
tblVillas.sleeps,
tblVillas.postcode,
tblLkUpRegions.regionName,
tblLkUpAccomodationTypes.accomodationType,
MIN(price) As MinPrice,
MAX(price) As MaxPrice
FROM tblVillas
LEFT JOIN tblLkUpRegions on tblVillas.regionFK = tblLkUpRegions.regionID
LEFT JOIN tblLkUpAccomodationTypes on tblVillas.accomodationTypeFK = tblLkUpAccomodationTypes.accomodationId
LEFT JOIN tblWeeklyPrices on tblWeeklyPrices.villaFK = tblVillas.villaId
WHERE
((@accomodationTypeFK is null OR accomodationTypeFK = @accomodationTypeFK)
AND (@regionFK is null OR regionFK = @regionFK)
AND (@sleeps is null OR sleeps = @sleeps)
AND tblVillas.deleted = 0)
GROUP BY tblVillas.name
</code></pre>
| [
{
"answer_id": 320256,
"author": "Tony Andrews",
"author_id": 18747,
"author_profile": "https://Stackoverflow.com/users/18747",
"pm_score": 2,
"selected": false,
"text": "GROUP BY tblVillas.name, \n tblVillas.introduction,\n tblVillas.italian_introduction,\n tblVillas.uk_content,\n tblVillas.italian_content,\n tblVillas.sleeps,\n tblVillas.postcode,\n tblLkUpRegions.regionName,\n tblLkUpAccomodationTypes.accomodationType\n SELECT tblVillas.name, \n tblVillas.introduction,\n tblVillas.italian_introduction,\n tblVillas.uk_content,\n tblVillas.italian_content,\n tblVillas.sleeps,\n tblVillas.postcode,\n tblLkUpRegions.regionName,\n tblLkUpAccomodationTypes.accomodationType,\n (SELECT MIN(price) FROM tblWeeklyPrices where tblWeeklyPrices.villaFK = tblVillas.villaId) As MinPrice,\n (SELECT MAX(price) FROM tblWeeklyPrices where tblWeeklyPrices.villaFK = tblVillas.villaId) As MaxPrice\nFROM tblVillas\nLEFT JOIN tblLkUpRegions on tblVillas.regionFK = tblLkUpRegions.regionID\nLEFT JOIN tblLkUpAccomodationTypes on tblVillas.accomodationTypeFK = tblLkUpAccomodationTypes.accomodationId \nWHERE\n ((@accomodationTypeFK is null OR accomodationTypeFK = @accomodationTypeFK)\n AND (@regionFK is null OR regionFK = @regionFK)\n AND (@sleeps is null OR sleeps = @sleeps) \n AND tblVillas.deleted = 0)\n"
},
{
"answer_id": 320278,
"author": "mancmanomyst",
"author_id": 40623,
"author_profile": "https://Stackoverflow.com/users/40623",
"pm_score": 0,
"selected": false,
"text": "Msg 306, Level 16, State 2, Procedure spVillaGet, Line 22\n"
}
] | 2008/11/26 | [
"https://Stackoverflow.com/questions/320250",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/40623/"
] |
320,264 | <p>I have some javascript menu code that works just fine from a separate directory.
But, when I try to call the same .js files from within the same directory, it won't see the files.</p>
<p>The following works from another directory:</p>
<p>script type="text/javascript"> var <strong>vbImgPath="../00-Menu-Files/"</strong></p>
<p>But, if I do this from within the same folder, how would I do it?</p>
<p><strong>THE SOLUTION (edited this in after much experimentation):</strong></p>
<p>I experimented A LOT!!!
There is only ONE solution that ultimately worked:</p>
<p>"../00-Menu-Files/"</p>
<p>The SAME thing as from the other directory!
Pretty strange that there is no other way to call this from within its own directory. But I cannot find another alternative that actually works.</p>
| [
{
"answer_id": 320270,
"author": "dylanfm",
"author_id": 38795,
"author_profile": "https://Stackoverflow.com/users/38795",
"pm_score": 0,
"selected": false,
"text": "script type=\"text/javascript\"> var vbImgPath=\"00-Menu-Files/\"\n script type=\"text/javascript\"> var vbImgPath=\"/00-Menu-Files/\"\n"
}
] | 2008/11/26 | [
"https://Stackoverflow.com/questions/320264",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/40091/"
] |
320,272 | <p>I have a dll that contains a dot net assembly - common intermediate language. The problem is that it's lacking documentation and I need to figure out the api like available classes, properties and methods, correct parameters to pass etc.</p>
<p>Whats the best way to do this. I need some sort of viewer/inspector but I couldn't find any.</p>
<p>Thanks.</p>
| [
{
"answer_id": 24016802,
"author": "nawfal",
"author_id": 661933,
"author_profile": "https://Stackoverflow.com/users/661933",
"pm_score": 1,
"selected": false,
"text": "F12"
}
] | 2008/11/26 | [
"https://Stackoverflow.com/questions/320272",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/36157/"
] |
320,281 | <p>I need to determine the number of pages in a specified PDF file using C# code (.NET 2.0). The PDF file will be read from the file system, and not from an URL. Does anyone have any idea on how this could be done? Note: Adobe Acrobat Reader is installed on the PC where this check will be carried out.</p>
| [
{
"answer_id": 320325,
"author": "darkdog",
"author_id": 1094,
"author_profile": "https://Stackoverflow.com/users/1094",
"pm_score": 7,
"selected": true,
"text": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\nusing iTextSharp.text.pdf;\nusing iTextSharp.text.xml;\nnamespace GetPages_PDF\n{\n class Program\n{\n static void Main(string[] args)\n {\n // Right side of equation is location of YOUR pdf file\n string ppath = \"C:\\\\aworking\\\\Hawkins.pdf\";\n PdfReader pdfReader = new PdfReader(ppath);\n int numberOfPages = pdfReader.NumberOfPages;\n Console.WriteLine(numberOfPages);\n Console.ReadLine();\n }\n }\n}\n"
},
{
"answer_id": 320492,
"author": "Peter Gfader",
"author_id": 35693,
"author_profile": "https://Stackoverflow.com/users/35693",
"pm_score": 2,
"selected": false,
"text": " p = new pdflib();\n\n /* Open the input PDF */\n indoc = p.open_pdi_document(\"myTestFile.pdf\", \"\");\n pageCount = (int) p.pcos_get_number(indoc, \"length:pages\");\n"
},
{
"answer_id": 1751348,
"author": "Barrett",
"author_id": 29815,
"author_profile": "https://Stackoverflow.com/users/29815",
"pm_score": 6,
"selected": false,
"text": "public int getNumberOfPdfPages(string fileName)\n{\n using (StreamReader sr = new StreamReader(File.OpenRead(fileName)))\n {\n Regex regex = new Regex(@\"/Type\\s*/Page[^s]\");\n MatchCollection matches = regex.Matches(sr.ReadToEnd());\n\n return matches.Count;\n }\n}\n"
},
{
"answer_id": 6127192,
"author": "Bobrovsky",
"author_id": 249690,
"author_profile": "https://Stackoverflow.com/users/249690",
"pm_score": 2,
"selected": false,
"text": "PdfDocument document = new PdfDocument();\ndocument.Open(\"file.pdf\");\nint pageCount = document.PageCount;\n"
},
{
"answer_id": 35596314,
"author": "Medo Medo",
"author_id": 1421165,
"author_profile": "https://Stackoverflow.com/users/1421165",
"pm_score": 2,
"selected": false,
"text": "int pdfPageCount = System.IO.File.ReadAllText(\"example.pdf\").Split(new string[] { \"/Type /Page\" }, StringSplitOptions.None).Count()-2;\n"
}
] | 2008/11/26 | [
"https://Stackoverflow.com/questions/320281",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/35483/"
] |
320,289 | <p>What is the C# equivalent of Delphi's <code>FillChar</code>?</p>
| [
{
"answer_id": 320320,
"author": "Marc Gravell",
"author_id": 23354,
"author_profile": "https://Stackoverflow.com/users/23354",
"pm_score": 3,
"selected": true,
"text": "for(int i = 0 ; i < arr.Length ; i++) {\n arr[i] = value;\n}\n Array.Clear public static void FillChar<T>(this T[] arr, T value) {...}\n int[] data = {1,2,3,4,5};\n//...\ndata.FillChar(7);\n Buffer.BlockCopy"
},
{
"answer_id": 320399,
"author": "FerranB",
"author_id": 40441,
"author_profile": "https://Stackoverflow.com/users/40441",
"pm_score": 1,
"selected": false,
"text": "String text = \"hello\";\ntext.PadRight(10, 'h').ToCharArray();\n"
},
{
"answer_id": 320631,
"author": "rusvdw",
"author_id": 5180,
"author_profile": "https://Stackoverflow.com/users/5180",
"pm_score": 3,
"selected": false,
"text": "byte[] buffer = new byte[1024];\n"
}
] | 2008/11/26 | [
"https://Stackoverflow.com/questions/320289",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/38940/"
] |
320,291 | <p>My current code looks like the following. How can I pass my array to the controller and what kind of parameters must my controller action accept?</p>
<pre><code>function getplaceholders() {
var placeholders = $('.ui-sortable');
var result = new Array();
placeholders.each(function() {
var ph = $(this).attr('id');
var sections = $(this).find('.sort');
var section;
sections.each(function(i, item) {
var sid = $(item).attr('id');
result.push({ 'SectionId': sid, 'Placeholder': ph, 'Position': i });
});
});
alert(result.toString());
$.post(
'/portal/Designer.mvc/SaveOrUpdate',
result,
function(data) {
alert(data.Result);
}, "json");
};
</code></pre>
<p>My controller action method looks like</p>
<pre><code>public JsonResult SaveOrUpdate(IList<PageDesignWidget> widgets)
</code></pre>
| [
{
"answer_id": 320653,
"author": "JSC",
"author_id": 37311,
"author_profile": "https://Stackoverflow.com/users/37311",
"pm_score": 7,
"selected": true,
"text": "function getplaceholders() {\n var placeholders = $('.ui-sortable');\n var results = new Array();\n placeholders.each(function() {\n var ph = $(this).attr('id');\n var sections = $(this).find('.sort');\n var section;\n\n sections.each(function(i, item) {\n var sid = $(item).attr('id');\n var o = { 'SectionId': sid, 'Placeholder': ph, 'Position': i };\n results.push(o);\n });\n });\n var postData = { widgets: results };\n var widgets = results;\n $.ajax({\n url: '/portal/Designer.mvc/SaveOrUpdate',\n type: 'POST',\n dataType: 'json',\n data: $.toJSON(widgets),\n contentType: 'application/json; charset=utf-8',\n success: function(result) {\n alert(result.Result);\n }\n });\n };\n [JsonFilter(Param = \"widgets\", JsonDataType = typeof(List<PageDesignWidget>))]\npublic JsonResult SaveOrUpdate(List<PageDesignWidget> widgets\n public class JsonFilter : ActionFilterAttribute\n{\n public string Param { get; set; }\n public Type JsonDataType { get; set; }\n public override void OnActionExecuting(ActionExecutingContext filterContext)\n {\n if (filterContext.HttpContext.Request.ContentType.Contains(\"application/json\"))\n {\n string inputContent;\n using (var sr = new StreamReader(filterContext.HttpContext.Request.InputStream))\n {\n inputContent = sr.ReadToEnd();\n }\n var result = JsonConvert.DeserializeObject(inputContent, JsonDataType);\n filterContext.ActionParameters[Param] = result;\n }\n }\n}\n"
},
{
"answer_id": 4878410,
"author": "Sanchitos",
"author_id": 317832,
"author_profile": "https://Stackoverflow.com/users/317832",
"pm_score": 3,
"selected": false,
"text": " var commissions = new Array();\n // Do several row data and do some push. In this example is just one push.\n var rowData = $(GRID_AGENTS).getRowData(ids[i]);\n commissions.push(rowData);\n $.ajax({\n type: \"POST\",\n traditional: true,\n url: '<%= Url.Content(\"~/\") %>' + AREA + CONTROLLER + 'SubmitCommissions',\n async: true,\n data: JSON.stringify(commissions),\n dataType: \"json\",\n contentType: 'application/json; charset=utf-8',\n success: function (data) {\n if (data.Result) {\n jQuery(GRID_AGENTS).trigger('reloadGrid');\n }\n else {\n jAlert(\"A problem ocurred during updating\", \"Commissions Report\");\n }\n }\n });\n [HttpPost]\n [JsonFilter(Param = \"commissions\", JsonDataType = typeof(List<CommissionsJs>))]\n public ActionResult SubmitCommissions(List<CommissionsJs> commissions)\n {\n var result = dosomething(commissions);\n var jsonData = new\n {\n Result = true,\n Message = \"Success\"\n };\n if (result < 1)\n {\n jsonData = new\n {\n Result = false,\n Message = \"Problem\"\n };\n }\n return Json(jsonData);\n }\n public class JsonFilter : ActionFilterAttribute\n {\n public string Param { get; set; }\n public Type JsonDataType { get; set; }\n public override void OnActionExecuting(ActionExecutingContext filterContext)\n {\n if (filterContext.HttpContext.Request.ContentType.Contains(\"application/json\"))\n {\n string inputContent;\n using (var sr = new StreamReader(filterContext.HttpContext.Request.InputStream))\n {\n inputContent = sr.ReadToEnd();\n }\n var result = JsonConvert.DeserializeObject(inputContent, JsonDataType);\n filterContext.ActionParameters[Param] = result;\n }\n }\n }\n public class CommissionsJs\n {\n public string Amount { get; set; }\n\n public string CheckNumber { get; set; }\n\n public string Contract { get; set; }\n public string DatePayed { get; set; }\n public string DealerName { get; set; }\n public string ID { get; set; }\n public string IdAgentPayment { get; set; }\n public string Notes { get; set; }\n public string PaymentMethodName { get; set; }\n public string RowNumber { get; set; }\n public string AgentId { get; set; }\n }\n"
},
{
"answer_id": 7354496,
"author": "Levitikon",
"author_id": 467339,
"author_profile": "https://Stackoverflow.com/users/467339",
"pm_score": 5,
"selected": false,
"text": "$.post('SomeController/Batch', { 'ids': ['1', '2', '3']}, function (r) {\n ...\n});\n [HttpPost]\npublic ActionResult Batch(string[] ids)\n{\n}\n jQuery.ajaxSettings.traditional = true;\n"
},
{
"answer_id": 27963227,
"author": "Matas Vaitkevicius",
"author_id": 1509764,
"author_profile": "https://Stackoverflow.com/users/1509764",
"pm_score": 4,
"selected": false,
"text": ".NET4.5 MVC 5 $('.button-green-large').click(function() {\n $.ajax({\n url: 'Quote',\n type: \"POST\",\n dataType: \"json\",\n data: JSON.stringify(document.selectedProduct),\n contentType: 'application/json; charset=utf-8',\n });\n });\n public class WillsQuoteViewModel\n{\n public string Product { get; set; }\n\n public List<ClaimedFee> ClaimedFees { get; set; }\n}\n\npublic partial class ClaimedFee //Generated by EF6\n{\n public long Id { get; set; }\n public long JourneyId { get; set; }\n public string Title { get; set; }\n public decimal Net { get; set; }\n public decimal Vat { get; set; }\n public string Type { get; set; }\n\n public virtual Journey Journey { get; set; }\n}\n [AcceptVerbs(HttpVerbs.Post)]\npublic ActionResult Quote(WillsQuoteViewModel data)\n{\n....\n}\n"
},
{
"answer_id": 38853304,
"author": "JsonW",
"author_id": 6696121,
"author_profile": "https://Stackoverflow.com/users/6696121",
"pm_score": -1,
"selected": false,
"text": " [HttpPost]\n public bool parseAllDocs([FromBody] IList<docObject> data)\n {\n // do stuff\n\n }\n"
},
{
"answer_id": 54899427,
"author": "mahdi moghimi",
"author_id": 6468147,
"author_profile": "https://Stackoverflow.com/users/6468147",
"pm_score": -1,
"selected": false,
"text": " $.post(yourURL,{ '': results})(function(e){ ...}\n public ActionResult MethodName(List<yourViewModel> model){...}\n"
}
] | 2008/11/26 | [
"https://Stackoverflow.com/questions/320291",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/37311/"
] |
320,299 | <p>Is there a way to limit the rows returned at the Oracle datasource level in a Tomcat application?</p>
<p>It seems <code>maxRows</code> is only available if you set it on the datasource in the Java code. Putting <code>maxRows="2"</code> on the datasource doesn't apply.</p>
<p>Is there any other way limit the rows returned? Without a code change?</p>
| [
{
"answer_id": 5106590,
"author": "Chucky",
"author_id": 73643,
"author_profile": "https://Stackoverflow.com/users/73643",
"pm_score": 1,
"selected": false,
"text": "public class DataSourceWrapper implements DataSource\n{\n private DataSource mDelegate;\n\n public DataSourceWrapper( DataSource delegate )\n {\n if( delegate == null ) { throw new NullPointerException( \"Delegate cannot be null\" );\n mDelegate = delegate;\n }\n\n public Connection getConnection(String username, String password)\n {\n return new ConnectionWrapper( mDelegate.getConnection( username, password ) );\n }\n\n public Connection getConnection()\n {\n ... <same as getConnection(String, String)> ...\n }\n}\n"
}
] | 2008/11/26 | [
"https://Stackoverflow.com/questions/320299",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/40976/"
] |
320,313 | <p>I'm using GNU bash, version 3.00.15(1)-release (x86_64-redhat-linux-gnu). And this command:</p>
<pre><code>echo "-e"
</code></pre>
<p>doesn't print anything. I guess this is because "-e" is one of a valid options of echo command because echo "-n" and echo "-E" (the other two options) also produce empty strings.</p>
<p>The question is how to escape the sequence "-e" for echo to get the natural output ("-e").</p>
| [
{
"answer_id": 320321,
"author": "Joachim Sauer",
"author_id": 40342,
"author_profile": "https://Stackoverflow.com/users/40342",
"pm_score": 2,
"selected": false,
"text": "echo \"-e \"\n echo -e \\\\\\\\x2De\n"
},
{
"answer_id": 320328,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 5,
"selected": true,
"text": "$ echo -- -e\n-- -e\n $ echo -e '\\055e'\n-e\n echo /bin/echo POSIXLY_CORRECT $ POSIXLY_CORRECT=1 /bin/echo -e\n-e\n"
},
{
"answer_id": 320336,
"author": "Stephen Darlington",
"author_id": 2998,
"author_profile": "https://Stackoverflow.com/users/2998",
"pm_score": 3,
"selected": false,
"text": "printf -- \"-e\\n\"\n"
},
{
"answer_id": 320369,
"author": "FerranB",
"author_id": 40441,
"author_profile": "https://Stackoverflow.com/users/40441",
"pm_score": 0,
"selected": false,
"text": "echo -e' '\necho -e \" \\b-e\"\n"
},
{
"answer_id": 320430,
"author": "The Archetypal Paul",
"author_id": 21755,
"author_profile": "https://Stackoverflow.com/users/21755",
"pm_score": 1,
"selected": false,
"text": "SYSV3=1 /usr/bin/echo -e\n"
},
{
"answer_id": 321252,
"author": "wheleph",
"author_id": 15647,
"author_profile": "https://Stackoverflow.com/users/15647",
"pm_score": -1,
"selected": false,
"text": "/bin/echo -e\n [resin@nevada ~]$ which echo \n/bin/echo\n"
},
{
"answer_id": 328108,
"author": "CesarB",
"author_id": 28258,
"author_profile": "https://Stackoverflow.com/users/28258",
"pm_score": 1,
"selected": false,
"text": "echo x-e | sed 's/^x//'\n"
},
{
"answer_id": 2582593,
"author": "nanaya",
"author_id": 260761,
"author_profile": "https://Stackoverflow.com/users/260761",
"pm_score": 4,
"selected": false,
"text": "printf \"%s\" \"$vars\"\n"
},
{
"answer_id": 17526589,
"author": "Tilman Vogel",
"author_id": 119725,
"author_profile": "https://Stackoverflow.com/users/119725",
"pm_score": 1,
"selected": false,
"text": "cat <<<\"-e\"\n"
}
] | 2008/11/26 | [
"https://Stackoverflow.com/questions/320313",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15647/"
] |
320,330 | <p>When using <a href="http://log4perl.sourceforge.net/" rel="nofollow noreferrer">log4perl</a>, the debug log layout that I'm using is :</p>
<pre><code>log4perl.appender.D10.layout=PatternLayout
log4perl.appender.D10.layout.ConversionPattern=%d [pid=%P] %p %F{1} (%L) %M %m%n
log4perl.appender.D10.Filter = DebugAndUp
</code></pre>
<p>This produces very verbose debug logs, for example:</p>
<pre><code>2008/11/26 11:57:28 [pid=25485] DEBUG SomeModule.pm (331) functions::SomeModule::Test Test XXX was successfull
2008/11/26 11:57:29 [pid=25485] ERROR SomeOtherUnrelatedModule.pm (99999) functions::SomeModule::AnotherTest AnotherTest YYY has faled
</code></pre>
<p>This works great, and provides excellent debugging data.</p>
<p>However, each line of the debug log contains different function names, pid length, etc. This makes each line layout differently, and makes reading debug logs much harder than it needs to be.</p>
<p>Is there a way in log4perl to format the line so that the debugging metadata (everything up until the actual log message) be padded at the end with spaces/tabs, and have the actual message start at the same column of text?</p>
| [
{
"answer_id": 320519,
"author": "brian d foy",
"author_id": 2766176,
"author_profile": "https://Stackoverflow.com/users/2766176",
"pm_score": 3,
"selected": false,
"text": "%n"
}
] | 2008/11/26 | [
"https://Stackoverflow.com/questions/320330",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13523/"
] |
320,333 | <p>I'd like to have some of the ScriptManager features in the new Asp.net MVC model:</p>
<p>1- Script combining<br>
2- Resolving different paths for external Javascript files<br>
3- Minify and Gzip Compression </p>
<p><a href="http://www.codeproject.com/KB/aspnet/HttpCombine.aspx" rel="nofollow noreferrer">Here</a> is what I found, but I'm not sure is the best way for MVC approach. In general what is a good approach to deal with Javascript code in the MVC model?</p>
| [
{
"answer_id": 320397,
"author": "Franck",
"author_id": 38072,
"author_profile": "https://Stackoverflow.com/users/38072",
"pm_score": 5,
"selected": true,
"text": "<script src=\"http://your_domain/scripts/all\"/>\n"
},
{
"answer_id": 815188,
"author": "Bellarmine Head",
"author_id": 98689,
"author_profile": "https://Stackoverflow.com/users/98689",
"pm_score": 2,
"selected": false,
"text": "<form runat=\"server\"> <form runat=\"server\">\n <asp:ScriptManager ID=\"ScriptManager1\" runat=\"server\" EnableScriptGlobalization=\"true\">\n </asp:ScriptManager>\n </form>\n"
}
] | 2008/11/26 | [
"https://Stackoverflow.com/questions/320333",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1929/"
] |
320,335 | <p>I have a piece of code which sends e-mails using a third party e-mail sending component.</p>
<p>When the e-mails are delivered, the HTML which should be appearing in the body of the e-mail is <em>also</em> being added as an attachment with the filename ATT00001.</p>
<p>I <em>suspect</em> the attachment is being created by the receiving e-mail server (which in this case is Exchange 2007).</p>
<p>My question is - does anybody know why this is happening? I suspect some sort of character set problem, but I'm not really sure.</p>
<p>Any help would be appreciated!</p>
| [
{
"answer_id": 320427,
"author": "PhiLho",
"author_id": 15459,
"author_profile": "https://Stackoverflow.com/users/15459",
"pm_score": 1,
"selected": false,
"text": "Content-Type: multipart/mixed; boundary=----------whatever Content-Type: multipart/alternative; boundary=\"----something\""
}
] | 2008/11/26 | [
"https://Stackoverflow.com/questions/320335",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/475/"
] |
320,355 | <p>I would like to create a WLST script to create my Weblogic domain. However I'm having problems adding the LDAP config.</p>
<pre><code>cd("/SecurityConfiguration/myDomain")
cmo.createRealm("myrealm")
cd("/SecurityConfiguration/myDomain/Realms/myrealm")
cmo.createAuthenticationProvider("myLDAP", "weblogic.security.providers.authentication.NovellAuthenticator")
</code></pre>
<p>This is currently failing because at this point I don't seem to have a SecurityConfiguration object</p>
<pre><code>No SecurityConfiguration object with name myDomain
</code></pre>
<p>Does this configuration have to be done online? Are there any other work arounds?</p>
| [
{
"answer_id": 325454,
"author": "Mark Sailes",
"author_id": 33167,
"author_profile": "https://Stackoverflow.com/users/33167",
"pm_score": 2,
"selected": true,
"text": "connect(\"username\", \"password\", \"t3://ip:port\");\n\nedit()\nstartEdit()\n\ncreate_AuthenticationProvider_54(\"/SecurityConfiguration/myDomain/Realms/myrealm\", \"value\")\ncd(\"/SecurityConfiguration/myDomain/Realms/myrealm\")\ncmo.createAuthenticationProvider(\"myLDAP\", \"weblogic.security.providers.authentication.NovellAuthenticator\")\n\ncd(\"/SecurityConfiguration/myDomain/Realms/myrealm/AuthenticationProviders/myLDAP\")\nset(\"GroupBaseDN\", \"value\")\nset(\"UserNameAttribute\", \"value\")\nset(\"StaticGroupObjectClass\", \"value\")\nset(\"UserBaseDN\", \"value\")\nset(\"UserObjectClass\", \"value\")\nset(\"AllGroupsFilter\", \"value\")\nset(\"Principal\", \"value\")\nset(\"UseRetrievedUserNameAsPrincipal\", \"value\")\nset(\"Host\", \"value\")\nset(\"StaticGroupDNsfromMemberDNFilter\", \"value\")\nset(\"StaticMemberDNAttribute\", \"value\")\nset(\"ControlFlag\", \"value\")\nset(\"UserFromNameFilter\", \"value\")\nset(\"Credential\", \"value\")\nset(\"GroupFromNameFilter\", \"value\")\n\nstartEdit()\nsave()\nactivate(block=\"true\")\n"
},
{
"answer_id": 364377,
"author": "David G",
"author_id": 3150,
"author_profile": "https://Stackoverflow.com/users/3150",
"pm_score": 0,
"selected": false,
"text": "realm = cmo.getSecurityConfiguration().getDefaultRealm()\nmyProvider = realm.createAuthenticationProvider(\"weblogic.security.providers.authentication.NovellAuthenticator\")\n"
}
] | 2008/11/26 | [
"https://Stackoverflow.com/questions/320355",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/33167/"
] |
320,357 | <p>What is the safe width in pixels to print a web page? </p>
<p>My page includes large images and I want to make sure they will not be cut of when printed.</p>
<p>I know about different browser margins and US Letter / DIN A4 paper sizes. So we got standard letter sized and some default DPI values. But can I convert these into <strong>pixel</strong> values to specify in the image's <code>width</code> attribute?</p>
| [
{
"answer_id": 320462,
"author": "ARemesal",
"author_id": 36599,
"author_profile": "https://Stackoverflow.com/users/36599",
"pm_score": 3,
"selected": false,
"text": "<link href=\"style.css\" rel=\"stylesheet\" type=\"text/css\" media=\"screen\">\n<link href=\"style_print.css\" rel=\"stylesheet\" type=\"text/css\" media=\"print\">\n"
},
{
"answer_id": 1890969,
"author": "Gyuri",
"author_id": 186850,
"author_profile": "https://Stackoverflow.com/users/186850",
"pm_score": 6,
"selected": false,
"text": "pt width: 511pt;"
},
{
"answer_id": 5092154,
"author": "dontcallmedom",
"author_id": 139591,
"author_profile": "https://Stackoverflow.com/users/139591",
"pm_score": 3,
"selected": false,
"text": "@media print { \n img { \n max-width:100% !important;\n } \n}\n"
},
{
"answer_id": 19884147,
"author": "jHouse",
"author_id": 2975085,
"author_profile": "https://Stackoverflow.com/users/2975085",
"pm_score": 4,
"selected": false,
"text": "@media print {\n .printEl { \n width: 8.5in;\n height: 11in;\n }\n}\n"
}
] | 2008/11/26 | [
"https://Stackoverflow.com/questions/320357",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/28150/"
] |
320,387 | <p>I am wondering if it is possible to have a sort of thumbnail image gallery, in which clicking on a thumbnail would show the full image in a layer. I was wondering if it was possible to load all layers and respective images and use javascript to change the z index or something similar to avoid having to reload or leave the page. I would prefer to avoid using a server side technology but don't know if this is possible.</p>
<p>edit:</p>
<p>I am not after a "lightbox" solution or anything that overlays the page, I rather want an image to appear as part of the page, and change without reloading the page, basically like PIctureSlide linked below. But more importanlt, I am wondering if this would be easy to write without using a framework, and if it would work as I thought above?</p>
| [
{
"answer_id": 320764,
"author": "Diodeus - James MacFarlane",
"author_id": 12579,
"author_profile": "https://Stackoverflow.com/users/12579",
"pm_score": 3,
"selected": true,
"text": "<div id='big' style='width:500px;height:500px'></div>\n<a href=\"javascript://load big image\" onclick=\"document.getElementById('big').style.backgroundImage='url(Big.gif)'\"><img border=\"0\" src=\"images/Thumb.gif\" /></a>\n <div id='big' style='width:500px;height:500px'></div>\n<a href=\"javascript://load big image\" onclick=\"$('big').style.backgroundImage='url(Big1.gif)'\"><img border=\"0\" src=\"thumb1.gif\" /></a>\n <div id='big'></div>\n<a href=\"javascript://load big image\" onclick=\"loadBig('Big1.gif')\"><img border=\"0\" src=\"thumb1.gif\" /></a>\n<script type=\"text/javascript\">\nfunction loadBig() {\n $('big').innerHTML = \"<img src='Big1.gif'>\"\n}\n</script>\n"
}
] | 2008/11/26 | [
"https://Stackoverflow.com/questions/320387",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1246613/"
] |
320,396 | <p>I've written my first C# iterator today. Woohoo.</p>
<p>Interestingly, it has side effects. My iterator filters out invalid files from a directory and returns a sequence of valid files to process. Wheneve it encounters an invlaid file, it moves it to another directory.</p>
<p>I tried implementing it as a LINQ query, but really don't like the fact that the predicate for the where clause has side effects. That's a definite smell.</p>
<p>I could implement it explicitly, looping over all files and handling the good or the bad in turn, but it's not very elegant. A better solution is to split it into two lists (good and bad) and process each in turn.</p>
<p>But then I remembered iterators. And I've now got an iterator that yields the valid files and handles (moves) the invalid ones.</p>
<p>So, my question is this: is it a bad idea for an iterator to have side effects such as this? Am I hiding too much functionality in an iterator?</p>
| [
{
"answer_id": 320432,
"author": "Henrik Gustafsson",
"author_id": 2010,
"author_profile": "https://Stackoverflow.com/users/2010",
"pm_score": 2,
"selected": false,
"text": "good_handler = new FileHandler() {\n handle(File f) { print \"Yay!\"; }\n}\n\nbad_handler = new FileHandler() {\n handle(File f) { print \"Nay!\"; }\n}\n\nfiles = YourFileSequence();\nvisitor = new Visitor(good_handler, bad_handler);\nvisitor.visit(files);\n"
}
] | 2008/11/26 | [
"https://Stackoverflow.com/questions/320396",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
320,405 | <p>I'm trying to create a cube with a single measure. This measure is a distinct count of a "name" column. The cube works perfectly if the measure is set to "count" type. However when I set distinct count I get this error:</p>
<p>"Errors in the OLAP storage engine: The sort order specified for distinct count records is incorrect"</p>
<p>I have read in some blogs that you can only have a distinct count on a numeric column. I can't see a good reason for this, and I can't find that info on official documentation. However, it may be true. Anyways, I'm really stuck with this issue. What are my options? </p>
| [
{
"answer_id": 39361892,
"author": "pso",
"author_id": 2990805,
"author_profile": "https://Stackoverflow.com/users/2990805",
"pm_score": 0,
"selected": false,
"text": "SUBSTRING(master.dbo.fn_varbintohexstr(HashBytes('MD5', [column_name])), 3, 32)\n"
}
] | 2008/11/26 | [
"https://Stackoverflow.com/questions/320405",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/36897/"
] |
320,436 | <p>In a C# application I am working on I have a very long identifier as follows:-</p>
<pre><code>foo.bar.bwah.blah.whatever.very.very.huge
</code></pre>
<p>Whenever I to reference this object it's an absolute nightmare, and unfortunately I do need to reference it a lot:-</p>
<pre><code>var something = foo.bar.bwah.blah.whatever.very.very.huge.a;
var somethingElse = foo.bar.bwah.blah.whatever.very.very.huge.b;
foo.bar.bwah.blah.whatever.very.very.huge.c = 12;
</code></pre>
<p>etc. etc.</p>
<p>I want to update this code using a far smaller alias of some kind, the problem is however that I want to change the underlying reference, and have the alias update also <em>without explicitly updating the alias</em>.</p>
<p>Currently if I do the following:-</p>
<pre><code>foo.bar.bwah.blah.whatever.very.very.huge.a = "hello";
string shorter = foo.bar.bwah.blah.whatever.very.very.huge.a;
foo.bar.bwah.blah.whatever.very.very.huge.a = "world";
Console.WriteLine(shorter);
</code></pre>
<p>It will output "hello". What I want to achieve is something like the following:-</p>
<pre><code>foo.bar.bwah.blah.whatever.very.very.huge.a = "hello";
string** shorterPointer = &foo.bar.bwah.blah.whatever.very.very.huge.a;
foo.bar.bwah.blah.whatever.very.very.huge.a = "world";
Console.WriteLine(**shorter);
</code></pre>
<p>Which would output "world" as required.</p>
<p>I believe you can achieve something like this using unsafe code in C#, however I <em>cannot</em> do that, I have to use safe code only.</p>
<p>Does anybody have any ideas how I might achieve this?</p>
<p><strong>Please Note:</strong> This question is not about strings being immutable, I know they are - in fact I assumed they are for the purposes of the question. It might perhaps be simpler if I used some other type... so when I assign "hello" to a then "world" to a, I am <em>instantiating different objects</em> on each occasion, hence my stored reference to a becomes invalid after re-assignment.</p>
| [
{
"answer_id": 320451,
"author": "Barry Kelly",
"author_id": 3712,
"author_profile": "https://Stackoverflow.com/users/3712",
"pm_score": 4,
"selected": true,
"text": "Func<string> getter = () => blah_de_blah;\nAction<string> setter = x => blah_de_blah = x;\n var myHuge = foo.bar.bwah.blah.whatever.very.very.huge;\n// now access myHuge.a everywhere\n"
},
{
"answer_id": 320594,
"author": "Sergio",
"author_id": 32037,
"author_profile": "https://Stackoverflow.com/users/32037",
"pm_score": 1,
"selected": false,
"text": "using myAlias = foo.bar.bwah.blah.whatever.very.very\n myAlias.huge.a = \"hello\";"
}
] | 2008/11/26 | [
"https://Stackoverflow.com/questions/320436",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3394/"
] |
320,448 | <p>I can't seem to find an answer to this problem, and I'm wondering if one exists. Simplified example:</p>
<p>Consider a string "nnnn", where I want to find all matches of "nn" - but also those that overlap with each other. So the regex would provide the following 3 matches:</p>
<ol>
<li><b>nn</b>nn</li>
<li>n<b>nn</b>n</li>
<li>nn<b>nn</b></li>
</ol>
<p>I realize this is not exactly what regexes are meant for, but walking the string and parsing this manually seems like an awful lot of code, considering that in reality the matches would have to be done using a pattern, not a literal string.</p>
| [
{
"answer_id": 320478,
"author": "VonC",
"author_id": 6309,
"author_profile": "https://Stackoverflow.com/users/6309",
"pm_score": 6,
"selected": true,
"text": "nn nn nn (?=(nn)) (?=(nn))\n (?<=n)n\n (?=nn)n (n)(?=(n))\n"
},
{
"answer_id": 321391,
"author": "Jan Goyvaerts",
"author_id": 33358,
"author_profile": "https://Stackoverflow.com/users/33358",
"pm_score": 5,
"selected": false,
"text": "Regex regexObj = new Regex(\"nn\");\nMatch matchObj = regexObj.Match(subjectString);\nwhile (matchObj.Success) {\n matchObj = regexObj.Match(subjectString, matchObj.Index + 1); \n}\n"
}
] | 2008/11/26 | [
"https://Stackoverflow.com/questions/320448",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4333/"
] |
320,452 | <p>I have a SQL table which has a number of fields</p>
<p>ID | Value | Type</p>
<p>A typical record may be :-
1000,10,[int]</p>
<p>a second row may be:-</p>
<p>1001,foo,[string]</p>
<p>a third row may be:-</p>
<p>1002,10/12/2008,[DateTime]</p>
<p>I have been asked to look at this as at the moment, each time we wish to select from this table we have to cast the value to the type specified. I am able to do a database redesign on this and am wondering the best route to go to optimise this. (SQL 2000).</p>
| [
{
"answer_id": 320650,
"author": "Tony Andrews",
"author_id": 18747,
"author_profile": "https://Stackoverflow.com/users/18747",
"pm_score": 3,
"selected": true,
"text": "ID Type StringValue DateValue NumberValue\n1001 String Foo\n1002 Date 10/12/2008\n1003 Number 123.46\n"
},
{
"answer_id": 320673,
"author": "Tom H",
"author_id": 5696608,
"author_profile": "https://Stackoverflow.com/users/5696608",
"pm_score": 2,
"selected": false,
"text": "CREATE TABLE dbo.My_Table (\n id INT NOT NULL,\n data_type VARCHAR(10) NOT NULL,\n string_value VARCHAR(100) NULL,\n int_value INT NULL,\n date_value DATETIME NULL,\n CONSTRAINT CK_My_Table_data_type CHECK data_type IN ('int', 'string', 'datetime'),\n CONSTRAINT PK_My_Table PRIMARY KEY CLUSTERED (id)\n)\nGO\n SELECT\n id,\n CASE data_type\n WHEN 'string' THEN string_value\n WHEN 'int' THEN int_value\n WHEN 'datetime' THEN date_value\n ELSE NULL\n END\n"
}
] | 2008/11/26 | [
"https://Stackoverflow.com/questions/320452",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/35441/"
] |
320,461 | <p>Why main must be declared as if it has external linkage?
<p>Why it should not be static?
<p>what is meant by external linkage??</p>
| [
{
"answer_id": 320463,
"author": "Johannes Schaub - litb",
"author_id": 34509,
"author_profile": "https://Stackoverflow.com/users/34509",
"pm_score": 6,
"selected": true,
"text": "external linkage translation-units static linkage translation units readelf -sW <file>.o void bar(void);\n\nstatic int foo(void) {\n return 1;\n}\n\nint main(void) {\n bar();\n return foo();\n}\n Symbol table '.symtab' contains 10 entries:\n Num: Value Size Type Bind Vis Ndx Name\n 0: 00000000 0 NOTYPE LOCAL DEFAULT UND\n 1: 00000000 0 FILE LOCAL DEFAULT ABS test.c\n 2: 00000000 0 SECTION LOCAL DEFAULT 1\n 3: 00000000 0 SECTION LOCAL DEFAULT 3\n 4: 00000000 0 SECTION LOCAL DEFAULT 4\n 5: 00000000 10 FUNC LOCAL DEFAULT 1 foo\n 6: 00000000 0 SECTION LOCAL DEFAULT 6\n 7: 00000000 0 SECTION LOCAL DEFAULT 5\n 8: 0000000a 36 FUNC GLOBAL DEFAULT 1 main\n 9: 00000000 0 NOTYPE GLOBAL DEFAULT UND bar\n readelf -r <file>.o Relocation section '.rel.text' at offset 0x308 contains 1 entries:\n Offset Info Type Sym.Value Sym. Name\n0000001c 00000902 R_386_PC32 00000000 bar\n"
}
] | 2008/11/26 | [
"https://Stackoverflow.com/questions/320461",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/31116/"
] |
320,479 | <p>I have a threading issue,</p>
<p>I'm setting the <code>ThreadPool.SetMaxThreads(maxThreads, System.Environment.ProcessorCount)</code> to 10.</p>
<p>But when I check how many are avaliable <code>ThreadPool.GetAvailableThreads()</code> it says there are (maxThreads - 1) so 9, but then goes on to use 10 threads.</p>
<p>Any ideas why this is?</p>
<p>Thanks for the help.</p>
| [
{
"answer_id": 321019,
"author": "Ian P",
"author_id": 10853,
"author_profile": "https://Stackoverflow.com/users/10853",
"pm_score": 1,
"selected": false,
"text": "ThreadPool.QueueUserWorkItem(callback, obj)\n WaitHandle.WaitAll(WaitHandle)\n"
}
] | 2008/11/26 | [
"https://Stackoverflow.com/questions/320479",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
320,480 | <p>Nested If or single if with And operator, which is better approach?<br>
<strong>Single If with And</strong> </p>
<pre><code>if (txtPackage.Text != string.Empty && txtPackage.Text == "abc")
{
//
}
</code></pre>
<p><strong>Nested If</strong> </p>
<pre><code>if (txtPackage.Text != string.Empty)
{
if (txtPackage.Text == "abc")
{
//
}
}
</code></pre>
| [
{
"answer_id": 320488,
"author": "itsmatt",
"author_id": 7862,
"author_profile": "https://Stackoverflow.com/users/7862",
"pm_score": 4,
"selected": true,
"text": "if (txtPackage.Text == \"abc\")\n{\n\n//\n\n}\n"
},
{
"answer_id": 320491,
"author": "The Archetypal Paul",
"author_id": 21755,
"author_profile": "https://Stackoverflow.com/users/21755",
"pm_score": 2,
"selected": false,
"text": "if (!user_option.work_offline) {\n if (no_current_connection) {\n start_connection()\n }\n}\n"
},
{
"answer_id": 320502,
"author": "Timothy Khouri",
"author_id": 11917,
"author_profile": "https://Stackoverflow.com/users/11917",
"pm_score": 3,
"selected": false,
"text": "if (myThingy != null)\n{\n if (myThingy.Text = \"Hello\") ...\n\n if (myThingy.SomethingElse = 123) ...\n}\n if (somethingQuick() && somethingThatTakesASecondToCalculate()) ...\n if (somethingThatTakesASecondToCalculate() && somethingQuick()) ...\n"
},
{
"answer_id": 320503,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "if (thisIsTrue) {\nif (thisIsTrueToo) doStuff();\n}\n if (thisIsTrue && thisIsTrueToo) doStuff();\n"
},
{
"answer_id": 320526,
"author": "codeape",
"author_id": 3571,
"author_profile": "https://Stackoverflow.com/users/3571",
"pm_score": 1,
"selected": false,
"text": "# I prefer:\nif a and b:\n foo()\nelif a and not b:\n bar()\nelif not a and b:\n foobar()\nelif not a and not b:\n baz()\n\n# Instead of:\nif a:\n if b:\n foo()\n else:\n bar()\nelse:\n if b:\n foobar()\n else:\n baz() if a and b:\n foo()\nelif a and not b:\n bar()\nelif not a and b:\n foobar()\nelif not a and not b:\n baz()\nelse:\n assert not a and not b\n baz()"
},
{
"answer_id": 27951750,
"author": "vicki",
"author_id": 4455056,
"author_profile": "https://Stackoverflow.com/users/4455056",
"pm_score": 3,
"selected": false,
"text": "if (thisIsTrue && thisIsTrueToo)\n doStuff();\n if (thisIsTrue) {\n if (thisIsTrueToo)\n doStuff();\n}\n"
}
] | 2008/11/26 | [
"https://Stackoverflow.com/questions/320480",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/34588/"
] |
320,481 | <p>Is it possible to access the following formatted menu item like any other standard menu item (using the underscore-method, e.g. "_File" would be accessible by pressing "f")? I would like to use "O" as "access key" here.</p>
<p>Unfortunately, <code><AccessText></code> does not seem to be usable directly (I imaginged something like </p>
<pre><code><AccessText Visibility="Collapsed">_O2-Genion</AccessText>
</code></pre>
<p>in a <code><StackPanel></code>, but alas, this did not work out.)</p>
<pre><code><MenuItem>
<MenuItem.Header>
<TextBlock>
O
<Span BaselineAlignment="Subscript">
<TextBlock Margin="-3,0,0,0" FontSize="8">
2
</TextBlock>
</Span>
-Genion
</TextBlock>
</MenuItem.Header>
</MenuItem>
</code></pre>
<p>Any suggestions?</p>
| [
{
"answer_id": 320617,
"author": "Andy",
"author_id": 3857,
"author_profile": "https://Stackoverflow.com/users/3857",
"pm_score": 0,
"selected": false,
"text": "<MenuItem HeaderText=\"_02\" />\n"
},
{
"answer_id": 320683,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<MenuItem>\n <MenuItem.Header>\n <StackPanel Orientation=\"Horizontal\">\n <AccessText>_O</AccessText>\n <TextBlock>\n <Span BaselineAlignment=\"Subscript\" FontSize=\"8\">2</Span>-Genion\n </TextBlock>\n </StackPanel>\n </MenuItem.Header>\n</MenuItem>\n"
}
] | 2008/11/26 | [
"https://Stackoverflow.com/questions/320481",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
320,482 | <p>There is a groupwall of which I want to download and store all messages in a db.
In the documentation I cannot find a good way to do it. Did I miss something? What's the good way to do this?</p>
| [
{
"answer_id": 320617,
"author": "Andy",
"author_id": 3857,
"author_profile": "https://Stackoverflow.com/users/3857",
"pm_score": 0,
"selected": false,
"text": "<MenuItem HeaderText=\"_02\" />\n"
},
{
"answer_id": 320683,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<MenuItem>\n <MenuItem.Header>\n <StackPanel Orientation=\"Horizontal\">\n <AccessText>_O</AccessText>\n <TextBlock>\n <Span BaselineAlignment=\"Subscript\" FontSize=\"8\">2</Span>-Genion\n </TextBlock>\n </StackPanel>\n </MenuItem.Header>\n</MenuItem>\n"
}
] | 2008/11/26 | [
"https://Stackoverflow.com/questions/320482",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/553923/"
] |
320,484 | <p>Marked a javascript file as "Embedded resource"<br />
Added WebResource attribute to my AssemblyInfo class<br /><br />
Now i'm trying to output the embedded javascript to my master page. All I'm getting is a "Web Resource not found" from the web resource url.</p>
<p><br />Project Assembly Name:<br /></p>
<pre><code>CompanyProduct
</code></pre>
<p><br />Project Default Namespace:<br /></p>
<pre><code>Company.Product.Web
</code></pre>
<p><br />Javascript file located:<br />
Library/navigation.js</p>
<p><br />AssemblyInfo:<br /></p>
<pre><code>[assembly: WebResource("CompanyProduct.Library.navigation.js", "text/javascript")]
</code></pre>
<p><br />Code in master page:<br /></p>
<pre><code>Page.ClientScript.RegisterClientScriptInclude("NavigationScript", Page.ClientScript.GetWebResourceUrl(this.GetType(), "CompanyProduct.Library.navigation.js"));
</code></pre>
<p><H1>Server Error in '/' Application.</H1>
<h2> <i>The resource cannot be found.</i> </h2>
<b> Description: </b>HTTP 404. The resource you are looking for (or one of its dependencies) could have been removed, had its name changed, or is temporarily unavailable. Please review the following URL and make sure that it is spelled correctly.
<br><br>
<b> Requested URL: </b>/WebResource.axd<br>
<b>Version Information:</b> Microsoft .NET Framework Version:2.0.50727.1433; ASP.NET Version:2.0.50727.1433</p>
| [
{
"answer_id": 322635,
"author": "Thomas Hansen",
"author_id": 29746,
"author_profile": "https://Stackoverflow.com/users/29746",
"pm_score": 0,
"selected": false,
"text": "Page.ClientScript.RegisterClientScriptInclude(\"NavigationScript\"...\n Page.ClientScript.RegisterClientScriptInclude(\"CompanyProduct.Library.navigation.js\"...\n"
},
{
"answer_id": 526007,
"author": "meandmycode",
"author_id": 63751,
"author_profile": "https://Stackoverflow.com/users/63751",
"pm_score": 5,
"selected": true,
"text": "this.GetType() typeof(Company.Product.Web.Library.Class1)\n"
},
{
"answer_id": 592916,
"author": "Helephant",
"author_id": 13028,
"author_profile": "https://Stackoverflow.com/users/13028",
"pm_score": 1,
"selected": false,
"text": "<httpHandlers>\n <add path=\"WebResource.axd\" verb=\"GET\" type=\"System.Web.Handlers.AssemblyResourceLoader\" validate=\"True\"/>\n</httpHandlers>\n"
},
{
"answer_id": 3440279,
"author": "dh.",
"author_id": 266584,
"author_profile": "https://Stackoverflow.com/users/266584",
"pm_score": 2,
"selected": false,
"text": "GetWebResourceUrl typeof Page.ClientScript.RegisterClientScriptInclude(\n \"NavigationScript\",\n Page.ClientScript.GetWebResourceUrl(\n typeof(MyMasterPage),\n \"CompanyProduct.Library.navigation.js\"));\n"
},
{
"answer_id": 4443894,
"author": "david",
"author_id": 542515,
"author_profile": "https://Stackoverflow.com/users/542515",
"pm_score": 1,
"selected": false,
"text": "GetWebResourceUrl() GetWebResourceUrl() GetWebResourceUrl(typeof(MasterPage)"
},
{
"answer_id": 5745363,
"author": "jaraics",
"author_id": 113108,
"author_profile": "https://Stackoverflow.com/users/113108",
"pm_score": 0,
"selected": false,
"text": "string[] embeddedResNames = Assembly.LoadFile(\"YourDll.dll\").GetManifestResourceNames()\n"
},
{
"answer_id": 7915525,
"author": "mizuki nakeshu",
"author_id": 1016410,
"author_profile": "https://Stackoverflow.com/users/1016410",
"pm_score": 0,
"selected": false,
"text": "GetWebResourceUrl static public string GetEmbeddedResourceLink(Page page, string assemblyName, string resource) {\n var assembly = Assembly.Load(assemblyName);\n var types = assembly.GetTypes();\n if (types.Length == 0) {\n throw new ArgumentException(\"assembly does not contain any type\");\n }\n return page.ClientScript.GetWebResourceUrl(types[0], resource);\n}\n"
},
{
"answer_id": 14636991,
"author": "Mark Dornian",
"author_id": 1864995,
"author_profile": "https://Stackoverflow.com/users/1864995",
"pm_score": 1,
"selected": false,
"text": "ScriptManager.RegisterClientScriptInclude"
},
{
"answer_id": 19523018,
"author": "Guish",
"author_id": 1456661,
"author_profile": "https://Stackoverflow.com/users/1456661",
"pm_score": 1,
"selected": false,
"text": "Page.ClientScript.GetWebResourceUrl"
},
{
"answer_id": 64449916,
"author": "NightOwl888",
"author_id": 181087,
"author_profile": "https://Stackoverflow.com/users/181087",
"pm_score": 0,
"selected": false,
"text": "WebResource.axd"
}
] | 2008/11/26 | [
"https://Stackoverflow.com/questions/320484",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/40986/"
] |
320,500 | <p>I'm generating compiled getter methods at runtime for a given member. Right now, my code just assumes that the result of the getter method is a string (worked good for testing). However, I'd like to make this work with a custom converter class I've written, see below, "ConverterBase" reference that I've added.</p>
<p>I can't figure out how to add the call to the converter class to my expression tree.</p>
<pre><code> public Func<U, string> GetGetter<U>(MemberInfo info)
{
Type t = null;
if (info is PropertyInfo)
{
t = ((PropertyInfo)info).PropertyType;
}
else if (info is FieldInfo)
{
t = ((FieldInfo)info).FieldType;
}
else
{
throw new Exception("Unknown member type");
}
//TODO, replace with ability to specify in custom attribute
ConverterBase typeConverter = new ConverterBase();
ParameterExpression target = Expression.Parameter(typeof(U), "target");
MemberExpression memberAccess = Expression.MakeMemberAccess(target, info);
//TODO here, make the expression call "typeConverter.FieldToString(fieldValue)"
LambdaExpression getter = Expression.Lambda(memberAccess, target);
return (Func<U, string>)getter.Compile();
}
</code></pre>
<p>I'm looking for what to put in the second TODO area (I can handle the first :)).</p>
<p>The resulting compiled lambda should take an instance of type U as a param, call the specified member access function, then call the converter's "FieldToString" method with the result, and return the resulting string.</p>
| [
{
"answer_id": 320507,
"author": "Barry Kelly",
"author_id": 3712,
"author_profile": "https://Stackoverflow.com/users/3712",
"pm_score": 2,
"selected": false,
"text": "class MyConverter\n{\n public string MyToString(int x)\n {\n return x.ToString();\n }\n}\n\nstatic void Main()\n{\n MyConverter c = new MyConverter();\n\n ParameterExpression p = Expression.Parameter(typeof(int), \"p\");\n LambdaExpression intToStr = Expression.Lambda(\n Expression.Call(\n Expression.Constant(c),\n c.GetType().GetMethod(\"MyToString\"),\n p),\n p);\n\n Func<int,string> f = (Func<int,string>) intToStr.Compile();\n\n Console.WriteLine(f(42));\n Console.ReadLine();\n}\n"
},
{
"answer_id": 320518,
"author": "Marc Gravell",
"author_id": 23354,
"author_profile": "https://Stackoverflow.com/users/23354",
"pm_score": 4,
"selected": true,
"text": " ConverterBase typeConverter = new ConverterBase();\n var target = Expression.Parameter(typeof(U), \"target\");\n var getter = Expression.MakeMemberAccess(target, info);\n var converter = Expression.Constant(typeConverter, typeof(ConverterBase));\n\n return Expression.Lambda<Func<U, string>>(\n Expression.Call(converter, typeof(ConverterBase).GetMethod(\"FieldToString\"),\n getter), target).Compile();\n MethodInfo method = typeof(ConverterBase).GetMethod(\"FieldToString\");\n return Expression.Lambda<Func<U, string>>(\n Expression.Call(converter, method,\n Expression.Convert(getter, method.GetParameters().Single().ParameterType)),\n target).Compile();\n"
}
] | 2008/11/26 | [
"https://Stackoverflow.com/questions/320500",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18941/"
] |
320,501 | <p>I have MAMP set up on my iMac and on my Macbook. I want to keep both installs synced using <a href="http://www.getdropbox.com" rel="noreferrer">dropbox</a>. When upgrading MAMP the only 2 folders you need to transfer are 'db' & 'htdocs'. My theory is then that these are the only 2 folders I need to keep in sync. Sound right to you so far?</p>
<p>Syncing the 'htdocs' folder is easy as you can put it in your dropbox and point the MAMP preferences to the dropbox folder, but the 'db' folder has no such option.</p>
<p>Any suggestions on how I could keep the 'db' folder synced? Thanks.</p>
| [
{
"answer_id": 323795,
"author": "dbr",
"author_id": 745,
"author_profile": "https://Stackoverflow.com/users/745",
"pm_score": 1,
"selected": false,
"text": ".sql importdatabase dumpdatabase db /Applications/MAMP/db/ ln -s /Applications/MAMP/db/ /Volumes/DropBoxFolder/db/"
}
] | 2008/11/26 | [
"https://Stackoverflow.com/questions/320501",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/38020/"
] |
320,506 | <p>Consider the following piece of Java code.</p>
<pre><code>int N = 10;
Object obj[] = new Object[N];
for (int i = 0; i < N; i++) {
int capacity = 1000 * i;
obj[i] = new ArrayList(capacity);
}
</code></pre>
<p>Because in Java, all objects live on the Heap, the array does not
contain the objects themselves, but references to the objects. Also,
the array itself is also an object, thus it lives on the heap.</p>
<p>What is the equivalent in C++, but keeping the array and objects on
the stack, to avoid as much as possible needing new and delete ?</p>
<p>Edit: changed the code to use a custom constructor.</p>
| [
{
"answer_id": 320512,
"author": "Joris Timmermans",
"author_id": 33987,
"author_profile": "https://Stackoverflow.com/users/33987",
"pm_score": 3,
"selected": false,
"text": "Object array_of_objects[10];\n"
},
{
"answer_id": 320514,
"author": "Johannes Schaub - litb",
"author_id": 34509,
"author_profile": "https://Stackoverflow.com/users/34509",
"pm_score": 2,
"selected": false,
"text": "int N = 10;\nstd::vector<Object> obj(N);\n// non-default ctor: std::vector<Object> obj(N, Object(a1, a2));\n// now they are all initialized and ready to be used\n int const N = 10;\nObject obj[N];\n// non-default ctor: Object obj[N] = \n// { Object(a1, a2), Object(a2, a3), ... (up to N times) };\n// now they are all initialized and ready to be used\n int const N = 10;\nboost::array<Object, N> obj;\n// non-default ctor: boost::array<Object, N> obj = \n// { { Object(a1, a2), Object(a2, a3), ... (up to N times) } };\n// now they are all initialized and ready to be used\n"
},
{
"answer_id": 320515,
"author": "Steve Jessop",
"author_id": 13005,
"author_profile": "https://Stackoverflow.com/users/13005",
"pm_score": 3,
"selected": true,
"text": "ArrayList obj[10];\n std::vector<ArrayList> obj(10, ArrayList());\n"
},
{
"answer_id": 320536,
"author": "Nils Pipenbrinck",
"author_id": 15955,
"author_profile": "https://Stackoverflow.com/users/15955",
"pm_score": 2,
"selected": false,
"text": "// allocate storage for N objects on the stack\n// you may have to call _alloca and include something to use this.\nobject * data = (object *) alloca (N * sizeof (object));\n\n// initialize via placement new.\nfor (int i=0; i<N; i++)\n new (&data[i])();\n"
},
{
"answer_id": 320562,
"author": "xtofl",
"author_id": 6610,
"author_profile": "https://Stackoverflow.com/users/6610",
"pm_score": 2,
"selected": false,
"text": "int myarray[10];\n alloca int* myarray = (int*) alloca( n*sizeof(int) );\n std::vector vector"
},
{
"answer_id": 20359570,
"author": "Elliott",
"author_id": 1030331,
"author_profile": "https://Stackoverflow.com/users/1030331",
"pm_score": 0,
"selected": false,
"text": "//the following ints will all be stored on the stack,\n//and a heap allocation is never performed to store the array\nQVarLengthArray<int, 10> objArray;\nfor (int i = 0; i < 8; i++) {\n int capacity = 1000 * i;\n objArray.push_back(capacity);\n}\n\n//since it's a class and not a raw array, we can get the array's size\nstd::cout << objArray.size(); //result is 8\n\n//a heap allocation will be performed if we add an eleventh item,\n//since the template parameter of 10 says to only statically allocate 10 items\nobjArray.push_back(0); //9 items\nobjArray.push_back(0); //10 items\nobjArray.push_back(0); //11 items - heap allocation is performed\n"
}
] | 2008/11/26 | [
"https://Stackoverflow.com/questions/320506",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15649/"
] |
320,509 | <p>I'm sure this must be possible, but I can't find out how to do it.</p>
<p>Any clues?</p>
| [
{
"answer_id": 320539,
"author": "Alex",
"author_id": 26564,
"author_profile": "https://Stackoverflow.com/users/26564",
"pm_score": 4,
"selected": false,
"text": "$startinfo = new-object System.Diagnostics.ProcessStartInfo \n$startinfo.FileName = \"explorer.exe\"\n$startinfo.WorkingDirectory = 'D:\\foldername'\n\n[System.Diagnostics.Process]::Start($startinfo)\n"
},
{
"answer_id": 320573,
"author": "tomasr",
"author_id": 10292,
"author_profile": "https://Stackoverflow.com/users/10292",
"pm_score": 5,
"selected": false,
"text": "Invoke-Item Invoke-Item .\n"
},
{
"answer_id": 320581,
"author": "Daniel Kreiseder",
"author_id": 31406,
"author_profile": "https://Stackoverflow.com/users/31406",
"pm_score": 5,
"selected": false,
"text": "explorer .\n"
},
{
"answer_id": 320609,
"author": "codeape",
"author_id": 3571,
"author_profile": "https://Stackoverflow.com/users/3571",
"pm_score": 7,
"selected": false,
"text": "PS C:\\> explorer\nPS C:\\> explorer .\nPS C:\\> explorer /n\nPS C:\\> Invoke-Item c:\\path\\\nPS C:\\> ii c:\\path\\\nPS C:\\> Invoke-Item c:\\windows\\explorer.exe\nPS C:\\> ii c:\\windows\\explorer.exe\nPS C:\\> [diagnostics.process]::start(\"explorer.exe\")\n"
},
{
"answer_id": 321092,
"author": "EBGreen",
"author_id": 1358,
"author_profile": "https://Stackoverflow.com/users/1358",
"pm_score": 11,
"selected": true,
"text": "ii .\n Invoke-Item .\n"
},
{
"answer_id": 2698556,
"author": "powershelluser",
"author_id": 324190,
"author_profile": "https://Stackoverflow.com/users/324190",
"pm_score": 3,
"selected": false,
"text": "start explorer.exe \n"
},
{
"answer_id": 12162855,
"author": "shovavnik",
"author_id": 213343,
"author_profile": "https://Stackoverflow.com/users/213343",
"pm_score": 5,
"selected": false,
"text": "Invoke-Expression \"explorer '/select,$filePath'\"\n"
},
{
"answer_id": 39157636,
"author": "T Sandwich",
"author_id": 1339972,
"author_profile": "https://Stackoverflow.com/users/1339972",
"pm_score": 2,
"selected": false,
"text": "Invoke-Item C:\\Users\\Foo\\bar.txt\nexplorer.exe C:\\Users\\Foo\\bar.html\n $foo = \"C:\\Users\\Foo\\foo.txt\" \n[some code] $fooPath\n# opens C:\\Users\\Foo\\ and not the default program for .txt file extension\n"
},
{
"answer_id": 43268778,
"author": "20B2",
"author_id": 6293412,
"author_profile": "https://Stackoverflow.com/users/6293412",
"pm_score": 6,
"selected": false,
"text": "start . explorer . start explorer . ii . invoke-item ."
},
{
"answer_id": 44479403,
"author": "Beej",
"author_id": 813599,
"author_profile": "https://Stackoverflow.com/users/813599",
"pm_score": 2,
"selected": false,
"text": "$objShell = New-Object -ComObject \"Shell.Application\"\n$objShell.Explore(\"path\")\n"
},
{
"answer_id": 66024232,
"author": "mutong",
"author_id": 9596327,
"author_profile": "https://Stackoverflow.com/users/9596327",
"pm_score": 2,
"selected": false,
"text": "explorer .\\"
}
] | 2008/11/26 | [
"https://Stackoverflow.com/questions/320509",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1088682/"
] |
320,510 | <p>What would be the easiest way to view classes, methods, properties, etc. inside a jar file?
I'm looking for something equivalent to the very useful <I> Lutz Roeder .NET Reflector </I> - for Java</p>
| [
{
"answer_id": 321029,
"author": "Tom Hawtin - tackline",
"author_id": 4725,
"author_profile": "https://Stackoverflow.com/users/4725",
"pm_score": 8,
"selected": false,
"text": "jar -tf javap"
},
{
"answer_id": 991151,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 4,
"selected": false,
"text": "jar tvf jarfile.jar"
},
{
"answer_id": 12940118,
"author": "james",
"author_id": 1486944,
"author_profile": "https://Stackoverflow.com/users/1486944",
"pm_score": 2,
"selected": false,
"text": "jar -tf .\\[JAR_NAME] | where {$_ -match \"[FILENAME]\"}\n"
},
{
"answer_id": 31698573,
"author": "Jose Miguel",
"author_id": 1134604,
"author_profile": "https://Stackoverflow.com/users/1134604",
"pm_score": 4,
"selected": false,
"text": "jar tf my-fat-jar-file.jar | grep filename"
},
{
"answer_id": 33690835,
"author": "Some Java Guy",
"author_id": 387774,
"author_profile": "https://Stackoverflow.com/users/387774",
"pm_score": 3,
"selected": false,
"text": "F2 & Rename to jarfile.zip jar tvf jarfile.jar jar tf jarfile.jar"
},
{
"answer_id": 42365315,
"author": "Amit",
"author_id": 4039431,
"author_profile": "https://Stackoverflow.com/users/4039431",
"pm_score": 6,
"selected": false,
"text": "unzip unzip -l <jar-file-name>.jar test.jar unzip -l test.jar 7 zip JDK zipinfo <your jar file>"
},
{
"answer_id": 49889949,
"author": "MyounghoonKim",
"author_id": 1115332,
"author_profile": "https://Stackoverflow.com/users/1115332",
"pm_score": 0,
"selected": false,
"text": "java -xf some-j.jar"
},
{
"answer_id": 53865509,
"author": "Anil Kapoor",
"author_id": 2955930,
"author_profile": "https://Stackoverflow.com/users/2955930",
"pm_score": 4,
"selected": false,
"text": "jar -tvf file_name.jar\n jar -xvf file_name.jar\n"
},
{
"answer_id": 55001762,
"author": "Subhashree Pradhan",
"author_id": 7353353,
"author_profile": "https://Stackoverflow.com/users/7353353",
"pm_score": 2,
"selected": false,
"text": "unzip -p myjar.jar myfile.txt\n"
},
{
"answer_id": 67408824,
"author": "grepit",
"author_id": 717630,
"author_profile": "https://Stackoverflow.com/users/717630",
"pm_score": 0,
"selected": false,
"text": "$(find / -type f -name \"jar\" 2>&1 |grep '/JDK' |head -1 ) tf FULLY_QUALIFIED_NAME_TO_YOUR_FILE\n"
}
] | 2008/11/26 | [
"https://Stackoverflow.com/questions/320510",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/28772/"
] |
320,523 | <p>I have a loop on page to update an access database that takes 15-20 seconds to complete. I only run it once a month at most but I noticed that every time I run it the web site (IIS 6) simply stops serving pages.</p>
<p>After the loop ends, pages begin opening again.</p>
<p>Here's my code:</p>
<pre><code>For each Email in Emails
if Trim(Email) <> "" then
' execute the update
Set MM_editCmd = Server.CreateObject("ADODB.Command")
MM_editCmd.ActiveConnection = MM_Customers_STRING
MM_editCmd.CommandText = "UPDATE Customers SET MailingListUpdates=False WHERE Email='" & Trim(Email) & "'"
MM_editCmd.Execute
MM_editCmd.ActiveConnection.Close
Response.Write "Email address " & Email & " successfully removed from the mailing list.<br>"
end if
Next
</code></pre>
<p>Is there anything I can do to avoid this?</p>
<p>Emails on the last update was around 700 records.</p>
| [
{
"answer_id": 320612,
"author": "Martin Brown",
"author_id": 20553,
"author_profile": "https://Stackoverflow.com/users/20553",
"pm_score": 3,
"selected": true,
"text": "Set MM_editCmd = Server.CreateObject(\"ADODB.Command\")\nMM_editCmd.ActiveConnection = MM_Customers_STRING\nFor each Email in Emails\n if Trim(Email) <> \"\" then\n ' execute the update\n MM_editCmd.CommandText = \"UPDATE Customers SET MailingListUpdates=False WHERE Email='\" & Trim(Email) & \"'\"\n MM_editCmd.Execute\n Response.Write \"Email address \" & Email & \" successfully removed from the mailing list.<br>\"\n end if\nNext\nMM_editCmd.ActiveConnection.Close\n"
},
{
"answer_id": 320613,
"author": "AnthonyWJones",
"author_id": 17516,
"author_profile": "https://Stackoverflow.com/users/17516",
"pm_score": 2,
"selected": false,
"text": "Dim con : Set con = Server.CreateObject(\"ADODB.Connection\")\nDim cmd : Set cmd = Server.CreateObject(\"ADODB.Command\")\ncon.Open MM_Customers_STRING\nSet cmd.ActiveConnection = con\ncmd.CommandType = 1 // adCmdText (note SO not good at detecting VB comment)\ncmd.CommandText = \"UPDATE Customers SET MailingListUpdates=False WHERE Email=?\"\nDim param : Set param = cmd.CreateParameter(\"email\", 200, 1, 50) // adVarChar, adParamInput, size: 50\ncmd.Parameters.Append param\nDim Email\nFor Each Email in Emails\n Email = Trim(Email)\n If Email <> \"\" Then\n param.value = Email\n cmd.Execute\n End If\nNext\ncon.Close\n"
}
] | 2008/11/26 | [
"https://Stackoverflow.com/questions/320523",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/36544/"
] |
320,532 | <p>How can I simplify a basic arithmetic expression?</p>
<p>e.g.</p>
<pre><code>module ExprOps where
simplify :: Expr -> Expr
simplify (Plus(Var"x") (Const 0)) = Var "x"
</code></pre>
<p>What do I have to do?</p>
<hr>
<pre><code>module Expr where
-- Variables are named by strings, assumed to be identifiers.
type Variable = String
-- Representation of expressions.
data Expr = Const Integer
| Var Variable
| Plus Expr Expr
| Minus Expr Expr
| Mult Expr Expr
deriving (Eq, Show)
</code></pre>
<p>The simplifications I have in mind are:</p>
<pre><code>0*e = e*0 = 0
1*e = e*1 = 0+e = e+0 = e-0 = e
</code></pre>
<p>and simplifying constant subexpressions, e.g. Plus (Const 1) (Const 2) would become Const 3. I would not expect variables (or variables and constants) to be concatenated: Var "st" is a distinct variable from Var "s". </p>
<p>What I want to achieve is to create a module like the one above that uses a function called <code>simplify :: Expr->Expr</code></p>
| [
{
"answer_id": 321381,
"author": "Edward Kmett",
"author_id": 34707,
"author_profile": "https://Stackoverflow.com/users/34707",
"pm_score": 4,
"selected": false,
"text": "simplify :: Expr -> Expr \nsimplify (Mult (Const 0) x) = Const 0 \nsimplify (Mult x (Const 0)) = Const 0\nsimplify (Plus (Const 0) x) = simplify x\nsimplify (Plus x (Const 0)) = simplify x \nsimplify (Mult (Const 1) x) = simplify x \nsimplify (Mult x (Const 1)) = simplify x \nsimplify (Minus x (Const 0)) = simpify x\nsimplify (Plus (Const x) (Const y)) = Const (x + y)\nsimplify (Minus (Const x) (Const y)) = Const (x - y)\nsimplify (Mult (Const x) (Const y)) = Const (x * y)\nsimplify x = x\n"
},
{
"answer_id": 1314598,
"author": "Michael Steele",
"author_id": 71116,
"author_profile": "https://Stackoverflow.com/users/71116",
"pm_score": 1,
"selected": false,
"text": "simplify :: Expr -> Expr\nsimplify (Plus l (Const 0)) = simplify l\nsimplify (Plus (Const 0) r ) = simplify r\nsimplify x = x\n"
}
] | 2008/11/26 | [
"https://Stackoverflow.com/questions/320532",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/41000/"
] |
320,535 | <p>Edit: Closing this because i've found the reason why it's erroring, but instead of removing this post .. i generate a newer post with a more refined question.</p>
<hr>
<p>Hi folks,</p>
<p>i have some binary data i've read in. i wish to convert it to an <code>System.Drawing.Image</code>, so i create an instance of an <code>Image object</code>, using a <code>memory stream</code> as the input data. </p>
<p>After i've done that, i serialize then deserialize the image (for some business logic). The deserialize throws an exception. If i create the <code>Image</code> instance with the file name constructor instead of the memory stream constructor, it all works 100%. This suggests that the <code>Image</code> object can be serialized over the wire.</p>
<p>What am i doing wrong with <code>memory stream</code>, i've used?</p>
<p>this is the code i use to make the Image object, before it gets serialized:-</p>
<pre><code>// Fake way of getting some binary (image) data.
byte[] data = File.ReadAllBytes("Chick.jpg");
using (Stream originalBinaryDataStream = new MemoryStream(data))
{
// This works perfectly fine, if use this method (which i can't).
//image = new Bitmap("Chick.jpg");
// This throws an exception when it's deserialized.
// It doesn't like the memory stream reference?
image = new Bitmap(originalBinaryDataStream);
}
</code></pre>
<p>this is the code that tries to deserialize the image, which throws an exception (<a href="http://img254.imageshack.us/img254/9748/step1zx3wk5.png" rel="nofollow noreferrer">this is a seperate image of the exception</a>)</p>
<p><a href="http://img254.imageshack.us/img254/9748/step1zx3wk5.png" rel="nofollow noreferrer">alt text http://img254.imageshack.us/img254/9748/step1zx3wk5.png</a></p>
<p>is there something that is not correctly disposed off OR cannot be serialised .. hence throwing the exception?</p>
<p>Please help :)</p>
<hr>
<p>EDIT: The exception is called in my <em>Image Debugger Visualizer</em>. </p>
<p>I've uploaded the complete VS2008 solution <a href="http://drop.io/lssibqa" rel="nofollow noreferrer">here</a> (1.28MB download). </p>
<p>In it are two projects -> the <strong>visualizer class</strong> and the <strong>MS Test class</strong>. If u run the only unit test, it will throw the generic (read: useless) GDI+ exception as it fails to deserialize the Image instance that was passed across the wire to the debugger viz. If you passed it an Image instance that was created using the file path constructor, the deserialization works perfectly.</p>
<p>EDIT 2: used a different file upload site - cheers!</p>
<p>EDIT 3: How to actually reproduce the error. </p>
<ul>
<li>Change project to DEBUG mode (not release mode)</li>
<li>Remove all break points.</li>
<li>Open up ImageDebuggerVisualizer.cs</li>
<li>Add a breakpoint to line 22.</li>
<li>Now <em>debug</em> the UnitTest1 unit test method. An image will show .. close that window .. then suddenly you will be on the break point. step over that and BOOM!!!! CRASH!! BANG.</li>
</ul>
<p>EDIT 4: Here are two SCREEN SHOTS of the exception (if you don't want to download the solution file).</p>
<ul>
<li><a href="http://img254.imageshack.us/img254/9748/step1zx3wk5.png" rel="nofollow noreferrer">Before I step over the offending line</a></li>
<li><a href="http://img383.imageshack.us/img383/1677/step2uj0.png" rel="nofollow noreferrer">After I step over the offending line</a>, where the exception is thrown.</li>
</ul>
| [
{
"answer_id": 320561,
"author": "Ovidiu Pacurar",
"author_id": 28419,
"author_profile": "https://Stackoverflow.com/users/28419",
"pm_score": 2,
"selected": false,
"text": "private void Form1_Load(object sender, EventArgs e) \n {\n byte[] data = File.ReadAllBytes(\"c:\\\\t.jpg\");\n\n using (Stream originalBinaryDataStream = new MemoryStream(data))\n {\n // This works perfectly fine, if use this method (which i can't).\n //image = new Bitmap(\"Chick.jpg\");\n\n\n // This throws an exception when it's deserialized.\n // It doesn't like the memory stream reference?\n originalBinaryDataStream.Seek(0, SeekOrigin.End);\n pictureBox1.Image= new Bitmap(originalBinaryDataStream);\n }\n }\n"
},
{
"answer_id": 320564,
"author": "Marc Gravell",
"author_id": 23354,
"author_profile": "https://Stackoverflow.com/users/23354",
"pm_score": 2,
"selected": false,
"text": "MemoryStream"
}
] | 2008/11/26 | [
"https://Stackoverflow.com/questions/320535",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/30674/"
] |
320,542 | <p>My code runs inside a JAR file, say <strong>foo.jar</strong>, and I need to know, in the code, in which folder the running <strong>foo.jar</strong> is.</p>
<p>So, if <strong>foo.jar</strong> is in <code>C:\FOO\</code>, I want to get that path no matter what my current working directory is.</p>
| [
{
"answer_id": 320554,
"author": "Jon Skeet",
"author_id": 22656,
"author_profile": "https://Stackoverflow.com/users/22656",
"pm_score": 5,
"selected": false,
"text": "package foo;\n\npublic class Test\n{\n public static void main(String[] args)\n {\n ClassLoader loader = Test.class.getClassLoader();\n System.out.println(loader.getResource(\"foo/Test.class\"));\n }\n}\n"
},
{
"answer_id": 320595,
"author": "Zarkonnen",
"author_id": 15255,
"author_profile": "https://Stackoverflow.com/users/15255",
"pm_score": 10,
"selected": true,
"text": "return new File(MyClass.class.getProtectionDomain().getCodeSource().getLocation()\n .toURI()).getPath();\n"
},
{
"answer_id": 4189058,
"author": "ZZZ",
"author_id": 508801,
"author_profile": "https://Stackoverflow.com/users/508801",
"pm_score": 2,
"selected": false,
"text": "String path = getClass().getResource(\"\").getPath();\n"
},
{
"answer_id": 5667601,
"author": "Bacup Lad",
"author_id": 708497,
"author_profile": "https://Stackoverflow.com/users/708497",
"pm_score": -1,
"selected": false,
"text": "\n private String getJarFolder() {\n String name = this.getClass().getName().replace('.', '/');\n String s = this.getClass().getResource(\"/\" + name + \".class\").toString();\n s = s.replace('/', File.separatorChar);\n s = s.substring(0, s.indexOf(\".jar\")+4);\n s = s.substring(s.lastIndexOf(':')-1);\n return s.substring(0, s.lastIndexOf(File.separatorChar)+1);\n } \n\n"
},
{
"answer_id": 5678263,
"author": "bacup lad",
"author_id": 709985,
"author_profile": "https://Stackoverflow.com/users/709985",
"pm_score": 2,
"selected": false,
"text": " private String getJarFolder() {\n // get name and path\n String name = getClass().getName().replace('.', '/');\n name = getClass().getResource(\"/\" + name + \".class\").toString();\n // remove junk\n name = name.substring(0, name.indexOf(\".jar\"));\n name = name.substring(name.lastIndexOf(':')-1, name.lastIndexOf('/')+1).replace('%', ' ');\n // remove escape characters\n String s = \"\";\n for (int k=0; k<name.length(); k++) {\n s += name.charAt(k);\n if (name.charAt(k) == ' ') k += 2;\n }\n // replace '/' with system separator char\n return s.replace('/', File.separatorChar);\n }\n"
},
{
"answer_id": 6849255,
"author": "Fab",
"author_id": 866064,
"author_profile": "https://Stackoverflow.com/users/866064",
"pm_score": 8,
"selected": false,
"text": "String path = Test.class.getProtectionDomain().getCodeSource().getLocation().getPath();\nString decodedPath = URLDecoder.decode(path, \"UTF-8\");\n"
},
{
"answer_id": 7060464,
"author": "Benny Neugebauer",
"author_id": 451634,
"author_profile": "https://Stackoverflow.com/users/451634",
"pm_score": 6,
"selected": false,
"text": "CodeSource codeSource = YourMainClass.class.getProtectionDomain().getCodeSource();\nFile jarFile = new File(codeSource.getLocation().toURI().getPath());\nString jarDir = jarFile.getParentFile().getPath();\n"
},
{
"answer_id": 7579697,
"author": "lviggiani",
"author_id": 645854,
"author_profile": "https://Stackoverflow.com/users/645854",
"pm_score": 2,
"selected": false,
"text": " try {\n return URLDecoder.decode(ClassLoader.getSystemClassLoader().getResource(\".\").getPath(), \"UTF-8\");\n } catch (UnsupportedEncodingException e) {\n return \"\";\n }\n"
},
{
"answer_id": 9924414,
"author": "Zon",
"author_id": 1112963,
"author_profile": "https://Stackoverflow.com/users/1112963",
"pm_score": 3,
"selected": false,
"text": "String path = \n YourMainClassName.class.getProtectionDomain().\n getCodeSource().getLocation().getPath();\n\npath = \n URLDecoder.decode(\n path, \n \"UTF-8\");\n\nBufferedImage img = \n ImageIO.read(\n new File((\n new File(path).getParentFile().getPath()) + \n File.separator + \n \"folder\" + \n File.separator + \n \"yourfile.jpg\"));\n"
},
{
"answer_id": 12733172,
"author": "ctrueden",
"author_id": 1207769,
"author_profile": "https://Stackoverflow.com/users/1207769",
"pm_score": 7,
"selected": false,
"text": "File Class Class URL URL File File getParentFile Class URL URL Class URL url = Bar.class.getProtectionDomain().getCodeSource().getLocation(); URL url = Bar.class.getResource(Bar.class.getSimpleName() + \".class\"); getProtectionDomain SecurityException getProtectionDomain() getResource file: jar:file: bundleresource://346.fwk2106232034:4/foo/Bar.class getProtectionDomain file: getResource(\"\") getResource(\".\") URL File URL File new File(url.toURI()) URLDecoder : / URLDecoder IllegalArgumentException %20 + URLDecoder /**\n * Gets the base location of the given class.\n * <p>\n * If the class is directly on the file system (e.g.,\n * \"/path/to/my/package/MyClass.class\") then it will return the base directory\n * (e.g., \"file:/path/to\").\n * </p>\n * <p>\n * If the class is within a JAR file (e.g.,\n * \"/path/to/my-jar.jar!/my/package/MyClass.class\") then it will return the\n * path to the JAR (e.g., \"file:/path/to/my-jar.jar\").\n * </p>\n *\n * @param c The class whose location is desired.\n * @see FileUtils#urlToFile(URL) to convert the result to a {@link File}.\n */\npublic static URL getLocation(final Class<?> c) {\n if (c == null) return null; // could not load the class\n\n // try the easy way first\n try {\n final URL codeSourceLocation =\n c.getProtectionDomain().getCodeSource().getLocation();\n if (codeSourceLocation != null) return codeSourceLocation;\n }\n catch (final SecurityException e) {\n // NB: Cannot access protection domain.\n }\n catch (final NullPointerException e) {\n // NB: Protection domain or code source is null.\n }\n\n // NB: The easy way failed, so we try the hard way. We ask for the class\n // itself as a resource, then strip the class's path from the URL string,\n // leaving the base path.\n\n // get the class's raw resource path\n final URL classResource = c.getResource(c.getSimpleName() + \".class\");\n if (classResource == null) return null; // cannot find class resource\n\n final String url = classResource.toString();\n final String suffix = c.getCanonicalName().replace('.', '/') + \".class\";\n if (!url.endsWith(suffix)) return null; // weird URL\n\n // strip the class's path from the URL string\n final String base = url.substring(0, url.length() - suffix.length());\n\n String path = base;\n\n // remove the \"jar:\" prefix and \"!/\" suffix, if present\n if (path.startsWith(\"jar:\")) path = path.substring(4, path.length() - 2);\n\n try {\n return new URL(path);\n }\n catch (final MalformedURLException e) {\n e.printStackTrace();\n return null;\n }\n} \n\n/**\n * Converts the given {@link URL} to its corresponding {@link File}.\n * <p>\n * This method is similar to calling {@code new File(url.toURI())} except that\n * it also handles \"jar:file:\" URLs, returning the path to the JAR file.\n * </p>\n * \n * @param url The URL to convert.\n * @return A file path suitable for use with e.g. {@link FileInputStream}\n * @throws IllegalArgumentException if the URL does not correspond to a file.\n */\npublic static File urlToFile(final URL url) {\n return url == null ? null : urlToFile(url.toString());\n}\n\n/**\n * Converts the given URL string to its corresponding {@link File}.\n * \n * @param url The URL to convert.\n * @return A file path suitable for use with e.g. {@link FileInputStream}\n * @throws IllegalArgumentException if the URL does not correspond to a file.\n */\npublic static File urlToFile(final String url) {\n String path = url;\n if (path.startsWith(\"jar:\")) {\n // remove \"jar:\" prefix and \"!/\" suffix\n final int index = path.indexOf(\"!/\");\n path = path.substring(4, index);\n }\n try {\n if (PlatformUtils.isWindows() && path.matches(\"file:[A-Za-z]:.*\")) {\n path = \"file:/\" + path.substring(5);\n }\n return new File(new URL(path).toURI());\n }\n catch (final MalformedURLException e) {\n // NB: URL is not completely well-formed.\n }\n catch (final URISyntaxException e) {\n // NB: URL is not completely well-formed.\n }\n if (path.startsWith(\"file:\")) {\n // pass through the URL as-is, minus \"file:\" prefix\n path = path.substring(5);\n return new File(path);\n }\n throw new IllegalArgumentException(\"Invalid URL: \" + url);\n}\n"
},
{
"answer_id": 15831228,
"author": "Denton",
"author_id": 2248569,
"author_profile": "https://Stackoverflow.com/users/2248569",
"pm_score": 2,
"selected": false,
"text": "public static String dir() throws URISyntaxException\n{\n URI path=Main.class.getProtectionDomain().getCodeSource().getLocation().toURI();\n String name= Main.class.getPackage().getName()+\".jar\";\n String path2 = path.getRawPath();\n path2=path2.substring(1);\n\n if (path2.contains(\".jar\"))\n {\n path2=path2.replace(name, \"\");\n }\n return path2;}\n"
},
{
"answer_id": 16775059,
"author": "Charlie",
"author_id": 2425320,
"author_profile": "https://Stackoverflow.com/users/2425320",
"pm_score": 3,
"selected": false,
"text": "File currentJavaJarFile = new File(Main.class.getProtectionDomain().getCodeSource().getLocation().getPath()); \nString currentJavaJarFilePath = currentJavaJarFile.getAbsolutePath();\nString currentRootDirectoryPath = currentJavaJarFilePath.replace(currentJavaJarFile.getName(), \"\");\n"
},
{
"answer_id": 18341646,
"author": "Dmitry Trofimov",
"author_id": 429873,
"author_profile": "https://Stackoverflow.com/users/429873",
"pm_score": 4,
"selected": false,
"text": "public static String getJarContainingFolder(Class aclass) throws Exception {\n CodeSource codeSource = aclass.getProtectionDomain().getCodeSource();\n\n File jarFile;\n\n if (codeSource.getLocation() != null) {\n jarFile = new File(codeSource.getLocation().toURI());\n }\n else {\n String path = aclass.getResource(aclass.getSimpleName() + \".class\").getPath();\n String jarFilePath = path.substring(path.indexOf(\":\") + 1, path.indexOf(\"!\"));\n jarFilePath = URLDecoder.decode(jarFilePath, \"UTF-8\");\n jarFile = new File(jarFilePath);\n }\n return jarFile.getParentFile().getAbsolutePath();\n}\n"
},
{
"answer_id": 18482428,
"author": "mat_boy",
"author_id": 1983997,
"author_profile": "https://Stackoverflow.com/users/1983997",
"pm_score": 5,
"selected": false,
"text": "Path Path Path Path path = Paths.get(Test.class.getProtectionDomain().getCodeSource().getLocation().toURI());\n"
},
{
"answer_id": 21938309,
"author": "TheGreatPsychoticBunny",
"author_id": 3032706,
"author_profile": "https://Stackoverflow.com/users/3032706",
"pm_score": 2,
"selected": false,
"text": "String folder = MyClassName.class.getProtectionDomain().getCodeSource().getLocation().getPath();\n File test = new File(folder);\nif(file.isDirectory() && file.canRead()) { //always false }\n String fold= new File(folder).getParentFile().getPath()\nFile test = new File(fold);\n"
},
{
"answer_id": 22160106,
"author": "sudoBen",
"author_id": 3376389,
"author_profile": "https://Stackoverflow.com/users/3376389",
"pm_score": -1,
"selected": false,
"text": "try {\n fooDir = new File(this.getClass().getClassLoader().getResource(\"\").toURI());\n} catch (URISyntaxException e) {\n //may be sloppy, but don't really need anything here\n}\nfooDirPath = fooDir.toString(); // converts abstract (absolute) path to a String\n fooPath = fooDirPath + File.separator + \"foo.jar\";\n"
},
{
"answer_id": 30244209,
"author": "Vasu",
"author_id": 301444,
"author_profile": "https://Stackoverflow.com/users/301444",
"pm_score": -1,
"selected": false,
"text": "getProtectionDomain StringBuilder public static void main(String[] args) {\n System.out.println(findSource(MyClass.class));\n // OR\n System.out.println(findSource(String.class));\n}\n\npublic static String findSource(Class<?> clazz) {\n String resourceToSearch = '/' + clazz.getName().replace(\".\", \"/\") + \".class\";\n java.net.URL location = clazz.getResource(resourceToSearch);\n String sourcePath = location.getPath();\n // Optional, Remove junk\n return sourcePath.replace(\"file:\", \"\").replace(\"!\" + resourceToSearch, \"\");\n}\n"
},
{
"answer_id": 30381871,
"author": "NoSegfault",
"author_id": 4434038,
"author_profile": "https://Stackoverflow.com/users/4434038",
"pm_score": -1,
"selected": false,
"text": "URL path = Thread.currentThread().getContextClassLoader().getResource(\"\");\nPath p = Paths.get(path.toURI());\nString location = p.toString();\n C:\\Users\\Administrator\\new Workspace\\...\n file:/"
},
{
"answer_id": 33242475,
"author": "Max Heiber",
"author_id": 2482570,
"author_profile": "https://Stackoverflow.com/users/2482570",
"pm_score": 2,
"selected": false,
"text": "java -jar my-jar.jar .\n ."
},
{
"answer_id": 33473211,
"author": "phchen2",
"author_id": 4926275,
"author_profile": "https://Stackoverflow.com/users/4926275",
"pm_score": 3,
"selected": false,
"text": "System.getProperty(\"java.class.path\")\n"
},
{
"answer_id": 34261049,
"author": "Alexander",
"author_id": 699952,
"author_profile": "https://Stackoverflow.com/users/699952",
"pm_score": 1,
"selected": false,
"text": "MyClass.class.getProtectionDomain().getCodeSource().getLocation() /bin /myjarname.jar URL applicationRootPathURL = getClass().getProtectionDomain().getCodeSource().getLocation();\nFile applicationRootPath = new File(applicationRootPathURL.getPath());\nFile myFile;\nif(applicationRootPath.isDirectory()){\n myFile = new File(applicationRootPath, \"filename\");\n}\nelse{\n myFile = new File(applicationRootPath.getParentFile(), \"filename\");\n}\n"
},
{
"answer_id": 37747707,
"author": "F.O.O",
"author_id": 1464389,
"author_profile": "https://Stackoverflow.com/users/1464389",
"pm_score": 3,
"selected": false,
"text": "return new File(MyClass.class.getProtectionDomain().getCodeSource().getLocation().toURI().getPath()).getParentFile();\n"
},
{
"answer_id": 37949237,
"author": "Fahad Alkamli",
"author_id": 3126202,
"author_profile": "https://Stackoverflow.com/users/3126202",
"pm_score": 1,
"selected": false,
"text": " String path=new java.io.File(Server.class.getProtectionDomain()\n .getCodeSource()\n .getLocation()\n .getPath())\n .getAbsolutePath();\n path=path.substring(0, path.lastIndexOf(\".\"));\n path=path+System.getProperty(\"java.class.path\");\n"
},
{
"answer_id": 39229561,
"author": "Jelle den Burger",
"author_id": 5976604,
"author_profile": "https://Stackoverflow.com/users/5976604",
"pm_score": 2,
"selected": false,
"text": "jarLocation file:\\ jar:file\\ String#substring() URL jarLocationUrl = MyClass.class.getProtectionDomain().getCodeSource().getLocation();\nString jarLocation = new File(jarLocationUrl.toString()).getParent();\n"
},
{
"answer_id": 44071072,
"author": "GOXR3PLUS",
"author_id": 4970079,
"author_profile": "https://Stackoverflow.com/users/4970079",
"pm_score": 0,
"selected": false,
"text": "Windows Linux,MacOs,Solaris .jar .jar .jar cmd system32 ;][[;'57f2g34g87-8+9-09!2#@!$%^^&() ()%&$%^@# ProcessBuilder //The class from which i called this was the class `Main`\nString path = getBasePathForClass(Main.class);\nString applicationPath= new File(path + \"application.jar\").getAbsolutePath();\n\n\nSystem.out.println(\"Directory Path is : \"+applicationPath);\n\n//Your know try catch here\n//Mention that sometimes it doesn't work for example with folder `;][[;'57f2g34g87-8+9-09!2#@!$%^^&()` \nProcessBuilder builder = new ProcessBuilder(\"java\", \"-jar\", applicationPath);\nbuilder.redirectErrorStream(true);\nProcess process = builder.start();\n\n//...code\n getBasePathForClass(Class<?> classs) /**\n * Returns the absolute path of the current directory in which the given\n * class\n * file is.\n * \n * @param classs\n * @return The absolute path of the current directory in which the class\n * file is.\n * @author GOXR3PLUS[StackOverFlow user] + bachden [StackOverFlow user]\n */\n public static final String getBasePathForClass(Class<?> classs) {\n\n // Local variables\n File file;\n String basePath = \"\";\n boolean failed = false;\n\n // Let's give a first try\n try {\n file = new File(classs.getProtectionDomain().getCodeSource().getLocation().toURI().getPath());\n\n if (file.isFile() || file.getPath().endsWith(\".jar\") || file.getPath().endsWith(\".zip\")) {\n basePath = file.getParent();\n } else {\n basePath = file.getPath();\n }\n } catch (URISyntaxException ex) {\n failed = true;\n Logger.getLogger(classs.getName()).log(Level.WARNING,\n \"Cannot firgue out base path for class with way (1): \", ex);\n }\n\n // The above failed?\n if (failed) {\n try {\n file = new File(classs.getClassLoader().getResource(\"\").toURI().getPath());\n basePath = file.getAbsolutePath();\n\n // the below is for testing purposes...\n // starts with File.separator?\n // String l = local.replaceFirst(\"[\" + File.separator +\n // \"/\\\\\\\\]\", \"\")\n } catch (URISyntaxException ex) {\n Logger.getLogger(classs.getName()).log(Level.WARNING,\n \"Cannot firgue out base path for class with way (2): \", ex);\n }\n }\n\n // fix to run inside eclipse\n if (basePath.endsWith(File.separator + \"lib\") || basePath.endsWith(File.separator + \"bin\")\n || basePath.endsWith(\"bin\" + File.separator) || basePath.endsWith(\"lib\" + File.separator)) {\n basePath = basePath.substring(0, basePath.length() - 4);\n }\n // fix to run inside netbeans\n if (basePath.endsWith(File.separator + \"build\" + File.separator + \"classes\")) {\n basePath = basePath.substring(0, basePath.length() - 14);\n }\n // end fix\n if (!basePath.endsWith(File.separator)) {\n basePath = basePath + File.separator;\n }\n return basePath;\n }\n"
},
{
"answer_id": 46116016,
"author": "John Lockwood",
"author_id": 161644,
"author_profile": "https://Stackoverflow.com/users/161644",
"pm_score": 0,
"selected": false,
"text": "private static String getJarPath() throws IOException, URISyntaxException {\n File f = new File(LicensingApp.class.getProtectionDomain().().getLocation().toURI());\n String jarPath = f.getCanonicalPath().toString();\n String jarDir = jarPath.substring( 0, jarPath.lastIndexOf( File.separator ));\n return jarDir;\n }\n"
},
{
"answer_id": 55279816,
"author": "DragonGamer",
"author_id": 1695537,
"author_profile": "https://Stackoverflow.com/users/1695537",
"pm_score": 1,
"selected": false,
"text": "String surroundingJar = null;\n\n// gets the path to the jar file if it exists; or the \"bin\" directory if calling from Eclipse\nString jarDir = new File(ClassLoader.getSystemClassLoader().getResource(\".\").getPath()).getAbsolutePath();\n\n// gets the \"bin\" directory if calling from eclipse or the name of the .jar file alone (without its path)\nString jarFileFromSys = System.getProperty(\"java.class.path\").split(\";\")[0];\n\n// If both are equal that means it is running from an IDE like Eclipse\nif (jarFileFromSys.equals(jarDir))\n{\n System.out.println(\"RUNNING FROM IDE!\");\n // The path to the jar is the \"bin\" directory in that case because there is no actual .jar file.\n surroundingJar = jarDir;\n}\nelse\n{\n // Combining the path and the name of the .jar file to achieve the final result\n surroundingJar = jarDir + jarFileFromSys.substring(1);\n}\n\nSystem.out.println(\"JAR File: \" + surroundingJar);\n"
},
{
"answer_id": 56887852,
"author": "Blarzek",
"author_id": 8059259,
"author_profile": "https://Stackoverflow.com/users/8059259",
"pm_score": 2,
"selected": false,
"text": "String path = new File(\"\").getAbsolutePath();\n"
},
{
"answer_id": 58986478,
"author": "Jairo Martínez",
"author_id": 3908401,
"author_profile": "https://Stackoverflow.com/users/3908401",
"pm_score": 2,
"selected": false,
"text": "private static boolean isRunningOverJar() {\n try {\n String pathJar = Application.class.getResource(Application.class.getSimpleName() + \".class\").getFile();\n\n if (pathJar.toLowerCase().contains(\".jar\")) {\n return true;\n } else {\n return false;\n }\n } catch (Exception e) {\n return false;\n }\n}\n private static String getPathJar() {\n try {\n final URI jarUriPath =\n Application.class.getResource(Application.class.getSimpleName() + \".class\").toURI();\n String jarStringPath = jarUriPath.toString().replace(\"jar:\", \"\");\n String jarCleanPath = Paths.get(new URI(jarStringPath)).toString();\n\n if (jarCleanPath.toLowerCase().contains(\".jar\")) {\n return jarCleanPath.substring(0, jarCleanPath.lastIndexOf(\".jar\") + 4);\n } else {\n return null;\n }\n } catch (Exception e) {\n log.error(\"Error getting JAR path.\", e);\n return null;\n }\n }\n CommandLineRunner @SpringBootApplication\npublic class Application implements CommandLineRunner {\n public static void main(String[] args) throws IOException {\n Console console = System.console();\n\n if (console == null && !GraphicsEnvironment.isHeadless() && isRunningOverJar()) {\n Runtime.getRuntime().exec(new String[]{\"cmd\", \"/c\", \"start\", \"cmd\", \"/k\",\n \"java -jar \\\"\" + getPathJar() + \"\\\"\"});\n } else {\n SpringApplication.run(Application.class, args);\n }\n }\n\n @Override\n public void run(String... args) {\n /*\n Additional code here...\n */\n }\n\n private static boolean isRunningOverJar() {\n try {\n String pathJar = Application.class.getResource(Application.class.getSimpleName() + \".class\").getFile();\n\n if (pathJar.toLowerCase().contains(\".jar\")) {\n return true;\n } else {\n return false;\n }\n } catch (Exception e) {\n return false;\n }\n }\n\n private static String getPathJar() {\n try {\n final URI jarUriPath =\n Application.class.getResource(Application.class.getSimpleName() + \".class\").toURI();\n String jarStringPath = jarUriPath.toString().replace(\"jar:\", \"\");\n String jarCleanPath = Paths.get(new URI(jarStringPath)).toString();\n\n if (jarCleanPath.toLowerCase().contains(\".jar\")) {\n return jarCleanPath.substring(0, jarCleanPath.lastIndexOf(\".jar\") + 4);\n } else {\n return null;\n }\n } catch (Exception e) {\n return null;\n }\n }\n}\n"
},
{
"answer_id": 62979122,
"author": "White_King",
"author_id": 1180993,
"author_profile": "https://Stackoverflow.com/users/1180993",
"pm_score": 4,
"selected": false,
"text": "new File(\".\").getCanonicalPath()\n String localPath=new File(getClass().getProtectionDomain().getCodeSource().getLocation().toURI()).getParentFile().getPath()+\"\\\\\"; \n \"C:\\Users\\User\\Desktop\\Folder\\\"\n"
},
{
"answer_id": 65349441,
"author": "Devxln",
"author_id": 11239174,
"author_profile": "https://Stackoverflow.com/users/11239174",
"pm_score": 1,
"selected": false,
"text": "Permissions \npublic static Path getEnclosingDirectory() {\n return Paths.get(FileUtils.class.getProtectionDomain().getPermissions()\n .elements().nextElement().getName()).getParent();\n}\n"
},
{
"answer_id": 67000570,
"author": "Michael Sims",
"author_id": 4068123,
"author_profile": "https://Stackoverflow.com/users/4068123",
"pm_score": -1,
"selected": false,
"text": "runCommand(\"pwd\");\n public static String runCommand(String command) {\n StringBuilder sb = new StringBuilder();\n try {\n ProcessBuilder pb = new ProcessBuilder(command);\n final Process p = pb.start();\n BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream()));\n String line;\n sb.append(br.read());\n while ((line= br.readLine()) != null) sb.append(line).append(\"\\n\");\n }\n catch (IOException e) {e.printStackTrace();}\n return sb.toString();\n}\n"
},
{
"answer_id": 70051410,
"author": "Mehdi",
"author_id": 1970299,
"author_profile": "https://Stackoverflow.com/users/1970299",
"pm_score": 2,
"selected": false,
"text": "String jarPath = File(MyClass.class.getProtectionDomain().getCodeSource().getLocation()\n .toURI()).getPath();\n String dirPath = new File(MyClass.class.getProtectionDomain().getCodeSource().getLocation()\n .toURI()).getParent();\n"
}
] | 2008/11/26 | [
"https://Stackoverflow.com/questions/320542",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16873/"
] |
320,567 | <p>How can I simplify an expression using basic arithmetic?</p>
| [
{
"answer_id": 321174,
"author": "Chris Eidhof",
"author_id": 36929,
"author_profile": "https://Stackoverflow.com/users/36929",
"pm_score": 2,
"selected": false,
"text": "data Exp = Lit Int\n | Plus Exp Exp\n | Times Exp Exp\n\neval :: Exp -> Int\neval (Lit x) = x\neval (Plus x y) = eval x + eval y\neval (Times x y) = eval x * eval y\n"
}
] | 2008/11/26 | [
"https://Stackoverflow.com/questions/320567",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/41000/"
] |
320,588 | <p>I'm looking at some open source Java projects to get into Java and notice a lot of them have some sort of 'constants' interface.</p>
<p>For instance, <a href="http://www.processing.org" rel="noreferrer">processing.org</a> has an interface called <a href="http://dev.processing.org/source/index.cgi/tags/processing-1.0/core/src/processing/core/PConstants.java?view=markup" rel="noreferrer">PConstants.java</a>, and most other core classes implement this interface. The interface is riddled with static members. Is there a reason for this approach, or is this considered bad practice? Why not use enums <em>where it makes sense</em>, or a static class?</p>
<p>I find it strange to use an interface to allow for some sort of pseudo 'global variables'.</p>
<pre><code>public interface PConstants {
// LOTS OF static fields...
static public final int SHINE = 31;
// emissive (by default kept black)
static public final int ER = 32;
static public final int EG = 33;
static public final int EB = 34;
// has this vertex been lit yet
static public final int BEEN_LIT = 35;
static public final int VERTEX_FIELD_COUNT = 36;
// renderers known to processing.core
static final String P2D = "processing.core.PGraphics2D";
static final String P3D = "processing.core.PGraphics3D";
static final String JAVA2D = "processing.core.PGraphicsJava2D";
static final String OPENGL = "processing.opengl.PGraphicsOpenGL";
static final String PDF = "processing.pdf.PGraphicsPDF";
static final String DXF = "processing.dxf.RawDXF";
// platform IDs for PApplet.platform
static final int OTHER = 0;
static final int WINDOWS = 1;
static final int MACOSX = 2;
static final int LINUX = 3;
static final String[] platformNames = {
"other", "windows", "macosx", "linux"
};
// and on and on
}
</code></pre>
| [
{
"answer_id": 320610,
"author": "Zarkonnen",
"author_id": 15255,
"author_profile": "https://Stackoverflow.com/users/15255",
"pm_score": 7,
"selected": false,
"text": "import static com.kittens.kittenpolisher.KittenConstants.*;\n /** Set of constants needed for Kitten Polisher. */\npublic final class KittenConstants\n{\n private KittenConstants() {}\n\n public static final String KITTEN_SOUND = \"meow\";\n public static final double KITTEN_CUTENESS_FACTOR = 1;\n}\n"
},
{
"answer_id": 12888827,
"author": "pleerock",
"author_id": 925151,
"author_profile": "https://Stackoverflow.com/users/925151",
"pm_score": 3,
"selected": false,
"text": "public interface CarConstants {\n\n static final String ENGINE = \"mechanical\";\n static final String WHEEL = \"round\";\n // ...\n\n}\n\npublic interface ToyotaCar extends CarConstants //, ICar, ... {\n void produce();\n}\n\npublic interface FordCar extends CarConstants //, ICar, ... {\n void produce();\n}\n\n// and this is implementation #1\npublic class CamryCar implements ToyotaCar {\n\n public void produce() {\n System.out.println(\"the engine is \" + ENGINE );\n System.out.println(\"the wheel is \" + WHEEL);\n }\n}\n\n// and this is implementation #2\npublic class MustangCar implements FordCar {\n\n public void produce() {\n System.out.println(\"the engine is \" + ENGINE );\n System.out.println(\"the wheel is \" + WHEEL);\n }\n}\n public interface InnovativeCarConstants {\n\n static final String ENGINE = \"electronic\";\n static final String WHEEL = \"flat\";\n // ...\n}\n public interface ToyotaCar extends CarConstants\n public interface ToyotaCar extends InnovativeCarConstants \n"
},
{
"answer_id": 14211634,
"author": "Loek Bergman",
"author_id": 1719509,
"author_profile": "https://Stackoverflow.com/users/1719509",
"pm_score": 0,
"selected": false,
"text": "public List<Decision> compareCars(List<I_Somecar> pCars);\n"
},
{
"answer_id": 32099794,
"author": "phil_20686",
"author_id": 2882136,
"author_profile": "https://Stackoverflow.com/users/2882136",
"pm_score": 3,
"selected": false,
"text": "public interface SyntaxExtensions {\n // query type\n String NEAR_TO_QUERY = \"nearTo\";\n\n // params for query\n String POINT = \"coordinate\";\n String DISTANCE_KM = \"distanceInKm\";\n}\n"
}
] | 2008/11/26 | [
"https://Stackoverflow.com/questions/320588",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13466/"
] |
320,590 | <p>I'm trying to add a special markup to Python documentation strings in emacs (python-mode).</p>
<p>Currently I'm able to extract a single line with:</p>
<pre><code>(font-lock-add-keywords
'python-mode
'(("\\(\"\\{3\\}\\.+\"\\{3\\}\\)"
1 font-lock-doc-face prepend)))
</code></pre>
<p>This works now:</p>
<pre><code>"""Foo"""
</code></pre>
<p>But as soon there is a newline like:</p>
<pre><code>"""
Foo
"""
</code></pre>
<p>It doesn't work anymore. This is logical, since <code>.</code> doesn't include newlines (<code>\n</code>).
Should I use a character class?</p>
<p>How can I correct this regular expression to include everything between <code>""" """</code>?</p>
<p>Thanks in advance!</p>
| [
{
"answer_id": 320755,
"author": "huaiyuan",
"author_id": 16240,
"author_profile": "https://Stackoverflow.com/users/16240",
"pm_score": 2,
"selected": false,
"text": "\"\\\\(\\\"\\\\{3\\\\}\\\\(.*\\n?\\\\)*?\\\"\\\\{3\\\\}\\\\)\"\n"
},
{
"answer_id": 320833,
"author": "Joel Borggrén-Franck",
"author_id": 38222,
"author_profile": "https://Stackoverflow.com/users/38222",
"pm_score": 0,
"selected": false,
"text": "\\(\"\\{3\\}\\(.\\| \\)+\"\\{3\\}\\)"
},
{
"answer_id": 321089,
"author": "wunki",
"author_id": 34020,
"author_profile": "https://Stackoverflow.com/users/34020",
"pm_score": 0,
"selected": false,
"text": "(font-lock-add-keywords\n 'python-mode\n '((\"\\\\(\\\"\\\\{3\\\\}\\\\(.\\\\|\\n\\\\)*?\\\"\\\\{3\\\\}\\\\)\" \n 1 font-lock-warning-face prepend)))\n \"\\\\(\\\"\\\\{3\\\\}\\\\(.*\\n?\\\\)*?\\\"\\\\{3\\\\}\\\\)\""
},
{
"answer_id": 18513014,
"author": "iberion",
"author_id": 2724889,
"author_profile": "https://Stackoverflow.com/users/2724889",
"pm_score": 0,
"selected": false,
"text": "font-lock-add-keywords\n 'python-mode\n '((\"\\\\(\\\"\\\\{3\\\\}\\\\[^|]*?\\\"\\\\{3\\\\}\\\\)\"\n 1 font-lock-doc-face prepend)))\n"
}
] | 2008/11/26 | [
"https://Stackoverflow.com/questions/320590",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/34020/"
] |
320,600 | <p>I have a library consisting of approx 100 source files. I want one of the sources to be always rebuilt if any of the other files have been compiled but I don't want it built every time I run the make/build.</p>
<p>Basically I want this file to have the last build date/time built into it so any application linking to the library can check the last build time/date. Is there any other way to do this?</p>
| [
{
"answer_id": 320623,
"author": "JesperE",
"author_id": 13051,
"author_profile": "https://Stackoverflow.com/users/13051",
"pm_score": 3,
"selected": false,
"text": "version.o: $(OBJECTS)\n"
},
{
"answer_id": 320701,
"author": "Steve Jessop",
"author_id": 13005,
"author_profile": "https://Stackoverflow.com/users/13005",
"pm_score": 3,
"selected": true,
"text": "blah.exe : whatever\n rm -f version.o\n $(CC) $(CFLAGS) -c version.c\n $(CC) $(CFLAGS) $(OBJFILES) version.o -o blah.exe\n"
}
] | 2008/11/26 | [
"https://Stackoverflow.com/questions/320600",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3685/"
] |
320,618 | <p>I am currently doing some socket programming using C/C++. To be able to use a somewhat cleaner interface, and a more OO structure, I decided to write a few simple wrapper classes around parts of the C socket API, but while doing so I stumbled upon a problem:</p>
<p>Given the following code:</p>
<pre><code>// Global method
int foo(int x)
{
return x;
}
// Class that calls the global method
class FooBar
{
public:
void foo() { return; };
void baz() { foo(1); }
};
</code></pre>
<p>g++ gives the following error message:</p>
<pre><code>test.cpp: In member function ‘void FooBar::baz()’:
test.cpp:10: error: no matching function for call to ‘FooBar::foo(int)’
test.cpp:9: note: candidates are: void FooBar::foo()
</code></pre>
<p>Renaming the class method solves the problem.</p>
<p>Why is it that there is some kind of naming conflict even though the method signatures are different? What is the best way to fix this?</p>
<p>Thanks
/Erik</p>
| [
{
"answer_id": 320627,
"author": "Johannes Schaub - litb",
"author_id": 34509,
"author_profile": "https://Stackoverflow.com/users/34509",
"pm_score": 4,
"selected": true,
"text": "::foo(1);\n void baz() { int foo(int); foo(1); }\n"
},
{
"answer_id": 320632,
"author": "Steve Jessop",
"author_id": 13005,
"author_profile": "https://Stackoverflow.com/users/13005",
"pm_score": 2,
"selected": false,
"text": "void baz() { ::foo(1); }\n foo() foo(int) struct A {\n virtual void foo(int) = 0;\n // attempt to provide a useful helper\n virtual void foo() { foo(23); }\n};\n\nstruct B : public A {\n void foo(int i) {\n std::cout << i << \"\\n\";\n }\n};\n\nint main() {\n B b;\n b.foo(); // oops, can't find foo(), because class B hid it\n A &a = b;\n a.foo(); // that works. So much for Liskov's substitution principle.\n}\n"
}
] | 2008/11/26 | [
"https://Stackoverflow.com/questions/320618",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/276/"
] |
320,629 | <p>if i have :</p>
<pre><code><div class="carBig"></div>
</code></pre>
<p>and</p>
<pre><code><div class="car"></div>
</code></pre>
<p>and $(".car").size();</p>
<p>i get 2 items ..</p>
| [
{
"answer_id": 320666,
"author": "BrianH",
"author_id": 40619,
"author_profile": "https://Stackoverflow.com/users/40619",
"pm_score": 2,
"selected": false,
"text": "<html><head><title>Testing</title>\n<script type=\"text/javascript\" src=\"/js/jquery/jquery-1.2.6.min.js\">\n</script>\n<script type=\"text/javascript\">\n$(document).ready(function() {\n $(\".car\").each(function() {\n $(\"#carResults\").append($(\".car\").size());\n $(\"#carResults\").append($(this).text());\n });\n});\n</script>\n</head><body>\n<div class=\"carBig\">Big Car</div>\n<div class=\"car\">Regular Car</div>\n<div id=\"carResults\"></div>\n</body></html>\n Big Car\nRegular Car\n1Regular Car\n"
},
{
"answer_id": 320667,
"author": "Jeff Sheldon",
"author_id": 33910,
"author_profile": "https://Stackoverflow.com/users/33910",
"pm_score": 2,
"selected": true,
"text": "<html>\n<head>\n</head>\n<script type=\"text/javascript\" src=\"jquery-1.2.6.pack.js\"></script>\n<script type=\"text/javascript\">\n $(document).ready(function() {\n $(\".car\").hide();\n });\n</script>\n<body>\n <div id=container>\n <div class=\"carBig\">Car Big</div>\n <div class=\"car\">Car</div>\n </div>\n</body>\n</html>\n"
}
] | 2008/11/26 | [
"https://Stackoverflow.com/questions/320629",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1409636/"
] |
320,636 | <p>I have a class 'Database' that works as a wrapper for ADO.net. For instance, when I need to execute a procedure, I call Database.ExecuteProcedure(procedureName, parametersAndItsValues).</p>
<p>We are experiencing serious problems with Deadlock situations in SQL Server 2000. Part of our team is working on the sql code and transactions to minimize these events, but I'm thinking about making this Database class robust against deadlock situations.</p>
<p>We want the deadlock victim to retry perhaps after some time delay, but I don't know if it is possible. Here is the code for a method we use:</p>
<pre><code>public int ExecuteQuery(string query)
{
int rows = 0;
try
{
Command.Connection = Connection;
Command.CommandType = CommandType.Text;
if(DatabaseType != enumDatabaseType.ORACLE)
Command.CommandText = query;
else
Command.CommandText ="BEGIN " + query + " END;";
if (DatabaseType != enumDatabaseType.SQLCOMPACT)
Command.CommandTimeout = Connection.ConnectionTimeout;
if (Connection.State == ConnectionState.Closed)
Connection.Open();
rows = Command.ExecuteNonQuery();
}
catch (Exception exp)
{
//Could I add here any code to handle it?
throw new Exception(exp.Message);
}
finally
{
if (Command.Transaction == null)
{
Connection.Close();
_connection.Dispose();
_connection = null;
Command.Dispose();
Command = null;
}
}
return rows;
}
</code></pre>
<p>Can I do this handling inside a catch block?</p>
| [
{
"answer_id": 333555,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 3,
"selected": false,
"text": "bool OK = false;\nRandom Rnd = new Random();\n\nwhile(!OK)\n{\n try\n {\n rows = Command.ExecuteNonQuery();\n OK = true;\n }\n catch(Exception exDead)\n {\n if(exDead.Message.ToLower().Contains(\"deadlock\"))\n System.Threading.Thread.Sleep(Rnd.Next(1000, 5000));\n else\n throw exDead;\n }\n}\n"
},
{
"answer_id": 335669,
"author": "Sam Saffron",
"author_id": 17174,
"author_profile": "https://Stackoverflow.com/users/17174",
"pm_score": 6,
"selected": true,
"text": "select count(*) from bob int retryCount = 3;\nbool success = false; \nwhile (retryCount > 0 && !success) \n{\n try\n {\n // your sql here\n success = true; \n } \n catch (SqlException exception)\n {\n if (exception.Number != 1205)\n {\n // a sql exception that is not a deadlock \n throw; \n }\n // Add delay here if you wish. \n retryCount--; \n if (retryCount == 0) throw;\n }\n}\n"
},
{
"answer_id": 6692286,
"author": "Neil",
"author_id": 148593,
"author_profile": "https://Stackoverflow.com/users/148593",
"pm_score": 5,
"selected": false,
"text": "private static T Retry<T>(Func<T> func)\n{\n int count = 3;\n TimeSpan delay = TimeSpan.FromSeconds(5);\n while (true)\n {\n try\n {\n return func();\n }\n catch(SqlException e)\n {\n --count;\n if (count <= 0) throw;\n\n if (e.Number == 1205)\n _log.Debug(\"Deadlock, retrying\", e);\n else if (e.Number == -2)\n _log.Debug(\"Timeout, retrying\", e);\n else\n throw;\n\n Thread.Sleep(delay);\n }\n }\n}\n\nprivate static void Retry(Action action)\n{\n Retry(() => { action(); return true; });\n}\n\n// Example usage\nprotected static void Execute(string connectionString, string commandString)\n{\n _log.DebugFormat(\"SQL Execute \\\"{0}\\\" on {1}\", commandString, connectionString);\n\n Retry(() => {\n using (SqlConnection connection = new SqlConnection(connectionString))\n using (SqlCommand command = new SqlCommand(commandString, connection))\n command.ExecuteNonQuery();\n });\n}\n\nprotected static T GetValue<T>(string connectionString, string commandString)\n{\n _log.DebugFormat(\"SQL Scalar Query \\\"{0}\\\" on {1}\", commandString, connectionString);\n\n return Retry(() => { \n using (SqlConnection connection = new SqlConnection(connectionString))\n using (SqlCommand command = new SqlCommand(commandString, connection))\n {\n object value = command.ExecuteScalar();\n if (value is DBNull) return default(T);\n return (T) value;\n }\n });\n}\n"
}
] | 2008/11/26 | [
"https://Stackoverflow.com/questions/320636",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21668/"
] |
320,645 | <p>I want to programmatically verify the status of an application to see if it has crashed or stopped. I know how to see if the process exists in C# but can I also see if it is "Not responding"?</p>
| [
{
"answer_id": 320670,
"author": "Student for Life",
"author_id": 38041,
"author_profile": "https://Stackoverflow.com/users/38041",
"pm_score": 5,
"selected": true,
"text": "using System;\nusing System.Diagnostics;\n\nnamespace ProcessStatus\n{\n class Program\n {\n static void Main(string[] args)\n {\n Process[] processes = Process.GetProcesses();\n\n foreach (Process process in processes)\n {\n Console.WriteLine(\"Process Name: {0}, Responding: {1}\", process.ProcessName, process.Responding);\n }\n\n Console.Write(\"press enter\");\n Console.ReadLine();\n }\n }\n}\n"
}
] | 2008/11/26 | [
"https://Stackoverflow.com/questions/320645",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9077/"
] |
320,659 | <p>I was using an mxml class but since i need to pass some properties at construction time, to make it easier i will convert it to as3 code.</p>
<p>The class is RectangleShape and it just draws a rectangle.</p>
<p><strong>Original mxml working</strong></p>
<pre><code><?xml version="1.0" encoding="utf-8"?>
<BaseShape name="rectangle"
xmlns="org.edorado.edoboard.view.components.shapes.*"
xmlns:mx="http://www.adobe.com/2006/mxml"
xmlns:degrafa="http://www.degrafa.com/2007"
xmlns:objecthandles="com.roguedevelopment.objecthandles.*">
<mx:Script>
<![CDATA[
import org.edorado.edoboard.view.components.shapes.IShape;
import mx.events.FlexEvent;
override public function drag(movePt:Point):void {
this.width = movePt.x - this.x;
this.height = movePt.y - this.y;
}
override public function updateFillColor(color:int):void {
solidFill.color = color;
}
]]>
</mx:Script>
<degrafa:Surface >
<degrafa:GeometryGroup id="geo">
<degrafa:fills>
<degrafa:SolidFill id="solidFill" color="white" alpha="0.3"/>
</degrafa:fills>
<degrafa:strokes>
<degrafa:SolidStroke id="stroke1" color="white"/>
</degrafa:strokes>
<degrafa:RegularRectangle
id="rect"
fill = "{solidFill}"
width="{width}"
height="{height}"
stroke="{stroke1}" />
</degrafa:GeometryGroup>
</degrafa:Surface>
</BaseShape>
</code></pre>
<p><strong>My attempt to AS3</strong></p>
<p>package org.edorado.edoboard.view.components.shapes
{
import com.degrafa.geometry.RegularRectangle;
import com.degrafa.paint.SolidFill;
import com.degrafa.paint.SolidStroke;
import com.degrafa.GeometryGroup;
import com.degrafa.Surface;
import flash.geom.Point;</p>
<pre><code>public class RectangleShape extends BaseShape
{
public var surface:Surface = new Surface();
public var geoGroup:GeometryGroup = new GeometryGroup();
public var solidFill:SolidFill = new SolidFill("white");
public var solidStroke:SolidStroke = new SolidStroke("black");
public var rect:RegularRectangle = new RegularRectangle();
public static const name:String = "rectangle";
public function RectangleShape() {
addChild(surface);
//surface.addChild(geoGroup);
surface.graphicsCollection.addItem(geoGroup);
solidFill.alpha = 0.3;
rect.fill = solidFill;
rect.stroke = solidStroke;
rect.width = this.width;
rect.height = this.height;
geoGroup.geometry = [rect];
geoGroup.draw(null, null);
}
override public function drag(movePt:Point):void {
this.width = movePt.x - this.x;
this.height = movePt.y - this.y;
trace('dragging ', this.width, this.height);
}
override public function updateFillColor(color:int):void {
solidFill.color = color;
}
}
</code></pre>
<p>}</p>
<p>The problem is that the shape is not drawing anymore, the BaseShape container is there and i can see the trace drag working but not the rectangle anymore.</p>
<p>Any obvious stuff i missed ?
Thanks</p>
| [
{
"answer_id": 321831,
"author": "Christophe Herreman",
"author_id": 17255,
"author_profile": "https://Stackoverflow.com/users/17255",
"pm_score": 3,
"selected": true,
"text": "BindingUtils.bindProperty(component, \"height\", this, \"height\"); \n"
}
] | 2008/11/26 | [
"https://Stackoverflow.com/questions/320659",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/32032/"
] |
320,677 | <p>How do I set the executable icon for my C++ application in visual studio 2008?</p>
| [
{
"answer_id": 320722,
"author": "ravenspoint",
"author_id": 16582,
"author_profile": "https://Stackoverflow.com/users/16582",
"pm_score": 3,
"selected": false,
"text": "/////////////////////////////////////////////////////////////////////////////\n//\n// Icon\n//\n\n// Icon with lowest ID value placed first to ensure application icon\n// remains consistent on all systems.\n(icon ID ) ICON \"res\\\\filename.ico\"\n"
},
{
"answer_id": 9365755,
"author": "bobobobo",
"author_id": 111307,
"author_profile": "https://Stackoverflow.com/users/111307",
"pm_score": 6,
"selected": false,
"text": "*.ico *.ico resource.h resource.h //resource.h\n#define IDI_ICON1 102\n#define IDI_ICON2 103\n //resource.h\n#define IDI_ICON1 106\n#define IDI_ICON2 103\n"
},
{
"answer_id": 25446613,
"author": "Cretzu",
"author_id": 2867623,
"author_profile": "https://Stackoverflow.com/users/2867623",
"pm_score": 1,
"selected": false,
"text": "m_hIcon = AfxGetApp()->LoadIcon(ICON_ID_FROM_RESOURCE.H);"
}
] | 2008/11/26 | [
"https://Stackoverflow.com/questions/320677",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/30352/"
] |
320,682 | <p>Wnen I use external resources such as files or DB connection I need to close them before I let them go.</p>
<p>Do I need to do the same thing with Swing components ? If yes then how ?</p>
| [
{
"answer_id": 320690,
"author": "Vincent Ramdhanie",
"author_id": 27439,
"author_profile": "https://Stackoverflow.com/users/27439",
"pm_score": 0,
"selected": false,
"text": "JPanel p = new JPanel();\np = null;\n"
},
{
"answer_id": 320998,
"author": "Tom Hawtin - tackline",
"author_id": 4725,
"author_profile": "https://Stackoverflow.com/users/4725",
"pm_score": 0,
"selected": false,
"text": "Graphics paintComponent WeakReference"
}
] | 2008/11/26 | [
"https://Stackoverflow.com/questions/320682",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/24028/"
] |
320,692 | <p>Is it possible to create an XML Schema which imposes a co-occurrence constraint to an attribute/element pair?</p>
<pre><code><primitive-list>
<primitive name="P1">
<definition><!-- primitive specification --></definition>
</primitive>
<primitive name="P2">
<definition><!-- primitive specification --></definition>
</primitive>
<!-- other common primitives are specified here-->
<primitive-list>
<composite-list>
<composite name="C1">
<primitive ref="P1" />
<primitive ref="P2" />
<primitive>
<definition><!-- inline primitive specification --></definition>
</primitive>
</composite>
<!-- Other compisites are specified here-->
</composite-list>
</code></pre>
<p>The schema should imply that:</p>
<ul>
<li>If a <b>primitive</b> element is specified inside a <b>primitive-list</b> element, then it should contain the <b>name</b> attribute and the embedded <b>definition</b> element, but not the <b>ref</b> attribute.</li>
<li>If a <b>primitive</b> element is specified in the <b>composite</b> element, then it should contain either the <b>ref</b> attribute or the <b>definition</b> element. The <b>name</b> is allowed in neither cases.</li>
</ul>
<p>I am pretty sure that it is possible since the <b>element</b> element in XML Schema itself behaves just like that. So anybody who is in possession of that sacred knowledge please share :-)</p>
<p>Thank you in advance.</p>
| [
{
"answer_id": 323167,
"author": "Mitchel Sellers",
"author_id": 13279,
"author_profile": "https://Stackoverflow.com/users/13279",
"pm_score": 0,
"selected": false,
"text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<xs:schema targetNamespace=\"http://www.iowacomputergurus.com/stackoverflow/samples/xsdexample\"\n elementFormDefault=\"qualified\"\n xmlns=\"http://www.iowacomputergurus.com/stackoverflow/samples/xsdexample\"\n xmlns:xs=\"http://www.w3.org/2001/XMLSchema\"\n>\n\n <xs:complexType name=\"PrimitiveType\">\n <xs:sequence>\n <xs:element name=\"definition\" type=\"xs:string\" minOccurs=\"1\" maxOccurs=\"1\" />\n </xs:sequence>\n <xs:attribute name =\"name\" use=\"required\" type=\"xs:string\" />\n </xs:complexType>\n\n <xs:element name=\"root\">\n <xs:complexType>\n <xs:sequence>\n <xs:element name=\"primitive-list\" minOccurs=\"1\" maxOccurs=\"1\">\n <xs:complexType>\n <xs:sequence>\n <xs:element name=\"primitive\" type=\"PrimitiveType\" minOccurs=\"1\" maxOccurs=\"unbounded\" />\n </xs:sequence>\n </xs:complexType>\n </xs:element>\n <xs:element name=\"composite-list\" minOccurs=\"1\" maxOccurs=\"1\">\n <xs:complexType>\n <xs:sequence>\n <xs:element name=\"composite\">\n <xs:complexType>\n <xs:sequence>\n <xs:element name=\"primitive\" minOccurs=\"1\" maxOccurs=\"unbounded\">\n <xs:complexType>\n <xs:sequence>\n <xs:element name=\"definition\" minOccurs=\"0\" maxOccurs=\"1\" />\n </xs:sequence>\n <xs:attribute name=\"ref\" use=\"optional\" type=\"xs:string\" />\n </xs:complexType>\n </xs:element>\n </xs:sequence>\n <xs:attribute name=\"name\" type=\"xs:string\" use=\"required\" />\n </xs:complexType>\n </xs:element>\n </xs:sequence>\n </xs:complexType>\n </xs:element>\n </xs:sequence>\n </xs:complexType>\n </xs:element> \n</xs:schema>\n"
},
{
"answer_id": 336494,
"author": "Maxim Vladimirsky",
"author_id": 31993,
"author_profile": "https://Stackoverflow.com/users/31993",
"pm_score": 4,
"selected": true,
"text": "<xs:complexType name=\"primitive\" abstract=\"true\">\n <xs:sequence>\n <xs:element ref=\"definition\" minOccurs=\"0\" maxOccurs=\"unbounded\" />\n </xs:sequence>\n <xs:attribute name=\"name\" type=\"xs:Name\" />\n <xs:attribute name=\"ref\" type=\"xs:Name\" />\n</xs:complexType>\n <xs:complexType name=\"public-primitive\">\n <xs:complexContent>\n <xs:restriction base=\"primitive\">\n <xs:sequence>\n <xs:element ref=\"definition\" minOccurs=\"1\" maxOccurs=\"unbounded\" />\n </xs:sequence>\n <xs:attribute name=\"name\" type=\"xs:Name\" use=\"required\" />\n <xs:attribute name=\"ref\" use=\"prohibited\" />\n </xs:restriction>\n </xs:complexContent>\n</xs:complexType>\n\n<xs:complexType name=\"private-primitive\">\n <xs:complexContent>\n <xs:restriction base=\"primitive\">\n <xs:sequence>\n <xs:element ref=\"definition\" minOccurs=\"0\" maxOccurs=\"unbounded\" />\n </xs:sequence>\n <xs:attribute name=\"name\" use=\"prohibited\" />\n </xs:restriction>\n </xs:complexContent>\n</xs:complexType>\n <xs:element name=\"primitive-list\">\n <xs:complexType>\n <xs:sequence>\n <xs:element name=\"primitive\" type=\"public-primitive\" maxOccurs=\"unbounded\" />\n </xs:sequence>\n </xs:complexType>\n</xs:element>\n\n<xs:element name=\"composite\">\n <xs:complexType>\n <xs:sequence>\n <xs:element name=\"primitive\" type=\"private-primitive\" maxOccurs=\"unbounded\">\n <xs:key name=\"definition-ref--co-occurrence--constraint\">\n <xs:selector xpath=\".\" />\n <xs:field xpath=\"definition|@ref\" />\n </xs:key>\n </xs:element>\n </xs:sequence>\n </xs:complexType>\n</xs:element>\n"
}
] | 2008/11/26 | [
"https://Stackoverflow.com/questions/320692",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/31993/"
] |
320,693 | <p>Is it possible to checkout only those files from a SVN repository that were modified in a revision or range of revisions, without checking out any files that were not modified? </p>
| [
{
"answer_id": 320706,
"author": "Drejc",
"author_id": 6482,
"author_profile": "https://Stackoverflow.com/users/6482",
"pm_score": 0,
"selected": false,
"text": "svn checkout --revision <revisionNumber> \n svn log --revision <revisionNumber> \n"
},
{
"answer_id": 320775,
"author": "Ciaran McNulty",
"author_id": 34024,
"author_profile": "https://Stackoverflow.com/users/34024",
"pm_score": 1,
"selected": false,
"text": "svn log -r <revision> -v <path>\n r3 | ciaran | 2008-11-16 12:24:30 +0000 (Sun, 16 Nov 2008) | 1 line\nChanged paths:\n A /trunk/apache/apache.conf\n A /trunk/application/controllers\n\nCommit message goes here\n"
},
{
"answer_id": 320790,
"author": "flolo",
"author_id": 36472,
"author_profile": "https://Stackoverflow.com/users/36472",
"pm_score": 2,
"selected": false,
"text": "VERSION=42\nsvn list -v -R -r $VERSION svn://... | awk \"/^[ ]*$VERSION/ {print \\$7}\" > files_to_checkout\n svn update -r $VERSION 'cat files_to_checkout'"
},
{
"answer_id": 320823,
"author": "Shyam Kumar Sundarakumar",
"author_id": 35392,
"author_profile": "https://Stackoverflow.com/users/35392",
"pm_score": 3,
"selected": true,
"text": "function checkout_files_in_revrange()\n{\n svn_url=$1;\n start_rev=$2;\n end_rev=$3;\n for theCheckoutCanditate in `svn log -r $start_rev:$end_rev --verbose --incremental | grep \" M \" | cut -f5 -d' ' | cut -f3- -d/`\n do\n svn co $svn_url/$theCheckoutCandidate -q;\n done\n}\n"
},
{
"answer_id": 320909,
"author": "user41040",
"author_id": 41040,
"author_profile": "https://Stackoverflow.com/users/41040",
"pm_score": 1,
"selected": false,
"text": "<Exec command=\"$(svnExecutable) diff -r $(StartRevision):$(EndRevision) $(DOUBLE_QUOTES)$(SvnRepositoryPath)/$(DOUBLE_QUOTES) --no-diff-deleted --summarize > $(TempFilePath)\" WorkingDirectory=\"$(WorkDirectory)\" />\n"
},
{
"answer_id": 460558,
"author": "Shyam Kumar Sundarakumar",
"author_id": 35392,
"author_profile": "https://Stackoverflow.com/users/35392",
"pm_score": 0,
"selected": false,
"text": "svn log -v --revision <revision_number> | grep \"^ \" | awk '{print $2}'"
}
] | 2008/11/26 | [
"https://Stackoverflow.com/questions/320693",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8952/"
] |
320,719 | <p>I have third-party workflow software (Captaris Teamplate) that's referencing an assembly from my project that's referencing other assemblies from our project solution all through the <a href="http://en.wikipedia.org/wiki/Global_Assembly_Cache" rel="nofollow noreferrer">GAC</a>. </p>
<p>When our application executes, it invokes a Captaris Teamplate method to create a workflow process which in turn uses project assemblies in the GAC to store data into
a database. </p>
<p>The problem is when I compile my project and remove assemblies from GAC replacing them with new versions, but when I run entire project, Captaris Teamplate throws an error: </p>
<blockquote>
<p>Exception Type: System.IO.FileNotFoundException<br/>
Message: File or assembly name VBAssembly, or one of its dependencies, was not found.<br/>
FileName: VBAssembly<br/>
FusionLog: === Pre-bind state information ===<br/>
LOG: DisplayName = VBAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null</p>
</blockquote>
<p>That is, it wouldn't give me the name of the assembly DLL file. It's trying to find nor version it's looking for. Troubleshooting of such an issue is like shooting in the dark and it can kill days of deleting old assemblies that are kept in the ASP.NET temporary files folder, project folder and website folder (inetpub), rebooting, etc., testing for error, getting an error, searching for some other old assemblies, etc.</p>
<p>So my questions are:</p>
<ol>
<li>Is there a technique that would allow me to extract more information on this exception such as the name of the assembly and version that is missing?</li>
<li>Is there an easy way to clean up all those old assembly versions from the system at compile time?</li>
<li>Any other suggestions in dealing with this <a href="http://en.wikipedia.org/wiki/DLL_Hell" rel="nofollow noreferrer">DLL Hell</a> and/or Captaris Teamplate?</li>
</ol>
<p>We're using ASP.NET version 1.1 with Visual Studio 2003 with Captaris Workflow 5.0.</p>
| [
{
"answer_id": 321202,
"author": "Aaron Fischer",
"author_id": 5618,
"author_profile": "https://Stackoverflow.com/users/5618",
"pm_score": 1,
"selected": false,
"text": "WINDOWS/system32"
},
{
"answer_id": 321228,
"author": "Dillie-O",
"author_id": 71,
"author_profile": "https://Stackoverflow.com/users/71",
"pm_score": 1,
"selected": false,
"text": "<assemblies> \n <add assembly=\"CrystalDecisions.Web, Version=11.5.3700.0, Culture=neutral, PublicKeyToken=692FBEA5521E1304\"/>\n <add assembly=\"CrystalDecisions.Shared, Version=11.5.3700.0, Culture=neutral, PublicKeyToken=692FBEA5521E1304\"/>\n <add assembly=\"CrystalDecisions.ReportSource, Version=11.5.3700.0, Culture=neutral, PublicKeyToken=692FBEA5521E1304\"/>\n <add assembly=\"CrystalDecisions.Enterprise.Framework, Version=11.5.3300.0, Culture=neutral, PublicKeyToken=692FBEA5521E1304\"/> \n</assemblies>\n"
},
{
"answer_id": 352627,
"author": "Jox",
"author_id": 35425,
"author_profile": "https://Stackoverflow.com/users/35425",
"pm_score": 1,
"selected": false,
"text": "FusLogVW.exe"
}
] | 2008/11/26 | [
"https://Stackoverflow.com/questions/320719",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
320,721 | <p>I have a list of items (blue nodes below) which are categorized by the users of my application. The categories themselves can be grouped and categorized themselves.</p>
<p>The resulting structure can be represented as a <a href="http://en.wikipedia.org/wiki/Directed_acyclic_graph" rel="nofollow noreferrer">Directed Acyclic Graph (DAG)</a> where the items are sinks at the bottom of the graph's topology and the top categories are sources. Note that while some of the categories might be well defined, a lot is going to be user defined and might be very messy.</p>
<p>Example:</p>
<p><a href="https://i.stack.imgur.com/j2MOp.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/j2MOp.png" alt="example data"></a><br>
<sub>(source: <a href="http://theuprightape.net/dag.png" rel="nofollow noreferrer">theuprightape.net</a>)</sub> </p>
<p>On that structure, I want to perform the following operations:</p>
<ul>
<li>find all items (sinks) below a particular node (all items in Europe)</li>
<li>find all paths (if any) that pass through all of a set of n nodes (all items sent via SMTP from example.com)</li>
<li>find all nodes that lie below all of a set of nodes (intersection: goyish brown foods)</li>
</ul>
<p>The first seems quite straightforward: start at the node, follow all possible paths to the bottom and collect the items there. However, is there a faster approach? Remembering the nodes I already passed through probably helps avoiding unnecessary repetition, but are there more optimizations?</p>
<p>How do I go about the second one? It seems that the first step would be to determine the height of each node in the set, as to determine at which one(s) to start and then find all paths below that which include the rest of the set. But is this the best (or even a good) approach?</p>
<p>The <a href="http://en.wikipedia.org/wiki/Graph_traversal" rel="nofollow noreferrer">graph traversal algorithms listed at Wikipedia</a> all seem to be concerned with either finding a particular node or the shortest or otherwise most effective route between two nodes. I think both is not what I want, or did I just fail to see how this applies to my problem? Where else should I read?</p>
| [
{
"answer_id": 321202,
"author": "Aaron Fischer",
"author_id": 5618,
"author_profile": "https://Stackoverflow.com/users/5618",
"pm_score": 1,
"selected": false,
"text": "WINDOWS/system32"
},
{
"answer_id": 321228,
"author": "Dillie-O",
"author_id": 71,
"author_profile": "https://Stackoverflow.com/users/71",
"pm_score": 1,
"selected": false,
"text": "<assemblies> \n <add assembly=\"CrystalDecisions.Web, Version=11.5.3700.0, Culture=neutral, PublicKeyToken=692FBEA5521E1304\"/>\n <add assembly=\"CrystalDecisions.Shared, Version=11.5.3700.0, Culture=neutral, PublicKeyToken=692FBEA5521E1304\"/>\n <add assembly=\"CrystalDecisions.ReportSource, Version=11.5.3700.0, Culture=neutral, PublicKeyToken=692FBEA5521E1304\"/>\n <add assembly=\"CrystalDecisions.Enterprise.Framework, Version=11.5.3300.0, Culture=neutral, PublicKeyToken=692FBEA5521E1304\"/> \n</assemblies>\n"
},
{
"answer_id": 352627,
"author": "Jox",
"author_id": 35425,
"author_profile": "https://Stackoverflow.com/users/35425",
"pm_score": 1,
"selected": false,
"text": "FusLogVW.exe"
}
] | 2008/11/26 | [
"https://Stackoverflow.com/questions/320721",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2077/"
] |
320,723 | <p>I have just come across a Visual C++ option that allows you to force file(s) to be included - this came about when I was looking at some code that was missing a <code>#include "StdAfx.h"</code> on each .cpp file, but was actually doing so via this option.</p>
<p>The option can be found on the <strong>Advanced C/C++ Configuration Properties</strong> page and equates to the <strong>/FI</strong> compiler option.</p>
<p>This option could prove really useful but before I rush off and start using it I thought I'd ask if there are any gotchas?</p>
| [
{
"answer_id": 320745,
"author": "Johannes Schaub - litb",
"author_id": 34509,
"author_profile": "https://Stackoverflow.com/users/34509",
"pm_score": 5,
"selected": true,
"text": "#include"
},
{
"answer_id": 320774,
"author": "Skizz",
"author_id": 1898,
"author_profile": "https://Stackoverflow.com/users/1898",
"pm_score": 4,
"selected": false,
"text": "#include \"afile.h\"\n#include \"stdafx.h\"\n"
}
] | 2008/11/26 | [
"https://Stackoverflow.com/questions/320723",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9236/"
] |
320,743 | <p>I'm working on a site (<a href="http://easy2speak.com" rel="nofollow noreferrer">http://easy2speak.com</a>) with about 10 flash SWFs on each page. Each of the SWFs are playing back a sound when clicked. Loading the sound, and playing it without any latency works fine, but in Flash player version 9 on all major browsers except IE, the sound suddenly drops out. It usually works for the first 10-20 clicks, then the SWFs will be totally silent until the next machine/browser restart. </p>
<p>In Flash player v10 (exactly the same code) it works perfectly. It also works perfectly in Flash player v9 in Internet Explorer.</p>
<p>Any ideas ?</p>
<p>Would love to hear some brain-storming on how to get around this problem as well, as I start to suspect there is no easy fix I can do in code. </p>
<p>By the way, the site has 1000+ sounds in MP3, so any solution can't involve embedding the sounds.</p>
| [
{
"answer_id": 320745,
"author": "Johannes Schaub - litb",
"author_id": 34509,
"author_profile": "https://Stackoverflow.com/users/34509",
"pm_score": 5,
"selected": true,
"text": "#include"
},
{
"answer_id": 320774,
"author": "Skizz",
"author_id": 1898,
"author_profile": "https://Stackoverflow.com/users/1898",
"pm_score": 4,
"selected": false,
"text": "#include \"afile.h\"\n#include \"stdafx.h\"\n"
}
] | 2008/11/26 | [
"https://Stackoverflow.com/questions/320743",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
320,759 | <p>A bit of background first:</p>
<ul>
<li><p>I am using "base" code from a remote SVN repository, not under my control. The code is not tagged (yet), so I always need to keep up with the trunk. </p></li>
<li><p>For a number of reasons (the most important being that our local extensions to the code are of a "niche" nature, and intended to solve a specific problem with the project in which the code is used) I can't use the remote repository to do version control of any modifications I make locally.</p></li>
<li><p>I have a local SVN repository in which I am currently doing the "local" versioning.</p></li>
</ul>
<p>The problem I'm faced with: I can't figure out if there's a good way to have the code simultaneously synchronized with both repositories. That is, I would like to keep the "remote" version information (so that I can merge in future changes), but I would also like to have "local" version information at the same time (i.e., within the same directory structure).</p>
<p>At the moment I am doing this using two different directories, both containing identical code, but each containing different versioning information. Obviously this is quite a bit of overhead, especially since the code in the two directories needs to be synchronized independently. </p>
<p>Is there a way to do this in subversion? Or do you have suggestions about alternative ways of approaching this?</p>
| [
{
"answer_id": 320771,
"author": "boutta",
"author_id": 15108,
"author_profile": "https://Stackoverflow.com/users/15108",
"pm_score": 2,
"selected": false,
"text": "svn merge -r X:Y baseRepositoryURL // merge from base repo\nsvn commit // commit the changes to local repo\nsvn merge -r Y:Z baseRepositoryURL // merge from base repo\nsvn commit // commit the changes to local repo\n"
},
{
"answer_id": 320832,
"author": "richq",
"author_id": 4596,
"author_profile": "https://Stackoverflow.com/users/4596",
"pm_score": 4,
"selected": true,
"text": "# set up the mirror\ngit svn clone -s $SVN\ngit remote add origin git@$MACHINE:svnmirror.git\ngit push\n# + cron job to do git svn rebase && git push every N hours/minutes\n\n# set up the local working copy for development\ngit clone git://$MACHINE/svnmirror.git\n# that's an anonymous, read only clone \n# no push to the svn mirror for developers - only cronjob user can push there\ngit remote add newproject git@$MACHINE:myproject.git\ngit push newproject\n# now do the real deal\ngit clone git://$MACHINE/myproject.git\n# hack hack hack\ngit push # origin master not needed\ngit remote add svnmirror git://$MACHINE/svnmirror.git\ngit merge svnmirror/master\ngit push\n"
}
] | 2008/11/26 | [
"https://Stackoverflow.com/questions/320759",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/30859/"
] |
320,761 | <p>Environment: </p>
<blockquote>
<p>win2003 running IIS6 serving asp pages that call delphi code.</p>
</blockquote>
<p>Delphi code contacts a <strong>c# webservice</strong> for which it needs to login (<code>login.asmx</code>). Webservice logs show login is successful. Debug results show that <code>Context.User.Identity.IsAuthenticated returns true</code>.</p>
<p>After login, delphi code doublechecks if it is still authenticated. Webservice returns false -> <code>Context.User.Identity.IsAuthenticated returns false</code>.</p>
<p>Our guess: authentication cookie received by delphi code running under <strong>IIS6</strong> credentials (network service?) does not get saved to disk, so login is lost.</p>
<p>Filemon shows <code>'C:\WINDOWS\Temp\Temporary Internet Files'</code> access denied. Giving <strong>IIS6</strong> user admin rights on that folder fixes the problem, but is not acceptable since cookies should work by default. </p>
<p>Running <strong>IIS6</strong> in <strong>IIS5</strong> compatibility mode fixes the problem, but is also not preferred</p>
<p>Wanted solution: exact cause of problem and smallest modification possible in configuration (giving admin rights to IUSR is not an option)</p>
| [
{
"answer_id": 320771,
"author": "boutta",
"author_id": 15108,
"author_profile": "https://Stackoverflow.com/users/15108",
"pm_score": 2,
"selected": false,
"text": "svn merge -r X:Y baseRepositoryURL // merge from base repo\nsvn commit // commit the changes to local repo\nsvn merge -r Y:Z baseRepositoryURL // merge from base repo\nsvn commit // commit the changes to local repo\n"
},
{
"answer_id": 320832,
"author": "richq",
"author_id": 4596,
"author_profile": "https://Stackoverflow.com/users/4596",
"pm_score": 4,
"selected": true,
"text": "# set up the mirror\ngit svn clone -s $SVN\ngit remote add origin git@$MACHINE:svnmirror.git\ngit push\n# + cron job to do git svn rebase && git push every N hours/minutes\n\n# set up the local working copy for development\ngit clone git://$MACHINE/svnmirror.git\n# that's an anonymous, read only clone \n# no push to the svn mirror for developers - only cronjob user can push there\ngit remote add newproject git@$MACHINE:myproject.git\ngit push newproject\n# now do the real deal\ngit clone git://$MACHINE/myproject.git\n# hack hack hack\ngit push # origin master not needed\ngit remote add svnmirror git://$MACHINE/svnmirror.git\ngit merge svnmirror/master\ngit push\n"
}
] | 2008/11/26 | [
"https://Stackoverflow.com/questions/320761",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
320,782 | <p>I find that in my daily Flex/Flash work, I do this number a lot:</p>
<pre><code>//Calling a function...
MyCustomObject(container.getChildAt(i)).mySpecialFunction();
</code></pre>
<p>The question is - is this the best way to do this? Should I do this:</p>
<pre><code>//Calling a function
var tempItem:MyCustomObject = container.getChildAt(i) as MyCustomObject;
tempItem.mySpecialFunction();
</code></pre>
<p>It might be incidental but I'm just wondering if there is an "accepted" way or a preferred way to do this. The second option seems more readable but I wonder if it takes more of a performance hit to create a new variable. Or does it all come down to style and preference?</p>
| [
{
"answer_id": 329508,
"author": "aaaidan",
"author_id": 26331,
"author_profile": "https://Stackoverflow.com/users/26331",
"pm_score": 3,
"selected": false,
"text": "as as // a casting error\ntry {\n var number:int = 666;\n var urlreq:URLRequest = URLRequest( number );\n} catch(e:TypeError) {\n // TypeError: Error #1034: Type Coercion failed: cannot \n // convert 666 to flash.net.URLRequest.\n trace(e); \n}\n as var number:int = 666;\nvar urlreq:URLRequest = number as URLRequest;\ntrace(urlreq); // prints null to the debug pane\n"
},
{
"answer_id": 329554,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "var tempItem:MyCustomObject = container.getChildAt(i) as MyCustomObject;\n\nif ( tempItem )\n{\n tempItem.mySpecialFunction();\n}\n"
}
] | 2008/11/26 | [
"https://Stackoverflow.com/questions/320782",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3435/"
] |
320,797 | <p>Using a macro I have consolidated info from several workbooks into one sheet in new workbook.</p>
<p>In one column I have created a named range called ColRange. That column has numbers ranging from -350 to 500.</p>
<p>How do I change the color of the cells based on the value of the text in the cell.<br>
red(0-500)
yellow(-5-0)
green(-350--5)</p>
| [
{
"answer_id": 320851,
"author": "Vincent Ramdhanie",
"author_id": 27439,
"author_profile": "https://Stackoverflow.com/users/27439",
"pm_score": 0,
"selected": false,
"text": "If value >= 0 AND value <= 500 Then\n ColRange.Interior.Color = RGB(255,0,0)\nElseIf value >= -5 Then\n ColRange.Interior.Color = RGB(255,255,200)\nElse\n ColRange.Interior.Color = RGB(0,255,0)\nEnd If\n"
},
{
"answer_id": 320884,
"author": "e.James",
"author_id": 33686,
"author_profile": "https://Stackoverflow.com/users/33686",
"pm_score": 2,
"selected": false,
"text": "Public Sub colorit()\n Dim colRange As Range\n Dim rowNum As Integer\n Dim rnum As Integer\n\n rnum = 20\n Set colRange = Range(Cells(2, 9), Cells(rnum, 9))\n\n For rowNum = 1 To colRange.Rows.Count\n If colRange.Cells(rowNum, 1).Value <= -5 Then\n colRange.Cells(rowNum, 1).Interior.Color = RGB(0, 255, 0)\n ElseIf colRange.Cells(rowNum, 1).Value <= 0 Then\n colRange.Cells(rowNum, 1).Interior.Color = RGB(255, 255, 0)\n ElseIf colRange.Cells(rowNum, 1).Value <= 500 Then\n colRange.Cells(rowNum, 1).Interior.Color = RGB(255, 0, 0)\n End If\n Next rowNum\nEnd Sub"
},
{
"answer_id": 352682,
"author": "KnomDeGuerre",
"author_id": 24233,
"author_profile": "https://Stackoverflow.com/users/24233",
"pm_score": 0,
"selected": false,
"text": "Dim c As Range\n\nFor Each c In Range(\"ColRange\").Cells\n If c.Value >= 0 And c.Value <= 500 Then\n c.Interior.Color = RGB(255, 0, 0)\n ElseIf c.Value >= -5 Then\n c.Interior.Color = RGB(255, 255, 200)\n Else\n c.Interior.Color = RGB(0, 255, 0)\n End If\n\nNext c\n Dim c as Range\n\nFor Each c In colRange.Cells\n\n If c.Value >= 0 And c.Value <= 500 Then\n c.Interior.Color = RGB(255, 0, 0)\n ElseIf c.Value >= -5 Then\n c.Interior.Color = RGB(255, 255, 200)\n Else\n c.Interior.Color = RGB(0, 255, 0)\n End If\n\nNext c\n"
}
] | 2008/11/26 | [
"https://Stackoverflow.com/questions/320797",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
320,798 | <p>Is it acceptable to add types to the <code>std</code> namespace. For example, I want a TCHAR-friendly string, so is the following acceptable?</p>
<pre><code>#include <string>
namespace std
{
typedef basic_string<TCHAR> tstring;
}
</code></pre>
<p>Or should I use my own namespace?</p>
| [
{
"answer_id": 321039,
"author": "Johannes Schaub - litb",
"author_id": 34509,
"author_profile": "https://Stackoverflow.com/users/34509",
"pm_score": 4,
"selected": false,
"text": "std::numeric_limits std::"
},
{
"answer_id": 9149437,
"author": "Lightness Races in Orbit",
"author_id": 560648,
"author_profile": "https://Stackoverflow.com/users/560648",
"pm_score": 4,
"selected": false,
"text": "[C++11: 17.6.4.2.1/1]: std std"
}
] | 2008/11/26 | [
"https://Stackoverflow.com/questions/320798",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9236/"
] |
320,801 | <p>I'm developing a new ASP .NET website which is effectively a subset of the pages in another site we've just released. Two or three of the pages will need minor tweaks but nothing significant.</p>
<p>The obvious answer is to simply copy all of the code and markup files into the new project, make the aforementioned tweaks, and consider the job done. However I'm not keen on this at all due to the amount of duplicated code it will create.</p>
<p>My next idea was to move the code for the pages (i.e. the code-behind file) into a separate assembly which can then be referenced from both sites. This is a little awkward however as if you don't take the designer file with it, you get a lot of build errors relating to missing controls. I don't think moving the designer file is a good idea though as this will need to be regenerated each time the markup is altered.</p>
<p>Does anyone have any suggestions for a clean solution to this problem?</p>
| [
{
"answer_id": 321054,
"author": "Josh",
"author_id": 11702,
"author_profile": "https://Stackoverflow.com/users/11702",
"pm_score": 3,
"selected": true,
"text": "public class SomePresenter\n{\n public ISomeView View{get; set;}\n\n public void InitializeView()\n {\n //Setup all the stuff on the view the first time\n\n View.Name = //Load from database\n View.Orders = //Load from database\n }\n\n public void LoadView()\n {\n //Handle all the stuff that happens each time the view loads\n }\n\n public Int32 AddOrder(Order newOrder)\n {\n //Code to update orders and then update the view\n }\n}\n public interface ISomeView\n{\n String Name {get; set;}\n IList<Order> Orders{get; set;}\n}\n public partial class SomeConcreteView : System.Web.UI.Page, ISomeView\n{\n public SomePresenter Presenter{get; set;}\n\n public SomeConcreteView()\n {\n Presenter = new SomePresenter();\n\n //Use the current page as the view instance\n Presenter.View = this; \n }\n\n protected void Page_Load(object sender, EventArgs e)\n {\n if(!IsPostBack)\n {\n Presenter.InitializeView(); \n }\n\n Presenter.LoadView();\n }\n\n //Implement your members to bind to actual UI elements\n public String Name\n {\n get{ return lblName.Text; }\n set{ lblName.Text = value; }\n }\n\n public IList<Order> Orders\n {\n get{ return (IList<Order>)ordersGrid.DataSource; }\n set\n {\n ordersGrid.DataSource = value;\n ordersGrid.DataBind();\n }\n }\n\n //Respond to UI events and forward them to the presenter\n protected virtual void addOrderButton_OnClick(object sender, EventArgs e)\n {\n Order newOrder = //Get order from UI\n Presenter.AddOrder(newOrder);\n }\n}\n"
}
] | 2008/11/26 | [
"https://Stackoverflow.com/questions/320801",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12277/"
] |
320,841 | <p>I have a question about css selectors.</p>
<p>Say I have the following html </p>
<pre><code><div class="message">
<div class="messageheader">
<div class='name'>A news story</div>
</div>
</div>
</code></pre>
<p>In the css I could refer to the <code>class</code> called <code>name</code> either like this</p>
<pre><code>div.message div.messageheader div.name {}
</code></pre>
<p>or</p>
<pre><code>.name {} /* ie *.name{} */
</code></pre>
<p><strong>Is one way better than the other?</strong></p>
<p>I understand that if I have an additional "instance" of the class called <code>name</code>, ie</p>
<pre><code><div class="message">
<div class="messageheader">
<div class='name'>A news story</div>
</div>
</div>
<a class='name'>A news story</div>
</code></pre>
<p>I could use <code>div.message div.messageheader div.name {}</code> to refer the first instance and <code>a.name {}</code> to the second instance, but I am interested in the initial scenario only.</p>
| [
{
"answer_id": 320889,
"author": "annakata",
"author_id": 13018,
"author_profile": "https://Stackoverflow.com/users/13018",
"pm_score": 1,
"selected": false,
"text": "'div' #foo .bar .baz div.foo .foo #foo .bar {}\n"
},
{
"answer_id": 324001,
"author": "Ola Tuvesson",
"author_id": 6903,
"author_profile": "https://Stackoverflow.com/users/6903",
"pm_score": 0,
"selected": false,
"text": "<style>\ndiv.product {\nfloat: left;\npadding: 1em;\nborder: 1px solid blue;\n}\n.price { \ncolor: #009900;\n}\np.price {\ntext-align: right;\n}\n</style>\n\n<div class=\"product\">\n <p>Lorem ipsum <span class=\"price\">£8.99</span> dolor sit amet.</p>\n <p class=\"price\">£5.99</p>\n</div>\n"
},
{
"answer_id": 324052,
"author": "alexmeia",
"author_id": 36587,
"author_profile": "https://Stackoverflow.com/users/36587",
"pm_score": 2,
"selected": false,
"text": "div.message div.messageheader div.name {}\n .name {}\n div.name\n div.messageheader div\n div.message div\n"
}
] | 2008/11/26 | [
"https://Stackoverflow.com/questions/320841",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/31765/"
] |
320,861 | <p>I have a class <code>Application</code> that my global.asax inherits from. The class has this method:</p>
<pre><code>protected void Application_Start(object sender, EventArgs e)
{
// ...
}
</code></pre>
<p>In my understanding this is basically an event handler that is automatically added to an event (based on the method name [*]). I tried to find out what event exactly, so I put a breakpoint inside the method and checked the call stack:</p>
<blockquote>
<p>Foo.DLL!Foo.Application.Application_Start(object
sender =
{System.Web.HttpApplicationFactory},
System.EventArgs e =
{System.EventArgs})</p>
</blockquote>
<p>The sender is <code>System.Web.HttpApplicationFactory</code>, but I can't find that class using the Object Browser in Visual Studio 2008 or on the MSDN library website. </p>
<p>Where can I find more information about this class?</p>
<p>Thank you!</p>
<hr>
<p>[*] Compare it to the <code>Application_BeginRequest(object sender, EventArgs e)</code> method, which is added as a handler to the <code>BeginRequest</code> event of the <code>System.Web.HttpApplication</code> class.</p>
| [
{
"answer_id": 321011,
"author": "configurator",
"author_id": 9536,
"author_profile": "https://Stackoverflow.com/users/9536",
"pm_score": 2,
"selected": false,
"text": "HttpApplicationFactory"
}
] | 2008/11/26 | [
"https://Stackoverflow.com/questions/320861",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4830/"
] |
320,887 | <p>I was thinking about how to create a program that would only be valid for X period of time, (within a C# app).</p>
<p>What I was thinking was that you would have the current date as a constant inside the program and it would check to see if it is X days older than that. Naturally I do not want to store the date, or the X outside of the program as it can be tampered with.</p>
<p>What I also do not want to manually change this regularly and recompile and deploy it. So is there a way to set a variable to be the current date when it is compiled?</p>
<p>I could have a batch file that would compile it and deploy the new exe to the distribution server.</p>
<p>Thanks</p>
| [
{
"answer_id": 320910,
"author": "Amy B",
"author_id": 8155,
"author_profile": "https://Stackoverflow.com/users/8155",
"pm_score": 3,
"selected": false,
"text": "// You can specify all the values or you can default the Build and Revision Numbers \n// by using the '*' as shown below:\n// [assembly: AssemblyVersion(\"1.0.*\")]\n[assembly: AssemblyVersion(\"1.0.0.0\")]\n[assembly: AssemblyFileVersion(\"1.0.0.0\")]\n [assembly: AssemblyVersion(\"1.0.*\")]\n[assembly: AssemblyFileVersion(\"1.0.0.0\")]\n System.Version MyVersion = System.Reflection.Assembly.GetExecutingAssembly().GetName().Version;\n\n// MyVersion.Build = days after 2000-01-01\n// MyVersion.Revision*2 = seconds after 0-hour (NEVER daylight saving time)\nDateTime MyTime = new DateTime(2000, 1, 1).AddDays(MyVersion.Build).AddSeconds(MyVersion.Revision * 2);\nreturn string.Format(\"Version:{0} Compiled:{1:s}\", MyVersion, MyTime);\n"
},
{
"answer_id": 320925,
"author": "James Curran",
"author_id": 12725,
"author_profile": "https://Stackoverflow.com/users/12725",
"pm_score": 2,
"selected": false,
"text": " public struct TimeLimit { public DateTime Date = new DateTime(2009,1,1); }\n"
}
] | 2008/11/26 | [
"https://Stackoverflow.com/questions/320887",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6486/"
] |
320,893 | <p>WinAPI OpenFile function returns HFILE, and GetFileTime for instance needs HANDLE. When I feed it with (HANDLE)some_hFile it seems to work fine. Is there any difference in this types, or one of these is simply rudimental?</p>
| [
{
"answer_id": 320965,
"author": "James Curran",
"author_id": 12725,
"author_profile": "https://Stackoverflow.com/users/12725",
"pm_score": 2,
"selected": false,
"text": "HANDLES int HANDLES HANDLE HANDLE HFILE HWND typedef int typedef struct _hfile {} * HFILE;\ntypedef struct _hwnd {} * HWND;\n int"
}
] | 2008/11/26 | [
"https://Stackoverflow.com/questions/320893",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/25459/"
] |
320,894 | <p>I have an Access 2002 application which links an Oracle table via ODBC with this code:</p>
<pre><code>Set HRSWsp = CreateWorkspace("CONNODBC", "", "", dbUseODBC)
Set HRSConn = HRSWsp.OpenConnection("HRSCONN", dbDriverPrompt, , "ODBC;")
DoCmd.TransferDatabase acLink, "Database ODBC", HRSConn.Connect, acTable, "SCHEMA.TABLE", "TABLE", False, True
</code></pre>
<p>Unfortunately, Access 2007 doesn't accept this syntax anymore, saying that ODBCDirect is no more supported (Runtime error 3847) and suggesting to use ADO instead of DAO.
Could someone please tell me how can I modify this code to satisfy Access 2007?</p>
| [
{
"answer_id": 322809,
"author": "Patrick Cuff",
"author_id": 7903,
"author_profile": "https://Stackoverflow.com/users/7903",
"pm_score": -1,
"selected": false,
"text": "Dim tbl As New ADOX.Table\nDim cat As New ADOX.Catalog\n\ncat.ActiveConnection = _\n \"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=[x:\\your_access_db.mdb];Jet OLEDB:Engine Type=4\"\n\ntbl.NAME = \"[Access_table_name]\"\n\nSet tbl.ParentCatalog = cat\n\ntbl.Properties(\"Jet OLEDB:Create Link\") = True\ntbl.Properties(\"Jet OLEDB:Link Provider String\") = \"ODBC;Driver={Microsoft ODBC For Oracle};Server=OracleServerName;Uid=[user];Pwd=[password];\"\ntbl.Properties(\"Jet OLEDB:Cache Link Name/Password\") = True\ntbl.Properties(\"Jet OLEDB:Remote Table Name\") = \"[Oracle_Schema].[Table]\"\n\ncat.Tables.Append tbl\ncat.ActiveConnection.Close\n []"
},
{
"answer_id": 323215,
"author": "Andrea Bertani",
"author_id": 1005,
"author_profile": "https://Stackoverflow.com/users/1005",
"pm_score": 3,
"selected": true,
"text": "DoCmd.TransferDatabase acLink, \"ODBC Database\", \"ODBC;DRIVER=Microsoft ODBC for Oracle;SERVER=myserver;UID=myuser;PWD=mypassword\", acTable, \"SCHEMA.TABLE\", \"TABLE\", False, True\n"
}
] | 2008/11/26 | [
"https://Stackoverflow.com/questions/320894",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1005/"
] |
320,895 | <blockquote>
<p><strong>Possible Duplicate:</strong><br>
<a href="https://stackoverflow.com/questions/167304/is-it-possible-to-pivot-data-using-linq">Is it possible to Pivot data using LINQ?</a> </p>
</blockquote>
<p>I'm wondering if its at all possible to create crosstab style results with Linq.
I have some data that looks like the following:</p>
<pre><code> var list = new[]
{
new {GroupId = 1, Country = "UK", Value = 10},
new {GroupId = 1, Country = "FR", Value = 12},
new {GroupId = 1, Country = "US", Value = 18},
new {GroupId = 2, Country = "UK", Value = 54},
new {GroupId = 2, Country = "FR", Value = 55},
new {GroupId = 2, Country = "UK", Value = 56}
};
</code></pre>
<p>and I'm trying to output to a repeater control something like the following:</p>
<pre><code>GroupId.....UK.....FR.....US
1...........10.....12.....18
2...........54.....55.....56
</code></pre>
<p>Its the dynamic columns that are causing my problems. Any solutions to this?</p>
| [
{
"answer_id": 321032,
"author": "Amy B",
"author_id": 8155,
"author_profile": "https://Stackoverflow.com/users/8155",
"pm_score": 2,
"selected": false,
"text": "XElement result = new XElement(\"result\",\n list.GroupBy(i => i.GroupId)\n .Select(g =>\n new XElement(\"Group\", new XAttribute(\"GroupID\", g.Key),\n g.Select(i => new XAttribute(i.Country, i.Value))\n )\n )\n);\n"
},
{
"answer_id": 1530424,
"author": "Nmducit",
"author_id": 180181,
"author_profile": "https://Stackoverflow.com/users/180181",
"pm_score": 1,
"selected": false,
"text": "var labResults = from lab in CoreLabResults\n where lab.Patient == 8\n group lab by new { lab.Patient, lab.TestNo, lab.CollectedDate }\n into labtests\n select new\n {\n labtests.Key.Patient,\n labtests.Key.TestNo,\n labtests.Key.CollectedDate,\n MCHC = labtests.Where(lab => lab.TestVar == \"MCHC\").FirstOrDefault().Result,\n LYABS = labtests.Where(lab => lab.TestVar == \"LYABS\").FirstOrDefault().Result,\n TotalTests = labtests.Count()\n }\n"
}
] | 2008/11/26 | [
"https://Stackoverflow.com/questions/320895",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
320,902 | <p>Microsoft SQL Server has a nice feature, which allows a database to be automatically expanded when it becomes full. In MySQL, I understand that a database is, in fact, a directory with a bunch of files corresponding to various objects. Does it mean that a concept of database size is not applicable and a MySQL database can be as big as available disk space allows without any additional concern? If yes, is this behavior the same across different storage engines?</p>
| [
{
"answer_id": 321217,
"author": "Gary Richardson",
"author_id": 2506,
"author_profile": "https://Stackoverflow.com/users/2506",
"pm_score": 3,
"selected": true,
"text": "innodb_file_per_table autoextend innodb_file_per_table"
}
] | 2008/11/26 | [
"https://Stackoverflow.com/questions/320902",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/40548/"
] |
320,906 | <p>I am using a piece of html something like the following:-</p>
<pre><code><a class="somePseudoClass" title="Blablabla">Something</a>
</code></pre>
<p>and I have the following css in an imported file.</p>
<pre><code>a.somePseudoClass:hover {color: #000000; text-decoration: underline;}
</code></pre>
<p>This works perfectly in Firefox 2.0 but in IE6 the underline fails to show.</p>
<p>Does anyone know of a workaround?</p>
| [
{
"answer_id": 320922,
"author": "PhiLho",
"author_id": 15459,
"author_profile": "https://Stackoverflow.com/users/15459",
"pm_score": 3,
"selected": false,
"text": "a.somePseudoClass {text-decoration: none;}\na.somePseudoClass:hover {color: #000000; text-decoration: underline;}\n<a class=\"somePseudoClass\" title=\"Blablabla\" href=\"#\" onclick=\"return false;\">Something</a>\n"
},
{
"answer_id": 320931,
"author": "Diodeus - James MacFarlane",
"author_id": 12579,
"author_profile": "https://Stackoverflow.com/users/12579",
"pm_score": 0,
"selected": false,
"text": "text-decoration: underline"
},
{
"answer_id": 3690416,
"author": "karim mohammadi",
"author_id": 445012,
"author_profile": "https://Stackoverflow.com/users/445012",
"pm_score": 2,
"selected": false,
"text": "div#nav a {\n text-decoration:none;\n}\n a:link"
}
] | 2008/11/26 | [
"https://Stackoverflow.com/questions/320906",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
320,921 | <p>I would like to modify an MSI installer (created through <a href="http://en.wikipedia.org/wiki/WiX" rel="noreferrer">WiX</a>) to delete an entire directory on uninstall.</p>
<p>I understand the <code>RemoveFile</code> and <code>RemoveFolder</code> options in WiX, but these are not robust enough to recursively delete an entire folder that has content created after the installation.</p>
<p>I noticed the similar Stack Overflow question <em><a href="https://stackoverflow.com/questions/195919">Removing files when uninstalling WiX</a></em>, but I was wondering if this could be done more simply using a call to a batch script to delete the folder.</p>
<p>This is my first time using WiX, and I'm still getting the hang of <a href="http://wix.sourceforge.net/manual-wix2/authoring_custom_actions.htm" rel="noreferrer">custom actions</a>. What would be a basic example of a custom action that will run a batch script on uninstall?</p>
| [
{
"answer_id": 321721,
"author": "csexton",
"author_id": 19839,
"author_profile": "https://Stackoverflow.com/users/19839",
"pm_score": 6,
"selected": false,
"text": "<InstallExecuteSequence> <InstallExecuteSequence>\n...\n <Custom Action=\"FileCleaner\" After='InstallFinalize'>\n Installed AND NOT UPGRADINGPRODUCTCODE</Custom>\n <Product> <Product> \n...\n <CustomAction Id='FileCleaner' BinaryKey='FileCleanerEXE' \n ExeCommand='' Return='asyncNoWait' />\n <Product> <Product> \n...\n <Binary Id=\"FileCleanerEXE\" SourceFile=\"path\\to\\fileCleaner.exe\" />\n Installed AND NOT UPGRADINGPRODUCTCODE"
},
{
"answer_id": 321874,
"author": "Rob Mensching",
"author_id": 23852,
"author_profile": "https://Stackoverflow.com/users/23852",
"pm_score": 5,
"selected": false,
"text": "REMOVE ~= \"ALL\"\n"
},
{
"answer_id": 731700,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 8,
"selected": false,
"text": "<Custom Action='CA_ID' Before='other_CA_ID'>\n (NOT UPGRADINGPRODUCTCODE) AND (REMOVE=\"ALL\")</Custom>\n"
},
{
"answer_id": 17608049,
"author": "ahmd0",
"author_id": 670017,
"author_profile": "https://Stackoverflow.com/users/670017",
"pm_score": 7,
"selected": false,
"text": "Installed INSTALLED REMOVE True"
},
{
"answer_id": 23293713,
"author": "Sid",
"author_id": 1654691,
"author_profile": "https://Stackoverflow.com/users/1654691",
"pm_score": 0,
"selected": false,
"text": "<CustomAction Id=\"Uninstall\" BinaryKey=\"Dll_Name\" \n DllEntry=\"Function_Name\" Execute=\"deferred\" />\n"
},
{
"answer_id": 51215272,
"author": "Bill Tarbell",
"author_id": 1721136,
"author_profile": "https://Stackoverflow.com/users/1721136",
"pm_score": 4,
"selected": false,
"text": "<!-- truth table for installer varables (install vs uninstall vs repair vs upgrade) https://stackoverflow.com/a/17608049/1721136 -->\n <SetProperty Id=\"_INSTALL\" After=\"FindRelatedProducts\" Value=\"1\"><![CDATA[Installed=\"\" AND PREVIOUSVERSIONSINSTALLED=\"\"]]></SetProperty>\n <SetProperty Id=\"_UNINSTALL\" After=\"FindRelatedProducts\" Value=\"1\"><![CDATA[PREVIOUSVERSIONSINSTALLED=\"\" AND REMOVE=\"ALL\"]]></SetProperty>\n <SetProperty Id=\"_CHANGE\" After=\"FindRelatedProducts\" Value=\"1\"><![CDATA[Installed<>\"\" AND REINSTALL=\"\" AND PREVIOUSVERSIONSINSTALLED<>\"\" AND REMOVE=\"\"]]></SetProperty>\n <SetProperty Id=\"_REPAIR\" After=\"FindRelatedProducts\" Value=\"1\"><![CDATA[REINSTALL<>\"\"]]></SetProperty>\n <SetProperty Id=\"_UPGRADE\" After=\"FindRelatedProducts\" Value=\"1\"><![CDATA[PREVIOUSVERSIONSINSTALLED<>\"\" ]]></SetProperty>\n <Custom Action=\"CaptureExistingLocalSettingsValues\" After=\"InstallInitialize\">NOT _UNINSTALL</Custom>\n <Custom Action=\"GetConfigXmlToPersistFromCmdLineArgs\" After=\"InstallInitialize\">_INSTALL OR _UPGRADE</Custom>\n <Custom Action=\"ForgetProperties\" Before=\"InstallFinalize\">_UNINSTALL OR _UPGRADE</Custom>\n <Custom Action=\"SetInstallCustomConfigSettingsArgs\" Before=\"InstallCustomConfigSettings\">NOT _UNINSTALL</Custom>\n <Custom Action=\"InstallCustomConfigSettings\" Before=\"InstallFinalize\">NOT _UNINSTALL</Custom>\n"
},
{
"answer_id": 74023116,
"author": "user2103458",
"author_id": 2103458,
"author_profile": "https://Stackoverflow.com/users/2103458",
"pm_score": 0,
"selected": false,
"text": "<Custom Action=\"ActionName\" Before=\"InstallFinalize\"><![CDATA[Installed AND NOT UPGRADINGPRODUCTCODE]]></Custom>\n"
}
] | 2008/11/26 | [
"https://Stackoverflow.com/questions/320921",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
320,929 | <p>I am looking to format a number like 188518982.18 to £188,518,982.18 using Python.</p>
<p>How can I do this?</p>
| [
{
"answer_id": 320951,
"author": "S.Lott",
"author_id": 10661,
"author_profile": "https://Stackoverflow.com/users/10661",
"pm_score": 9,
"selected": true,
"text": ">>> import locale\n>>> locale.setlocale( locale.LC_ALL, '' )\n'English_United States.1252'\n>>> locale.currency( 188518982.18 )\n'$188518982.18'\n>>> locale.currency( 188518982.18, grouping=True )\n'$188,518,982.18'\n"
},
{
"answer_id": 321013,
"author": "Johan Dahlin",
"author_id": 14337,
"author_profile": "https://Stackoverflow.com/users/14337",
"pm_score": 2,
"selected": false,
"text": ">>> from kiwi.datatypes import currency\n>>> v = currency('10.5').format()\n '$10.50'\n '10,50 kr'\n"
},
{
"answer_id": 3393776,
"author": "nate c",
"author_id": 397474,
"author_profile": "https://Stackoverflow.com/users/397474",
"pm_score": 7,
"selected": false,
"text": ">>> '{:20,.2f}'.format(18446744073709551616.0)\n'18,446,744,073,709,551,616.00'\n"
},
{
"answer_id": 3866014,
"author": "simoes",
"author_id": 467099,
"author_profile": "https://Stackoverflow.com/users/467099",
"pm_score": 4,
"selected": false,
"text": "Traceback (most recent call last):File \"<stdin>\", line 1, in <module> File \"/System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/locale.py\", line 221, in currency\nraise ValueError(\"Currency formatting is not possible using \"ValueError: Currency formatting is not possible using the 'C' locale.\n locale.setlocale(locale.LC_ALL, 'en_US')\n"
},
{
"answer_id": 8851191,
"author": "glenc",
"author_id": 288502,
"author_profile": "https://Stackoverflow.com/users/288502",
"pm_score": 6,
"selected": false,
"text": ">>> import babel.numbers\n>>> import decimal\n>>> babel.numbers.format_currency( decimal.Decimal( \"188518982.18\" ), \"GBP\" )\n£188,518,982.18\n"
},
{
"answer_id": 26771637,
"author": "Anshul Goyal",
"author_id": 1860929,
"author_profile": "https://Stackoverflow.com/users/1860929",
"pm_score": 0,
"selected": false,
"text": "converter = lambda amount, currency: \"%s%s%s\" %(\n \"-\" if amount < 0 else \"\", \n currency, \n ('{:%d,.2f}'%(len(str(amount))+3)).format(abs(amount)).lstrip())\n >>> converter(123132132.13, \"$\")\n'$123,132,132.13'\n\n>>> converter(-123132132.13, \"$\")\n'-$123,132,132.13'\n"
},
{
"answer_id": 40725768,
"author": "Marie",
"author_id": 7190586,
"author_profile": "https://Stackoverflow.com/users/7190586",
"pm_score": 2,
"selected": false,
"text": "print ('Total:', '{:7,.3f}'.format(zum1))\n"
},
{
"answer_id": 42753618,
"author": "elPastor",
"author_id": 6163621,
"author_profile": "https://Stackoverflow.com/users/6163621",
"pm_score": 6,
"selected": false,
"text": "num1 = 4153.53\nnum2 = -23159.398598\n\nprint 'This: ${:0,.0f} and this: ${:0,.2f}'.format(num1, num2).replace('$-','-$')\n This: $4,154 and this: -$23,159.40\n $ £"
},
{
"answer_id": 48938099,
"author": "Carlos",
"author_id": 2022848,
"author_profile": "https://Stackoverflow.com/users/2022848",
"pm_score": 3,
"selected": false,
"text": "from babel.numbers import format_decimal\n\n\nformat_decimal(188518982.18, locale='en_US')\n"
},
{
"answer_id": 55573753,
"author": "Vanjith",
"author_id": 3967750,
"author_profile": "https://Stackoverflow.com/users/3967750",
"pm_score": 0,
"selected": false,
"text": "def format_us_currency(value):\n value=str(value)\n if value.count(',')==0:\n b,n,v='',1,value\n value=value[:value.rfind('.')]\n for i in value[::-1]:\n b=','+i+b if n==3 else i+b\n n=1 if n==3 else n+1\n b=b[1:] if b[0]==',' else b\n value=b+v[v.rfind('.'):]\n return '$'+(value.rstrip('0').rstrip('.') if '.' in value else value)\n"
},
{
"answer_id": 57348563,
"author": "Eugene Gr. Philippov",
"author_id": 529442,
"author_profile": "https://Stackoverflow.com/users/529442",
"pm_score": 5,
"selected": false,
"text": "\"{:0,.2f}\".format(float(your_numeric_value)) 10,938.29\n10,899.00\n10,898.99\n2,328.99\n"
},
{
"answer_id": 62577702,
"author": "Elmer Gonzalez",
"author_id": 12822102,
"author_profile": "https://Stackoverflow.com/users/12822102",
"pm_score": 2,
"selected": false,
"text": "def money_format(value):\n value = str(value).split('.')\n money = ''\n count = 1\n\n for digit in value[0][::-1]:\n if count != 3:\n money += digit\n count += 1\n else:\n money += f'{digit},'\n count = 1\n\n if len(value) == 1:\n money = ('$' + money[::-1]).replace('$-','-$')\n else:\n money = ('$' + money[::-1] + '.' + value[1]).replace('$-','-$')\n\n return money\n"
},
{
"answer_id": 67510228,
"author": "neves",
"author_id": 10335,
"author_profile": "https://Stackoverflow.com/users/10335",
"pm_score": 3,
"selected": false,
"text": "locale.currency() import locale\n# this sets locale to the current Operating System value\nlocale.setlocale(locale.LC_ALL, '') \nprint(locale.currency(1346896.67444, grouping=True, symbol=True)\n R$ 1.346.896,67\n fmt = lambda x: locale.currency(x, grouping=True, symbol=True)\nprint(f\"Value: {fmt(1346896.67444)}\"\n setlocale symbol=False"
}
] | 2008/11/26 | [
"https://Stackoverflow.com/questions/320929",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/30786/"
] |
320,946 | <p>The Replace Temp with Query refactoring method is recommended quite widely now but
seems to be very inefficient for very little gain. </p>
<p>The method from the Martin Fowler's site gives the following example:</p>
<p>Extract the expression into a method. Replace all references to the temp with the expression. The new method can then be used in other methods.</p>
<pre><code> double basePrice = _quantity * _itemPrice;
if (basePrice > 1000)
return basePrice * 0.95;
else
return basePrice * 0.98;
</code></pre>
<p>becomes</p>
<pre><code> if (basePrice() > 1000)
return basePrice() * 0.95;
else
return basePrice() * 0.98;
double basePrice() {
return _quantity * _itemPrice;
}
</code></pre>
<p>Why is this a good idea? surely it means the calculation is needlessly repeated and you have the overhead of calling a function. I know CPU cycles
are cheap but throwing them away like this seems careless? </p>
<p>Am I missing something?</p>
| [
{
"answer_id": 320983,
"author": "MikeJ",
"author_id": 10676,
"author_profile": "https://Stackoverflow.com/users/10676",
"pm_score": 2,
"selected": false,
"text": " if (basePrice() > 1000)\n return bigTicketDiscount()\n else\n return regularDiscount()\n\ndouble bigTicketDiscount(){\n return basePrice() * 0.95;\n}\n\ndouble regularDiscount(){\n return basePrice() * 0.98\n}\n"
},
{
"answer_id": 320993,
"author": "James Curran",
"author_id": 12725,
"author_profile": "https://Stackoverflow.com/users/12725",
"pm_score": 3,
"selected": false,
"text": " double basePrice = basePrice();\n if (basePrice > 1000)\n return basePrice * 0.95;\n else\n return basePrice * 0.98;\n"
},
{
"answer_id": 29298039,
"author": "Bernd Elkemann",
"author_id": 618598,
"author_profile": "https://Stackoverflow.com/users/618598",
"pm_score": 3,
"selected": false,
"text": "Extract Method Extract Method Inline Method Method with Method Object"
},
{
"answer_id": 54169002,
"author": "Sandra",
"author_id": 4186357,
"author_profile": "https://Stackoverflow.com/users/4186357",
"pm_score": 3,
"selected": false,
"text": "if basePrice() if"
}
] | 2008/11/26 | [
"https://Stackoverflow.com/questions/320946",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
320,948 | <pre><code>Type.GetType("System.String")
</code></pre>
<p>Is there a lookup for the aliases available somewhere?</p>
<pre><code>Type.GetType("string")
</code></pre>
<p>returns <code>null</code>.</p>
| [
{
"answer_id": 320956,
"author": "configurator",
"author_id": 9536,
"author_profile": "https://Stackoverflow.com/users/9536",
"pm_score": 5,
"selected": true,
"text": "Type.GetType bool System.Boolean\n byte System.Byte\n sbyte System.SByte\n char System.Char\n decimal System.Decimal\n double System.Double\n float System.Single\n int System.Int32\n uint System.UInt32\n long System.Int64\n ulong System.UInt64\n object System.Object\n short System.Int16\n ushort System.UInt16\n string System.String\n"
},
{
"answer_id": 320971,
"author": "Mindaugas Mozūras",
"author_id": 26408,
"author_profile": "https://Stackoverflow.com/users/26408",
"pm_score": 2,
"selected": false,
"text": "Type.GetType(typeof (string).ToString())\n"
}
] | 2008/11/26 | [
"https://Stackoverflow.com/questions/320948",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21909/"
] |
320,950 | <p>I have seen the error "The ';' character, hexadecimal value 0x3B, cannot be included in a name." in my log files for an ASP.NET Web App. The url that's logged looks something like this:</p>
<pre><code>mypage.aspx?paramone=one+two&amp;paramtwo=zero+1
</code></pre>
<p>So my first question is what type of system/browser is encoding the original query string? (This happens rarely)</p>
<p>I've tried to address this problem with the following snippet of code in the Page_Load() event:</p>
<pre><code>string rawUrl = Request.RawUrl;
if (rawUrl.Contains(amp))
{
rawUrl = rawUrl.Replace("&amp;", "&");
Server.Transfer(rawUrl, false);
return;
}
</code></pre>
<p>However when it transfers back to this page the <code>&amp;</code> is back in the query string. So I'm guessing that the .Transfer() function encodes the first param.</p>
<p>Suggestions about solving this problem?</p>
| [
{
"answer_id": 9091903,
"author": "Philip",
"author_id": 1155613,
"author_profile": "https://Stackoverflow.com/users/1155613",
"pm_score": 0,
"selected": false,
"text": "The range 0x0021 – 0x002F includes ! “ # $ % & ‘ ( ) * + , - . /\nThe range 0x03A – 0x0040 includes : ; < = > ? @\nThe range 0x007B – 0x007E includes { | } ~\nThe range 0x005B – 0x005E [ \\ ] ^**\n"
}
] | 2008/11/26 | [
"https://Stackoverflow.com/questions/320950",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1463/"
] |
320,959 | <p>I need to <strong>disable PUT, DELETE & TRACE HTTP requests</strong> on my Application Server, Apache Tomcat 6.0.</p>
<p>All other sources, i have searched till now, have directed me towards the limit parameter in <em>httpd.conf</em>, Hence I'd put it before-hand that I am not using Apache Web Server, and requests are directly being handled by Tomcat, and so there is no <em>httpd.conf</em> in picture.</p>
<p>Please suggest how should I do it on Tomcat?</p>
| [
{
"answer_id": 321069,
"author": "James Schek",
"author_id": 17871,
"author_profile": "https://Stackoverflow.com/users/17871",
"pm_score": 5,
"selected": true,
"text": "<security-constraint>\n <web-resource-collection>\n <web-resource-name>Forbidden</web-resource-name>\n <url-pattern>/blah/*</url-pattern>\n <http-method>PUT</http-method>\n <http-method>DELETE</http-method>\n <http-method>TRACE</http-method>\n </web-resource-collection>\n <auth-constraint>\n <role-name>empty_role</role-name>\n </auth-constraint>\n</security-constraint>\n <connector> allowTrace=\"false\" <servlet>\n <servlet-name>default</servlet-name>\n <servlet-class>\n org.apache.catalina.servlets.DefaultServlet\n </servlet-class>\n <!-- blah blah blah -->\n <init-param>\n <param-name>readonly</param-name>\n <param-value>true</param-value>\n </init-param>\n</servlet>\n"
}
] | 2008/11/26 | [
"https://Stackoverflow.com/questions/320959",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18615/"
] |
320,979 | <p>I need to have the output of a PHP snippet in a Plone site. It was delivered to be a small library that has a display() function, in PHP, that outputs a line of text. But I need to put it in a Plone site. Do you have any recommendations?</p>
<p>I was thinking a long the lines of having a display.php that just runs display() and from the Plone template to download that URL and output the content. Do you think it might work? What methods of hitting a URL, retrieve the content and outputting can I use from inside a Plone template?</p>
<p>One important and critical constraint is that the output should be directly on the HTML and not an an iframe. This is a constraint coming from the outside, nothing technical.</p>
| [
{
"answer_id": 325149,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": true,
"text": "import os\nprint os.popen('php YourScript.php').read()"
}
] | 2008/11/26 | [
"https://Stackoverflow.com/questions/320979",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6068/"
] |
320,980 | <p><strong>What happens in the memory when a class instantiates the following object?</strong> </p>
<pre><code>public class SomeObject{
private String strSomeProperty;
public SomeObject(String strSomeProperty){
this.strSomeProperty = strSomeProperty;
}
public void setSomeProperty(String strSomeProperty){
this.strSomeProperty = strSomeProperty;
}
public String getSomeProperty(){
return this.strSomeProperty;
}
}
</code></pre>
<p>In class <code>SomeClass1</code>:</p>
<pre><code>SomeObject so1 = new SomeObject("some property value");
</code></pre>
<p>In class <code>SomeClass2</code>:</p>
<pre><code>SomeObject so2 = new SomeObject("another property value");
</code></pre>
<p><strong>How is memory allocated to the newly instantiated object and its properties?</strong> </p>
| [
{
"answer_id": 321060,
"author": "slim",
"author_id": 7512,
"author_profile": "https://Stackoverflow.com/users/7512",
"pm_score": 5,
"selected": true,
"text": "SomeObject so1 = new SomeObject(\"some property value\");\n String tmp = new String(\"some property value\");\nSomeObject so1 = new SomeObject(tmp);\n// Not that you would normally write it in this way.\n tmp strSomeProperty strSomeProperty this.strSomeProperty = strSomeProperty;\n strSomeProperty so1 so2"
}
] | 2008/11/26 | [
"https://Stackoverflow.com/questions/320980",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/37740/"
] |
320,986 | <p>I am trying to set up a simple transaction for my Linq-to-Sql actions against my Sql 2000 database. Using TransactionScope it looks like this:</p>
<pre><code>using (TransactionScope transaction = new TransactionScope())
{
try
{
Store.DBDataContext dc = new Store.DBDataContext();
Store.Product product = GetProduct("foo");
dc.InsertOnSubmit(product);
dc.SubmitChanges();
transaction.Complete();
}
catch (Exception ex)
{
throw ex;
}
}
</code></pre>
<p>However, i keep getting the following error:</p>
<p><em>The partner transaction manager has disabled its support for remote/network transactions. (Exception from HRESULT: 0x8004D025)</em></p>
<p>But, if I set up the transaction using a traditional transaction, it works fine. So this works fine:</p>
<pre><code>Store.DBDataContext dc = new Store.DBDataContext();
try
{
dc.Connection.Open();
dc.Transaction = dc.Connection.BeginTransaction();
Store.Product product = GetProduct("foo");
dc.InsertOnSubmit(product);
dc.SubmitChanges();
dc.Transaction.Commit();
}
catch (Exception ex)
{
dc.Transaction.Rollback();
throw ex;
}
finally
{
dc.Connection.Close();
dc.Transaction = null;
}
</code></pre>
<p>I'm wondering if the TransactionScope is doing something different under the covers than my second implementation. If not, what am I losing by not using TransactionScope? Also, any guidance on what is causing the error would be good too. I've confirmed that MSDTC is running in both sql server and on my client machine.</p>
| [
{
"answer_id": 321184,
"author": "Bramha Ghosh",
"author_id": 3268,
"author_profile": "https://Stackoverflow.com/users/3268",
"pm_score": 2,
"selected": false,
"text": "Store.DBDataContext dc = new Store.DBDataContext();\nusing (TransactionScope transaction = new TransactionScope())\n{\n try\n {\n var dbAdapter = new DatabaseTransactionAdapter(dc.Connection);\n dc.Connection.Open();\n dbAdapter.Begin();\n dc.Transaction = (SqlTransaction)dbAdapter.Transaction;\n Store.Product product = GetProduct(\"foo\");\n dc.InsertOnSubmit(product);\n dc.SubmitChanges();\n transaction.Complete();\n }\n catch (Exception ex)\n { \n throw ex;\n }\n}\n"
},
{
"answer_id": 50277771,
"author": "Greg",
"author_id": 3390350,
"author_profile": "https://Stackoverflow.com/users/3390350",
"pm_score": 1,
"selected": false,
"text": "db.SomeStoredProcedure();\n db.Database.ExecuteSqlCommand(\"exec [SomeDB].[dbo].[SomeStoredProcedure]\");\n var connectionString = db.Database.Connection.ConnectionString;\nvar connection = new System.Data.SqlClient.SqlConnection(connectionString); \nvar cmd = connection.CreateCommand();\ncmd.CommandText = \"exec [SomeDB].[dbo].[SomeStoredProcedure]\";\n\nconnection.Open();\nvar result = cmd.ExecuteNonQuery();\n"
}
] | 2008/11/26 | [
"https://Stackoverflow.com/questions/320986",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3268/"
] |
320,999 | <p>I wish to execute a javascript function after asp.net postback with out using ajax.</p>
<p>I've tried the following in my even method with no luck:</p>
<pre><code>Page.ClientScript.RegisterStartupScript(GetType(), "ShowPopup", "showCheckOutPopIn('Livraison',556);");
</code></pre>
| [
{
"answer_id": 321028,
"author": "Alexandre Brisebois",
"author_id": 18619,
"author_profile": "https://Stackoverflow.com/users/18619",
"pm_score": 3,
"selected": false,
"text": "Page.ClientScript.RegisterClientScriptBlock(this.GetType(), \"script\", \"alert('Success!');\", true);\n"
},
{
"answer_id": 2689646,
"author": "reSPAWNed",
"author_id": 71793,
"author_profile": "https://Stackoverflow.com/users/71793",
"pm_score": 7,
"selected": true,
"text": "ScriptManager.RegisterStartupScript(this, this.GetType(), \"ShowPopup\", \"showCheckOutPopIn('Livraison',556);\", true);\n ScriptManager.RegisterStartupScript(MainUpdatePanel, typeof(string), \"ShowPopup\", \"showCheckOutPopIn('Livraison',556);\", true);\n"
},
{
"answer_id": 29087696,
"author": "Dhananjay",
"author_id": 871726,
"author_profile": "https://Stackoverflow.com/users/871726",
"pm_score": 0,
"selected": false,
"text": "\nScriptManager.RegisterStartupScript(this, typeof(Sections), \"Initialize\", \"initialize();\", true); "
},
{
"answer_id": 44727113,
"author": "Alican Kablan",
"author_id": 7825088,
"author_profile": "https://Stackoverflow.com/users/7825088",
"pm_score": 0,
"selected": false,
"text": " ScriptManager.RegisterStartupScript(this, typeof(Page),\n \"ShowRegister\", string.Format(@\"$( document ).ready(function() {{ShowErrorMessage('{0}');}});\", message), true);true);\n Page.ClientScript.RegisterClientScriptBlock(GetType(), \"MEssage\",\n \"$( document ).ready(function() {\nShowMessage('{0}');\", true);\n"
}
] | 2008/11/26 | [
"https://Stackoverflow.com/questions/320999",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18619/"
] |
321,000 | <p>I've learned that <a href="http://en.wikipedia.org/wiki/Static_scoping#Static_scoping_.28also_known_as_lexical_scoping.29" rel="noreferrer">static scoping</a> is the only sane way to do things, and that <a href="http://en.wikipedia.org/wiki/Static_scoping#Dynamic_scoping" rel="noreferrer">dynamic scoping</a> is the tool of the devil, and results only from poor implementations of interpreters/compilers. </p>
<p>Then I saw this snippet from a <a href="http://community.schemewiki.org/?scheme-vs-common-lisp" rel="noreferrer">Common Lisp vs. Scheme</a> article:</p>
<pre>
Both Lexically and Dynamically Lexical scope only, per the standard.
scoped special vars. Common Dynamically scoped vars are provided
Lisp just wins on this point. by some implementations as an extension
but code using them is not portable.
(I have heard the arguments about whether Dynamic scoping
is or is not a Bad Idea in the first place. I don't care.
I'm just noting that you can do things with it that you
can't easily do without it.)
</pre>
<p>Why does Common Lisp "just win on this point"? What things are easier to do with dynamic scoping? I really can't justify ever needing it / seeing it as a good thing.</p>
| [
{
"answer_id": 5524159,
"author": "imz -- Ivan Zakharyaschev",
"author_id": 94687,
"author_profile": "https://Stackoverflow.com/users/94687",
"pm_score": 3,
"selected": false,
"text": " <cynic>Otherwise you'd have the equivalent of true closures,\nand if you had that java would be a\n*really* powerful and useful language, so they obviously couldn't do that.\n</cynic>\n"
},
{
"answer_id": 18415615,
"author": "Andreas Röhler",
"author_id": 1546473,
"author_profile": "https://Stackoverflow.com/users/1546473",
"pm_score": 0,
"selected": false,
"text": "(defun foo1 ()\n (message \"%s\" a))\n\n(defun foo2 ()\n (let ((a 2))\n (message \"%s\" a)))\n\n(defun foo3 ()\n (let ((a 1))\n (foo1)\n (foo2)))\n\n==>\n1\n2\n"
}
] | 2008/11/26 | [
"https://Stackoverflow.com/questions/321000",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15055/"
] |
321,024 | <p>I know python functions are virtual by default. Let's say I have this:</p>
<pre><code>class Foo:
def __init__(self, args):
do some stuff
def goo():
print "You can overload me"
def roo():
print "You cannot overload me"
</code></pre>
<p>I don't want them to be able to do this:</p>
<pre><code>class Aoo(Foo):
def roo():
print "I don't want you to be able to do this"
</code></pre>
<p>Is there a way to prevent users from overloading roo()?</p>
| [
{
"answer_id": 321119,
"author": "S.Lott",
"author_id": 10661,
"author_profile": "https://Stackoverflow.com/users/10661",
"pm_score": 4,
"selected": false,
"text": "class Foo( object ):\n def _roo( self ):\n \"\"\"Change this at your own risk.\"\"\"\n"
},
{
"answer_id": 321240,
"author": "Martin v. Löwis",
"author_id": 33006,
"author_profile": "https://Stackoverflow.com/users/33006",
"pm_score": 6,
"selected": true,
"text": "class NonOverridable(type):\n def __new__(self, name, bases, dct):\n if bases and \"roo\" in dct:\n raise SyntaxError, \"Overriding roo is not allowed\"\n return type.__new__(self, name, bases, dct)\n\nclass foo:\n __metaclass__=NonOverridable\n ...\n"
},
{
"answer_id": 321334,
"author": "M. Utku ALTINKAYA",
"author_id": 40948,
"author_profile": "https://Stackoverflow.com/users/40948",
"pm_score": 3,
"selected": false,
"text": "def non_overridable(f):\n f.non_overridable = True\n return f\n\nclass ToughMeta(type):\n def __new__(cls, name, bases, dct):\n non_overridables = get_non_overridables(bases)\n for name in dct:\n if name in non_overridables:\n raise Exception (\"You can not override %s, it is non-overridable\" % name)\n return type.__new__(cls, name, bases, dct)\n\ndef get_non_overridables(bases):\n ret = []\n for source in bases:\n for name, attr in source.__dict__.items():\n if getattr(attr, \"non_overridable\", False):\n ret.append(name)\n ret.extend(get_non_overridables(source.__bases__))\n return ret\n\nclass ToughObject(object):\n __metaclass__ = ToughMeta\n @non_overridable\n def test1():\n pass\n\n# Tests ---------------\nclass Derived(ToughObject):\n @non_overridable\n def test2(self):\n print \"hello\"\n\nclass Derived2(Derived):\n def test1(self):\n print \"derived2\"\n\n# --------------------\n"
},
{
"answer_id": 42079145,
"author": "Mr_and_Mrs_D",
"author_id": 281545,
"author_profile": "https://Stackoverflow.com/users/281545",
"pm_score": 2,
"selected": false,
"text": "class B(object):\n def __priv(self): print '__priv:', repr(self)\n\n def call_private(self):\n print self.__class__.__name__\n self.__priv()\n\nclass E(B):\n def __priv(self): super(E, self).__priv()\n\n def call_my_private(self):\n print self.__class__.__name__\n self.__priv()\n\nB().call_private()\nE().call_private()\nE().call_my_private()\n B\n__priv: <__main__.B object at 0x02050670>\nE\n__priv: <__main__.E object at 0x02050670>\nE\nTraceback (most recent call last):\n File \"C:/Users/MrD/.PyCharm2016.3/config/scratches/test_double__underscore\", line 35, in <module>\n E().call_my_private()\n File \"C:/Users/MrD/.PyCharm2016.3/config/scratches/test_double__underscore\", line 31, in call_my_private\n self.__priv()\n File \"C:/Users/MrD/.PyCharm2016.3/config/scratches/test_double__underscore\", line 27, in __priv\n def __priv(self): super(E, self).__priv()\nAttributeError: 'super' object has no attribute '_E__priv'\n \"\"\"DON'T OVERRIDE THIS METHOD\"\"\"\n"
},
{
"answer_id": 58939735,
"author": "Tagar",
"author_id": 470583,
"author_profile": "https://Stackoverflow.com/users/470583",
"pm_score": 6,
"selected": false,
"text": "final final final from typing import final\n\nclass Base:\n @final\n def foo(self) -> None:\n ...\n\nclass Derived(Base):\n def foo(self) -> None: # Error: Cannot override final attribute \"foo\"\n # (previously declared in base class \"Base\")\n ...\n\n"
},
{
"answer_id": 74101535,
"author": "Daniel Walker",
"author_id": 8075540,
"author_profile": "https://Stackoverflow.com/users/8075540",
"pm_score": 0,
"selected": false,
"text": "__init_subclass__ class Base:\n def __init_subclass__(cls) -> None:\n if cls.roo is not Base.roo:\n raise Exception('Oh, noes! Cannot override Base.roo!')\n Base Base"
}
] | 2008/11/26 | [
"https://Stackoverflow.com/questions/321024",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/34395/"
] |
321,034 | <p>My company currently evaluates the development of a Java FAT client. It should support a dynamic GUI and has as much logic as possible on the server side. Hence the idea came up to send the screen as XML to the FAT client, show it to the user and send the entered data similar to "html form" back in a structure like:</p>
<pre><code><fields>
<field type="checkbox" name="active" checked="false" x="10" y="10" />
<field type="textbox" name="username" value="dummy" x="10" y="30" />
<field type="selection" name="group" selectedIndex="1" x="10" y="50">
<data index="0">user</data>
<data index="1">admin</data>
</field>
<field type="button" name="ok" x="10" y="70" />
<field type="button" name="cancel" x="10" y="90" />
</field>
</code></pre>
<p><em>Background</em><br>
The sponsor is looking for an data entry and review application which they can adapt to their needs by simply changing the configuration. Hence we have to provide a possibility for their administrators to design so called "screens" (aka forms) and provide a client/server system enabling them to distribute those to their end users. Incoming data (i.e. data entered by an user) will be then forwarded to an already existing workflow engine which is handling the business logic.</p>
<p><strong>Question</strong><br>
Has anybody out there developed something similar? Which libraries would you suggest? Any pro & cons? Many thanks!</p>
<p><em>Update</em><br>
Many thanks for your input, <a href="http://www.thinlet.com" rel="noreferrer">Thinlet</a> looks very promising as well as <a href="http://en.wikipedia.org/wiki/JavaFX" rel="noreferrer">JavaFX</a> - I will look into both.</p>
| [
{
"answer_id": 321575,
"author": "jamesh",
"author_id": 4737,
"author_profile": "https://Stackoverflow.com/users/4737",
"pm_score": 3,
"selected": true,
"text": "localhost"
}
] | 2008/11/26 | [
"https://Stackoverflow.com/questions/321034",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/33429/"
] |
321,037 | <p>I have a custom Jabber IM client and I'm having a problem with links. When something like <a href="http://something.com" rel="noreferrer">http://something.com</a> is entered I want it to show up as a link in the message window. The message window is a standard c# textbox. Is there a way to mark it as a link so that it can be clicked and open the webpage?</p>
<p>Thanks</p>
| [
{
"answer_id": 35259896,
"author": "Lemonseed",
"author_id": 5865492,
"author_profile": "https://Stackoverflow.com/users/5865492",
"pm_score": 3,
"selected": false,
"text": "LinkClicked RichTextBox // Event raised from RichTextBox when user clicks on a link:\nprivate void richTextBox_LinkClicked(object sender, LinkClickedEventArgs e)\n{\n LaunchWeblink(e.LinkText);\n}\n\n// Performs the actual browser launch to follow link:\nprivate void LaunchWeblink(string url)\n{\n if (IsHttpURL(url)) Process.Start(url);\n}\n\n// Simple check to make sure link is valid,\n// can be modified to check for other protocols:\nprivate bool IsHttpURL(string url)\n{\n return\n ((!string.IsNullOrWhiteSpace(url)) &&\n (url.ToLower().StartsWith(\"http\")));\n}\n DetectUrls RichTextBox"
}
] | 2008/11/26 | [
"https://Stackoverflow.com/questions/321037",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2164/"
] |
321,055 | <p>I'm using a preformatted text file as a template for emails. The file has line breaks where I want them. I'd like to use this template to send a plain text email, but when I do I'm losing all formatting. Line breaks are stripped.</p>
<p>How do I parse this file and retain line breaks? I don't want to use a <code><pre></code> tag because I want to send plain text emails. </p>
<p>I'm using the classic ASP ReadAll method to pull the template into a string:</p>
<pre><code> Dim TextStream
Set TextStream = FSO.OpenTextFile(Filepath, ForReading, False, TristateUseDefault)
' Read file in one hit
Dim Contents
GetTemplate = TextStream.ReadAll ' return file contents
</code></pre>
<p>What am I missing?</p>
| [
{
"answer_id": 321132,
"author": "Russ",
"author_id": 32772,
"author_profile": "https://Stackoverflow.com/users/32772",
"pm_score": 2,
"selected": false,
"text": "We've generated a new password for you at your request, you can use this new password with your username to log in to various sections of our site.\n\nUsername: ##UserName##\nTemporary Password: ##Password##\n\nTo use this temporary password, please copy and paste it into the password box.\n\nPlease keep this email for your records.\n ListDictionary dictionary = new ListDictionary\n {\n {\"##UserName##\", user.BaseUser.UserName},\n {\"##Password##\", newPassword}\n };\n\n\n string fromResources = GetFromResources(\"forgotpasswordEmail.html\");\n string textfromResources = GetFromResources(\"forgotpasswordEmail.txt\");\n foreach (DictionaryEntry entry in dictionary)\n {\n fromResources = fromResources.Replace(entry.Key.ToString(), entry.Value.ToString());\n textfromResources = textfromResources.Replace(entry.Key.ToString(), entry.Value.ToString());\n }\n"
}
] | 2008/11/26 | [
"https://Stackoverflow.com/questions/321055",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/26180/"
] |
321,061 | <p>The situation I'm trying to solve: in my Cocoa app, I need to encrypt a string with a symmetric cipher, POST it to PHP, and have that script decode the data. The process needs to work in reverse for returning an answer (PHP encodes, Cocoa decodes).</p>
<p>I'm missing something because even though I can get both the key and initialization vector (iv) to be the same in both PHP and Cocoa, the decoding never works when one app sends its encoded data to the other. Both work just fine encoding/decoding their own data (verified to make sure there wasn't some PEBKAC issue at hand). I have a suspicion that there's a padding issue someplace, I just don't see it.</p>
<p>My cocoa app encodes using SSCrypto (which is just a handy-dandy wrapper around OpenSSL functions). The cipher is Blowfish, mode is CBC. (forgive the memory leaks, code has been stripped to the bare essentials)</p>
<pre><code>NSData *secretText = [@"secretTextToEncode" dataUsingEncoding:NSUTF8StringEncoding];
NSData *symmetricKey = [@"ThisIsMyKey" dataUsingEncoding:NSUTF8StringEncoding];
unsigned char *input = (unsigned char *)[secretText bytes];
unsigned char *outbuf;
int outlen, templen, inlen;
inlen = [secretText length];
unsigned char evp_key[EVP_MAX_KEY_LENGTH] = {"\0"};
int cipherMaxIVLength = EVP_MAX_IV_LENGTH;
EVP_CIPHER_CTX cCtx;
const EVP_CIPHER *cipher = EVP_bf_cbc();
cipherMaxIVLength = EVP_CIPHER_iv_length( cipher );
unsigned char iv[cipherMaxIVLength];
EVP_BytesToKey(cipher, EVP_md5(), NULL, [symmetricKey bytes], [symmetricKey length], 1, evp_key, iv);
NSData *initVector = [NSData dataWithBytes:iv length:cipherMaxIVLength];
EVP_CIPHER_CTX_init(&cCtx);
if (!EVP_EncryptInit_ex(&cCtx, cipher, NULL, evp_key, iv)) {
EVP_CIPHER_CTX_cleanup(&cCtx);
return nil;
}
int ctx_CipherKeyLength = EVP_CIPHER_CTX_key_length( &cCtx );
EVP_CIPHER_CTX_set_key_length(&cCtx, ctx_CipherKeyLength);
outbuf = (unsigned char *)calloc(inlen + EVP_CIPHER_CTX_block_size(&cCtx), sizeof(unsigned char));
if (!EVP_EncryptUpdate(&cCtx, outbuf, &outlen, input, inlen)){
EVP_CIPHER_CTX_cleanup(&cCtx);
return nil;
}
if (!EVP_EncryptFinal(&cCtx, outbuf + outlen, &templen)){
EVP_CIPHER_CTX_cleanup(&cCtx);
return nil;
}
outlen += templen;
EVP_CIPHER_CTX_cleanup(&cCtx);
NSData *cipherText = [NSData dataWithBytes:outbuf length:outlen];
NSString *base64String = [cipherText encodeBase64WithNewlines:NO];
NSString *iv = [initVector encodeBase64WithNewlines:NO];
</code></pre>
<p>base64String and iv are then POSTed to PHP that attempts to decode it:</p>
<pre><code><?php
import_request_variables( "p", "p_" );
if( $p_data != "" && $p_iv != "" )
{
$encodedData = base64_decode( $p_data, true );
$iv = base64_decode( $p_iv, true );
$td = mcrypt_module_open( MCRYPT_BLOWFISH, '', MCRYPT_MODE_CBC, '' );
$keySize = mcrypt_enc_get_key_size( $td );
$key = substr( md5( "ThisIsMyKey" ), 0, $keySize );
$decodedData = mcrypt_decrypt(MCRYPT_BLOWFISH, $key, $encodedData, MCRYPT_MODE_CBC, $iv );
mcrypt_module_close( $td );
echo "decoded: " . $decodedData;
}
?>
</code></pre>
<p>decodedData is always gibberish.</p>
<p>I've tried reversing the process, sending the encoded output from PHP to Cocoa but EVP_DecryptFinal() fails, which is what leads me to believe there's a NULL padding issue somewhere. I've read and re-read the PHP and OpenSSL docs but it's all blurring together now and I'm out of ideas to try.</p>
| [
{
"answer_id": 321587,
"author": "Boaz Stuller",
"author_id": 1464654,
"author_profile": "https://Stackoverflow.com/users/1464654",
"pm_score": 3,
"selected": true,
"text": "EVP_BytesToKey openssl enc"
},
{
"answer_id": 331726,
"author": "MyztikJenz",
"author_id": 4233,
"author_profile": "https://Stackoverflow.com/users/4233",
"pm_score": 1,
"selected": false,
"text": "EVP_BytesToKey $cipher = MCRYPT_TRIPLEDES;\n$cipherMode = MCRYPT_MODE_CBC;\n\n$keySize = mcrypt_get_key_size( $cipher, $cipherMode );\n$ivSize = mcrypt_get_iv_size( $cipher, $cipherMode );\n\n$rawKey = \"ThisIsMyKey\";\n$genKeyData = '';\ndo\n{\n $genKeyData = $genKeyData.md5( $genKeyData.$rawKey, true );\n} while( strlen( $genKeyData ) < ($keySize + $ivSize) );\n\n$generatedKey = substr( $genKeyData, 0, $keySize );\n$generatedIV = substr( $genKeyData, $keySize, $ivSize );\n\n$output = mcrypt_decrypt( $cipher, $generatedKey, $encodedData, $cipherMode, $generatedIV );\n\necho \"output (hex)\" . bin2hex($output);\n pkcs5_pad pkcs5_unpad EVP_BytesToKey() mcrypt_get_key_size() $keySize = mcrypt_enc_get_key_size( $td );\n$key = substr( md5( \"ThisIsMyKey\" ), 0, $keySize );\n $cipher = MCRYPT_BLOWFISH;\n$cipherMode = MCRYPT_MODE_CBC;\n\n$keySize = 16;\n EVP_BytesToKey()"
}
] | 2008/11/26 | [
"https://Stackoverflow.com/questions/321061",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4233/"
] |
321,067 | <p>This is in the context of <a href="http://en.wikipedia.org/wiki/Automatic_differentiation" rel="noreferrer">Automatic Differentiation</a> - what would such a system do with a function like <code>map</code>, or <code>filter</code> - or even one of the <a href="http://en.wikipedia.org/wiki/SKI_combinator_calculus" rel="noreferrer">SKI Combinators</a>?</p>
<p>Example: I have the following function:</p>
<pre><code>def func(x):
return sum(map(lambda a: a**x, range(20)))
</code></pre>
<p>What would its derivative be? What will an AD system yield as a result? (This function is well-defined on real-number inputs).</p>
| [
{
"answer_id": 2747023,
"author": "sigfpe",
"author_id": 207442,
"author_profile": "https://Stackoverflow.com/users/207442",
"pm_score": 2,
"selected": false,
"text": "sum sum + sum"
},
{
"answer_id": 11200054,
"author": "Edward Kmett",
"author_id": 34707,
"author_profile": "https://Stackoverflow.com/users/34707",
"pm_score": 2,
"selected": false,
"text": "ghci> :m + Numeric.AD\nghci> diff (\\x -> sum (map (**x) [1..20])) 10\n7.073726805128313e13\n ghci> :m + Debug.Traced\nghci> putStrLn $ showAsExp $ diff (\\x -> sum (map (**x) [1..20])) (unknown \"x\" :: Traced Double) \n1.0 * (1.0 ** x * log 1.0) + \n1.0 * (2.0 ** x * log 2.0) +\n1.0 * (3.0 ** x * log 3.0) +\n1.0 * (4.0 ** x * log 4.0) +\n1.0 * (5.0 ** x * log 5.0) +\n1.0 * (6.0 ** x * log 6.0) +\n1.0 * (7.0 ** x * log 7.0) +\n1.0 * (8.0 ** x * log 8.0) +\n1.0 * (9.0 ** x * log 9.0) +\n1.0 * (10.0 ** x * log 10.0) +\n1.0 * (11.0 ** x * log 11.0) +\n1.0 * (12.0 ** x * log 12.0) +\n1.0 * (13.0 ** x * log 13.0) +\n1.0 * (14.0 ** x * log 14.0) +\n1.0 * (15.0 ** x * log 15.0) +\n1.0 * (16.0 ** x * log 16.0) +\n1.0 * (17.0 ** x * log 17.0) +\n1.0 * (18.0 ** x * log 18.0) +\n1.0 * (19.0 ** x * log 19.0) +\n1.0 * (20.0 ** x * log 20.0)\n ghci> putStrLn $ showAsExp $ reShare $ diff (\\x -> sum (map (**x) [1..20])) \n (unknown \"x\" :: Traced Double)\nlet _21 = 1.0 ** x;\n _23 = log 1.0;\n _20 = _21 * _23;\n _19 = 1.0 * _20;\n _26 = 2.0 ** x;\n _27 = log 2.0;\n _25 = _26 * _27;\n _24 = 1.0 * _25;\n _18 = _19 + _24;\n _30 = 3.0 ** x;\n _31 = log 3.0;\n _29 = _30 * _31;\n _28 = 1.0 * _29;\n _17 = _18 + _28;\n _34 = 4.0 ** x;\n _35 = log 4.0;\n _33 = _34 * _35;\n _32 = 1.0 * _33;\n _16 = _17 + _32;\n _38 = 5.0 ** x;\n _39 = log 5.0;\n _37 = _38 * _39;\n _36 = 1.0 * _37;\n _15 = _16 + _36;\n _42 = 6.0 ** x;\n _43 = log 6.0;\n _41 = _42 * _43;\n _40 = 1.0 * _41;\n _14 = _15 + _40;\n _46 = 7.0 ** x;\n _47 = log 7.0;\n _45 = _46 * _47;\n _44 = 1.0 * _45;\n _13 = _14 + _44;\n _50 = 8.0 ** x;\n _51 = log 8.0;\n _49 = _50 * _51;\n _48 = 1.0 * _49;\n _12 = _13 + _48;\n _54 = 9.0 ** x;\n _55 = log 9.0;\n _53 = _54 * _55;\n _52 = 1.0 * _53;\n _11 = _12 + _52;\n _58 = 10.0 ** x;\n _59 = log 10.0;\n _57 = _58 * _59;\n _56 = 1.0 * _57;\n _10 = _11 + _56;\n _62 = 11.0 ** x;\n _63 = log 11.0;\n _61 = _62 * _63;\n _60 = 1.0 * _61;\n _9 = _10 + _60;\n _66 = 12.0 ** x;\n _67 = log 12.0;\n _65 = _66 * _67;\n _64 = 1.0 * _65;\n _8 = _9 + _64;\n _70 = 13.0 ** x;\n _71 = log 13.0;\n _69 = _70 * _71;\n _68 = 1.0 * _69;\n _7 = _8 + _68;\n _74 = 14.0 ** x;\n _75 = log 14.0;\n _73 = _74 * _75;\n _72 = 1.0 * _73;\n _6 = _7 + _72;\n _78 = 15.0 ** x;\n _79 = log 15.0;\n _77 = _78 * _79;\n _76 = 1.0 * _77;\n _5 = _6 + _76;\n _82 = 16.0 ** x;\n _83 = log 16.0;\n _81 = _82 * _83;\n _80 = 1.0 * _81;\n _4 = _5 + _80;\n _86 = 17.0 ** x;\n _87 = log 17.0;\n _85 = _86 * _87;\n _84 = 1.0 * _85;\n _3 = _4 + _84;\n _90 = 18.0 ** x;\n _91 = log 18.0;\n _89 = _90 * _91;\n _88 = 1.0 * _89;\n _2 = _3 + _88;\n _94 = 19.0 ** x;\n _95 = log 19.0;\n _93 = _94 * _95;\n _92 = 1.0 * _93;\n _1 = _2 + _92;\n _98 = 20.0 ** x;\n _99 = log 20.0;\n _97 = _98 * _99;\n _96 = 1.0 * _97;\n _0 = _1 + _96;\nin _0\n"
}
] | 2008/11/26 | [
"https://Stackoverflow.com/questions/321067",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15055/"
] |
321,068 | <p>Is there a preferred way to return multiple values from a C++ function? For example, imagine a function that divides two integers and returns both the quotient and the remainder. One way I commonly see is to use reference parameters:</p>
<pre><code>void divide(int dividend, int divisor, int& quotient, int& remainder);
</code></pre>
<p>A variation is to return one value and pass the other through a reference parameter:</p>
<pre><code>int divide(int dividend, int divisor, int& remainder);
</code></pre>
<p>Another way would be to declare a struct to contain all of the results and return that:</p>
<pre><code>struct divide_result {
int quotient;
int remainder;
};
divide_result divide(int dividend, int divisor);
</code></pre>
<p>Is one of these ways generally preferred, or are there other suggestions?</p>
<p>Edit: In the real-world code, there may be more than two results. They may also be of different types.</p>
| [
{
"answer_id": 321080,
"author": "Rob",
"author_id": 9236,
"author_profile": "https://Stackoverflow.com/users/9236",
"pm_score": 9,
"selected": true,
"text": "std::pair boost::tuple std::tuple std::tuple"
},
{
"answer_id": 321082,
"author": "James Curran",
"author_id": 12725,
"author_profile": "https://Stackoverflow.com/users/12725",
"pm_score": 5,
"selected": false,
"text": "std::pair<int, int> divide(int dividend, int divisor)\n{\n // :\n return std::make_pair(quotient, remainder);\n}\n\nstd::pair<int, int> answer = divide(5,2);\n // answer.first == quotient\n // answer.second == remainder\n"
},
{
"answer_id": 321142,
"author": "Patrick",
"author_id": 38892,
"author_profile": "https://Stackoverflow.com/users/38892",
"pm_score": 2,
"selected": false,
"text": "x = divide( x, y, z ) + divide( a, b, c ); void divide(int dividend, int divisor, Answer &ans)"
},
{
"answer_id": 321157,
"author": "AndyUK",
"author_id": 6795,
"author_profile": "https://Stackoverflow.com/users/6795",
"pm_score": 1,
"selected": false,
"text": "include \"boost/tuple/tuple.hpp\"\n\ntuple <int,int> divide( int dividend,int divisor ) \n\n{\n return make_tuple(dividend / divisor,dividend % divisor )\n}\n"
},
{
"answer_id": 321431,
"author": "Fred Larson",
"author_id": 10077,
"author_profile": "https://Stackoverflow.com/users/10077",
"pm_score": 7,
"selected": false,
"text": "result.first pair<double,double> calculateResultingVelocity(double windSpeed, double windAzimuth,\n double planeAirspeed, double planeCourse);\n\npair<double,double> result = calculateResultingVelocity(25, 320, 280, 90);\ncout << result.first << endl;\ncout << result.second << endl;\n struct Velocity {\n double speed;\n double azimuth;\n};\nVelocity calculateResultingVelocity(double windSpeed, double windAzimuth,\n double planeAirspeed, double planeCourse);\n\nVelocity result = calculateResultingVelocity(25, 320, 280, 90);\ncout << result.speed << endl;\ncout << result.azimuth << endl;\n"
},
{
"answer_id": 321528,
"author": "Jonathan Leffler",
"author_id": 15168,
"author_profile": "https://Stackoverflow.com/users/15168",
"pm_score": 3,
"selected": false,
"text": "div ldiv lldiv <stdlib.h> <cstdlib>"
},
{
"answer_id": 321542,
"author": "Michel",
"author_id": 31122,
"author_profile": "https://Stackoverflow.com/users/31122",
"pm_score": 3,
"selected": false,
"text": "std::pair divide_result"
},
{
"answer_id": 16516315,
"author": "oblitum",
"author_id": 1000282,
"author_profile": "https://Stackoverflow.com/users/1000282",
"pm_score": 8,
"selected": false,
"text": "#include <tuple>\n\nstd::tuple<int, int> divide(int dividend, int divisor) {\n return std::make_tuple(dividend / divisor, dividend % divisor);\n}\n\n#include <iostream>\n\nint main() {\n using namespace std;\n\n int quotient, remainder;\n\n tie(quotient, remainder) = divide(14, 3);\n\n cout << quotient << ',' << remainder << endl;\n}\n #include <tuple>\n\nstd::tuple<int, int> divide(int dividend, int divisor) {\n return {dividend / divisor, dividend % divisor};\n}\n\n#include <iostream>\n\nint main() {\n using namespace std;\n\n auto [quotient, remainder] = divide(14, 3);\n\n cout << quotient << ',' << remainder << endl;\n}\n auto divide(int dividend, int divisor) {\n struct result {int quotient; int remainder;};\n return result {dividend / divisor, dividend % divisor};\n}\n\n#include <iostream>\n\nint main() {\n using namespace std;\n\n auto result = divide(14, 3);\n\n cout << result.quotient << ',' << result.remainder << endl;\n\n // or\n\n auto [quotient, remainder] = divide(14, 3);\n\n cout << quotient << ',' << remainder << endl;\n}\n"
},
{
"answer_id": 27059013,
"author": "Roland",
"author_id": 1845672,
"author_profile": "https://Stackoverflow.com/users/1845672",
"pm_score": 2,
"selected": false,
"text": "class div{\n public:\n int remainder;\n\n int quotient(int dividend, int divisor){\n remainder = ...;\n return ...;\n }\n};\n"
},
{
"answer_id": 28319292,
"author": "PRAFUL ANAND",
"author_id": 4501434,
"author_profile": "https://Stackoverflow.com/users/4501434",
"pm_score": 2,
"selected": false,
"text": "# include <tuple>\n# include <iostream>\n\nusing namespace std; \n\ntuple < int,int,int,int,int > cal(int n1, int n2)\n{\n return make_tuple(n1/n2,n1%n2,n1+n2,n1-n2,n1*n2);\n}\n\nint main()\n{\n int qut,rer,add,sub,mul,a,b;\n cin>>a>>b;\n tie(qut,rer,add,sub,mul)=cal(a,b);\n cout << \"quotient= \"<<qut<<endl;\n cout << \"remainder= \"<<rer<<endl;\n cout << \"addition= \"<<add<<endl;\n cout << \"subtraction= \"<<sub<<endl;\n cout << \"multiplication= \"<<mul<<endl;\n return 0;\n}\n"
},
{
"answer_id": 38531743,
"author": "Johan Lundberg",
"author_id": 1149664,
"author_profile": "https://Stackoverflow.com/users/1149664",
"pm_score": 4,
"selected": false,
"text": "template<typename T1,typename T2,typename T3>\nstruct many {\n T1 a;\n T2 b;\n T3 c;\n};\n\n// guide:\ntemplate<class T1, class T2, class T3>\nmany(T1, T2, T3) -> many<T1, T2, T3>;\n\nauto f(){ return many{string(),5.7, unmovable()}; }; \n\nint main(){\n // in place construct x,y,z with a string, 5.7 and unmovable.\n auto [x,y,z] = f();\n}\n many"
},
{
"answer_id": 47337111,
"author": "Anchit Rana",
"author_id": 8953567,
"author_profile": "https://Stackoverflow.com/users/8953567",
"pm_score": 2,
"selected": false,
"text": "int divide(int a,int b,int quo,int &rem)\n"
},
{
"answer_id": 52842140,
"author": "Yakk - Adam Nevraumont",
"author_id": 1774667,
"author_profile": "https://Stackoverflow.com/users/1774667",
"pm_score": 4,
"selected": false,
"text": "void foo( int& result, int& other_result );\n void foo( int* result, int* other_result );\n & template<class T>\nstruct out {\n std::function<void(T)> target;\n out(T* t):target([t](T&& in){ if (t) *t = std::move(in); }) {}\n out(std::optional<T>* t):target([t](T&& in){ if (t) t->emplace(std::move(in)); }) {}\n out(std::aligned_storage_t<sizeof(T), alignof(T)>* t):\n target([t](T&& in){ ::new( (void*)t ) T(std::move(in)); } ) {}\n template<class...Args> // TODO: SFINAE enable_if test\n void emplace(Args&&...args) {\n target( T(std::forward<Args>(args)...) );\n }\n template<class X> // TODO: SFINAE enable_if test\n void operator=(X&&x){ emplace(std::forward<X>(x)); }\n template<class...Args> // TODO: SFINAE enable_if test\n void operator()(Args...&&args){ emplace(std::forward<Args>(args)...); }\n};\n void foo( out<int> result, out<int> other_result )\n foo out struct foo_r { int result; int other_result; };\nfoo_r foo();\n auto&&[result, other_result]=foo();\n std::tuple std::tuple<int, int> foo();\n auto&&[result, other_result]=foo();\n int result, other_result;\nstd::tie(result, other_result) = foo();\n out<> void foo( std::function<void(int result, int other_result)> );\n foo( [&](int result, int other_result) {\n /* code */\n} );\n void get_all_values( std::function<void(int)> value )\n value get_all_values( [&](int value){} ) void foo( std::function<void(int, std::function<void(int)>)> result );\n foo( [&](int result, auto&& other){ other([&](int other){\n /* code */\n}) });\n result other void foo( std::function< void(span<int>) > results )\n void foo( std::function< void(span<int>) > results ) {\n int local_buffer[1024];\n std::size_t used = 0;\n auto send_data=[&]{\n if (!used) return;\n results({ local_buffer, used });\n used = 0;\n };\n auto add_datum=[&](int x){\n local_buffer[used] = x;\n ++used;\n if (used == 1024) send_data();\n };\n auto add_data=[&](gsl::span<int const> xs) {\n for (auto x:xs) add_datum(x);\n };\n for (int i = 0; i < 7+(1<<20); ++i) {\n add_datum(i);\n }\n send_data(); // any leftover\n}\n std::function function_view std::function<void(std::function<void(int result, int other_result)>)> foo(int input);\n foo foo(7)([&](int result, int other_result){ /* code */ });\n variant foo template<class...Args>\nstruct broadcaster;\n\nbroadcaster<int, int> foo();\n foo foo( int_source )( int_dest1, int_dest2 );\n int_source int_dest1 int_dest2"
},
{
"answer_id": 56244154,
"author": "Carsten",
"author_id": 11535429,
"author_profile": "https://Stackoverflow.com/users/11535429",
"pm_score": 0,
"selected": false,
"text": "static struct SomeReturnType {int a,b,c; string str;} SomeFunction()\n{\n return {1,2,3,string(\"hello world\")}; // make sure you return values in the right order!\n}\n SomeReturnType st = SomeFunction();\n cout << \"a \" << st.a << endl;\n cout << \"b \" << st.b << endl;\n cout << \"c \" << st.c << endl;\n cout << \"str \" << st.str << endl;\n"
},
{
"answer_id": 64187488,
"author": "myworldbox",
"author_id": 12192271,
"author_profile": "https://Stackoverflow.com/users/12192271",
"pm_score": -1,
"selected": false,
"text": "#include <iostream>\nusing namespace std;\n\n// different values of [operate] can return different number.\nint yourFunction(int a, int b, int operate)\n{\n a = 1;\n b = 2;\n\n if (operate== 1)\n {\n return a;\n }\n else\n {\n return b;\n }\n}\n\nint main()\n{\n int a, b;\n\n a = yourFunction(a, b, 1); // get return 1\n b = yourFunction(a, b, 2); // get return 2\n\n return 0;\n}\n"
},
{
"answer_id": 70769118,
"author": "Piotr Henryk Dabrowski",
"author_id": 10245694,
"author_profile": "https://Stackoverflow.com/users/10245694",
"pm_score": 3,
"selected": false,
"text": "std::make_tuple auto #include <tuple>\n\n#include <string>\n#include <cstring>\n\nauto func() {\n // ...\n return std::make_tuple(1, 2.2, std::string(\"str\"), \"cstr\");\n}\n\nint main() {\n auto [i, f, s, cs] = func();\n return i + f + s.length() + strlen(cs);\n}\n -O1 -O3 rdi+N"
}
] | 2008/11/26 | [
"https://Stackoverflow.com/questions/321068",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10077/"
] |
321,077 | <p>I have an ASP.NET program where i am downloading a file from web using DownloadFile method of webClient Class and the do some modifications on it. then i am Saving it to another folder with a unique name.When I am getting this error</p>
<blockquote>
<p>The process cannot access the file 'D:\RD\dotnet\abc\abcimageupload\images\TempStorage\tempImage.jpg' because it is being used by another process</p>
</blockquote>
<p>Can anyone tell me how to solve this.</p>
| [
{
"answer_id": 321163,
"author": "Joel Meador",
"author_id": 1976,
"author_profile": "https://Stackoverflow.com/users/1976",
"pm_score": 4,
"selected": true,
"text": "WebClient wc = new WebClient();\nwc.DownloadFile(\"http://stackoverflow.com/Content/Img/stackoverflow-logo-250.png\", \"Foo.png\");\nFileStream fooStream;\nusing (fooStream = new FileStream(\"foo.png\", FileMode.Open))\n{\n // do stuff\n}\nFile.Move(\"foo.png\", \"foo2.png\");\n"
},
{
"answer_id": 679995,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "FileStream myStream = File.Create(fileName, results.Length,FileOptions.Asynchronous);\n//make sure you close the file\nmyStream.Write(results, 0, results.Length);\nmyStream.Flush();\nmyStream.Close();\nmyStream.Dispose();\n File.SetAttributes(Server.MapPath(sendFilepath), FileAttributes.Normal);\n"
},
{
"answer_id": 730513,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": " Dim fs As FileStream = Nothing\n fs = File.Create(\"H:\\test.txt\")\n fs.Close()\n File.Delete(\"H:\\test.txt\")\n File.Create(\"H:\\test.txt\")\n File.Delete(\"H:\\test.txt\")\n"
}
] | 2008/11/26 | [
"https://Stackoverflow.com/questions/321077",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/40521/"
] |
321,081 | <p>I have an xml file ('videofaq.xml') that defines a DTD using the following DOCTYPE</p>
<pre><code><!DOCTYPE video-faq SYSTEM "videofaq.dtd">
</code></pre>
<p>I am loading the file from the classpath (from a JAR actually) at Servlet initialization time using:</p>
<pre><code>getClass().getResourceAsStream("videofaq.xml")
</code></pre>
<p>The XML is found correctly, but for the DTD in the same package, Xerces gives me a FileNotFoundException, and displays the path to the Tomcat startup script with "videofaq.dtd" appended to the end. What hints, if any, can I pass on to Xerces to make it load the DTD properly?</p>
| [
{
"answer_id": 321224,
"author": "Loki",
"author_id": 39057,
"author_profile": "https://Stackoverflow.com/users/39057",
"pm_score": 1,
"selected": false,
"text": "getClass().getResourceAsStream(\"videofaq.xml\")\n"
},
{
"answer_id": 321233,
"author": "Joachim Sauer",
"author_id": 40342,
"author_profile": "https://Stackoverflow.com/users/40342",
"pm_score": 0,
"selected": false,
"text": "EntityResolver"
},
{
"answer_id": 321275,
"author": "erickson",
"author_id": 3474,
"author_profile": "https://Stackoverflow.com/users/3474",
"pm_score": 0,
"selected": false,
"text": "String getClass().getResource(\"videofaq.xml\")"
},
{
"answer_id": 325847,
"author": "Mads Hansen",
"author_id": 14419,
"author_profile": "https://Stackoverflow.com/users/14419",
"pm_score": 2,
"selected": true,
"text": "// construct a Source that reads from an InputStream\nSource mySrc = new StreamSource(anInputStream);\n// specify a system ID (a String) so the \n// Source can resolve relative URLs\n// that are encountered in XSLT stylesheets\nmySrc.setSystemId(aSystemId);\n"
}
] | 2008/11/26 | [
"https://Stackoverflow.com/questions/321081",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/41060/"
] |
321,096 | <p>If I'm using an ArrayList in C#.NET, is the order guaranteed to stay the same as the order I add items to it?</p>
| [
{
"answer_id": 321104,
"author": "Jon Skeet",
"author_id": 22656,
"author_profile": "https://Stackoverflow.com/users/22656",
"pm_score": 6,
"selected": true,
"text": "int size = list.Count;\nint index = list.Add(element);\nAssert.AreEqual(size, index); // Element is always added at the end\nAssert.AreEqual(element, list[index]); // Returned index is position in list\n ArrayList List<T> List<T>"
}
] | 2008/11/26 | [
"https://Stackoverflow.com/questions/321096",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2462/"
] |
321,106 | <p>I have the occasion to produce Drupal web sites using development, staging, and production environments. Keeping the code in sync between the sites is a simple task using subversion. What is not so simple is propagating changes to the database data (not just the schema) between installations.</p>
<p>The reason for this will be familiar to any Drupal developer. Drupal stores certain configuration settings in the database, specifically related to CCK fields, Views, and other modules that allow things to be set dynamically using the admin interface. Simply syncing the schema isn't enough - essential information is also in the data.</p>
<p>What I'm looking for is a way to sync these database changes so that if one developer makes CCK field changes on the staging server, they can be propagated down to local development environments for more work, and eventually up to the production environment.</p>
<p>Is there a tool that will do this? What is your process for handling single or multiple developers on a project like this?</p>
| [
{
"answer_id": 415913,
"author": "Stewart Robinson",
"author_id": 47424,
"author_profile": "https://Stackoverflow.com/users/47424",
"pm_score": 1,
"selected": false,
"text": "function ec_install() {\n $ret = array();\n $num = 0;\n while (1) {\n $version = 6000 + $num;\n $funcname = 'ec_update_' . $version;\n if (function_exists($funcname)) {\n $ret[] = $funcname();\n $num++;\n } else {\n break;\n }\n }\nreturn $ret;\n}\n // Create editor role and set permissions for comment module\nfunction ec_update_6000() {\n install_include(array('user'));\n $editor_rid = install_add_role('editor');\n install_add_permissions(DRUPAL_ANONYMOUS_RID, array('access comments'));\n install_add_permissions(DRUPAL_AUTHENTICATED_RID, array('access comments', 'post comments', 'post comments without approval'));\n install_add_permissions($editor_rid, array('administer comments', 'administer nodes'));\n return array();\n}\n// Enable the pirc theme.\nfunction ec_update_6001() {\n install_include(array('system'));\n // TODO: line below is not working due to a bug in Install Profile API. See http://drupal.org/node/316789.\n install_enable_theme('pirc');\n return array();\n}\n\n// Add the content types for article and mtblog\nfunction ec_update_6002() {\n install_include(array('node'));\n $props = array(\n 'description' => 'Historical Movable Type blog entries',\n );\n install_create_content_type('mtblog', 'MT Blog entry', $props);\n $props = array(\n 'description' => 'Article',\n );\ninstall_create_content_type('article', 'Article', $props);\nreturn array();\n}\n // Enable CCK modules, add CCK types for Articles in prep for first stage of migration,\n// enable body for article, enable migration modules.\nfunction ec_update_6023() {\n $ret = array();\n drupal_install_modules(array('content', 'content_copy', 'text', 'number', 'optionwidgets'));\n install_include(array('content', 'content_copy'));\n install_content_copy_import_from_file(drupal_get_path('module', 'ec') . '/' . 'article.type', 'article');\n $sql = \"UPDATE {node_type} SET body_label='Body', has_body=1\n WHERE type = 'article'\";\n $ret[] = update_sql($sql);\n return $ret;\n} \n"
}
] | 2008/11/26 | [
"https://Stackoverflow.com/questions/321106",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/40413/"
] |
321,112 | <p>How would you run the Selenium process (thread) from a Java process so I don't have to start Selenium by hand?</p>
| [
{
"answer_id": 321243,
"author": "BraveSirFoobar",
"author_id": 39263,
"author_profile": "https://Stackoverflow.com/users/39263",
"pm_score": 4,
"selected": true,
"text": "import org.openqa.selenium.server.SeleniumServer;\npublic class SeleniumServerControl {\n private static final SeleniumServerControl instance = new SeleniumServerControl();\n public static SeleniumServerControl getInstance() {\n return instance;\n }\n private SeleniumServer server = null;\n protected SeleniumServerControl() {\n }\n public void startSeleniumServer() {\n if (server == null) {\n try {\n server = new SeleniumServer(SeleniumServer.DEFAULT_PORT);\n System.out.println(\" selenium server \" + server.toString());\n } catch (Exception e) {\n System.err.println(\"Could not create Selenium Server because of: \"\n + e.getMessage());\n e.printStackTrace();\n }\n }\n try {\n server.start();\n } catch (Exception e) {\n System.err.println(\"Could not start Selenium Server because of: \"\n + e.getMessage());\n e.printStackTrace();\n }\n }\n public void stopSeleniumServer() {\n if (server != null) {\n try {\n server.stop();\n server = null;\n } catch (Exception e) {\n System.err.println(\"Could not stop Selenium Server because of: \"\n + e.getMessage());\n e.printStackTrace();\n }\n }\n }\n}\n browser = new DefaultSelenium(\"localhost\", 4444, \"*firefox\", \"http://www.google.com\");\nbrowser.start();\n"
},
{
"answer_id": 1426950,
"author": "Urszula Karzelek",
"author_id": 63852,
"author_profile": "https://Stackoverflow.com/users/63852",
"pm_score": 2,
"selected": false,
"text": " RemoteControlConfiguration settings = new RemoteControlConfiguration();\n File f = new File(\"/home/user/.mozilla/firefox/default\");\n settings.setFirefoxProfileTemplate(f);\n settings.setReuseBrowserSessions(true);\n settings.setSingleWindow(true);\n if (this.ServerWorks == false)\n {\n try\n {\n server = new SeleniumServer(settings);\n server.start();\n this.ServerWorks = true;\n } catch (Exception e)\n {\n e.printStackTrace();\n }\n }\n"
}
] | 2008/11/26 | [
"https://Stackoverflow.com/questions/321112",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6068/"
] |
321,113 | <p>I am trying to write a JavaScript function that will return its first argument(function) with all the rest of its arguments as preset parameters to that function.</p>
<p>So:</p>
<pre>function out(a, b) {
document.write(a + " " + b);
}
function setter(...) {...}
setter(out, "hello")("world");
setter(out, "hello", "world")();
</pre>
<p>Would output "hello world" twice. for some implementation of setter</p>
<p>I ran into an issue with manipulating the arguments array on my first try, but it seems there would be a better way to do this.</p>
| [
{
"answer_id": 321291,
"author": "Eugene Lazutkin",
"author_id": 26394,
"author_profile": "https://Stackoverflow.com/users/26394",
"pm_score": 2,
"selected": false,
"text": "dojo.hitch(out, \"hello\")(\"world\");\ndojo.hitch(out, \"hello\", \"world\")();\n var A = {\n sep: \", \",\n out: function(a, b){ console.log(a + this.sep + b); }\n};\n\n// using functions in context \ndojo.hitch(A, A.out, \"hello\")(\"world\");\ndojo.hitch(A, A.out, \"hello\", \"world\")();\n\n// using names in context\ndojo.hitch(A, \"out\", \"hello\")(\"world\");\ndojo.hitch(A, \"out\", \"hello\", \"world\")();\n df.curry(out)(\"hello\")(\"world\");\ndf.curry(out)(\"hello\", \"world\");\n df.partial(out, df.arg, \"world\")(\"hello\");\n"
},
{
"answer_id": 321408,
"author": "Illandril",
"author_id": 17887,
"author_profile": "https://Stackoverflow.com/users/17887",
"pm_score": 0,
"selected": false,
"text": "function out(a, b) {\n document.write(a + \" \" + b);\n}\n\nfunction getArgString( args, start ) {\n var argStr = \"\";\n for( var i = start; i < args.length; i++ ) {\n if( argStr != \"\" ) {\n argStr = argStr + \", \";\n }\n argStr = argStr + \"arguments[\" + i + \"]\"\n }\n return argStr;\n}\n\nfunction setter(func) {\n var argStr = getArgString( arguments, 1 );\n eval( \"func( \" + argStr + \");\" );\n var newSettter = function() {\n var argStr = getArgString( arguments, 0 );\n if( argStr == \"\" ) {\n argStr = \"func\";\n } else {\n argStr = \"func, \" + argStr;\n }\n return eval( \"setter( \" + argStr + \");\" );\n }\n return newSettter;\n}\n\nsetter(out, \"hello\")(\"world\");\nsetter(out, \"hello\", \"world\")();\n"
},
{
"answer_id": 321527,
"author": "Jason Bunting",
"author_id": 1790,
"author_profile": "https://Stackoverflow.com/users/1790",
"pm_score": 8,
"selected": true,
"text": "function partial(func /*, 0..n args */) {\n var args = Array.prototype.slice.call(arguments, 1);\n return function() {\n var allArguments = args.concat(Array.prototype.slice.call(arguments));\n return func.apply(this, allArguments);\n };\n}\n partial(out, \"hello\")(\"world\");\npartial(out, \"hello\", \"world\")();\n\n// and here is my own extended example\nvar sayHelloTo = partial(out, \"Hello\");\nsayHelloTo(\"World\");\nsayHelloTo(\"Alex\");\n partial()"
},
{
"answer_id": 30926166,
"author": "Scimonster",
"author_id": 3187556,
"author_profile": "https://Stackoverflow.com/users/3187556",
"pm_score": 1,
"selected": false,
"text": "Function.prototype.bind() this function out(a, b) {\n document.write(a + \" \" + b);\n}\n\nfunction setter(func) {\n return func.bind.apply(func, [window].concat([].slice.call(arguments).slice(1)));\n}\n\nsetter(out, \"hello\")(\"world\");\nsetter(out, \"hello\", \"world\")(); setter func.bind.apply(func, [window].concat([].slice.call(arguments).slice(1)))\nfunc.bind.apply( ) // need to use apply to pass multiple arguments as an array to bind()\n func, // apply needs a context to be run in\n [window].concat( ) // pass an array of arguments to bind(), starting with window, to be the global context\n [].slice.call(arguments).slice(1) // convert the arguments list to an array, and chop off the initial value\n"
},
{
"answer_id": 47826960,
"author": "Muhammad Umer",
"author_id": 1319799,
"author_profile": "https://Stackoverflow.com/users/1319799",
"pm_score": 2,
"selected": false,
"text": "apply() function prototype Function.prototype.pass = function() {\n var args = arguments,\n func = this;\n return function() {\n func.apply(this, args);\n }\n};\n out.pass('hello','world') apply arguments bind loadedFunc = func.bind(this, v1, v2, v3); loadedFunc() === this.func(v1,v2,v3);"
},
{
"answer_id": 60037203,
"author": "marjon4",
"author_id": 11566773,
"author_profile": "https://Stackoverflow.com/users/11566773",
"pm_score": 1,
"selected": false,
"text": "exportFile(docType) function(){ return exportFile(docType) }"
}
] | 2008/11/26 | [
"https://Stackoverflow.com/questions/321113",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/40397/"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.