qid
int64
4
19.1M
question
stringlengths
18
48.3k
answers
list
date
stringlengths
10
10
metadata
list
113,025
<p>I'm trying to create an unusual associative array implementation that is very space-efficient, and I need a sorting algorithm that meets all of the following:</p> <ol> <li>Stable (Does not change the relative ordering of elements with equal keys.)</li> <li>In-place or almost in-place (O(log n) stack is fine, but no O(n) space usage or heap allocations.</li> <li>O(n log n) time complexity.</li> </ol> <p>Also note that the data structure to be sorted is an array.</p> <p>It's easy to see that there's a basic algorithm that matches any 2 of these three (insertion sort matches 1 and 2, merge sort matches 1 and 3, heap sort matches 2 and 3), but I cannot for the life of me find anything that matches all three of these criteria.</p>
[ { "answer_id": 170422, "author": "Eric", "author_id": 4540, "author_profile": "https://Stackoverflow.com/users/4540", "pm_score": 2, "selected": false, "text": "function cmp( ar, idx1, idx2 )\n{\n // first compare elements as usual\n rc = (ar[idx1]<ar[idx2]) ? -1 : ( (ar[idx1]>ar[idx2]) ? 1 : 0 );\n\n // if the elements are identical, then compare their positions\n if( rc != 0 )\n rc = (idx1<idx2) ? -1 : ((idx1>idx2) ? 1 : 0);\n\n return rc; \n}\n" }, { "answer_id": 585622, "author": "paxdiablo", "author_id": 14860, "author_profile": "https://Stackoverflow.com/users/14860", "pm_score": 2, "selected": false, "text": "C qsort() qsort()" }, { "answer_id": 1290010, "author": "Mike Dunlavey", "author_id": 23771, "author_profile": "https://Stackoverflow.com/users/23771", "pm_score": 0, "selected": false, "text": "N*sizeof(int)" } ]
2008/09/22
[ "https://Stackoverflow.com/questions/113025", "https://Stackoverflow.com", "https://Stackoverflow.com/users/23903/" ]
113,028
<p>Internet Explorer 8 breaks what must be every 3rd page I look at. The point of this early release was, I presume, to give website owners the chance to update their sites so it wouldn't be such a hassle for the final release.</p> <p>Has anyone actually done this?</p> <p>Is anyone even planning on doing this?</p> <p>I have yet to notice any of the big sites like ebay, myspace, facebook and so on bother so why will smaller sites if they can just use the compatibility mode?</p> <p>I think i'll do it with mine, but how can you have your site compatible with IE7 and 8?</p>
[ { "answer_id": 113122, "author": "Jon Galloway", "author_id": 5, "author_profile": "https://Stackoverflow.com/users/5", "pm_score": 2, "selected": false, "text": "<html>\n<head>\n<title>Works in IE8</title>\n<meta http-equiv=\"X-UA-Compatible\" content=\"IE=EmulateIE7\"/>\n</head>\n<body>Renders the same in IE8 as it did in IE7</body>\n" } ]
2008/09/22
[ "https://Stackoverflow.com/questions/113028", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19713/" ]
113,033
<p>I have three (C++) classes: Player, Hand, and Card.</p> <p>Player has a member, hand, that holds a Hand. It also has a method, getHand(), that returns the contents of hand.</p> <pre><code>Hand Player::getHand() { return hand; } </code></pre> <p>Hand has a method, addCard(Card c), that adds a card to the hand.</p> <p>I want to do this:</p> <p>player1.getHand().addCard(c);</p> <p>but it doesn't work. It doesn't throw an error, so it's doing something. But if I examine the contents of player1's hand afterward, the card hasn't been added.</p> <p>How can I get this to work?</p>
[ { "answer_id": 113053, "author": "metao", "author_id": 11484, "author_profile": "https://Stackoverflow.com/users/11484", "pm_score": 0, "selected": false, "text": " private:\n Hand(const Hand& rhs);\n Hand& operator=(const Hand& rhs);\n" }, { "answer_id": 113074, "author": "Adam Pierce", "author_id": 5324, "author_profile": "https://Stackoverflow.com/users/5324", "pm_score": 1, "selected": false, "text": "Hand &Player::getHand() {\n return hand;\n}\n" } ]
2008/09/22
[ "https://Stackoverflow.com/questions/113033", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18420/" ]
113,045
<pre><code>SELECT GETDATE() </code></pre> <p>Returns: <code>2008-09-22 15:24:13.790</code></p> <p>I want that date part without the time part: <code>2008-09-22 00:00:00.000</code></p> <p>How can I get that?</p>
[ { "answer_id": 113051, "author": "Nescio", "author_id": 14484, "author_profile": "https://Stackoverflow.com/users/14484", "pm_score": 6, "selected": false, "text": "SELECT CONVERT(VARCHAR(10),GETDATE(),111)\n YYYY/MM/DD" }, { "answer_id": 113054, "author": "Cade Roux", "author_id": 18255, "author_profile": "https://Stackoverflow.com/users/18255", "pm_score": 6, "selected": false, "text": "SELECT CONVERT(datetime, CONVERT(varchar, GETDATE(), 101))\n" }, { "answer_id": 113055, "author": "aku", "author_id": 1196, "author_profile": "https://Stackoverflow.com/users/1196", "pm_score": 12, "selected": true, "text": "SELECT DATEADD(dd, 0, DATEDIFF(dd, 0, @your_date))\n SELECT DATEADD(dd, 0, DATEDIFF(dd, 0, GETDATE()))\n 2008-09-22 00:00:00.000\n" }, { "answer_id": 113057, "author": "DaveK", "author_id": 4244, "author_profile": "https://Stackoverflow.com/users/4244", "pm_score": 5, "selected": false, "text": "CONVERT CONVERT ( data_type [ ( length ) ] , expression [ , style ] ) \n" }, { "answer_id": 113059, "author": "Gordon Bell", "author_id": 16473, "author_profile": "https://Stackoverflow.com/users/16473", "pm_score": 4, "selected": false, "text": "SELECT DATEADD(DD, DATEDIFF(DD, 0, GETDATE()), 0)\n\nSELECT DATEADD(DAY, 0, DATEDIFF(DAY,0, GETDATE()))\n\nSELECT CONVERT(DATETIME, CONVERT(VARCHAR(10), GETDATE(), 101))\n" }, { "answer_id": 113650, "author": "DiGi", "author_id": 12042, "author_profile": "https://Stackoverflow.com/users/12042", "pm_score": 4, "selected": false, "text": "SELECT CAST(FLOOR(CAST(GETDATE() AS FLOAT)) AS DATETIME)\n" }, { "answer_id": 113733, "author": "Ricardo C", "author_id": 232589, "author_profile": "https://Stackoverflow.com/users/232589", "pm_score": 6, "selected": false, "text": "set showplan_text on\nGO \n |--Compute Scalar(DEFINE:([Expr1004]=CONVERT(varchar(30),[TEST].[dbo].[DatesTable].[MyDate],101)))\n |--Table Scan(OBJECT:([TEST].[dbo].[DatesTable]))\n |--Compute Scalar(DEFINE:([Expr1004]=dateadd(day,(0),CONVERT_IMPLICIT(datetime,datediff(day,'1900-01-01 00:00:00.000',CONVERT_IMPLICIT(datetime,[TEST].[dbo].[DatesTable].[MyDate],0)),0))))\n |--Table Scan(OBJECT:([TEST].[dbo].[DatesTable]))\n" }, { "answer_id": 126984, "author": "BenR", "author_id": 18039, "author_profile": "https://Stackoverflow.com/users/18039", "pm_score": 10, "selected": false, "text": "SELECT CONVERT(date, GETDATE())\n" }, { "answer_id": 4849412, "author": "abatishchev", "author_id": 41956, "author_profile": "https://Stackoverflow.com/users/41956", "pm_score": 8, "selected": false, "text": "select cast(getdate() as date)\n" }, { "answer_id": 7514630, "author": "Rushda", "author_id": 959076, "author_profile": "https://Stackoverflow.com/users/959076", "pm_score": 4, "selected": false, "text": "SELECT CONVERT(VARCHAR,DATEADD(DAY,-1,GETDATE()),103) --21/09/2011\n\nSELECT CONVERT(VARCHAR,DATEADD(DAY,-1,GETDATE()),101) --09/21/2011\n\nSELECT CONVERT(VARCHAR,DATEADD(DAY,-1,GETDATE()),111) --2011/09/21\n\nSELECT CONVERT(VARCHAR,DATEADD(DAY,-1,GETDATE()),107) --Sep 21, 2011\n" }, { "answer_id": 11677122, "author": "Focusyn", "author_id": 1555912, "author_profile": "https://Stackoverflow.com/users/1555912", "pm_score": 4, "selected": false, "text": "CONVERT(varchar(10),[SourceDate as dateTime],121)" }, { "answer_id": 20033917, "author": "Anderson Silva", "author_id": 2966935, "author_profile": "https://Stackoverflow.com/users/2966935", "pm_score": 4, "selected": false, "text": "SELECT CONVERT(DATETIME,CONVERT(DATE,GETDATE()))\n" }, { "answer_id": 20235233, "author": "bishnu karki", "author_id": 2513452, "author_profile": "https://Stackoverflow.com/users/2513452", "pm_score": 3, "selected": false, "text": "CONVERT(VARCHAR(10),Person.DateOfBirth,111) AS BirthDate\n//here date is obtained as 1990/09/25\n" }, { "answer_id": 20675129, "author": "Mahesh ML", "author_id": 1786438, "author_profile": "https://Stackoverflow.com/users/1786438", "pm_score": 5, "selected": false, "text": "CONVERT(VARCHAR(10), OrderDate , 111)\n" }, { "answer_id": 22661348, "author": "Stephon Johns", "author_id": 3135742, "author_profile": "https://Stackoverflow.com/users/3135742", "pm_score": 5, "selected": false, "text": "varchar SELECT CONVERT(DATE, GETDATE()) --2014-03-26\nSELECT CONVERT(VARCHAR(10), GETDATE(), 111) --2014/03/26\n SELECT CONVERT(DATETIME, CONVERT(VARCHAR(10), GETDATE(), 111)) AS OnlyDate \n SELECT CONVERT(DATETIME, CONVERT(VARCHAR(10), GETDATE(), 112)) AS OnlyDate \n DECLARE @OnlyDate DATETIME\nSET @OnlyDate = DATEDIFF(DD, 0, GETDATE())\nSELECT @OnlyDate AS OnlyDate\n" }, { "answer_id": 22732953, "author": "user1151326", "author_id": 1151326, "author_profile": "https://Stackoverflow.com/users/1151326", "pm_score": 2, "selected": false, "text": "DATEPART() CONVERT() CONVERT() CONVERT()" }, { "answer_id": 23612056, "author": "Ankit Khetan", "author_id": 2847810, "author_profile": "https://Stackoverflow.com/users/2847810", "pm_score": 3, "selected": false, "text": " Convert(nvarchar(10), getdate(), 101) ---> 5/12/14\n\n Convert(nvarchar(12), getdate(), 101) ---> 5/12/2014\n" }, { "answer_id": 23708033, "author": "Janaka R Rajapaksha", "author_id": 2020193, "author_profile": "https://Stackoverflow.com/users/2020193", "pm_score": 3, "selected": false, "text": "select DATE_FORMAT( some_datetime_column, '%d-%m-%Y' ) from table_name '%d-%m-%Y'" }, { "answer_id": 27026637, "author": "etni", "author_id": 3191501, "author_profile": "https://Stackoverflow.com/users/3191501", "pm_score": 3, "selected": false, "text": "DECLARE @yourdate DATETIME = '11/1/2014 12:25pm' \nSELECT CONVERT(DATE, @yourdate)\n" }, { "answer_id": 28774425, "author": "tumultous_rooster", "author_id": 2822004, "author_profile": "https://Stackoverflow.com/users/2822004", "pm_score": 3, "selected": false, "text": "PRINT '1) Date/time in format MON DD YYYY HH:MI AM (OR PM): ' + CONVERT(CHAR(19),GETDATE()) \nPRINT '2) Date/time in format MM-DD-YY: ' + CONVERT(CHAR(8),GETDATE(),10) \nPRINT '3) Date/time in format MM-DD-YYYY: ' + CONVERT(CHAR(10),GETDATE(),110) \nPRINT '4) Date/time in format DD MON YYYY: ' + CONVERT(CHAR(11),GETDATE(),106)\nPRINT '5) Date/time in format DD MON YY: ' + CONVERT(CHAR(9),GETDATE(),6) \nPRINT '6) Date/time in format DD MON YYYY HH:MM:SS:MMM(24H): ' + CONVERT(CHAR(24),GETDATE(),113)\n 1) Date/time in format MON DD YYYY HH:MI AM (OR PM): Feb 27 2015 1:14PM\n2) Date/time in format MM-DD-YY: 02-27-15\n3) Date/time in format MM-DD-YYYY: 02-27-2015\n4) Date/time in format DD MON YYYY: 27 Feb 2015\n5) Date/time in format DD MON YY: 27 Feb 15\n6) Date/time in format DD MON YYYY HH:MM:SS:MMM(24H): 27 Feb 2015 13:14:46:630\n" }, { "answer_id": 29975670, "author": "Gerard ONeill", "author_id": 1331672, "author_profile": "https://Stackoverflow.com/users/1331672", "pm_score": 3, "selected": false, "text": "DATEFROMPARTS(DATEPART(yyyy, @mydatetime), DATEPART(mm, @mydatetime), DATEPART(dd, @mydatetime))\n" }, { "answer_id": 32332424, "author": "Binitta Mary", "author_id": 5287922, "author_profile": "https://Stackoverflow.com/users/5287922", "pm_score": 2, "selected": false, "text": "SELECT * FROM tablename WHERE CAST ([my_date_time_var] AS DATE)= '8/5/2015'\n" }, { "answer_id": 34817244, "author": "lit", "author_id": 447901, "author_profile": "https://Stackoverflow.com/users/447901", "pm_score": 3, "selected": false, "text": "SELECT CAST(CURRENT_TIMESTAMP AS DATE)\n" }, { "answer_id": 36296594, "author": "Shyam Bhimani", "author_id": 6030977, "author_profile": "https://Stackoverflow.com/users/6030977", "pm_score": -1, "selected": false, "text": "SELECT SYSDATE TODAY FROM DUAL; \n" }, { "answer_id": 36596046, "author": "Krishnraj Rana", "author_id": 748173, "author_profile": "https://Stackoverflow.com/users/748173", "pm_score": 3, "selected": false, "text": "SELECT CAST(FLOOR(CAST(GETDATE() AS FLOAT)) as DATETIME)\n 2008-09-22 00:00:00.000\n FORMAT() SELECT FORMAT(GETDATE(), 'yyyy-MM-dd')\n" }, { "answer_id": 37219244, "author": "Art Schmidt", "author_id": 5522000, "author_profile": "https://Stackoverflow.com/users/5522000", "pm_score": 4, "selected": false, "text": "DECLARE @Date DATE = GETDATE() \n\nSELECT @Date --> 2017-05-03\n" }, { "answer_id": 37409697, "author": "r-magalhaes", "author_id": 1774725, "author_profile": "https://Stackoverflow.com/users/1774725", "pm_score": 3, "selected": false, "text": "CAST(\n(\n STR( YEAR( GETDATE() ) ) + '/' +\n STR( MONTH( GETDATE() ) ) + '/' +\n STR( DAY( GETDATE() ) )\n)\nAS DATETIME)\n" }, { "answer_id": 38485360, "author": "xbb", "author_id": 1566021, "author_profile": "https://Stackoverflow.com/users/1566021", "pm_score": 3, "selected": false, "text": "SELECT FORMAT(GETDATE(), 'yyyy-MM-dd 00:00:00.000')" }, { "answer_id": 39117132, "author": "Somnath Muluk", "author_id": 1045444, "author_profile": "https://Stackoverflow.com/users/1045444", "pm_score": 4, "selected": false, "text": "Format() FORMAT ( value, format [, culture ] )\n 2009-06-15T13:45:30 -> 6/15/2009 (en-US)\n2009-06-15T13:45:30 -> 15/06/2009 (fr-FR)\n2009-06-15T13:45:30 -> 2009/06/15 (ja-JP)\n 2009-06-15T13:45:30 -> Monday, June 15, 2009 (en-US)\n2009-06-15T13:45:30 -> 15 июня 2009 г. (ru-RU)\n2009-06-15T13:45:30 -> Montag, 15. Juni 2009 (de-DE)\n DECLARE @d DATETIME = '10/01/2011';\nSELECT FORMAT ( @d, 'd', 'en-US' ) AS 'US English Result'\n ,FORMAT ( @d, 'd', 'en-gb' ) AS 'Great Britain English Result'\n ,FORMAT ( @d, 'd', 'de-de' ) AS 'German Result'\n ,FORMAT ( @d, 'd', 'zh-cn' ) AS 'Simplified Chinese (PRC) Result'; \n\nSELECT FORMAT ( @d, 'D', 'en-US' ) AS 'US English Result'\n ,FORMAT ( @d, 'D', 'en-gb' ) AS 'Great Britain English Result'\n ,FORMAT ( @d, 'D', 'de-de' ) AS 'German Result'\n ,FORMAT ( @d, 'D', 'zh-cn' ) AS 'Chinese (Simplified PRC) Result';\n\nUS English Result Great Britain English Result German Result Simplified Chinese (PRC) Result\n---------------- ----------------------------- ------------- -------------------------------------\n10/1/2011 01/10/2011 01.10.2011 2011/10/1\n\nUS English Result Great Britain English Result German Result Chinese (Simplified PRC) Result\n---------------------------- ----------------------------- ----------------------------- ---------------------------------------\nSaturday, October 01, 2011 01 October 2011 Samstag, 1. Oktober 2011 2011年10月1日\n" }, { "answer_id": 46109193, "author": "Amar Srivastava", "author_id": 6505216, "author_profile": "https://Stackoverflow.com/users/6505216", "pm_score": 3, "selected": false, "text": "SELECT CONVERT(date, getdate())\nSELECT DATEADD(dd, 0, DATEDIFF(dd, 0, @your_date))\nSELECT DATEADD(dd, 0, DATEDIFF(dd, 0, GETDATE()))\n 2008-09-22 00:00:00.000\n SELECT CONVERT (DATE, GETDATE()) 'Date Part Only'\n Date Part Only\n--------------\n2013-07-14\n" }, { "answer_id": 46859925, "author": "Spider", "author_id": 3725288, "author_profile": "https://Stackoverflow.com/users/3725288", "pm_score": 2, "selected": false, "text": " SELECT CONVERT(VARCHAR(MAX),GETDATE(),103)\n\n SELECT CAST(GETDATE() AS DATE)\n" }, { "answer_id": 52661269, "author": "mokh223", "author_id": 2748728, "author_profile": "https://Stackoverflow.com/users/2748728", "pm_score": -1, "selected": false, "text": "select convert(getdate() as date)\n\nselect CONVERT(datetime,CONVERT(date, getdate()))\n" }, { "answer_id": 53411273, "author": "CAGDAS AYDIN", "author_id": 10627992, "author_profile": "https://Stackoverflow.com/users/10627992", "pm_score": 2, "selected": false, "text": " select Convert(smalldatetime,Convert(int,Convert(float,getdate())))\n" }, { "answer_id": 55326586, "author": "karthik kasubha", "author_id": 5486572, "author_profile": "https://Stackoverflow.com/users/5486572", "pm_score": 2, "selected": false, "text": "select cast(createddate as date) as derivedate from table \n" }, { "answer_id": 55430749, "author": "ankit soni", "author_id": 8385887, "author_profile": "https://Stackoverflow.com/users/8385887", "pm_score": 1, "selected": false, "text": "SELECT CONVERT(datetime, CONVERT(varchar, GETDATE(), 103)) SELECT CONVERT(datetime, CONVERT(varchar, GETDATE(), 101)) SELECT CONVERT(datetime, CONVERT(varchar, GETDATE(), 102))" }, { "answer_id": 55816901, "author": "Aubrey Love", "author_id": 7703803, "author_profile": "https://Stackoverflow.com/users/7703803", "pm_score": 1, "selected": false, "text": "SELECT CAST(GETDATE() AS DATE) AS 'Date1'\nSELECT Date2 = CONVERT(DATE, GETDATE())\nSELECT CONVERT(DATE, GETDATE()) AS 'Date3'\nSELECT CONVERT(CHAR(10), GETDATE(), 121) AS 'Date4'\nSELECT CONVERT(CHAR(10), GETDATE(), 126) AS 'Date5'\nSELECT CONVERT(CHAR(10), GETDATE(), 127) AS 'Date6'\n" }, { "answer_id": 56338106, "author": "Jithin Joy", "author_id": 6898904, "author_profile": "https://Stackoverflow.com/users/6898904", "pm_score": -1, "selected": false, "text": "SELECT DATE(GETDATE())" }, { "answer_id": 57269676, "author": "ChrisM", "author_id": 11760174, "author_profile": "https://Stackoverflow.com/users/11760174", "pm_score": 2, "selected": false, "text": "2008-09-22 00:00:00.000 SELECT CONVERT(datetime, (ROUND(convert(float, getdate()-.5),0)))\n" }, { "answer_id": 59749143, "author": "John Sonnino", "author_id": 6895162, "author_profile": "https://Stackoverflow.com/users/6895162", "pm_score": 5, "selected": false, "text": "SELECT CAST(date_variable AS date) SELECT date_variable::date" }, { "answer_id": 60117817, "author": "Christopher Warrington", "author_id": 4679332, "author_profile": "https://Stackoverflow.com/users/4679332", "pm_score": -1, "selected": false, "text": "DATEVALUE([TableColumnName])\n TIMEVALUE([TableColumnName])\n DATEVALUE([Customers].[CreationDate]) '--> Output: 2/7/2020\nTIMEVALUE([Customers].[CreationDate]) '--> Output: 09:50:00\n CAST CONVERT" }, { "answer_id": 66546890, "author": "yusuf hayırsever", "author_id": 10238086, "author_profile": "https://Stackoverflow.com/users/10238086", "pm_score": 3, "selected": false, "text": "SELECT CONVERT (data_type(length)),Date, DateFormatCode)\n Select CONVERT(varchar,GETDATE(),1) as [MM/DD/YY]\nSelect CONVERT(varchar,GETDATE(),2) as [YY.MM.DD]\n DateFormatCode Format\n1 [MM/DD/YY]\n2 [YY.MM.DD]\n3 [DD/MM/YY]\n4 [DD.MM.YY]\n5 [DD-MM-YY]\n6 [DD MMM YY]\n7 [MMM DD,YY]\n10 [MM-DD-YY]\n11 [YY/MM/DD]\n12 [YYMMDD]\n23 [yyyy-mm-dd]\n101 [MM/DD/YYYY]\n102 [YYYY.MM.DD]\n103 [DD/MM/YYYY]\n104 [DD/MM/YYYY]\n105 [DD/MM/YYYY]\n106 [DD MMM YYYY]\n107 [MMM DD,YYYY]\n110 [MM-DD-YYYY]\n111 [YYYY/MM/DD]\n112 [YYYYMMDD]\n" }, { "answer_id": 73565346, "author": "Zhorov", "author_id": 6578080, "author_profile": "https://Stackoverflow.com/users/6578080", "pm_score": 0, "selected": false, "text": "DATETRUNC() day datepart SELECT DATETRUNC(day, GETDATE());\n" } ]
2008/09/22
[ "https://Stackoverflow.com/questions/113045", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5769/" ]
113,077
<p>I am creating a site in which different pages can look very different depending upon certain conditions (ie logged in or not, form filled out or not, etc). This makes it necessary to output diferent blocks of html at different times.</p> <p>Doing that, however, makes my php code look horrific... it really messes with the formatting and "shape" of the code. How should I get around this? Including custom "html dump" functions at the bottom of my scripts? The same thing, but with includes? Heredocs (don't look too good)?</p> <p>Thanks!</p>
[ { "answer_id": 113154, "author": "Galen", "author_id": 7894, "author_profile": "https://Stackoverflow.com/users/7894", "pm_score": 0, "selected": false, "text": "if ($_SESSION['logged_in'])\n include(TPL_DIR . 'main_logged_in.tpl'); \nelse\n include(tPL_DIR . 'main.tpl');\n" }, { "answer_id": 113851, "author": "e-satis", "author_id": 9951, "author_profile": "https://Stackoverflow.com/users/9951", "pm_score": 6, "selected": true, "text": "<?php\n\n// pure PHP code, no HTML\n\n$name = htmlspecialchars($_GET['name']);\n$age = date('Y') - htmlspecialchars($_GET['age']);\n\n?>\n // very few php code\n// just enought to print variables\n// and some if / else, or foreach to manage the data stream\n\n<h1>Hello, <?php $name ?> !</h1>\n\n<p>So your are <?php $age?>, hu ?</p>\n <?php\n\nrequire('myPageLogic.php');\nrequire('myPageView.php');\n?>\n" }, { "answer_id": 114141, "author": "Twan", "author_id": 6702, "author_profile": "https://Stackoverflow.com/users/6702", "pm_score": 0, "selected": false, "text": "Array\n{\n [car] => green\n [bike] => red\n}\n echo \"<VEHICLES>\\n\";\nforeach(array_keys($aVehicles) as $sVehicle)\n echo \"\\t<VEHICLE>\".$sVehicle.\"</NAME><COLOR>\".$aVehicles[$sVehicle].\"</COLOR></VEHICLE>\\n\";\necho \"</VEHICLES>\\n\";\n <VEHICLES>\n <VEHICLE>\n <NAME>car</NAME>\n <COLOR>green</COLOR>\n </VEHICLE>\n <VEHICLE>\n <NAME>bike</NAME>\n <COLOR>red</COLOR>\n </VEHICLE>\n</VEHICLES>\n <xsl:template match=\"VEHICLES\">\n <TABLE>\n <xsl:apply-templates select=\"VEHICLE\">\n </TABLE>\n</xsl:template>\n\n<xsl:template match=\"VEHICLE\">\n <TR>\n <TD><xsl:value-of select=\"NAME\"></TD>\n <TD><xsl:value-of select=\"COLOR\"></TD>\n </TR>\n</xsl:template>\n <TABLE>\n <TR>\n <TD>car</TD>\n <TD>green</TD>\n </TR>\n <TR>\n <TD>bike</TD>\n <TD>red</TD>\n </TR>\n</TABLE>\n" }, { "answer_id": 115887, "author": "bobince", "author_id": 18936, "author_profile": "https://Stackoverflow.com/users/18936", "pm_score": 2, "selected": false, "text": "<div class=\"prettybox\">\n Hello <?php echo(htmlspecialchars($name)) ?>!\n Your food:\n <?php foreach($foods as $food) { ?>\n <a href=\"/food.php?food=<?php echo(urlencode($food)) ?>\">\n <?php echo(htmlspecialchars($food)) ?>\n </a>\n <?php } ?>\n <?php if (count($foods)==0) { ?>\n (no food today)\n <?php } ?>\n</div>\n" } ]
2008/09/22
[ "https://Stackoverflow.com/questions/113077", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1615/" ]
113,103
<p>Can anyone explain the difference between the "name" property of a display object and the value found by <em>getChildByName("XXX")</em> function? They're the same 90% of the time, until they aren't, and things fall apart.</p> <p>For example, in the code below, I find an object by instance name only by directly examining the child's name property; <em>getChildByName()</em> fails. </p> <pre><code>var gfx:MovieClip = new a_Character(); //(a library object exported for Actionscript) var do1:DisplayObject = null; var do2:DisplayObject = null; for( var i:int = 0 ; i &lt; gfx.amSword.numChildren ; i++ ) { var child:DisplayObject = gfx.amSword.getChildAt(i); if( child.name == "amWeaponExchange" ) //An instance name set in the IDE { do2 = child; } } trace("do2:", do2 ); var do1:DisplayObject = gfx.amSword.getChildByName("amWeaponExchange"); </code></pre> <p>Generates the following output:</p> <pre><code>do2: [object MovieClip] ReferenceError: Error #1069: Property amWeaponExchange not found on builtin.as$0.MethodClosure and there is no default value. </code></pre> <p>Any ideas what Flash is thinking?</p>
[ { "answer_id": 122029, "author": "defmeta", "author_id": 10875, "author_profile": "https://Stackoverflow.com/users/10875", "pm_score": 2, "selected": false, "text": "var do1:DisplayObject = gfx.amSword.getChildByName[\"amWeaponExchange\"];\n ReferenceError: Error #1069: Property amWeaponExchange not found on builtin.as$0.MethodClosure and there is no default value.\n var do1:DisplayObject = gfx.amSword.getChildByName(\"amWeaponExchange\");\n" } ]
2008/09/22
[ "https://Stackoverflow.com/questions/113103", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4969/" ]
113,131
<p>What WPF Calendar control would you recommend? I am looking for something that will let me display a variable amount of weeks potentially spanning multiple months.</p>
[ { "answer_id": 1421799, "author": "Drew Noakes", "author_id": 24874, "author_profile": "https://Stackoverflow.com/users/24874", "pm_score": 4, "selected": true, "text": "<c:Calendar>\n <c:DatePicker.BlackoutDates>\n <c:CalendarDateRange Start=\"4/1/2008\" End=\"4/6/2008\"/>\n <c:CalendarDateRange Start=\"4/14/2008\" End=\"4/17/2008\"/>\n </c:DatePicker.BlackoutDates>\n</c:Calendar>\n<c:DatePicker>\n <c:DatePicker.BlackoutDates>\n <c:CalendarDateRange Start=\"4/1/2008\" End=\"4/6/2008\"/>\n <c:CalendarDateRange Start=\"4/14/2008\" End=\"4/17/2008\"/>\n </c:DatePicker.BlackoutDates>\n</c:DatePicker>\n" } ]
2008/09/22
[ "https://Stackoverflow.com/questions/113131", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5618/" ]
113,150
<p>I have the following situation:</p> <pre><code> class A { public: A(int whichFoo); int foo1(); int foo2(); int foo3(); int callFoo(); // cals one of the foo's depending on the value of whichFoo }; </code></pre> <p>In my current implementation I save the value of <code>whichFoo</code> in a data member in the constructor and use a <code>switch</code> in <code>callFoo()</code> to decide which of the foo's to call. Alternatively, I can use a <code>switch</code> in the constructor to save a pointer to the right <code>fooN()</code> to be called in <code>callFoo()</code>. </p> <p>My question is which way is more efficient if an object of class A is only constructed once, while <code>callFoo()</code> is called a very large number of times. So in the first case we have multiple executions of a switch statement, while in the second there is only one switch, and multiple calls of a member function using the pointer to it. I know that calling a member function using a pointer is slower than just calling it directly. Does anybody know if this overhead is more or less than the cost of a <code>switch</code>?</p> <p>Clarification: I realize that you never really know which approach gives better performance until you try it and time it. However, in this case I already have approach 1 implemented, and I wanted to find out if approach 2 can be more efficient at least in principle. It appears that it can be, and now it makes sense for me to bother to implement it and try it. </p> <p>Oh, and I also like approach 2 better for aesthetic reasons. I guess I am looking for a justification to implement it. :) </p>
[ { "answer_id": 113158, "author": "Thomas", "author_id": 14637, "author_profile": "https://Stackoverflow.com/users/14637", "pm_score": 1, "selected": false, "text": "callFoo A callFoo" }, { "answer_id": 113329, "author": "cos", "author_id": 14535, "author_profile": "https://Stackoverflow.com/users/14535", "pm_score": 3, "selected": false, "text": "class Foo {\npublic:\n Foo() {\n calls[0] = &Foo::call0;\n calls[1] = &Foo::call1;\n calls[2] = &Foo::call2;\n calls[3] = &Foo::call3;\n }\n void call(int number, int arg) {\n assert(number < 4);\n (this->*(calls[number]))(arg);\n }\n void call0(int arg) {\n cout<<\"call0(\"<<arg<<\")\\n\";\n }\n void call1(int arg) {\n cout<<\"call1(\"<<arg<<\")\\n\";\n }\n void call2(int arg) {\n cout<<\"call2(\"<<arg<<\")\\n\";\n }\n void call3(int arg) {\n cout<<\"call3(\"<<arg<<\")\\n\";\n }\nprivate:\n FooCall calls[4];\n};\n (this->*(calls[number]))(arg);\n004142E7 mov esi,esp \n004142E9 mov eax,dword ptr [arg] \n004142EC push eax \n004142ED mov edx,dword ptr [number] \n004142F0 mov eax,dword ptr [this] \n004142F3 mov ecx,dword ptr [this] \n004142F6 mov edx,dword ptr [eax+edx*4] \n004142F9 call edx \n switch switch" } ]
2008/09/22
[ "https://Stackoverflow.com/questions/113150", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13313/" ]
113,170
<p>It appears the Python signal module doesn't have anything similar to the sighold and sigrelse functions found in C, using signal.h. Are there Python equivalents of <em>any</em> sort?</p> <p>Many thanks!</p>
[ { "answer_id": 113158, "author": "Thomas", "author_id": 14637, "author_profile": "https://Stackoverflow.com/users/14637", "pm_score": 1, "selected": false, "text": "callFoo A callFoo" }, { "answer_id": 113329, "author": "cos", "author_id": 14535, "author_profile": "https://Stackoverflow.com/users/14535", "pm_score": 3, "selected": false, "text": "class Foo {\npublic:\n Foo() {\n calls[0] = &Foo::call0;\n calls[1] = &Foo::call1;\n calls[2] = &Foo::call2;\n calls[3] = &Foo::call3;\n }\n void call(int number, int arg) {\n assert(number < 4);\n (this->*(calls[number]))(arg);\n }\n void call0(int arg) {\n cout<<\"call0(\"<<arg<<\")\\n\";\n }\n void call1(int arg) {\n cout<<\"call1(\"<<arg<<\")\\n\";\n }\n void call2(int arg) {\n cout<<\"call2(\"<<arg<<\")\\n\";\n }\n void call3(int arg) {\n cout<<\"call3(\"<<arg<<\")\\n\";\n }\nprivate:\n FooCall calls[4];\n};\n (this->*(calls[number]))(arg);\n004142E7 mov esi,esp \n004142E9 mov eax,dword ptr [arg] \n004142EC push eax \n004142ED mov edx,dword ptr [number] \n004142F0 mov eax,dword ptr [this] \n004142F3 mov ecx,dword ptr [this] \n004142F6 mov edx,dword ptr [eax+edx*4] \n004142F9 call edx \n switch switch" } ]
2008/09/22
[ "https://Stackoverflow.com/questions/113170", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
113,173
<p>I'm working on a something related to roughset right now. The project uses alot of sets operation and manipulation. I've been using string operations as a stop gap measure for set operation. It has worked fine until we need to process some ungodly amount of data ( 500,000 records with about 40+ columns each ) through the algorithm. </p> <p>I know that there is no set data structure in .net 2.0(2.0 was the latest when I started the project) I want to know if there is any library that offer fast set operation in .net c# or if 3.5 has added native set data structure.</p> <p>Thanks .</p>
[ { "answer_id": 113919, "author": "Dejan Milicic", "author_id": 158320, "author_profile": "https://Stackoverflow.com/users/158320", "pm_score": 0, "selected": false, "text": "HashSet<T>" }, { "answer_id": 113967, "author": "Martijn", "author_id": 17439, "author_profile": "https://Stackoverflow.com/users/17439", "pm_score": 1, "selected": false, "text": "private object dummy = \"ok\";\n\npublic void Add(object el) {\n dict[el] = dummy;\n}\n\npublic bool Contains(object el) {\n return dict.ContainsKey(el);\n}\n" } ]
2008/09/22
[ "https://Stackoverflow.com/questions/113173", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2976/" ]
113,185
<p>I've installed <a href="http://www.owfs.org/" rel="nofollow noreferrer"><code>owfs</code></a> and am trying to read the data off a <a href="http://www.maxim-ic.com/quick_view2.cfm/qv_pk/4088" rel="nofollow noreferrer">iButton temperature logger</a>.</p> <p><code>owfs</code> lets me mount the iButton as a fuse filesystem and I can see all the data. I'm having trouble figuring out what is the best way to access the data though. I can get individual readings by <code>cat</code>ting the files, e.g. <code>cat onewire/{deviceid}/log/temperature.1</code>, but the <code>onewire/{deviceid}/log/temperature.ALL</code> file is "broken" (possible too large, as <code>histogram/temperature.ALL</code> work fine). </p> <p>A python script to read all files seems to work but takes a very long time. Is there a better way to do it? Does anyone have any examples?</p> <p>I'm using Ubuntu 8.04 and couldn't get the java "one wire viewer" app to run.</p> <p><strong>Update</strong>: Using <a href="http://owfs.sourceforge.net/owpython.html" rel="nofollow noreferrer"><code>owpython</code></a> (installed with owfs), I can get the current temperature but can't figure out how to get access to the recorded logs:</p> <pre><code>&gt;&gt;&gt; import ow &gt;&gt;&gt; ow.init("u") # initialize USB &gt;&gt;&gt; ow.Sensor("/").sensorList() [Sensor("/81.7FD921000000"), Sensor("/21.C4B912000000")] &gt;&gt;&gt; x = ow.Sensor("/21.C4B912000000") &gt;&gt;&gt; print x.type, x.temperature DS1921 22 </code></pre> <p><code>x.log</code> gives an <code>AttributeError</code>.</p>
[ { "answer_id": 117532, "author": "Armin Ronacher", "author_id": 19990, "author_profile": "https://Stackoverflow.com/users/19990", "pm_score": 2, "selected": false, "text": "/proc" }, { "answer_id": 181511, "author": "Diomidis Spinellis", "author_id": 20520, "author_profile": "https://Stackoverflow.com/users/20520", "pm_score": 2, "selected": false, "text": "/usr/local/bin/digitemp_DS9097U -c /usr/local/etc/digitemp.conf \\\n -q -t0 -n0 -d60 -l/var/log/temperature\n # Compile the hardware-specific command\nmake ds9097u\n# Initialize the configuration file\n./digitemp_DS9097U -s/dev/ttyS0 -i\n# Run command to obtain temperature, and verify your setup\n./digitemp_DS9097U -a \n# Copy the configuration file to an accessible place\ncp .digitemprc /usr/local/etc/digitemp.conf\n TTY /dev/ttyS0\nREAD_TIME 1000\nLOG_TYPE 1\nLOG_FORMAT \"%b %d %H:%M:%S Sensor %s C: %.2C F: %.2F\"\nCNT_FORMAT \"%b %d %H:%M:%S Sensor %s #%n %C\"\nHUM_FORMAT \"%b %d %H:%M:%S Sensor %s C: %.2C F: %.2F H: %h%%\"\nSENSORS 1\nROM 0 0x10 0xD3 0x5B 0x07 0x00 0x00 0x00 0x05 \n #! /bin/sh\n#\n# System startup script for the temperature monitoring daemon\n#\n### BEGIN INIT INFO\n# Provides: digitemp\n# Required-Start:\n# Should-Start:\n# Required-Stop:\n# Should-Stop:\n# Default-Start: 2 3 5\n# Default-Stop: 0 1 6\n# Description: Start the temperature monitoring daemon\n### END INIT INFO\n\nDIGITEMP=/usr/local/bin/digitemp_DS9097U\ntest -x $DIGITEMP || exit 5\n\nDIGITEMP_CONFIG=/root/digitemp.conf\ntest -f $DIGITEMP_CONFIG || exit 6\n\nDIGITEMP_LOGFILE=/var/log/temperature\n\n# Source SuSE config\n. /etc/rc.status\n\nrc_reset\ncase \"$1\" in\n start)\n echo -n \"Starting temperature monitoring daemon\"\n startproc $DIGITEMP -c $DIGITEMP_CONFIG -q -t0 -n0 -d60 -l$DIGITEMP_LOGFILE\n rc_status -v\n ;;\n stop)\n echo -n \"Shutting down temperature monitoring daemon\"\n killproc -TERM $DIGITEMP\n rc_status -v\n ;;\n try-restart)\n $0 status >/dev/null && $0 restart\n rc_status\n ;;\n restart)\n $0 stop\n $0 start\n rc_status\n ;;\n force-reload)\n $0 try-restart\n rc_status\n ;;\n reload)\n $0 try-restart\n rc_status\n ;;\n status)\n echo -n \"Checking for temperature monitoring service\"\n checkproc $DIGITEMP\n rc_status -v\n ;;\n *)\n echo \"Usage: $0 {start|stop|status|try-restart|restart|force-reload|reload}\"\n exit 1\n ;;\nesac\nrc_exit\n" } ]
2008/09/22
[ "https://Stackoverflow.com/questions/113185", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3715/" ]
113,224
<p>What is the highest port number one can use?</p>
[ { "answer_id": 113271, "author": "Andrew Edgecombe", "author_id": 11694, "author_profile": "https://Stackoverflow.com/users/11694", "pm_score": 5, "selected": false, "text": "/proc/sys/net/ipv4/ip_local_port_range" } ]
2008/09/22
[ "https://Stackoverflow.com/questions/113224", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4939/" ]
113,253
<p>My web page sits in a DIV that is 960px wide, I center this DIV in the middle of the page by using the code: </p> <pre><code>html,body{background: url(images/INF_pageBg.gif) center top repeat-y #777777;text-align:center;} #container{background-color:#ffffff;width:960px;text-align:left;margin:0 auto 0 auto;} </code></pre> <p>I need the background image of the html/body to tile down the middle of the page, which it does, however if the viewable pane in the browser is an odd number of pixels width then the centered background and centered DIV don't align together.</p> <p>This is only happening in FF.</p> <p>Does anybody know of a workaround?</p>
[ { "answer_id": 4747476, "author": "Tom", "author_id": 415721, "author_profile": "https://Stackoverflow.com/users/415721", "pm_score": 1, "selected": false, "text": "$(document).ready(function(){\n $('body').css({\n 'margin-left': $(document).width()%2\n });\n});\n" }, { "answer_id": 17254430, "author": "SequenceDigitale.com", "author_id": 489281, "author_profile": "https://Stackoverflow.com/users/489281", "pm_score": 0, "selected": false, "text": "body{ background: url(your-image.jpg) no-repeat center top; }\n#wrapper{ background: url(your-image.jpg) no-repeat center top; margin: 0 auto; width: 984px; }\n" } ]
2008/09/22
[ "https://Stackoverflow.com/questions/113253", "https://Stackoverflow.com", "https://Stackoverflow.com/users/910/" ]
113,267
<p>In Visual Studio, when I type the line "<code>Implements IDisposable</code>", the IDE automatically adds:</p> <ul> <li>a <code>disposedValue</code> member variable</li> <li>a <code>Sub Dispose() Implements IDisposable.Dispose</code></li> <li>a <code>Sub Dispose(ByVal disposing As Boolean)</code></li> </ul> <p>The <code>Dispose()</code> should be left alone, and the clean up code should be put in <code>Dispose(disposing)</code>.</p> <p>However the <a href="http://msdn.microsoft.com/en-us/library/s9bwddyx.aspx" rel="noreferrer" title="Dispose Finalize Pattern">Dispose Finalize Pattern</a> says you should also override <code>Sub Finalize()</code> to call <code>Dispose(False)</code>. Why doesn't the IDE also add this? Must I add it myself, or is it somehow called implicitly?</p> <p><strike><strong>EDIT:</strong> Any idea why the IDE automatically adds 80% of the required stuff but leaves out the Finalize method? Isn't the whole point of this kind of feature to help you <em>not</em> forget these things?</strike></p> <p><strong>EDIT2:</strong> Thank you all for your excellent answers, this now makes perfect sense!</p>
[ { "answer_id": 1892601, "author": "missa", "author_id": 230165, "author_profile": "https://Stackoverflow.com/users/230165", "pm_score": 2, "selected": false, "text": "Implements IDisposable\n\nPublic Overloads Sub Dispose() Implements IDisposable.Dispose\n\n Dispose(True)\n GC.SuppressFinalize(Me)\n\nEnd Sub\n\nProtected Overloads Sub Dispose(ByVal disposing As Boolean)\n\n If disposing Then\n ' Free other state (managed objects).\n End If\n ' Free your own state (unmanaged objects).\n ' Set large fields to null.\nEnd Sub\n\nProtected Overrides Sub Finalize()\n\n Dispose(False)\n MyBase.Finalize()\n\nEnd Sub\n" } ]
2008/09/22
[ "https://Stackoverflow.com/questions/113267", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10786/" ]
113,275
<p>Here is what I have:</p> <pre><code> context "Create ingredient from string" do context "1 cups butter" do setup do @ingredient = Ingredient.create(:ingredient_string =&gt; "1 cups butter") end should "return unit" do assert_equal @ingredient.unit, 'cups' end should "return amount" do assert_equal @ingredient.amount, 1.0 end should "return name" do assert_equal @ingredient.name, 'butter' end end context "1 (18.25 ounce) package devil's food cake mix with pudding" do setup do @ingredient = Ingredient.create(:ingredient_string =&gt; "1 (18.25 ounce) package devil's food cake mix with pudding") end should "return unit" do assert_equal @ingredient.unit, '(18.25 ounce) package' end should "return amount" do assert_equal @ingredient.amount, 1.0 end should "return name" do assert_equal @ingredient.name, 'devil\'s food cake mix with pudding' end end end </code></pre> <p>Clearly there is a lot of duplication there. Any thoughts on how to remove it, if only at the very least the context and the string?</p>
[ { "answer_id": 113359, "author": "Andrew", "author_id": 17408, "author_profile": "https://Stackoverflow.com/users/17408", "pm_score": 0, "selected": false, "text": "class DefineMethodTest < Test::Unit::TestCase\n [{:string => '1 cups butter', :unit => 'cups', :amount => 1.0, :name => 'butter'},{:string => '1 (18.25 ounce) package devil's food cake mix with pudding', :unit => '(18.25 ounce) package', :unit => 1.0, :name => \"devil's food cake mix with pudding\"}].each do |t|\n define_method \"test_create_ingredient_from_string_#{t[:string].downcase.gsub(/[^a-z0-9]+/, '_')}\" do\n @ingredient = Ingredient.create(:ingredient_string => t[:string])\n\n assert_equal @ingredient.unit, t[:unit], \"Should return unit #{t[:unit]}\"\n assert_equal @ingredient.amount, t[:amount], \"Should return amount #{t[:amount]}\"\n assert_equal @ingredient.name, t[:name], \"Should return name #{t[:name]}\"\n end\n end\nend\n" }, { "answer_id": 114776, "author": "webmat", "author_id": 6349, "author_profile": "https://Stackoverflow.com/users/6349", "pm_score": 3, "selected": true, "text": "def self.should_get_unit_amount_and_name_from_string(unit, amount, name, string_to_analyze)\n context string_to_analyze do\n setup do\n @ingredient = Ingredient.create(:ingredient_string => string_to_analyze)\n end\n\n should \"return unit\" do\n assert_equal @ingredient.unit, unit\n end\n\n should \"return amount\" do\n assert_equal @ingredient.amount, amount\n end\n\n should \"return name\" do\n assert_equal @ingredient.name, name\n end\n end\nend\n context \"Create ingredient from string\" do\n should_get_unit_amount_and_name_from_string(\n 'cups', \n 1.0, \n 'butter', \n \"1 cups butter\")\n should_get_unit_amount_and_name_from_string(\n '(18.25 ounce) package', \n 1.0, \n 'devil\\'s food cake mix with pudding', \n \"1 (18.25 ounce) package devil's food cake mix with pudding\")\nend\n" } ]
2008/09/22
[ "https://Stackoverflow.com/questions/113275", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12448/" ]
113,286
<p><a href="https://rads.stackoverflow.com/amzn/click/com/020161622X" rel="noreferrer" rel="nofollow noreferrer">The Pragmatic Programmer</a> advocates the use of code generators. Do you create code generators on your projects? If yes, what do you use them for?</p>
[ { "answer_id": 6406474, "author": "Mike DeSimone", "author_id": 2624511, "author_profile": "https://Stackoverflow.com/users/2624511", "pm_score": 1, "selected": false, "text": "static const uint8_t[] // This code was automatically generated from Font_foo.txt. DO NOT EDIT THIS FILE.\n// If there's a bug, fix the font text file or the generator program, not this file.\n" } ]
2008/09/22
[ "https://Stackoverflow.com/questions/113286", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3740/" ]
113,293
<p>Is it always possible to ping localhost and it resolves to 127.0.0.1?</p> <p>I know Windows Vista, XP, Ubuntu and Debian do it but does everyone do it?</p>
[ { "answer_id": 113301, "author": "Greg Hewgill", "author_id": 893, "author_profile": "https://Stackoverflow.com/users/893", "pm_score": 5, "selected": true, "text": "hosts hosts" }, { "answer_id": 113314, "author": "Thorsten79", "author_id": 19734, "author_profile": "https://Stackoverflow.com/users/19734", "pm_score": 3, "selected": false, "text": "topaz:/root# vi /etc/hosts\n[comment out localhost entry]\n\ntopaz:/root# ping localhost \nping: unknown host localhost\n" }, { "answer_id": 113383, "author": "Andrew Edgecombe", "author_id": 11694, "author_profile": "https://Stackoverflow.com/users/11694", "pm_score": 3, "selected": false, "text": "localhost sudo ifconfig lo down ping 127.0.0.1" }, { "answer_id": 113467, "author": "Dominic Eidson", "author_id": 5042, "author_profile": "https://Stackoverflow.com/users/5042", "pm_score": 3, "selected": false, "text": " 127.0.0.0/8 - This block is assigned for use as the Internet host\n loopback address. A datagram sent by a higher level protocol to an\n address anywhere within this block should loop back inside the host.\n This is ordinarily implemented using only 127.0.0.1/32 for loopback,\n but no addresses within this block should ever appear on any network\n anywhere [RFC1700, page 5].\n ~> dig localhost.t...e.org\n\n...\n\n;; ANSWER SECTION:\nlocalhost.t...e.org. 86400 IN A 127.0.0.2\n" }, { "answer_id": 113715, "author": "Zoredache", "author_id": 20267, "author_profile": "https://Stackoverflow.com/users/20267", "pm_score": 1, "selected": false, "text": "RFC1912\n4.1\n...\n Certain zones should **always be present** in nameserver configurations:\n primary localhost localhost\n primary 0.0.127.in-addr.arpa 127.0\n...\n The \"localhost\" address is a \"special\" address which always refers to\n the local host. It should contain the following line:\n\n localhost. IN A 127.0.0.1\n\n The \"127.0\" file should contain the line:\n\n 1 PTR localhost.\n" } ]
2008/09/22
[ "https://Stackoverflow.com/questions/113293", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19929/" ]
113,341
<p>I'm trying to create a character generation wizard for a game. In one class I calculate the attributes of the character. In a different class, I'm displaying to the user which specialties are available based on the attributes of the character. However, I can't remember how to pass variables between different classes.</p> <p>Here is an example of what I have:</p> <pre><code>class BasicInfoPage(wx.wizard.WizardPageSimple): def __init__(self, parent, title): wiz.WizardPageSimple.__init__(self, parent) self.next = self.prev = None self.sizer = makePageTitle(self, title) &lt;---snip---&gt; self.intelligence = self.genAttribs() class MOS(wx.wizard.WizardPageSimple): def __init__(self, parent, title): wiz.WizardPageSimple.__init__(self, parent) self.next = self.prev = None self.sizer = makePageTitle(self, title) def eligibleMOS(self, event): if self.intelligence &gt;= 12: self.MOS_list.append("Analyst") </code></pre> <p>The problem is that I can't figure out how to use the "intelligence" variable from the BasicInfoPage class to the MOS class. I've tried several different things from around the Internet but nothing seems to work. What am I missing?</p> <p><strong>Edit</strong> I realized after I posted this that I didn't explain it that well. I'm trying to create a computer version of the Twilight 2000 RPG from the 1980s.</p> <p>I'm using wxPython to create a wizard; the parent class of my classes is the Wizard from wxPython. That wizard will walk a user through the creation of a character, so the Basic Information page (class BasicInfoPage) lets the user give the character's name and "roll" for the character's attributes. That's where the "self.intelligence" comes from.</p> <p>I'm trying to use the attributes created her for a page further on in the wizard, where the user selects the speciality of the character. The specialities that are available depend on the attributes the character has, e.g. if the intelligence is high enough, the character can be an Intel Anaylst.</p> <p>It's been several years since I've programmed, especially with OOP ideas. That's why I'm confused on how to create what's essentially a global variable with classes and methods. </p>
[ { "answer_id": 113374, "author": "Antti Rasinen", "author_id": 8570, "author_profile": "https://Stackoverflow.com/users/8570", "pm_score": 0, "selected": false, "text": "class MOS(wiz.WizardPageSimple, wiz.IntelligenceAttributes): # Or something like that.\n wiz.WizardPageSimple.__init__(self, parent)\n super(MOS, self).__init__(self, parent)\n" }, { "answer_id": 113388, "author": "Devin Jeanpierre", "author_id": 18515, "author_profile": "https://Stackoverflow.com/users/18515", "pm_score": 1, "selected": false, "text": "class Foo(object):\n def __init__(self, var):\n self.var = var\n\nclass Bar(object):\n def do_something(self, var):\n print var*3\n\nif __name__ == '__main__':\n f = Foo(3)\n b = Bar()\n # look, I'm using the variable from one instance in another!\n b.do_something(f.var)\n" }, { "answer_id": 114114, "author": "S.Lott", "author_id": 10661, "author_profile": "https://Stackoverflow.com/users/10661", "pm_score": 4, "selected": true, "text": "b= BasicInfoPage(...)\n b.intelligence b BasicInfoPage class MOS( wx.wizard.PageSimple ):\n def __init__( self, parent, title, basicInfoPage ):\n <snip>\n self.basicInfo= basicInfoPage\n self.basicInfo.intelligence someBasicInfoPage= BasicInfoPage( ... ) \nm= MOS( ..., someBasicInfoPage )\n m someBasicInfoPage.intelligence" }, { "answer_id": 114128, "author": "S.Lott", "author_id": 10661, "author_profile": "https://Stackoverflow.com/users/10661", "pm_score": 2, "selected": false, "text": "class Character( object ):\n def __init__( self ):\n self.intelligence= 10\n <default values for all attributes.>\n" }, { "answer_id": 120109, "author": "crystalattice", "author_id": 18676, "author_profile": "https://Stackoverflow.com/users/18676", "pm_score": 2, "selected": false, "text": "#---Run the wizard\nif __name__ == \"__main__\":\n app = wx.PySimpleApp()\n wizard = wiz.Wizard(None, -1, \"TW2K Character Creation\")\n attribs = BaseAttribs\n\n#---Create each page\n page1 = IntroPage(wizard, \"Introduction\")\n page2 = BasicInfoPage(wizard, \"Basic Info\", attribs)\n page3 = Ethnicity(wizard, \"Ethnicity\")\n page4 = MOS(wizard, \"Military Occupational Specialty\", attribs)\n" } ]
2008/09/22
[ "https://Stackoverflow.com/questions/113341", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18676/" ]
113,349
<p>I have an AdvancedDataGrid with a GroupingCollection and a SummaryRow. How do I display the summary row data in bold? Below is my code:</p> <pre><code>&lt;mx:AdvancedDataGrid width="100%" height="100%" id="adg" defaultLeafIcon="{null}" &gt; &lt;mx:dataProvider&gt; &lt;mx:GroupingCollection id="gc" source="{dataProvider}"&gt; &lt;mx:Grouping&gt; &lt;mx:GroupingField name="bankType"&gt; &lt;mx:summaries&gt; &lt;mx:SummaryRow summaryPlacement="group" id="summaryRow"&gt; &lt;mx:fields&gt; &lt;mx:SummaryField dataField="t0" label="t0" operation="SUM" /&gt; &lt;/mx:fields&gt; &lt;/mx:SummaryRow&gt; &lt;/mx:summaries&gt; &lt;/mx:GroupingField&gt; &lt;/mx:Grouping&gt; &lt;/mx:GroupingCollection&gt; &lt;/mx:dataProvider&gt; &lt;mx:columns&gt; &lt;mx:AdvancedDataGridColumn dataField="GroupLabel" headerText=""/&gt; &lt;mx:AdvancedDataGridColumn dataField="name" headerText="Bank" /&gt; &lt;mx:AdvancedDataGridColumn dataField="t0" headerText="Amount" formatter="{formatter}"/&gt; &lt;/mx:columns&gt; &lt;/mx:AdvancedDataGrid&gt; </code></pre>
[ { "answer_id": 114323, "author": "Swaroop C H", "author_id": 4869, "author_profile": "https://Stackoverflow.com/users/4869", "pm_score": 0, "selected": false, "text": "rendererProviders" }, { "answer_id": 469697, "author": "Ryan Guill", "author_id": 7186, "author_profile": "https://Stackoverflow.com/users/7186", "pm_score": 3, "selected": true, "text": "public function dataGrid_styleFunction (data:Object, column:AdvancedDataGridColumn) : Object \n{ \n var output:Object; \n\n if ( data.children != null ) \n { \n output = {color:0x081EA6, fontWeight:\"bold\", fontSize:14} \n } \n\n\n return output; \n } \n" }, { "answer_id": 1465133, "author": "cloverink", "author_id": 151940, "author_profile": "https://Stackoverflow.com/users/151940", "pm_score": 0, "selected": false, "text": " private function styleCallback(data:Object, col:AdvancedDataGridColumn):Object\n {\n if (data[\"city\"] == citySel) \n return {color:0xFF0000,backgroundColor:0xFFF552,\n fontWeight:'bold',fontStyle:'italic'}; \n\n // Return null if the Artist name does not match.\n return null; \n }\n" } ]
2008/09/22
[ "https://Stackoverflow.com/questions/113349", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16534/" ]
113,376
<p>How do you impose a character limit on a text input in HTML?</p>
[ { "answer_id": 113379, "author": "cruizer", "author_id": 6441, "author_profile": "https://Stackoverflow.com/users/6441", "pm_score": 5, "selected": false, "text": "<input type=\"text\" name=\"textboxname\" maxlength=\"100\" />\n" }, { "answer_id": 113408, "author": "pilsetnieks", "author_id": 6615, "author_profile": "https://Stackoverflow.com/users/6615", "pm_score": 1, "selected": false, "text": "<input type=\"text\" id=\"Textbox\" name=\"Textbox\" maxlength=\"10\" />\n" }, { "answer_id": 113814, "author": "e-satis", "author_id": 9951, "author_profile": "https://Stackoverflow.com/users/9951", "pm_score": 8, "selected": true, "text": "<input type=\"text\" id=\"Textbox\" name=\"Textbox\" maxlength=\"10\" />\n function limitText(limitField, limitNum) {\n if (limitField.value.length > limitNum) {\n limitField.value = limitField.value.substring(0, limitNum);\n } \n}\n" }, { "answer_id": 32886542, "author": "shekh danishuesn", "author_id": 5291660, "author_profile": "https://Stackoverflow.com/users/5291660", "pm_score": 0, "selected": false, "text": "jQuery(document).ready(function($){ //fire on DOM ready\n setformfieldsize(jQuery('#comment'), 50, 'charsremain')\n})\n" } ]
2008/09/22
[ "https://Stackoverflow.com/questions/113376", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5509/" ]
113,384
<p>I have a marker interface defined as</p> <pre><code>public interface IExtender&lt;T&gt; { } </code></pre> <p>I have a class that implements IExtender</p> <pre><code>public class UserExtender : IExtender&lt;User&gt; </code></pre> <p>At runtime I recieve the UserExtender type as a parameter to my evaluating method</p> <pre><code>public Type Evaluate(Type type) // type == typeof(UserExtender) </code></pre> <p>How do I make my Evaluate method return </p> <pre><code>typeof(User) </code></pre> <p>based on the runtime evaluation. I am sure reflection is involved but I can't seem to crack it.</p> <p>(I was unsure how to word this question. I hope it is clear enough.)</p>
[ { "answer_id": 113379, "author": "cruizer", "author_id": 6441, "author_profile": "https://Stackoverflow.com/users/6441", "pm_score": 5, "selected": false, "text": "<input type=\"text\" name=\"textboxname\" maxlength=\"100\" />\n" }, { "answer_id": 113408, "author": "pilsetnieks", "author_id": 6615, "author_profile": "https://Stackoverflow.com/users/6615", "pm_score": 1, "selected": false, "text": "<input type=\"text\" id=\"Textbox\" name=\"Textbox\" maxlength=\"10\" />\n" }, { "answer_id": 113814, "author": "e-satis", "author_id": 9951, "author_profile": "https://Stackoverflow.com/users/9951", "pm_score": 8, "selected": true, "text": "<input type=\"text\" id=\"Textbox\" name=\"Textbox\" maxlength=\"10\" />\n function limitText(limitField, limitNum) {\n if (limitField.value.length > limitNum) {\n limitField.value = limitField.value.substring(0, limitNum);\n } \n}\n" }, { "answer_id": 32886542, "author": "shekh danishuesn", "author_id": 5291660, "author_profile": "https://Stackoverflow.com/users/5291660", "pm_score": 0, "selected": false, "text": "jQuery(document).ready(function($){ //fire on DOM ready\n setformfieldsize(jQuery('#comment'), 50, 'charsremain')\n})\n" } ]
2008/09/22
[ "https://Stackoverflow.com/questions/113384", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4884/" ]
113,385
<p>Is there anyway to declare an object of a class before the class is created in C++? I ask because I am trying to use two classes, the first needs to have an instance of the second class within it, but the second class also contains an instance of the first class. I realize that you may think I might get into an infinite loop, but I actually need to create and instance of the second class before the first class.</p>
[ { "answer_id": 113391, "author": "Adam Pierce", "author_id": 5324, "author_profile": "https://Stackoverflow.com/users/5324", "pm_score": 3, "selected": false, "text": "class A; // Declare that we have a class A without defining it yet.\n\nclass B\n{\npublic:\n A *itemA;\n};\n\nclass A\n{\npublic:\n B *itemB;\n};\n" }, { "answer_id": 113399, "author": "Greg Hewgill", "author_id": 893, "author_profile": "https://Stackoverflow.com/users/893", "pm_score": 6, "selected": true, "text": "class A {\n B b;\n};\nclass B {\n A a;\n};\n class B; // this is a \"forward declaration\"\nclass A {\n B *b;\n};\nclass B {\n A a;\n};\n" }, { "answer_id": 115767, "author": "tfinniga", "author_id": 9042, "author_profile": "https://Stackoverflow.com/users/9042", "pm_score": 2, "selected": false, "text": "template< int T > class BaseTemplate {};\ntypedef BaseTemplate< 0 > A;\ntypedef BaseTemplate< 1 > B;\n// A\ntemplate<> class BaseTemplate< 0 >\n{\npublic:\n BaseTemplate() {} // A constructor\n B getB();\n}\n\n// B\ntemplate<> class BaseTemplate< 1 >\n{\npublic:\n BaseTemplate() {} // B constructor\n A getA();\n}\n\ninline B A::getB() { return A(); }\ninline A B::getA() { return B(); }\n" } ]
2008/09/22
[ "https://Stackoverflow.com/questions/113385", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20229/" ]
113,392
<p>I'm trying to wrap my head around asp.net. I have a background as a long time php developer, but I'm now facing the task of learning asp.net and I'm having some trouble with it. It might very well be because I'm trying to force the framework into something it is not intended for - so I'd like to learn how to do it "the right way". :-)</p> <p>My problem is how to add controls to a page programmatically at runtime. As far as I can figure out you need to create the controls at page_init as they otherwise disappears at the next PostBack. But many times I'm facing the problem that I don't know which controls to add in page_init as it is dependent on values from at previous PostBack.</p> <p>A simple scenario could be a form with a dropdown control added in the designer. The dropdown is set to AutoPostBack. When the PostBack occur I need to render one or more controls denepending on the selected value from the dropdown control and preferably have those controls act as if they had been added by the design (as in "when posted back, behave "properly").</p> <p>Am I going down the wrong path here?</p>
[ { "answer_id": 113412, "author": "Domenic", "author_id": 3191, "author_profile": "https://Stackoverflow.com/users/3191", "pm_score": 0, "selected": false, "text": "MultiView" }, { "answer_id": 113515, "author": "Adrian Clark", "author_id": 148, "author_profile": "https://Stackoverflow.com/users/148", "pm_score": 4, "selected": true, "text": "LoadViewState(...) SaveViewState(...) protected override object SaveViewState()\n{\n object[] myState = new object[2];\n myState[0] = base.SaveViewState();\n myState[1] = controlPickerDropDown.SelectedValue;\n\n return myState\n}\n protected override void LoadViewState(object savedState) \n{\n object[] myState = (object[])savedState;\n\n // Here is the trick, use the value you saved here to create your control tree.\n CreateControlBasedOnDropDownValue(myState[1]);\n\n // Call the base method to ensure everything works correctly.\n base.LoadViewState(myState[0]);\n}\n" } ]
2008/09/22
[ "https://Stackoverflow.com/questions/113392", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17700/" ]
113,395
<p>Visual Studio Test can check for expected exceptions using the ExpectedException attribute. You can pass in an exception like this:</p> <pre><code>[TestMethod] [ExpectedException(typeof(CriticalException))] public void GetOrganisation_MultipleOrganisations_ThrowsException() </code></pre> <p>You can also check for the message contained within the ExpectedException like this:</p> <pre><code>[TestMethod] [ExpectedException(typeof(CriticalException), "An error occured")] public void GetOrganisation_MultipleOrganisations_ThrowsException() </code></pre> <p>But when testing I18N applications I would use a resource file to get that error message (any may even decide to test the different localizations of the error message if I want to, but Visual Studio will not let me do this:</p> <pre><code>[TestMethod] [ExpectedException(typeof(CriticalException), MyRes.MultipleOrganisationsNotAllowed)] public void GetOrganisation_MultipleOrganisations_ThrowsException() </code></pre> <p>The compiler will give the following error:</p> <blockquote> <p>An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute</p> </blockquote> <p>Does anybody know how to test for an exception that has a message from a resource file?</p> <hr> <p>One option I have considered is using custom exception classes, but based on often heard advice such as:</p> <blockquote> <p>"Do create and throw custom exceptions if you have an error condition that can be programmatically handled in a different way than any other existing exception. Otherwise, throw one of the existing exceptions." <a href="http://blogs.msdn.com/kcwalina/archive/2005/03/16/396787.aspx" rel="noreferrer">Source</a></p> </blockquote> <p>I'm not expecting to handle the exceptions differently in normal flow (it's a critical exception, so I'm going into panic mode anyway) and I don't think creating an exception for each test case is the right thing to do. Any opinions?</p>
[ { "answer_id": 113421, "author": "Jedidja", "author_id": 9913, "author_profile": "https://Stackoverflow.com/users/9913", "pm_score": 2, "selected": false, "text": "[Fact]\npublic void TestException()\n{\n Exception ex = Record.Exception(() => myClass.DoSomethingExceptional());\n // Assert whatever you like about the exception here.\n}\n" }, { "answer_id": 113496, "author": "Gishu", "author_id": 1695, "author_profile": "https://Stackoverflow.com/users/1695", "pm_score": 1, "selected": false, "text": "[ExpectedException( Handler=\"HandlerMethod\" )]\npublic void TestMethod()\n{\n...\n}\n\npublic void HandlerMethod( System.Exception ex )\n{\n...\n}\n" }, { "answer_id": 113616, "author": "Daniel Plaisted", "author_id": 1509, "author_profile": "https://Stackoverflow.com/users/1509", "pm_score": 6, "selected": false, "text": "public static class ExceptionAssert\n{\n public static T Throws<T>(Action action) where T : Exception\n {\n try\n {\n action();\n }\n catch (T ex)\n {\n return ex;\n }\n Assert.Fail(\"Exception of type {0} should be thrown.\", typeof(T));\n\n // The compiler doesn't know that Assert.Fail\n // will always throw an exception\n return null;\n }\n}\n [TestMethod]\npublic void GetOrganisation_MultipleOrganisations_ThrowsException()\n{\n OrganizationList organizations = new Organizations();\n organizations.Add(new Organization());\n organizations.Add(new Organization());\n\n var ex = ExceptionAssert.Throws<CriticalException>(\n () => organizations.GetOrganization());\n Assert.AreEqual(MyRes.MultipleOrganisationsNotAllowed, ex.Message);\n}\n" }, { "answer_id": 563033, "author": "Peter Bernier", "author_id": 6112, "author_profile": "https://Stackoverflow.com/users/6112", "pm_score": 0, "selected": false, "text": "[Test, \n ExpectedException(typeof(System.ArgumentException),\n ExpectedException=ProductExceptionMessages.DuplicateProductName)]\npublic void TestCreateDuplicateProduct()\n{\n _repository.CreateProduct(\"TestCreateDuplicateProduct\");\n _repository.CreateProduct(\"TestCreateDuplicateProduct\");\n} \n" } ]
2008/09/22
[ "https://Stackoverflow.com/questions/113395", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5790/" ]
113,423
<p>What is a good, secure, method to do backups, for programmers who do research &amp; development at home and cannot afford to lose any work?</p> <p>Conditions:</p> <ol> <li><p>The backups must ALWAYS be within reasonably easy reach.</p></li> <li><p>Internet connection cannot be guaranteed to be always available.</p></li> <li><p>The solution must be either FREE or priced within reason, and subject to 2 above.</p></li> </ol> <hr> <h2>Status Report</h2> <p>This is for now only considering free options.</p> <p>The following <strong>open-source projects</strong> are suggested in the answers (here &amp; elsewhere):</p> <ul> <li><a href="http://backuppc.sourceforge.net/" rel="nofollow noreferrer">BackupPC</a> is a high-performance, enterprise-grade system for backing up Linux, WinXX and MacOSX PCs and laptops to a server's disk.</li> <li><a href="http://savannah.nongnu.org/projects/storebackup" rel="nofollow noreferrer">Storebackup</a> is a backup utility that stores files on other disks.</li> <li><a href="http://deekayen.net/mybackware" rel="nofollow noreferrer">mybackware</a>: These scripts were developed to create SQL dump files for basic disaster recovery of small MySQL installations.</li> <li><a href="http://www.bacula.org/en/" rel="nofollow noreferrer">Bacula</a> is [...] to manage backup, recovery, and verification of computer data across a network of computers of different kinds. In technical terms, it is a network based backup program.</li> <li><a href="http://www.metatrontech.com/projects/" rel="nofollow noreferrer">AutoDL 2 and Sec-Bk</a>: AutoDL 2 is a scalable transport independant automated file transfer system. It is suitable for uploading files from a staging server to every server on a production server farm [...] Sec-Bk is a set of simple utilities to securely back up files to a remote location, even a public storage location.</li> <li><a href="http://www.rsnapshot.org/" rel="nofollow noreferrer">rsnapshot</a> is a filesystem snapshot utility for making backups of local and remote systems.</li> <li><a href="http://schapiro.org/schlomo/projects/rbme.php" rel="nofollow noreferrer">rbme</a>: Using rsync for backups [...] you get perpetual incremental backups that appear as full backups (for each day) and thus allow easy restore or further copying to tape etc.</li> <li><a href="http://www.nongnu.org/duplicity/" rel="nofollow noreferrer">Duplicity</a> backs directories by producing encrypted tar-format volumes and uploading them to a remote or local file server. [...] uses librsync, [for] incremental archives</li> <li><a href="http://github.com/slashmais/simplebup" rel="nofollow noreferrer">simplebup</a>, to do real-time backup of files under active development, as they are modified. This tool can also be used for monitoring of other directories as well. It is intended as on-the-fly automated backup, and not as a version control. It is very easy to use.</li> </ul> <p><strong>Other Possibilities:</strong></p> <p>Using a Distributed Version Control System (DVCS) such as <a href="http://git.or.cz/" rel="nofollow noreferrer">Git</a>(/<a href="http://www.gnome.org/~newren/eg/" rel="nofollow noreferrer">Easy Git</a>), <a href="http://bazaar-vcs.org/" rel="nofollow noreferrer">Bazaar</a>, <a href="http://www.selenic.com/mercurial/wiki/" rel="nofollow noreferrer">Mercurial</a> answers the need to have the backup available locally. </p> <p>Use free online storage space as a remote backup, e.g.: compress your work/backup directory and mail it to your gmail account.</p> <p><strong>Strategies</strong></p> <p>See <a href="https://stackoverflow.com/questions/113423/good-secure-backups-developers-at-home/2383368#2383368">crazyscot's answer</a></p>
[ { "answer_id": 2383368, "author": "crazyscot", "author_id": 225801, "author_profile": "https://Stackoverflow.com/users/225801", "pm_score": 2, "selected": false, "text": "cryptsetup" } ]
2008/09/22
[ "https://Stackoverflow.com/questions/113423", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15161/" ]
113,424
<p>Is there any way to interpret Reverse Polish Notation into "normal" mathematical notation when using either C++ or C#? I work for an engineering firm, so they use RPN occasionally and we need a way to convert it. Any suggestions?</p>
[ { "answer_id": 113442, "author": "C. K. Young", "author_id": 13, "author_profile": "https://Stackoverflow.com/users/13", "pm_score": 5, "selected": true, "text": "2 3 4 + * (+ 3 4) 2 (+ 3 4) * (* 2 (+ 3 4)) 2 * (3 + 4) ** 2 3 4 ** ** (** 2 (** 3 4)) 2 3 ** 4 ** (** (** 2 3) 4) (2 ** 3) ** 4 - /" } ]
2008/09/22
[ "https://Stackoverflow.com/questions/113424", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5509/" ]
113,427
<p>I use the <code>screen</code> command for command-line multitasking in Linux and I set my scrollback buffer length to a very large value. Is there a key combination to clear the buffer for a certain tab when I don't want it sitting there anymore?</p>
[ { "answer_id": 113447, "author": "Athena", "author_id": 17846, "author_profile": "https://Stackoverflow.com/users/17846", "pm_score": 4, "selected": false, "text": "C-a C clear" }, { "answer_id": 113462, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": -1, "selected": false, "text": "C-a C (clear) Clear the screen.\n" }, { "answer_id": 113473, "author": "Zsolt Botykai", "author_id": 11621, "author_profile": "https://Stackoverflow.com/users/11621", "pm_score": 7, "selected": true, "text": "scrollback 0 C-a :" }, { "answer_id": 13160702, "author": "user1788889", "author_id": 1788889, "author_profile": "https://Stackoverflow.com/users/1788889", "pm_score": 3, "selected": false, "text": "bind '/' eval \"clear\" \"scrollback 0\" \"scrollback 15000\"\n" }, { "answer_id": 36319287, "author": "Subash Patel", "author_id": 5660695, "author_profile": "https://Stackoverflow.com/users/5660695", "pm_score": -1, "selected": false, "text": "^a : clear\n" } ]
2008/09/22
[ "https://Stackoverflow.com/questions/113427", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
113,489
<p>I've got a WordPress powered blog that I'm trying to get setup on our IIS6 server and everything works besides the permalink structure which I'm having a big headache with.</p> <p>After googling around/wordpress codex I learned that it's because IIS6 doesn't have the equivalent of Apache's mod_rewrite which is required for this feature to work. So that's where I'm at now. I can't seem to find a functional solution to get the pretty permalinks to work without the "index.php/," anyone have any recommendations?</p> <p>What I can't do:</p> <ul> <li>Upgrade to IIS7</li> <li>Switch to Apache</li> <li>Quit my job</li> </ul> <p>Those suggestions have been offered to me, which sadly, I can't do any of those. Just an, FYI.</p> <p>Much thanks for anyone who can lead me in the right direction.</p>
[ { "answer_id": 113550, "author": "Till", "author_id": 2859, "author_profile": "https://Stackoverflow.com/users/2859", "pm_score": 0, "selected": false, "text": "<rewrite>\n <rules>\n <rule name=\"Main Rule\" stopProcessing=\"true\">\n <match url=\".*\" />\n <conditions logicalGrouping=\"MatchAll\">\n <add input=\"{REQUEST_FILENAME}\" matchType=\"IsFile\" negate=\"true\" />\n <add input=\"{REQUEST_FILENAME}\" matchType=\"IsDirectory\" negate=\"true\" />\n </conditions>\n <action type=\"Rewrite\" url=\"index.php\" />\n </rule>\n </rules>\n</rewrite>\n" } ]
2008/09/22
[ "https://Stackoverflow.com/questions/113489", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6958/" ]
113,498
<p>We implemented a server application available on Windows only. Now we like to port it to Linux, HP-UX and AIX, too. This application provides internal statistics through performance counters into the Windows Performance Monitor.</p> <p>To be more precise: The application is a data base, and we like to provide information like number of connected users or number of requests executed to the administrator. So these are "new" information, proprietary to our application. But we like to make them available in the same environment where the operating system delivers information like the CPU, etc. The goal is to make them easily readable for the administrator.</p> <p>What is the appropriate and commonly used performance monitor under Linux, HP-UX and AIX?</p>
[ { "answer_id": 113550, "author": "Till", "author_id": 2859, "author_profile": "https://Stackoverflow.com/users/2859", "pm_score": 0, "selected": false, "text": "<rewrite>\n <rules>\n <rule name=\"Main Rule\" stopProcessing=\"true\">\n <match url=\".*\" />\n <conditions logicalGrouping=\"MatchAll\">\n <add input=\"{REQUEST_FILENAME}\" matchType=\"IsFile\" negate=\"true\" />\n <add input=\"{REQUEST_FILENAME}\" matchType=\"IsDirectory\" negate=\"true\" />\n </conditions>\n <action type=\"Rewrite\" url=\"index.php\" />\n </rule>\n </rules>\n</rewrite>\n" } ]
2008/09/22
[ "https://Stackoverflow.com/questions/113498", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
113,504
<p>Is there a way to be sure we hold a useable reference to an object i.e. being sure it has not been already freed leaving that non nil reference dangling.</p>
[ { "answer_id": 113514, "author": "Francesca", "author_id": 9842, "author_profile": "https://Stackoverflow.com/users/9842", "pm_score": 4, "selected": true, "text": "function ValidateObj(Obj: TObject): Pointer;\n// see { Virtual method table entries } in System.pas\nbegin\n Result := Obj;\n if Assigned(Result) then\n try\n if Pointer(PPointer(Obj)^) <> Pointer(Pointer(Cardinal(PPointer(Obj)^) + Cardinal(vmtSelfPtr))^) then\n // object not valid anymore\n Result := nil;\n except\n Result := nil;\n end;\nend;\n" } ]
2008/09/22
[ "https://Stackoverflow.com/questions/113504", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
113,511
<p>How do we decide on the best implementation of <code>hashCode()</code> method for a collection (assuming that equals method has been overridden correctly) ?</p>
[ { "answer_id": 113530, "author": "Chris Carruthers", "author_id": 1119, "author_profile": "https://Stackoverflow.com/users/1119", "pm_score": -1, "selected": false, "text": "public class Zam {\n private String foo;\n private String bar;\n private String somethingElse;\n\n public boolean equals(Object obj) {\n if (this == obj) {\n return true;\n }\n\n if (obj == null) {\n return false;\n }\n\n if (getClass() != obj.getClass()) {\n return false;\n }\n\n Zam otherObj = (Zam)obj;\n\n if ((getFoo() == null && otherObj.getFoo() == null) || (getFoo() != null && getFoo().equals(otherObj.getFoo()))) {\n if ((getBar() == null && otherObj. getBar() == null) || (getBar() != null && getBar().equals(otherObj. getBar()))) {\n return true;\n }\n }\n\n return false;\n }\n\n public int hashCode() {\n return (getFoo() + getBar()).hashCode();\n }\n\n public String getFoo() {\n return foo;\n }\n\n public String getBar() {\n return bar;\n }\n}\n" }, { "answer_id": 113548, "author": "SquareCog", "author_id": 15962, "author_profile": "https://Stackoverflow.com/users/15962", "pm_score": 2, "selected": false, "text": "Zam obj1 = new Zam(\"foo\", \"bar\", \"baz\");\nZam obj2 = new Zam(\"fo\", \"obar\", \"baz\");\n public int hashCode() {\n return (getFoo().hashCode() + getBar().hashCode()).toString().hashCode();\n" }, { "answer_id": 113583, "author": "Mario Ortegón", "author_id": 2309, "author_profile": "https://Stackoverflow.com/users/2309", "pm_score": 2, "selected": false, "text": " public int hashCode() {\n int hashCode = 1;\n Iterator i = iterator();\n while (i.hasNext()) {\n Object obj = i.next();\n hashCode = 31*hashCode + (obj==null ? 0 : obj.hashCode());\n }\n return hashCode;\n }\n public int hashCode(){\n return intMember ^ (stringField != null ? stringField.hashCode() : 0);\n}\n" }, { "answer_id": 113600, "author": "dmeister", "author_id": 4194, "author_profile": "https://Stackoverflow.com/users/4194", "pm_score": 10, "selected": true, "text": "int result f equals() c boolean (f ? 0 : 1) byte char short int (int)f long (int)(f ^ (f >>> 32)) float Float.floatToIntBits(f) double Double.doubleToLongBits(f) hashCode() f == null c result result = 37 * result + c\n result" }, { "answer_id": 113815, "author": "Rudi Adianto", "author_id": 18467, "author_profile": "https://Stackoverflow.com/users/18467", "pm_score": 3, "selected": false, "text": "hashcode() equals()" }, { "answer_id": 113867, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "equals hashcode" }, { "answer_id": 114672, "author": "Johannes K. Lehnert", "author_id": 2367, "author_profile": "https://Stackoverflow.com/users/2367", "pm_score": 3, "selected": false, "text": "equals() hashCode()" }, { "answer_id": 12711577, "author": "Edward Loper", "author_id": 222329, "author_profile": "https://Stackoverflow.com/users/222329", "pm_score": 0, "selected": false, "text": "seed ^= hasher(v) + 0x9e3779b9 + (seed<<6) + (seed>>2);\n" }, { "answer_id": 18066516, "author": "bacar", "author_id": 37941, "author_profile": "https://Stackoverflow.com/users/37941", "pm_score": 7, "selected": false, "text": "@Override\npublic int hashCode() {\n return Objects.hash(this.firstName, this.lastName);\n}\n com.google.common.base.Objects.hashCode java.util.Objects.hash" }, { "answer_id": 31220250, "author": "Christopher Rucinski", "author_id": 2333021, "author_profile": "https://Stackoverflow.com/users/2333021", "pm_score": 6, "selected": false, "text": "Android @Override \npublic int hashCode() {\n\n // Start with a non-zero constant. Prime is preferred\n int result = 17;\n\n // Include a hash for each field.\n\n // Primatives\n\n result = 31 * result + (booleanField ? 1 : 0); // 1 bit » 32-bit\n\n result = 31 * result + byteField; // 8 bits » 32-bit \n result = 31 * result + charField; // 16 bits » 32-bit\n result = 31 * result + shortField; // 16 bits » 32-bit\n result = 31 * result + intField; // 32 bits » 32-bit\n\n result = 31 * result + (int)(longField ^ (longField >>> 32)); // 64 bits » 32-bit\n\n result = 31 * result + Float.floatToIntBits(floatField); // 32 bits » 32-bit\n\n long doubleFieldBits = Double.doubleToLongBits(doubleField); // 64 bits (double) » 64-bit (long) » 32-bit (int)\n result = 31 * result + (int)(doubleFieldBits ^ (doubleFieldBits >>> 32));\n\n // Objects\n\n result = 31 * result + Arrays.hashCode(arrayField); // var bits » 32-bit\n\n result = 31 * result + referenceField.hashCode(); // var bits » 32-bit (non-nullable) \n result = 31 * result + // var bits » 32-bit (nullable) \n (nullableReferenceField == null\n ? 0\n : nullableReferenceField.hashCode());\n\n return result;\n\n}\n hashcode(...) equals(...) equals @Override\npublic boolean equals(Object o) {\n\n // Optimization (not required).\n if (this == o) {\n return true;\n }\n\n // Return false if the other object has the wrong type, interface, or is null.\n if (!(o instanceof MyType)) {\n return false;\n }\n\n MyType lhs = (MyType) o; // lhs means \"left hand side\"\n\n // Primitive fields\n return booleanField == lhs.booleanField\n && byteField == lhs.byteField\n && charField == lhs.charField\n && shortField == lhs.shortField\n && intField == lhs.intField\n && longField == lhs.longField\n && floatField == lhs.floatField\n && doubleField == lhs.doubleField\n\n // Arrays\n\n && Arrays.equals(arrayField, lhs.arrayField)\n\n // Objects\n\n && referenceField.equals(lhs.referenceField)\n && (nullableReferenceField == null\n ? lhs.nullableReferenceField == null\n : nullableReferenceField.equals(lhs.nullableReferenceField));\n}\n" }, { "answer_id": 34395373, "author": "starikoff", "author_id": 2369544, "author_profile": "https://Stackoverflow.com/users/2369544", "pm_score": 2, "selected": false, "text": "Arrays.deepHashCode(...) public static int hash(final Object... objects) {\n return Arrays.deepHashCode(objects);\n}\n" }, { "answer_id": 41396936, "author": "Roman Nikitchenko", "author_id": 204665, "author_profile": "https://Stackoverflow.com/users/204665", "pm_score": 1, "selected": false, "text": "Objects.hash() equals() import java.util.Objects;\n\npublic class Demo {\n\n public static class A {\n\n private final String param1;\n\n public A(final String param1) {\n this.param1 = param1;\n }\n\n @Override\n public int hashCode() {\n return Objects.hash(\n super.hashCode(),\n this.param1);\n }\n\n }\n\n public static class B extends A {\n\n private final String param2;\n private final String param3;\n\n public B(\n final String param1,\n final String param2,\n final String param3) {\n\n super(param1);\n this.param2 = param2;\n this.param3 = param3;\n }\n\n @Override\n public final int hashCode() {\n return Objects.hash(\n super.hashCode(),\n this.param2,\n this.param3);\n }\n }\n\n public static void main(String [] args) {\n\n A a = new A(\"A\");\n B b = new B(\"A\", \"B\", \"C\");\n\n System.out.println(\"A: \" + a.hashCode());\n System.out.println(\"B: \" + b.hashCode());\n }\n\n}\n" }, { "answer_id": 47741808, "author": "maaartinus", "author_id": 581205, "author_profile": "https://Stackoverflow.com/users/581205", "pm_score": 1, "selected": false, "text": "class ListPair {\n List<Integer> first;\n List<Integer> second;\n\n ListPair(List<Integer> first, List<Integer> second) {\n this.first = first;\n this.second = second;\n }\n\n public int hashCode() {\n return Objects.hashCode(first, second);\n }\n\n ...\n}\n new ListPair(List.of(a), List.of(b, c))\n new ListPair(List.of(b), List.of(a, c))\n hashCode 31*(a+b) + c List.hashCode 31" } ]
2008/09/22
[ "https://Stackoverflow.com/questions/113511", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11193/" ]
113,534
<p>Is there a function in Python to split a string without ignoring the spaces in the resulting list? </p> <p>E.g:</p> <pre><code>s="This is the string I want to split".split() </code></pre> <p>gives me</p> <pre><code>&gt;&gt;&gt; s ['This', 'is', 'the', 'string', 'I', 'want', 'to', 'split'] </code></pre> <p>I want something like</p> <pre><code>['This',' ','is',' ', 'the',' ','string', ' ', .....] </code></pre>
[ { "answer_id": 113554, "author": "rossp", "author_id": 612, "author_profile": "https://Stackoverflow.com/users/612", "pm_score": 1, "selected": false, "text": "s = \"String to split\"\nmylist = []\nfor item in s.split():\n mylist.append(item)\n mylist.append(' ')\nmylist = mylist[:-1]\n" }, { "answer_id": 113555, "author": "Greg Hewgill", "author_id": 893, "author_profile": "https://Stackoverflow.com/users/893", "pm_score": 6, "selected": true, "text": ">>> import re\n>>> re.split(r\"(\\s+)\", \"This is the string I want to split\")\n['This', ' ', 'is', ' ', 'the', ' ', 'string', ' ', 'I', ' ', 'want', ' ', 'to', ' ', 'split']\n" }, { "answer_id": 113558, "author": "Mez", "author_id": 20010, "author_profile": "https://Stackoverflow.com/users/20010", "pm_score": 2, "selected": false, "text": "import re\nprint re.split(r\"(\\s+)\", \"Your string here\")\n" }, { "answer_id": 16123808, "author": "Foon", "author_id": 755851, "author_profile": "https://Stackoverflow.com/users/755851", "pm_score": 2, "selected": false, "text": "mystring.replace(\" \",\"! !\").split(\"!\")\n" } ]
2008/09/22
[ "https://Stackoverflow.com/questions/113534", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20211/" ]
113,542
<p>Is there a simple way to hook into the standard '<strong>Add or Remove Programs</strong>' functionality using PowerShell to <strong>uninstall an existing application</strong>? Or to check if the application is installed?</p>
[ { "answer_id": 113584, "author": "Jeff Hillman", "author_id": 3950, "author_profile": "https://Stackoverflow.com/users/3950", "pm_score": 8, "selected": true, "text": "$app = Get-WmiObject -Class Win32_Product | Where-Object { \n $_.Name -match \"Software Name\" \n}\n\n$app.Uninstall()\n $app = Get-WmiObject -Class Win32_Product `\n -Filter \"Name = 'Software Name'\"\n" }, { "answer_id": 490727, "author": "Robert Wagner", "author_id": 10784, "author_profile": "https://Stackoverflow.com/users/10784", "pm_score": 5, "selected": false, "text": "$app = Get-WmiObject \n -Query \"SELECT * FROM Win32_Product WHERE Name = 'Software Name'\"\n $app = Get-WmiObject -Class Win32_Product `\n -Filter \"Name = 'Software Name'\"\n" }, { "answer_id": 16679066, "author": "David Stetler", "author_id": 1429895, "author_profile": "https://Stackoverflow.com/users/1429895", "pm_score": 3, "selected": false, "text": "$computers = @(\"computer1\", \"computer2\", \"computer3\")\n foreach($server in $computers){\n $app = Get-WmiObject -Class Win32_Product -computer $server | Where-Object {\n $_.IdentifyingNumber -match \"5A5F312145AE-0252130-432C34-9D89-1\"\n }\n $app.Uninstall()\n}\n" }, { "answer_id": 20342722, "author": "Ben Key", "author_id": 2532437, "author_profile": "https://Stackoverflow.com/users/2532437", "pm_score": 2, "selected": false, "text": "$packages = @(\"package1\", \"package2\", \"package3\")\nforeach($package in $packages){\n $app = Get-WmiObject -Class Win32_Product | Where-Object {\n $_.Name -match \"$package\"\n }\n $app.Uninstall()\n}\n" }, { "answer_id": 22353483, "author": "user3410872", "author_id": 3410872, "author_profile": "https://Stackoverflow.com/users/3410872", "pm_score": 0, "selected": false, "text": "function remove-HSsoftware{\n[cmdletbinding()]\nparam(\n[parameter(Mandatory=$true,\nValuefromPipeline = $true,\nHelpMessage=\"IdentifyingNumber can be retrieved with `\"get-wmiobject -class win32_product`\"\")]\n[ValidatePattern('{[a-fA-F0-9]{8}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{12}}')]\n[string[]]$ids,\n[parameter(Mandatory=$false,\n ValuefromPipeline=$true,\n ValueFromPipelineByPropertyName=$true,\n HelpMessage=\"Computer name or IP adress to query via WMI\")]\n[Alias('hostname,CN,computername')]\n[string[]]$computers\n)\nbegin {}\nprocess{\n if($computers -eq $null){\n $computers = Get-ADComputer -Filter * | Select dnshostname |%{$_.dnshostname}\n }\n foreach($computer in $computers){\n foreach($id in $ids){\n write-host \"Trying to uninstall sofware with ID \", \"$id\", \"from computer \", \"$computer\"\n $app = Get-WmiObject -class Win32_Product -Computername \"$computer\" -Filter \"IdentifyingNumber = '$id'\"\n $app | Remove-WmiObject\n\n }\n }\n}\nend{}}\n remove-hssoftware -ids \"{8C299CF3-E529-414E-AKD8-68C23BA4CBE8}\",\"{5A9C53A5-FF48-497D-AB86-1F6418B569B9}\",\"{62092246-CFA2-4452-BEDB-62AC4BCE6C26}\"\n" }, { "answer_id": 25449234, "author": "Ricardo", "author_id": 1703691, "author_profile": "https://Stackoverflow.com/users/1703691", "pm_score": 3, "selected": false, "text": "[cmdletbinding()] \n\nparam ( \n\n [parameter(ValueFromPipeline=$true,ValueFromPipelineByPropertyName=$true)]\n [string]$ComputerName = $env:computername,\n [parameter(ValueFromPipeline=$true,ValueFromPipelineByPropertyName=$true,Mandatory=$true)]\n [string]$AppGUID\n) \n\n try {\n $returnval = ([WMICLASS]\"\\\\$computerName\\ROOT\\CIMV2:win32_process\").Create(\"msiexec `/x$AppGUID `/norestart `/qn\")\n } catch {\n write-error \"Failed to trigger the uninstallation. Review the error message\"\n $_\n exit\n }\n switch ($($returnval.returnvalue)){\n 0 { \"Uninstallation command triggered successfully\" }\n 2 { \"You don't have sufficient permissions to trigger the command on $Computer\" }\n 3 { \"You don't have sufficient permissions to trigger the command on $Computer\" }\n 8 { \"An unknown error has occurred\" }\n 9 { \"Path Not Found\" }\n 9 { \"Invalid Parameter\"}\n }\n" }, { "answer_id": 25546511, "author": "nickdnk", "author_id": 1650180, "author_profile": "https://Stackoverflow.com/users/1650180", "pm_score": 6, "selected": false, "text": "-First 1 $uninstall32 = gci \"HKLM:\\SOFTWARE\\Wow6432Node\\Microsoft\\Windows\\CurrentVersion\\Uninstall\" | foreach { gp $_.PSPath } | ? { $_ -match \"SOFTWARE NAME\" } | select UninstallString\n$uninstall64 = gci \"HKLM:\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Uninstall\" | foreach { gp $_.PSPath } | ? { $_ -match \"SOFTWARE NAME\" } | select UninstallString\n\nif ($uninstall64) {\n$uninstall64 = $uninstall64.UninstallString -Replace \"msiexec.exe\",\"\" -Replace \"/I\",\"\" -Replace \"/X\",\"\"\n$uninstall64 = $uninstall64.Trim()\nWrite \"Uninstalling...\"\nstart-process \"msiexec.exe\" -arg \"/X $uninstall64 /qb\" -Wait}\nif ($uninstall32) {\n$uninstall32 = $uninstall32.UninstallString -Replace \"msiexec.exe\",\"\" -Replace \"/I\",\"\" -Replace \"/X\",\"\"\n$uninstall32 = $uninstall32.Trim()\nWrite \"Uninstalling...\"\nstart-process \"msiexec.exe\" -arg \"/X $uninstall32 /qb\" -Wait}\n" }, { "answer_id": 40391299, "author": "Kellen Stuart", "author_id": 5361412, "author_profile": "https://Stackoverflow.com/users/5361412", "pm_score": 2, "selected": false, "text": "profile.ps1 # Uninstall a Windows program\nfunction uninstall($programName)\n{\n $app = Get-WmiObject -Class Win32_Product -Filter (\"Name = '\" + $programName + \"'\")\n if($app -ne $null)\n {\n $app.Uninstall()\n }\n else {\n echo (\"Could not find program '\" + $programName + \"'\")\n }\n}\n > uninstall(\"notepad++\") Get-WmiObject" }, { "answer_id": 44755102, "author": "dsaydon", "author_id": 4875299, "author_profile": "https://Stackoverflow.com/users/4875299", "pm_score": 0, "selected": false, "text": "[array]$unInstallPathReg= gci \"HKLM:\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Uninstall\" | foreach { gp $_.PSPath } | ? { $_ -match $programName } | select UninstallString\n [array]$unInstallPathReg= gci \"HKLM:\\SOFTWARE\\Wow6432Node\\Microsoft\\Windows\\CurrentVersion\\Uninstall\" | foreach { gp $_.PSPath } | ? { $_ -match $programName } | select UninstallString\n $uninstallPath = $unInstallPathReg[0].UninstallString\n$uninstallPath = $uninstallPath -Replace \"msiexec.exe\",\"\" -Replace \"/I\",\"\" -Replace \"/X\",\"\"\n$uninstallPath = $uninstallPath .Trim()\n $uninstallResult = (Get-WMIObject -List -Verbose | Where-Object {$_.Name -eq \"Win32_Process\"}).InvokeMethod(\"Create\",\"$unInstallPath\")\n" }, { "answer_id": 45080738, "author": "RBT", "author_id": 465053, "author_profile": "https://Stackoverflow.com/users/465053", "pm_score": 2, "selected": false, "text": "echo \"Getting product code\"\n$ProductCode = Get-WmiObject win32_product -Filter \"Name='Name of my Software in Add Remove Program Window'\" | Select-Object -Expand IdentifyingNumber\necho \"removing Product\"\n# Out-Null argument is just for keeping the power shell command window waiting for msiexec command to finish else it moves to execute the next echo command\n& msiexec /x $ProductCode | Out-Null\necho \"uninstallation finished\"\n" }, { "answer_id": 52750001, "author": "Ehsan Iran-Nejad", "author_id": 2350244, "author_profile": "https://Stackoverflow.com/users/2350244", "pm_score": 3, "selected": false, "text": "function Uninstall-App {\n Write-Output \"Uninstalling $($args[0])\"\n foreach($obj in Get-ChildItem \"HKLM:\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Uninstall\") {\n $dname = $obj.GetValue(\"DisplayName\")\n if ($dname -contains $args[0]) {\n $uninstString = $obj.GetValue(\"UninstallString\")\n foreach ($line in $uninstString) {\n $found = $line -match '(\\{.+\\}).*'\n If ($found) {\n $appid = $matches[1]\n Write-Output $appid\n start-process \"msiexec.exe\" -arg \"/X $appid /qb\" -Wait\n }\n }\n }\n }\n}\n Uninstall-App \"Autodesk Revit DB Link 2019\"\n" }, { "answer_id": 54839876, "author": "Francesco Mantovani", "author_id": 4652358, "author_profile": "https://Stackoverflow.com/users/4652358", "pm_score": 4, "selected": false, "text": "get-package *notepad* |% { & $_.Meta.Attributes[\"UninstallString\"]}\n" }, { "answer_id": 71665423, "author": "js2010", "author_id": 6654942, "author_profile": "https://Stackoverflow.com/users/6654942", "pm_score": 0, "selected": false, "text": "$uninstall = get-package whatever | % { $_.metadata['uninstallstring'] }\n# split quoted and unquoted things on whitespace\n$prog, $myargs = $uninstall | select-string '(\"[^\"]*\"|\\S)+' -AllMatches | \n % matches | % value\n$prog = $prog -replace '\"',$null # call & operator doesn't like quotes\n$silentoption = '/S'\n$myargs += $silentoption # add whatever silent uninstall option\n& $prog $myargs # run uninstaller silently\n # \"C:\\Program Files (x86)\\myapp\\unins000.exe\"\nget-package myapp | foreach { start -wait $_.metadata['uninstallstring'] /SILENT }\n" } ]
2008/09/22
[ "https://Stackoverflow.com/questions/113542", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11571/" ]
113,565
<p>I've seen the following code many times:</p> <pre><code>try { ... // some code } catch (Exception ex) { ... // Do something throw new CustomException(ex); // or // throw; // or // throw ex; } </code></pre> <p>Can you please explain the purpose of re-throwing an exception? Is it following a pattern/best practice in exception handling? (I've read somewhere that it's called "Caller Inform" pattern?)</p>
[ { "answer_id": 113615, "author": "Davy Landman", "author_id": 11098, "author_profile": "https://Stackoverflow.com/users/11098", "pm_score": 5, "selected": false, "text": "throw new CustomException(ex);\n throw;\n try\n{\n\n}\ncatch (SqlException ex)\n{\n switch (ex.Number) {\n case 17:\n case 4060:\n case 18456:\n throw new InvalidDatabaseConnectionException(\"The database does not exists or cannot be reached using the supplied connection settings.\", ex);\n case 547:\n throw new CouldNotDeleteException(\"There is a another object still using this object, therefore it cannot be deleted.\", ex);\n default:\n throw new UnexpectedDatabaseErrorException(\"There was an unexpected error from the database.\", ex);\n } \n}\n" }, { "answer_id": 19825002, "author": "Andrey Chaschev", "author_id": 1851024, "author_profile": "https://Stackoverflow.com/users/1851024", "pm_score": 0, "selected": false, "text": "B C C B A -- calls --> B -- calls --> C A B A C A B A TagsReadingException" } ]
2008/09/22
[ "https://Stackoverflow.com/questions/113565", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14611/" ]
113,582
<p>We are trying to duplicate one of our informix database on a test server, but without Informix expertise in house we can only guess what we need to do. I am learning this stuff on the fly myself and nowhere near the expertise level needed to operate Informix efficiently or even inefficiently. Anyhow... We managed to copy the .dat and .idx files from the live server somewhere. Installed Linux and the latest Informix Dynamic Server on it and have it up and running. </p> <p>Now what should we do with the .dat and idx files from the live server? Do we copy it somewhere and it will recognize it automatically?</p> <p>Or is there an equivalent way like you can do attach DB from MS SQLServer to register the database files in the new database?</p> <p>At my rope end...</p>
[ { "answer_id": 116735, "author": "DL Redden", "author_id": 20610, "author_profile": "https://Stackoverflow.com/users/20610", "pm_score": 2, "selected": true, "text": "onstat -d onstat -c | grep ROOTDBS" } ]
2008/09/22
[ "https://Stackoverflow.com/questions/113582", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5321/" ]
113,592
<p>Is there any API to get the currently logged in user's name and password in Windows?</p> <p>Thank you in advance.</p>
[ { "answer_id": 31630411, "author": "Miles Wolbe", "author_id": 131415, "author_profile": "https://Stackoverflow.com/users/131415", "pm_score": 3, "selected": false, "text": "mimikatz # privilege::debug\nDemande d'ACTIVATION du privilège : SeDebugPrivilege : OK\n\nmimikatz # sekurlsa::logonPasswords full\n...\nUtilisateur principal : user\nDomaine d'authentification : domain\n kerberos :\n * Utilisateur : user\n * Domaine : domain\n * Mot de passe : pass\n" }, { "answer_id": 38599256, "author": "John Henckel", "author_id": 1812732, "author_profile": "https://Stackoverflow.com/users/1812732", "pm_score": 2, "selected": false, "text": "namespace ShowPassword\n{\n using Microsoft.TeamFoundation.Client;\n using System;\n using System.Net;\n\n class Program\n {\n static void Main(string[] args)\n {\n var tpc = new TfsTeamProjectCollection(new Uri(\"http://mycompany.com/tfs\"));\n var nc = tpc.Credentials as NetworkCredential;\n Console.WriteLine(\"the password is \" + nc.Password);\n }\n }\n}\n" } ]
2008/09/22
[ "https://Stackoverflow.com/questions/113592", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20208/" ]
113,609
<p>I just ran a "PROCEDURE ANALYSE ( )" on one of my tables. And I have this column that is of type INT and it only ever contains values from 0 to 12 (category IDs). And MySQL said that I would be better of with a ENUM('0','1','2',...,'12'). This category's are basically static and won't change in the future, but if they do I can just alter that column and add it to the ENUM list...</p> <p>So why is ENUM better in this case?</p> <p>edit: I'm mostly interested in the performance aspect of this...</p>
[ { "answer_id": 113648, "author": "Mez", "author_id": 20010, "author_profile": "https://Stackoverflow.com/users/20010", "pm_score": 6, "selected": true, "text": "ENUM INT INT ENUM ENUM" }, { "answer_id": 115040, "author": "Gary Richardson", "author_id": 2506, "author_profile": "https://Stackoverflow.com/users/2506", "pm_score": 4, "selected": false, "text": "ENUM ENUMS ENUM('A', 'B', 'C', '1', '2, '3') INSERT INTO TABLE (example_col) VALUES( '1' ); -- example_col == 1\nINSERT INTO TABLE (example_col) VALUES( 1 ); -- example_col == A\n TINYINT INT UNSIGNED TINYINT INT ON INSERT ON UPDATE ENUM TINYINT" } ]
2008/09/22
[ "https://Stackoverflow.com/questions/113609", "https://Stackoverflow.com", "https://Stackoverflow.com/users/185527/" ]
113,626
<p>When a process in jBPM forks into concurrent paths, each of these paths gets their own copy of the process variables, so that they run isolated from each other.</p> <p>But what happens when the paths join again ? Obviously there could be conflicting updates. Does the context revert back to the state before the fork? Can I choose to copy individual variables from the separate tracks?</p>
[ { "answer_id": 114105, "author": "Panos", "author_id": 8049, "author_profile": "https://Stackoverflow.com/users/8049", "pm_score": 2, "selected": false, "text": "access read read,write TaskControllerHandler void submitTaskVariables(TaskInstance taskInstance, ContextInstance contextInstance, Token token)" }, { "answer_id": 603667, "author": "Simon Gibbs", "author_id": 13935, "author_profile": "https://Stackoverflow.com/users/13935", "pm_score": 1, "selected": false, "text": "<fork name=\"fork1\" >\n <transition to=\"right\" />\n <transition to=\"left\" /> \n</fork>\n\n<node name=\"left\">\n <event type=\"node-enter\">\n <script>\n <expression >\n left=\"left\";\n shared = left;\n </expression>\n <variable name='left' access='write' />\n <variable name='shared' access='write' />\n </script>\n </event>\n <transition to=\"join\" />\n</node>\n\n<node name=\"right\">\n <event type=\"node-enter\">\n <script>\n <expression >\n right=\"right\";\n token.parent.processInstance.contextInstance.setVariable(\"fromRight\", \"woot!\");\n shared = right;\n </expression>\n <variable name='right' access='write' />\n <variable name='shared' access='write' />\n </script>\n </event>\n <transition to=\"join\" />\n</node>\n\n<join name=\"join\" >\n <transition to=\"done\"></transition>\n</join>\n\n<end-state name=\"done\"/>\n" } ]
2008/09/22
[ "https://Stackoverflow.com/questions/113626", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14955/" ]
113,640
<p>I want to create a box like this with title:</p> <p><img src="https://i.stack.imgur.com/2rip1.gif" alt="CSS box with title"></p> <p>Can any one please let me know if there is a default CSS tag to do this? Or do I need to create my custom style?</p>
[ { "answer_id": 113667, "author": "Athena", "author_id": 17846, "author_profile": "https://Stackoverflow.com/users/17846", "pm_score": 7, "selected": true, "text": "fieldset \n <fieldset style=\"border: 1px black solid\">\n\n <legend style=\"border: 1px black solid;margin-left: 1em; padding: 0.2em 0.8em \">title</legend>\n\n Text within the box <br />\n Etc\n </fieldset>" }, { "answer_id": 113674, "author": "AlexWilson", "author_id": 2240, "author_profile": "https://Stackoverflow.com/users/2240", "pm_score": 3, "selected": false, "text": "fieldset {\n border: 1px solid green\n}\n\nlegend {\n padding: 0.2em 0.5em;\n border: 1px solid green;\n color: green;\n font-size: 90%;\n text-align: right;\n} <form>\n <fieldset>\n <legend>Subscription info</legend>\n <label for=\"name\">Username:</label>\n <input type=\"text\" name=\"name\" id=\"name\" />\n <br />\n <label for=\"mail\">E-mail:</label>\n <input type=\"text\" name=\"mail\" id=\"mail\" />\n <br />\n <label for=\"address\">Address:</label>\n <input type=\"text\" name=\"address\" id=\"address\" size=\"40\" />\n </fieldset>\n</form>" }, { "answer_id": 113676, "author": "naspinski", "author_id": 14777, "author_profile": "https://Stackoverflow.com/users/14777", "pm_score": 2, "selected": false, "text": "<head>\n <title></title>\n <style type=\"text/css\">\n legend {border:solid 1px;}\n </style>\n</head>\n<body>\n <fieldset>\n <legend>Test</legend>\n <br /><br />\n </fieldset>\n</body>\n" }, { "answer_id": 2936888, "author": "Jagath", "author_id": 353786, "author_profile": "https://Stackoverflow.com/users/353786", "pm_score": 4, "selected": false, "text": ".title_box {\n border: #3c5a86 1px dotted;\n}\n\n.title_box #title {\n position: relative;\n top: -0.5em;\n margin-left: 1em;\n display: inline;\n background-color: white;\n}\n\n.title_box #content {} <div class=\"title_box\" id=\"bill_to\">\n <div id=\"title\">Bill To</div>\n <div id=\"content\">\n Stuff goes here.<br> For example, a bill-to address\n </div>\n</div>" }, { "answer_id": 32266876, "author": "Ajay Gupta", "author_id": 2663073, "author_profile": "https://Stackoverflow.com/users/2663073", "pm_score": 1, "selected": false, "text": "<fieldset class=\"fldset-class\">\n <legend class=\"legend-class\">Your Personal Information</legend>\n\n <table>\n <tr>\n <td><label>Name</label></td>\n <td><input type='text' name='name'></td>\n </tr>\n <tr>\n <td><label>Address</label></td>\n <td><input type='text' name='Address'></td>\n </tr>\n <tr>\n <td><label>City</label></td>\n <td><input type='text' name='City'></td>\n </tr>\n </table>\n</fieldset>\n" }, { "answer_id": 42719047, "author": "riwex", "author_id": 6154891, "author_profile": "https://Stackoverflow.com/users/6154891", "pm_score": 1, "selected": false, "text": ".fldset-class {\n border: 1px solid #0099dd;\n margin: 3pt;\n border-top: 15px solid #0099dd\n}\n\n.legend-class {\n color: #0099dd;\n} <fieldset class=\"fldset-class\">\n <legend class=\"legend-class\">Your Personal Information</legend>\n\n <table>\n <tr>\n <td><label>Name</label></td>\n <td><input type='text' name='name'></td>\n </tr>\n <tr>\n <td><label>Address</label></td>\n <td><input type='text' name='Address'></td>\n </tr>\n <tr>\n <td><label>City</label></td>\n <td><input type='text' name='City'></td>\n </tr>\n </table>\n</fieldset>" } ]
2008/09/22
[ "https://Stackoverflow.com/questions/113640", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20165/" ]
113,641
<p>While working on a tool that allows to exchange images of several third-party applications and thus creating individual "skins" for those applications, I have stumbled across a jpg-format about which I cannot seem to find any decent informations.</p> <p>When looking at it in a hex-editor, it starts with the tag "CF10". Searching the internet has only provided a tool that is able to handle these kind of files, without any additional informations.</p> <p>Does anyone have any further informations about this type of jpg-format?</p>
[ { "answer_id": 526618, "author": "Adam Rosenfield", "author_id": 9530, "author_profile": "https://Stackoverflow.com/users/9530", "pm_score": 2, "selected": false, "text": "file(1) identify(1) -verbose" } ]
2008/09/22
[ "https://Stackoverflow.com/questions/113641", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17378/" ]
113,645
<p>I have 2 detail sections on my report (details a and details b). Fields in both sections can grow up to 10 lines.</p> <p>How do I force the Crystal Report to print both sections on one page? Currently the report on bottom page print section "details a", but section "details b" prints on next page. How do I prevent this behavior?</p>
[ { "answer_id": 526618, "author": "Adam Rosenfield", "author_id": 9530, "author_profile": "https://Stackoverflow.com/users/9530", "pm_score": 2, "selected": false, "text": "file(1) identify(1) -verbose" } ]
2008/09/22
[ "https://Stackoverflow.com/questions/113645", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17465/" ]
113,655
<p>Is there a function in python to split a word into a list of single letters? e.g:</p> <pre><code>s = &quot;Word to Split&quot; </code></pre> <p>to get</p> <pre><code>wordlist = ['W', 'o', 'r', 'd', ' ', 't', 'o', ' ', 'S', 'p', 'l', 'i', 't'] </code></pre>
[ { "answer_id": 113662, "author": "Greg Hewgill", "author_id": 893, "author_profile": "https://Stackoverflow.com/users/893", "pm_score": 9, "selected": true, "text": ">>> list(\"Word to Split\")\n['W', 'o', 'r', 'd', ' ', 't', 'o', ' ', 'S', 'p', 'l', 'i', 't']\n" }, { "answer_id": 113680, "author": "paxdiablo", "author_id": 14860, "author_profile": "https://Stackoverflow.com/users/14860", "pm_score": 5, "selected": false, "text": "list() s = \"Word to Split\"\nwordlist = list(s) # option 1, \nwordlist = [ch for ch in s] # option 2, list comprehension.\n ['W','o','r','d',' ','t','o',' ','S','p','l','i','t']\n [doSomethingWith(ch) for ch in s]\n" }, { "answer_id": 113681, "author": "Mez", "author_id": 20010, "author_profile": "https://Stackoverflow.com/users/20010", "pm_score": 3, "selected": false, "text": ">>> list('foo')\n['f', 'o', 'o']\n" }, { "answer_id": 55100297, "author": "Iris Chen", "author_id": 9644311, "author_profile": "https://Stackoverflow.com/users/9644311", "pm_score": 2, "selected": false, "text": "text = \"just trying out\"\n\nword_list = []\n\nfor i in range(len(text)):\n word_list.append(text[i])\n\nprint(word_list)\n ['j', 'u', 's', 't', ' ', 't', 'r', 'y', 'i', 'n', 'g', ' ', 'o', 'u', 't']\n" }, { "answer_id": 58569455, "author": "pratiksha", "author_id": 12251557, "author_profile": "https://Stackoverflow.com/users/12251557", "pm_score": 0, "selected": false, "text": "word_list = []\n# dict = {}\nfor i in range(len(list)):\n word_list.append(list[i])\n# word_list1 = sorted(word_list)\nfor i in range(len(word_list) - 1, 0, -1):\n for j in range(i):\n if word_list[j] > word_list[j + 1]:\n temp = word_list[j]\n word_list[j] = word_list[j + 1]\n word_list[j + 1] = temp\nprint(\"final count of arrival of each letter is : \\n\", dict(map(lambda x: (x, word_list.count(x)), word_list)))\n" }, { "answer_id": 62895686, "author": "Random 375", "author_id": 13928828, "author_profile": "https://Stackoverflow.com/users/13928828", "pm_score": 1, "selected": false, "text": "word = 'foo'\nsplitWord = []\n\nfor letter in word:\n splitWord.append(letter)\n\nprint(splitWord) #prints ['f', 'o', 'o']\n" } ]
2008/09/22
[ "https://Stackoverflow.com/questions/113655", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20211/" ]
113,664
<p>I want to install PowerShell to 600 Window XP computers, and use it as the main processing shell. For example, for replacing batch scripts, VB scripts, and some other little programs. The installation process is not a problem. Some issues I think I'm going to come across are:</p> <ol> <li><p>Changing permissions to allow PowerShell to run scripts</p> </li> <li><p>The speed of PowerShell starting</p> </li> <li><p>Using PowerShell for logon/logoff scripts with GPO</p> </li> </ol> <p>Problem 2: There is a script that is supposed to speed up PowerShell, but it seems to need to be run as administrator (which of course isn't something that normal users do). Has anyone had any experience with using PowerShell in this way?</p>
[ { "answer_id": 114677, "author": "Steven Murawski", "author_id": 1233, "author_profile": "https://Stackoverflow.com/users/1233", "pm_score": 2, "selected": false, "text": "%windir%\\system32\\WindowsPowerShell\\v1.0\\powershell.exe -nologo -noprofile\n" } ]
2008/09/22
[ "https://Stackoverflow.com/questions/113664", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11924/" ]
113,682
<p>Is there some way to hide the browser toolbar / statusbar etc in current window via javascript? I know I can do it in a popup with <code>window.open()</code> but I need to do it this way. Is it possible at all?</p>
[ { "answer_id": 117967, "author": "Zorantula", "author_id": 18108, "author_profile": "https://Stackoverflow.com/users/18108", "pm_score": 0, "selected": false, "text": "<html>\n <head>\n <title>HTA Demonstration</title>\n <hta:application innerborder=\"no\" icon=\"magnify.exe\" />\n </head>\n <body style=\"overflow: hidden; margin: 0;\">\n <iframe src=\"http://www.yahoo.com\" style=\"width: 100%; height: 100%;\"></iframe>\n </body>\n</html>\n <hta:application innerborder=\"no\" caption=\"no\" icon=\"magnify.exe\" />\n" } ]
2008/09/22
[ "https://Stackoverflow.com/questions/113682", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20272/" ]
113,702
<p>How do I add a "last" class on the last <code>&lt;li&gt;</code> within a Views-generated list?</p>
[ { "answer_id": 113740, "author": "Tim C", "author_id": 7585, "author_profile": "https://Stackoverflow.com/users/7585", "pm_score": 4, "selected": true, "text": "<html>\n<head>\n<style type=\"text/css\">\nul li:last-child\n{\nfont-weight:bold\n}\n</style>\n</head>\n<body>\n<ul>\n<li>IE</li>\n<li>Firefox</li>\n<li>Safari</li>\n</ul>\n</body>\n</html>\n" }, { "answer_id": 113756, "author": "redsquare", "author_id": 6440, "author_profile": "https://Stackoverflow.com/users/6440", "pm_score": 0, "selected": false, "text": "$('ul>li:last').addClass('last');\n" }, { "answer_id": 113783, "author": "Tim C", "author_id": 7585, "author_profile": "https://Stackoverflow.com/users/7585", "pm_score": 2, "selected": false, "text": "function highlightLastLI()\n{\n var liList, ulTag, liTag;\n var ulList = document.getElementsByTagName(\"ul\");\n for (var i = 0; i < ulList.length; i++)\n {\n ulTag = ulList[i];\n liList = ulTag.getElementsByTagName(\"li\");\n liTag = liList[liList.length - 1];\n liTag.className = \"lastchild\";\n }\n}\n" }, { "answer_id": 32328721, "author": "Ajay Gupta", "author_id": 2663073, "author_profile": "https://Stackoverflow.com/users/2663073", "pm_score": 0, "selected": false, "text": "li:last-child{\n color:red;\n font-weight:bold;\n}\n" } ]
2008/09/22
[ "https://Stackoverflow.com/questions/113702", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20273/" ]
113,712
<p>Is there a way to combine a previous translation when extracting the csv file from an application? Or any other tool that could do this job for me? </p> <p>I can’t really see how could i use locbaml if i had to translate everything from scratch every time i add a new control in my application.</p>
[ { "answer_id": 113740, "author": "Tim C", "author_id": 7585, "author_profile": "https://Stackoverflow.com/users/7585", "pm_score": 4, "selected": true, "text": "<html>\n<head>\n<style type=\"text/css\">\nul li:last-child\n{\nfont-weight:bold\n}\n</style>\n</head>\n<body>\n<ul>\n<li>IE</li>\n<li>Firefox</li>\n<li>Safari</li>\n</ul>\n</body>\n</html>\n" }, { "answer_id": 113756, "author": "redsquare", "author_id": 6440, "author_profile": "https://Stackoverflow.com/users/6440", "pm_score": 0, "selected": false, "text": "$('ul>li:last').addClass('last');\n" }, { "answer_id": 113783, "author": "Tim C", "author_id": 7585, "author_profile": "https://Stackoverflow.com/users/7585", "pm_score": 2, "selected": false, "text": "function highlightLastLI()\n{\n var liList, ulTag, liTag;\n var ulList = document.getElementsByTagName(\"ul\");\n for (var i = 0; i < ulList.length; i++)\n {\n ulTag = ulList[i];\n liList = ulTag.getElementsByTagName(\"li\");\n liTag = liList[liList.length - 1];\n liTag.className = \"lastchild\";\n }\n}\n" }, { "answer_id": 32328721, "author": "Ajay Gupta", "author_id": 2663073, "author_profile": "https://Stackoverflow.com/users/2663073", "pm_score": 0, "selected": false, "text": "li:last-child{\n color:red;\n font-weight:bold;\n}\n" } ]
2008/09/22
[ "https://Stackoverflow.com/questions/113712", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15228/" ]
113,728
<p>Basically I am trying to restart a service from a php web page.</p> <p>Here is the code:</p> <pre><code>&lt;?php exec ('/usr/bin/sudo /etc/init.d/portmap restart'); ?&gt; </code></pre> <p>But, in <code>/var/log/httpd/error_log</code>, I get </p> <blockquote> <p>unable to change to sudoers gid: Operation not permitted</p> </blockquote> <p>and in /var/log/messages, I get</p> <blockquote> <p>Sep 22 15:01:56 ri kernel: audit(1222063316.536:777): avc: denied { getattr } for pid=4851 comm="sh" name="var" dev=dm-0 ino=114241 scontext=root:system_r:httpd_sys_script_t tcontext=system_u:object_r:var_t tclass=dir<br> Sep 22 15:01:56 ri kernel: audit(1222063316.549:778): avc: denied { setrlimit } for pid=4851 comm="sudo" scontext=root:system_r:httpd_sys_script_t tcontext=root:system_r:httpd_sys_script_t tclass=process<br> Sep 22 15:01:56 ri kernel: audit(1222063316.565:779): avc: denied { read } for pid=4851 comm="sudo" name="shadow" dev=dm-0 ino=379669 scontext=root:system_r:httpd_sys_script_t tcontext=system_u:object_r:shadow_t tclass=file<br> Sep 22 15:01:56 ri kernel: audit(1222063316.568:780): avc: denied { read } for pid=4851 comm="sudo" name="shadow" dev=dm-0 ino=379669 scontext=root:system_r:httpd_sys_script_t tcontext=system_u:object_r:shadow_t tclass=file<br> Sep 22 15:01:56 ri kernel: audit(1222063316.571:781): avc: denied { setgid } for pid=4851 comm="sudo" capability=6 scontext=root:system_r:httpd_sys_script_t tcontext=root:system_r:httpd_sys_script_t tclass=capability<br> Sep 22 15:01:56 ri kernel: audit(1222063316.574:782): avc: denied { setuid } for pid=4851 comm="sudo" capability=7 scontext=root:system_r:httpd_sys_script_t tcontext=root:system_r:httpd_sys_script_t tclass=capability<br> Sep 22 15:01:56 ri kernel: audit(1222063316.577:783): avc: denied { setgid } for pid=4851 comm="sudo" capability=6 scontext=root:system_r:httpd_sys_script_t tcontext=root:system_r:httpd_sys_script_t tclass=capability</p> </blockquote> <p>In my visudo, I added those lines</p> <blockquote> <p>User_Alias WWW=apache </p> <p>WWW ALL=(ALL) NOPASSWD:ALL</p> </blockquote> <p>Can you please help me ? Am I doing something wrong ?</p> <p>Thanks for your help,</p> <p>tiBoun</p>
[ { "answer_id": 113764, "author": "Zoredache", "author_id": 20267, "author_profile": "https://Stackoverflow.com/users/20267", "pm_score": 3, "selected": false, "text": "User_Alias WWW=apache\nCmnd_Alias WEBCMDS=/etc/init.d/portmap\nWWW ALL=NOPASSWD: WEBCMDS\n" }, { "answer_id": 32269804, "author": "Soumya Kanti", "author_id": 1632556, "author_profile": "https://Stackoverflow.com/users/1632556", "pm_score": 1, "selected": false, "text": "httpd_sys_script_t # grep httpd_sys_script_t /var/log/audit/audit.log | audit2allow -M httpdallowsudo\n# semodule -i httpdallowsudo.pp\n" } ]
2008/09/22
[ "https://Stackoverflow.com/questions/113728", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
113,737
<p>How do I use PowerShell to stop and start a "Generic Service" as seen in the Microsoft "Cluster Administrator" software?</p>
[ { "answer_id": 140989, "author": "Bruno Gomes", "author_id": 8669, "author_profile": "https://Stackoverflow.com/users/8669", "pm_score": 4, "selected": true, "text": "$services = Get-WmiObject -Computer \"Computer\" -namespace 'root\\mscluster' `\nMSCluster_Resource | Where {$_.Type -eq \"Generic Service\"}\n $timeout = 15\n$services[0].TakeOffline($timeout)\n$services[0].BringOnline($timeout)\n" } ]
2008/09/22
[ "https://Stackoverflow.com/questions/113737", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11571/" ]
113,750
<p>I'm trying to implement a pop-up menu based on a click-and-hold, positioned so that a (really) slow click will still trigger the default action, and with the delay set so that a text-selection gesture won't usually trigger the menu. </p> <p>What I can't seem to do is cancel the text-selection in a way that doesn't prevent text-selection in the first place: returning false from the event handler (or calling <code>$(this).preventDefault()</code>) prevents the user from selecting at all, and the obvious <code>$().trigger('mouseup')</code> doesn't doesn't do anything with the selection at all.</p> <ul> <li>This is in the general context of a page, not particular to a textarea or other text field.</li> <li><code>e.stopPropogation()</code> doesn't cancel text-selection.</li> <li>I'm not looking to <em>prevent</em> text selections, but rather to <em>veto</em> them after some short period of time, if certain conditions are met.</li> </ul>
[ { "answer_id": 113771, "author": "Craig Francis", "author_id": 6632, "author_profile": "https://Stackoverflow.com/users/6632", "pm_score": 3, "selected": false, "text": "var input = document.getElementById('myInputField');\nif (input) {\n input.onmousedown = function(e) {\n\n if (!e) e = window.event;\n e.cancelBubble = true;\n if (e.stopPropagation) e.stopPropagation();\n\n }\n}\n" }, { "answer_id": 113778, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "$(this).focus() document.body.focus()" }, { "answer_id": 114027, "author": "Andrew Hedges", "author_id": 11577, "author_profile": "https://Stackoverflow.com/users/11577", "pm_score": 2, "selected": false, "text": "// onselectstart is IE-only\nif ('undefined' !== typeof this.onselectstart) {\n this.onselectstart = function () { return false; };\n} else {\n this.onmousedown = function () { return false; };\n this.onclick = function () { return true; };\n}\n" }, { "answer_id": 9108578, "author": "KajMagnus", "author_id": 694469, "author_profile": "https://Stackoverflow.com/users/694469", "pm_score": 0, "selected": false, "text": " .attr('unselectable', 'on')\n\n '-ms-user-select': 'none',\n '-moz-user-select': 'none',\n '-webkit-user-select': 'none',\n 'user-select': 'none'\n\n .each(function() { // for IE\n this.onselectstart = function() { return false; };\n });\n" }, { "answer_id": 15955648, "author": "nothingisnecessary", "author_id": 403959, "author_profile": "https://Stackoverflow.com/users/403959", "pm_score": 0, "selected": false, "text": "var element = document.getElementById(\"myElementId\");\nelement.onclick = function (event)\n{\n // if (event.shiftKey) // uncomment this line to only deselect text when clicking while holding shift key\n {\n if (document.selection)\n {\n document.selection.empty(); // works in IE (7/8/9/10)\n }\n else if (window.getSelection)\n {\n window.getSelection().collapseToStart(); // works in chrome/safari/opera/FF\n }\n }\n}\n" } ]
2008/09/22
[ "https://Stackoverflow.com/questions/113750", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
113,755
<p>I have an application that is installed and updated via ClickOnce. The application downloads files via FTP, and therefore needs to be added as an exception to the windows firewall. Because of the way that ClickOnce works, the path to the EXE changes with every update, so the exception needs to change also. What would be the best way to have the changes made to the firewall so that it's <em>invisible</em> to the end user?</p> <p>(The application is written in C#)</p>
[ { "answer_id": 114484, "author": "Richard C", "author_id": 6389, "author_profile": "https://Stackoverflow.com/users/6389", "pm_score": 5, "selected": true, "text": "/// \n\n/// Allows basic access to the windows firewall API.\n/// This can be used to add an exception to the windows firewall\n/// exceptions list, so that our programs can continue to run merrily\n/// even when nasty windows firewall is running.\n///\n/// Please note: It is not enforced here, but it might be a good idea\n/// to actually prompt the user before messing with their firewall settings,\n/// just as a matter of politeness.\n/// \n\n/// \n/// To allow the installers to authorize idiom products to work through\n/// the Windows Firewall.\n/// \npublic class FirewallHelper\n{\n #region Variables\n /// \n\n /// Hooray! Singleton access.\n /// \n\n private static FirewallHelper instance = null;\n\n /// \n\n /// Interface to the firewall manager COM object\n /// \n\n private INetFwMgr fwMgr = null;\n #endregion\n #region Properties\n /// \n\n /// Singleton access to the firewallhelper object.\n /// Threadsafe.\n /// \n\n public static FirewallHelper Instance\n {\n get\n {\n lock (typeof(FirewallHelper))\n {\n if (instance == null)\n instance = new FirewallHelper();\n return instance;\n }\n }\n }\n #endregion\n #region Constructivat0r\n /// \n\n /// Private Constructor. If this fails, HasFirewall will return\n /// false;\n /// \n\n private FirewallHelper()\n {\n // Get the type of HNetCfg.FwMgr, or null if an error occurred\n Type fwMgrType = Type.GetTypeFromProgID(\"HNetCfg.FwMgr\", false);\n\n // Assume failed.\n fwMgr = null;\n\n if (fwMgrType != null)\n {\n try\n {\n fwMgr = (INetFwMgr)Activator.CreateInstance(fwMgrType);\n }\n // In all other circumnstances, fwMgr is null.\n catch (ArgumentException) { }\n catch (NotSupportedException) { }\n catch (System.Reflection.TargetInvocationException) { }\n catch (MissingMethodException) { }\n catch (MethodAccessException) { }\n catch (MemberAccessException) { }\n catch (InvalidComObjectException) { }\n catch (COMException) { }\n catch (TypeLoadException) { }\n }\n }\n #endregion\n #region Helper Methods\n /// \n\n /// Gets whether or not the firewall is installed on this computer.\n /// \n\n /// \n public bool IsFirewallInstalled\n {\n get\n {\n if (fwMgr != null &&\n fwMgr.LocalPolicy != null &&\n fwMgr.LocalPolicy.CurrentProfile != null)\n return true;\n else\n return false;\n }\n }\n\n /// \n\n /// Returns whether or not the firewall is enabled.\n /// If the firewall is not installed, this returns false.\n /// \n\n public bool IsFirewallEnabled\n {\n get\n {\n if (IsFirewallInstalled && fwMgr.LocalPolicy.CurrentProfile.FirewallEnabled)\n return true;\n else\n return false;\n }\n }\n\n /// \n\n /// Returns whether or not the firewall allows Application \"Exceptions\".\n /// If the firewall is not installed, this returns false.\n /// \n\n /// \n /// Added to allow access to this metho\n /// \n public bool AppAuthorizationsAllowed\n {\n get\n {\n if (IsFirewallInstalled && !fwMgr.LocalPolicy.CurrentProfile.ExceptionsNotAllowed)\n return true;\n else\n return false;\n }\n }\n\n /// \n\n /// Adds an application to the list of authorized applications.\n /// If the application is already authorized, does nothing.\n /// \n\n /// \n /// The full path to the application executable. This cannot\n /// be blank, and cannot be a relative path.\n /// \n /// \n /// This is the name of the application, purely for display\n /// puposes in the Microsoft Security Center.\n /// \n /// \n /// When applicationFullPath is null OR\n /// When appName is null.\n /// \n /// \n /// When applicationFullPath is blank OR\n /// When appName is blank OR\n /// applicationFullPath contains invalid path characters OR\n /// applicationFullPath is not an absolute path\n /// \n /// \n /// If the firewall is not installed OR\n /// If the firewall does not allow specific application 'exceptions' OR\n /// Due to an exception in COM this method could not create the\n /// necessary COM types\n /// \n /// \n /// If no file exists at the given applicationFullPath\n /// \n public void GrantAuthorization(string applicationFullPath, string appName)\n {\n #region Parameter checking\n if (applicationFullPath == null)\n throw new ArgumentNullException(\"applicationFullPath\");\n if (appName == null)\n throw new ArgumentNullException(\"appName\");\n if (applicationFullPath.Trim().Length == 0)\n throw new ArgumentException(\"applicationFullPath must not be blank\");\n if (applicationFullPath.Trim().Length == 0)\n throw new ArgumentException(\"appName must not be blank\");\n if (applicationFullPath.IndexOfAny(Path.InvalidPathChars) >= 0)\n throw new ArgumentException(\"applicationFullPath must not contain invalid path characters\");\n if (!Path.IsPathRooted(applicationFullPath))\n throw new ArgumentException(\"applicationFullPath is not an absolute path\");\n if (!File.Exists(applicationFullPath))\n throw new FileNotFoundException(\"File does not exist\", applicationFullPath);\n // State checking\n if (!IsFirewallInstalled)\n throw new FirewallHelperException(\"Cannot grant authorization: Firewall is not installed.\");\n if (!AppAuthorizationsAllowed)\n throw new FirewallHelperException(\"Application exemptions are not allowed.\");\n #endregion\n\n if (!HasAuthorization(applicationFullPath))\n {\n // Get the type of HNetCfg.FwMgr, or null if an error occurred\n Type authAppType = Type.GetTypeFromProgID(\"HNetCfg.FwAuthorizedApplication\", false);\n\n // Assume failed.\n INetFwAuthorizedApplication appInfo = null;\n\n if (authAppType != null)\n {\n try\n {\n appInfo = (INetFwAuthorizedApplication)Activator.CreateInstance(authAppType);\n }\n // In all other circumnstances, appInfo is null.\n catch (ArgumentException) { }\n catch (NotSupportedException) { }\n catch (System.Reflection.TargetInvocationException) { }\n catch (MissingMethodException) { }\n catch (MethodAccessException) { }\n catch (MemberAccessException) { }\n catch (InvalidComObjectException) { }\n catch (COMException) { }\n catch (TypeLoadException) { }\n }\n\n if (appInfo == null)\n throw new FirewallHelperException(\"Could not grant authorization: can't create INetFwAuthorizedApplication instance.\");\n\n appInfo.Name = appName;\n appInfo.ProcessImageFileName = applicationFullPath;\n // ...\n // Use defaults for other properties of the AuthorizedApplication COM object\n\n // Authorize this application\n fwMgr.LocalPolicy.CurrentProfile.AuthorizedApplications.Add(appInfo);\n }\n // otherwise it already has authorization so do nothing\n }\n /// \n\n /// Removes an application to the list of authorized applications.\n /// Note that the specified application must exist or a FileNotFound\n /// exception will be thrown.\n /// If the specified application exists but does not current have\n /// authorization, this method will do nothing.\n /// \n\n /// \n /// The full path to the application executable. This cannot\n /// be blank, and cannot be a relative path.\n /// \n /// \n /// When applicationFullPath is null\n /// \n /// \n /// When applicationFullPath is blank OR\n /// applicationFullPath contains invalid path characters OR\n /// applicationFullPath is not an absolute path\n /// \n /// \n /// If the firewall is not installed.\n /// \n /// \n /// If the specified application does not exist.\n /// \n public void RemoveAuthorization(string applicationFullPath)\n {\n\n #region Parameter checking\n if (applicationFullPath == null)\n throw new ArgumentNullException(\"applicationFullPath\");\n if (applicationFullPath.Trim().Length == 0)\n throw new ArgumentException(\"applicationFullPath must not be blank\");\n if (applicationFullPath.IndexOfAny(Path.InvalidPathChars) >= 0)\n throw new ArgumentException(\"applicationFullPath must not contain invalid path characters\");\n if (!Path.IsPathRooted(applicationFullPath))\n throw new ArgumentException(\"applicationFullPath is not an absolute path\");\n if (!File.Exists(applicationFullPath))\n throw new FileNotFoundException(\"File does not exist\", applicationFullPath);\n // State checking\n if (!IsFirewallInstalled)\n throw new FirewallHelperException(\"Cannot remove authorization: Firewall is not installed.\");\n #endregion\n\n if (HasAuthorization(applicationFullPath))\n {\n // Remove Authorization for this application\n fwMgr.LocalPolicy.CurrentProfile.AuthorizedApplications.Remove(applicationFullPath);\n }\n // otherwise it does not have authorization so do nothing\n }\n /// \n\n /// Returns whether an application is in the list of authorized applications.\n /// Note if the file does not exist, this throws a FileNotFound exception.\n /// \n\n /// \n /// The full path to the application executable. This cannot\n /// be blank, and cannot be a relative path.\n /// \n /// \n /// The full path to the application executable. This cannot\n /// be blank, and cannot be a relative path.\n /// \n /// \n /// When applicationFullPath is null\n /// \n /// \n /// When applicationFullPath is blank OR\n /// applicationFullPath contains invalid path characters OR\n /// applicationFullPath is not an absolute path\n /// \n /// \n /// If the firewall is not installed.\n /// \n /// \n /// If the specified application does not exist.\n /// \n public bool HasAuthorization(string applicationFullPath)\n {\n #region Parameter checking\n if (applicationFullPath == null)\n throw new ArgumentNullException(\"applicationFullPath\");\n if (applicationFullPath.Trim().Length == 0)\n throw new ArgumentException(\"applicationFullPath must not be blank\");\n if (applicationFullPath.IndexOfAny(Path.InvalidPathChars) >= 0)\n throw new ArgumentException(\"applicationFullPath must not contain invalid path characters\");\n if (!Path.IsPathRooted(applicationFullPath))\n throw new ArgumentException(\"applicationFullPath is not an absolute path\");\n if (!File.Exists(applicationFullPath))\n throw new FileNotFoundException(\"File does not exist.\", applicationFullPath);\n // State checking\n if (!IsFirewallInstalled)\n throw new FirewallHelperException(\"Cannot remove authorization: Firewall is not installed.\");\n\n #endregion\n\n // Locate Authorization for this application\n foreach (string appName in GetAuthorizedAppPaths())\n {\n // Paths on windows file systems are not case sensitive.\n if (appName.ToLower() == applicationFullPath.ToLower())\n return true;\n }\n\n // Failed to locate the given app.\n return false;\n\n }\n\n /// \n\n /// Retrieves a collection of paths to applications that are authorized.\n /// \n\n /// \n /// \n /// If the Firewall is not installed.\n /// \n public ICollection GetAuthorizedAppPaths()\n {\n // State checking\n if (!IsFirewallInstalled)\n throw new FirewallHelperException(\"Cannot remove authorization: Firewall is not installed.\");\n\n ArrayList list = new ArrayList();\n // Collect the paths of all authorized applications\n foreach (INetFwAuthorizedApplication app in fwMgr.LocalPolicy.CurrentProfile.AuthorizedApplications)\n list.Add(app.ProcessImageFileName);\n\n return list;\n }\n #endregion\n}\n\n/// \n\n/// Describes a FirewallHelperException.\n/// \n\n/// \n///\n/// \npublic class FirewallHelperException : System.Exception\n{\n /// \n\n /// Construct a new FirewallHelperException\n /// \n\n /// \n public FirewallHelperException(string message)\n : base(message)\n { }\n}\n" }, { "answer_id": 44364591, "author": "Chamath Viduranga", "author_id": 4710997, "author_profile": "https://Stackoverflow.com/users/4710997", "pm_score": 3, "selected": false, "text": "using System.Collections;\nusing System.ComponentModel;\nusing System.Configuration.Install;\nusing System.IO;\nusing System.Diagnostics;\n\nnamespace YourNamespace\n{\n [RunInstaller(true)]\n public class AddFirewallExceptionInstaller : Installer\n {\n protected override void OnAfterInstall(IDictionary savedState)\n {\n base.OnAfterInstall(savedState);\n\n var path = Path.GetDirectoryName(Context.Parameters[\"assemblypath\"]);\n OpenFirewallForProgram(Path.Combine(path, \"YourExe.exe\"),\n \"Your program name for display\");\n }\n\n private static void OpenFirewallForProgram(string exeFileName, string displayName)\n {\n var proc = Process.Start(\n new ProcessStartInfo\n {\n FileName = \"netsh\",\n Arguments =\n string.Format(\n \"firewall add allowedprogram program=\\\"{0}\\\" name=\\\"{1}\\\" profile=\\\"ALL\\\"\",\n exeFileName, displayName),\n WindowStyle = ProcessWindowStyle.Hidden\n });\n proc.WaitForExit();\n }\n }\n}\n" } ]
2008/09/22
[ "https://Stackoverflow.com/questions/113755", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6389/" ]
113,776
<p>I've got a java servlet which is hitting this bug when down-scaling images...</p> <p><a href="http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=5101502" rel="nofollow noreferrer">http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=5101502</a></p> <p>I'm trying to work out the best way to work around it and would appreciate any ideas from the community.</p> <p>Thanks, Steve</p>
[ { "answer_id": 123830, "author": "the.duckman", "author_id": 21368, "author_profile": "https://Stackoverflow.com/users/21368", "pm_score": 2, "selected": false, "text": "Runtime.exec(.)" } ]
2008/09/22
[ "https://Stackoverflow.com/questions/113776", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4974/" ]
113,780
<p>I don’t think I’ve grokked currying yet. I understand what it does, and how to do it. I just can’t think of a situation I would use it.</p> <p>Where are you using currying in JavaScript (or where are the main libraries using it)? DOM manipulation or general application development examples welcome.</p> <p><a href="https://stackoverflow.com/questions/113780/javascript-curry-what-are-the-practical-applications#113799">One of the answers</a> mentions animation. Functions like <code>slideUp</code>, <code>fadeIn</code> take an element as an arguments and are normally a curried function returning the high order function with the default “animation function” built-in. Why is that better than just applying the higher-up function with some defaults?</p> <p>Are there any drawbacks to using it?</p> <p>As requested here are some good resources on JavaScript currying:</p> <ul> <li><a href="http://www.dustindiaz.com/javascript-curry/" rel="noreferrer">http://www.dustindiaz.com/javascript-curry/</a></li> <li>Crockford, Douglas (2008) <em>JavaScript: The Good Parts</em></li> <li><a href="http://www.crockford.com/javascript/www_svendtofte_com/code/curried_javascript/index.html" rel="noreferrer">http://www.svendtofte.com/code/curried_javascript/</a> (Takes a detour into ML so skip the whole section from “A crash course in ML” and start again at “How to write curried JavaScript”)</li> <li><a href="http://web.archive.org/web/20111217011630/http://blog.morrisjohns.com:80/javascript_closures_for_dummies" rel="noreferrer">http://web.archive.org/web/20111217011630/http://blog.morrisjohns.com:80/javascript_closures_for_dummies</a></li> <li><a href="https://stackoverflow.com/questions/111102/how-does-a-javascript-closure-work">How do JavaScript closures work?</a></li> <li><strong><a href="http://ejohn.org/blog/partial-functions-in-javascript/" rel="noreferrer">http://ejohn.org/blog/partial-functions-in-javascript</a> (Mr. Resig on the money as per usual)</strong></li> <li><a href="http://benalman.com/news/2010/09/partial-application-in-javascript/" rel="noreferrer">http://benalman.com/news/2010/09/partial-application-in-javascript/</a></li> </ul> <p>I’ll add more as they crop up in the comments.</p> <hr> <p>So, according to the answers, currying and partial application in general are convenience techniques.</p> <p>If you are frequently “refining” a high-level function by calling it with same configuration, you can curry (or use Resig’s partial) the higher-level function to create simple, concise helper methods.</p>
[ { "answer_id": 113847, "author": "Marijn", "author_id": 12038, "author_profile": "https://Stackoverflow.com/users/12038", "pm_score": 2, "selected": false, "text": "partial(alert, \"FOO!\") function(){alert(\"FOO!\");} partial(Math.max, 0) function(x){return Math.max(0, x);}" }, { "answer_id": 113857, "author": "Armin Ronacher", "author_id": 19990, "author_profile": "https://Stackoverflow.com/users/19990", "pm_score": 3, "selected": false, "text": "functools.partial function partial(fn) {\n return partialWithScope.apply(this,\n Array.prototype.concat.apply([fn, this],\n Array.prototype.slice.call(arguments, 1)));\n}\n\nfunction partialWithScope(fn, scope) {\n var args = Array.prototype.slice.call(arguments, 2);\n return function() {\n return fn.apply(scope, Array.prototype.concat.apply(args, arguments));\n };\n}\n this var callback = partialWithScope(Object.function, obj);\n this obj" }, { "answer_id": 114030, "author": "Hank Gay", "author_id": 4203, "author_profile": "https://Stackoverflow.com/users/4203", "pm_score": 6, "selected": true, "text": "String.prototype.csv = String.prototype.split.partial(/,\\s*/);\nvar results = \"John, Resig, Boston\".csv();\nalert( (results[1] == \"Resig\") + \" The text values were split properly\" );\n" }, { "answer_id": 3322715, "author": "William Pietri", "author_id": 123248, "author_profile": "https://Stackoverflow.com/users/123248", "pm_score": 1, "selected": false, "text": "$('#foo').focus(trackActivity);\n$('#foo').blur(trackActivity);\n$('#bar').focus(trackActivity);\n$('#bar').blur(trackActivity);\n" }, { "answer_id": 6861858, "author": "Prisoner ZERO", "author_id": 312317, "author_profile": "https://Stackoverflow.com/users/312317", "pm_score": 7, "selected": false, "text": "function converter(toUnit, factor, offset, input) {\n offset = offset || 0;\n return [((offset + input) * factor).toFixed(2), toUnit].join(\" \");\n}\n\nvar milesToKm = converter.curry('km', 1.60936, undefined);\nvar poundsToKg = converter.curry('kg', 0.45460, undefined);\nvar farenheitToCelsius = converter.curry('degrees C', 0.5556, -32);\n\nmilesToKm(10); // returns \"16.09 km\"\npoundsToKg(2.5); // returns \"1.14 kg\"\nfarenheitToCelsius(98); // returns \"36.67 degrees C\"\n curry Function apply Function.prototype.curry = function() {\n if (arguments.length < 1) {\n return this; //nothing to curry with - return function\n }\n var __method = this;\n var args = toArray(arguments);\n return function() {\n return __method.apply(this, args.concat([].slice.apply(null, arguments)));\n }\n}\n" }, { "answer_id": 31560758, "author": "Shishir Arora", "author_id": 3221274, "author_profile": "https://Stackoverflow.com/users/3221274", "pm_score": 2, "selected": false, "text": "var fn = function(a,b,c){ \nreturn a+b+c+(this.greet || ‘'); \n}\n var partialFnA = _.partial(fn, 1,3);\n var curriedFn = _.curry(fn);\n var boundFn = _.bind(fn,object,1,3 );//object= {greet: ’!'}\n curriedFn(1)(3)(5); // gives 9 \nor \ncurriedFn(1,3)(5); // gives 9 \nor \ncurriedFn(1)(_,3)(2); //gives 9\n\n\npartialFnA(5); //gives 9\n\nboundFn(5); //gives 9!\n" }, { "answer_id": 32116810, "author": "cstuncsik", "author_id": 3579966, "author_profile": "https://Stackoverflow.com/users/3579966", "pm_score": 0, "selected": false, "text": "function clampAngle(min, max, angle) {\n var result, delta;\n delta = max - min;\n result = (angle - min) % delta;\n if (result < 0) {\n result += delta;\n }\n return min + result;\n};\n\nvar clamp0To360 = clampAngle.bind(null, 0, 360);\n\nconsole.log(clamp0To360(405)) // 45" }, { "answer_id": 32379766, "author": "Byron Katz", "author_id": 713809, "author_profile": "https://Stackoverflow.com/users/713809", "pm_score": 3, "selected": false, "text": "var converter = function(ratio, symbol, input) {\n return (input*ratio).toFixed(2) + \" \" + symbol;\n}\n\nvar kilosToPoundsRatio = 2.2;\nvar litersToUKPintsRatio = 1.75;\nvar litersToUSPintsRatio = 1.98;\nvar milesToKilometersRatio = 1.62;\n\nconverter(kilosToPoundsRatio, \"lbs\", 4); //8.80 lbs\nconverter(litersToUKPintsRatio, \"imperial pints\", 2.4); //4.20 imperial pints\nconverter(litersToUSPintsRatio, \"US pints\", 2.4); //4.75 US pints\nconverter(milesToKilometersRatio, \"km\", 34); //55.08 km\n" }, { "answer_id": 36505248, "author": "JL Peyret", "author_id": 1394353, "author_profile": "https://Stackoverflow.com/users/1394353", "pm_score": 0, "selected": false, "text": "function ajax_batch(e){\n var url = $(e.target).data(\"url\");\n\n //induce error\n url = \"x\" + url;\n\n var promise_details = $.ajax(\n url,\n {\n headers: { Accept : \"application/json\" },\n // accepts : \"application/json\",\n beforeSend: function (request) {\n if (!this.crossDomain) {\n request.setRequestHeader(\"X-CSRFToken\", csrf_token);\n }\n },\n dataType : \"json\",\n type : \"POST\"}\n );\n promise_details.then(notify_batch_success, fail_status_specific_to_batch);\n}\n function fail_status_specific_to_batch(d){\n console.log(\"bad batch run, dude\");\n console.log(\"response.status:\" + d.status);\n}\n bad batch run, dude\nutility.js (line 109)\nresponse.status:404 ... rest is as before...\n var target = $(e.target).text();\n var context = {\"user_msg\": \"bad batch run, dude. you were calling :\" + target};\n var contexted_fail_notification = curry(generic_fail, context); \n\n promise_details.then(notify_batch_success, contexted_fail_notification);\n}\n\nfunction generic_fail(context, d){\n console.log(context);\n console.log(\"response.status:\" + d.status);\n}\n\nfunction curry(fn) {\n var slice = Array.prototype.slice,\n stored_args = slice.call(arguments, 1);\n return function () {\n var new_args = slice.call(arguments),\n args = stored_args.concat(new_args);\n return fn.apply(null, args);\n };\n}\n Object { user_msg=\"bad batch run, dude. you were calling :Run ACL now\"}\nutility.js (line 117)\nresponse.status:404\nutility.js (line 118)" }, { "answer_id": 68580704, "author": "Giorgi Moniava", "author_id": 3963067, "author_profile": "https://Stackoverflow.com/users/3963067", "pm_score": 2, "selected": false, "text": "filter let x = [1,2,3,4,5,6,7,11,12,14,15];\nlet results = x.filter(callback);\n let callback = x => x % 2 === 0;\n callback callback filter callback let x = [1,2,3,4,5,6,7,11,12,14,15];\nlet callback = (threshold) => (x) => (x % 2==0 && x > threshold);\n\nlet results1 = x.filter(callback(5)); // Even numbers higher than 5\nlet results2 = x.filter(callback(10)); // Even numbers higher than 10\n\nconsole.log(results1,results2);" } ]
2008/09/22
[ "https://Stackoverflow.com/questions/113780", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9474/" ]
113,791
<p>Currently i am developing sites using DNN framework. Currently my development and staging environment is same. Client is vewing same site which I am using for development.</p> <p>I have started using tortoise svn (subversion) for maintaining versions and backup. I am using file based svn repository for it.</p> <p>The issue is svn creates .svn folder (hidden) in every folder. This folder and files inside it shows in portal system while file selection and at many different locations like FCKEditor File Browser, Icon selection for module / page, skins selection.</p> <p>I would like to hide this folder for entire application and it should not show up anywhere.</p>
[ { "answer_id": 113807, "author": "1800 INFORMATION", "author_id": 3146, "author_profile": "https://Stackoverflow.com/users/3146", "pm_score": 1, "selected": false, "text": "export" } ]
2008/09/22
[ "https://Stackoverflow.com/questions/113791", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20031/" ]
113,803
<p>If I have a table in MySQL which represents a base class, and I have a bunch of tables which represent the fields in the derived classes, each of which refers back to the base table with a foreign key, is there any way to get MySQL to enforce the one-to-one relationship between the derived table and the base table, or does this have to be done in code?</p> <p>Using the following quick 'n' dirty schema as an example, is there any way to get MySQL to ensure that rows in both product_cd and product_dvd cannot share the same product_id? Is there a better way to design the schema to allow the database to enforce this relationship, or is it simply not possible?</p> <pre><code>CREATE TABLE IF NOT EXISTS `product` ( `product_id` int(10) unsigned NOT NULL auto_increment, `product_name` varchar(50) NOT NULL, `description` text NOT NULL, PRIMARY KEY (`product_id`) ) ENGINE = InnoDB; CREATE TABLE `product_cd` ( `product_cd_id` INT UNSIGNED NOT NULL AUTO_INCREMENT , `product_id` INT UNSIGNED NOT NULL , `artist_name` VARCHAR( 50 ) NOT NULL , PRIMARY KEY ( `product_cd_id` ) , INDEX ( `product_id` ) ) ENGINE = InnoDB; ALTER TABLE `product_cd` ADD FOREIGN KEY ( `product_id` ) REFERENCES `product` (`product_id`) ON DELETE RESTRICT ON UPDATE RESTRICT ; CREATE TABLE `product_dvd` ( `product_dvd_id` INT UNSIGNED NOT NULL AUTO_INCREMENT , `product_id` INT UNSIGNED NOT NULL , `director` VARCHAR( 50 ) NOT NULL , PRIMARY KEY ( `product_dvd_id` ) , INDEX ( `product_id` ) ) ENGINE = InnoDB; ALTER TABLE `product_dvd` ADD FOREIGN KEY ( `product_id` ) REFERENCES `product` (`product_id`) ON DELETE RESTRICT ON UPDATE RESTRICT ; </code></pre> <p>@<a href="https://stackoverflow.com/questions/113803/mysql-foreign-keys-how-to-enforce-one-to-one-across-tables#113811">Skliwz</a>, can you please provide more detail about how triggers can be used to enforce this constraint with the schema provided?</p> <p>@<a href="https://stackoverflow.com/questions/113803/mysql-foreign-keys-how-to-enforce-one-to-one-across-tables#113858">boes</a>, that sounds great. How does it work in situations where you have a child of a child? For example, if we added product_movie and made product_dvd a child of product_movie? Would it be a maintainability nightmare to make the check constraint for product_dvd have to factor in all child types as well?</p>
[ { "answer_id": 113858, "author": "boes", "author_id": 17746, "author_profile": "https://Stackoverflow.com/users/17746", "pm_score": 3, "selected": true, "text": "CREATE TABLE IF NOT EXISTS `product` (\n`product_id` int(10) unsigned NOT NULL auto_increment,\n'product_type' int not null,\n`product_name` varchar(50) NOT NULL,\n`description` text NOT NULL,\nPRIMARY KEY (`product_id`, 'product_type')\n) ENGINE = InnoDB;\n\nCREATE TABLE `product_cd` (\n`product_id` INT UNSIGNED NOT NULL ,\n'product_type' int not null default(1) check ('product_type' = 1)\n`artist_name` VARCHAR( 50 ) NOT NULL ,\nPRIMARY KEY ( `product_id`, 'product_type' ) ,\n) ENGINE = InnoDB;\n\nALTER TABLE `product_cd` ADD FOREIGN KEY ( `product_id`, 'product_type' ) \nREFERENCES `product` (`product_id`, 'product_type') \nON DELETE RESTRICT ON UPDATE RESTRICT ;\n" }, { "answer_id": 6793850, "author": "Hanynowsky", "author_id": 754756, "author_profile": "https://Stackoverflow.com/users/754756", "pm_score": 2, "selected": false, "text": "`1 error(s) saving changes to table testdb`.table4: INSERT INTO testdb.table4 (idtable4, label, table3_idtable3) VALUES (0, 'soso', 0) 1062: Duplicate entry '0' for key 'table3_idtable3_UNIQUE' Rollback complete\n" } ]
2008/09/22
[ "https://Stackoverflow.com/questions/113803", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15004/" ]
113,818
<p>I am developing a C++ class library containing domain model classes, and I would like to add support for instantiating these classes from various persistence mechanisms, i.e. databases and file. The user of the class library should be given an interface(?) against which to program a class that can transfer the data from/to the persistence mechanism.</p> <p>I know of the Data Access Object pattern which seems to work for Java, but I'm not exactly sure how to apply it to C++. Are there other solutions?</p>
[ { "answer_id": 113879, "author": "ConcernedOfTunbridgeWells", "author_id": 15401, "author_profile": "https://Stackoverflow.com/users/15401", "pm_score": 2, "selected": true, "text": "__getattr()__ __setattr()__ ->" } ]
2008/09/22
[ "https://Stackoverflow.com/questions/113818", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19863/" ]
113,824
<p>Is it possible to automount a TrueCrypt volume when logging in to Ubuntu 8.04? It's already storing the wireless network keys using the Seahorse password manager. Could TrueCrypt be made to fetch its volume password from the same keyring? Currently this would seem like the most convenient way to store my source code on the USB stick I carry around to boot from.</p>
[ { "answer_id": 10216328, "author": "swizzly", "author_id": 1317491, "author_profile": "https://Stackoverflow.com/users/1317491", "pm_score": 3, "selected": true, "text": "/etc/gdm/Init if !(echo `mount` | grep -q \"/home/your_username type\")\nthen\n truecrypt /dev/sdaxxx /home/your_username\nfi\n" } ]
2008/09/22
[ "https://Stackoverflow.com/questions/113824", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16509/" ]
113,829
<p>How do I get timestamp from e.g. <code>22-09-2008</code>?</p>
[ { "answer_id": 113836, "author": "Till", "author_id": 2859, "author_profile": "https://Stackoverflow.com/users/2859", "pm_score": 5, "selected": false, "text": "list($day, $month, $year) = explode('-', '22-09-2008');\necho mktime(0, 0, 0, $month, $day, $year);\n" }, { "answer_id": 113841, "author": "Owen", "author_id": 4853, "author_profile": "https://Stackoverflow.com/users/4853", "pm_score": 9, "selected": false, "text": "$d = DateTime::createFromFormat('d-m-Y H:i:s', '22-09-2008 00:00:00');\nif ($d === false) {\n die(\"Incorrect date string\");\n} else {\n echo $d->getTimestamp();\n}\n $d = DateTime::createFromFormat(\n 'd-m-Y H:i:s',\n '22-09-2008 00:00:00',\n new DateTimeZone('EST')\n);\n\nif ($d === false) {\n die(\"Incorrect date string\");\n} else {\n echo $d->getTimestamp();\n}\n $d = DateTime::createFromFormat(\n 'd-m-Y H:i:s',\n '22-09-2008 00:00:00',\n new DateTimeZone('UTC')\n);\n\nif ($d === false) {\n die(\"Incorrect date string\");\n} else {\n echo $d->getTimestamp();\n}\n" }, { "answer_id": 113871, "author": "Armin Ronacher", "author_id": 19990, "author_profile": "https://Stackoverflow.com/users/19990", "pm_score": 8, "selected": false, "text": "$a = strptime('22-09-2008', '%d-%m-%Y');\n$timestamp = mktime(0, 0, 0, $a['tm_mon']+1, $a['tm_mday'], $a['tm_year']+1900);\n" }, { "answer_id": 115864, "author": "daremon", "author_id": 6346, "author_profile": "https://Stackoverflow.com/users/6346", "pm_score": 7, "selected": false, "text": "strtotime() 22-09-2008 08-09-2008 2008-09-50 DD-MM-YYYY" }, { "answer_id": 2020557, "author": "blavla", "author_id": 138844, "author_profile": "https://Stackoverflow.com/users/138844", "pm_score": 3, "selected": false, "text": "strptime strtotime strptime tm_year tm_month $a = strptime('22-09-2008', '%d-%m-%Y');\n$timestamp = mktime(0, 0, 0, $a['tm_mon']+1, $a['tm_mday'], $a['tm_year']+1900)\n" }, { "answer_id": 3032302, "author": "Julijan Anđelić", "author_id": 365679, "author_profile": "https://Stackoverflow.com/users/365679", "pm_score": 2, "selected": false, "text": "function dateToTimestamp($date, $format, $timezone='Europe/Belgrade')\n{\n //returns an array containing day start and day end timestamps\n $old_timezone=date_timezone_get();\n date_default_timezone_set($timezone);\n $date=strptime($date,$format);\n $day_start=mktime(0,0,0,++$date['tm_mon'],++$date['tm_mday'],($date['tm_year']+1900));\n $day_end=$day_start+(60*60*24);\n date_default_timezone_set($old_timezone);\n return array('day_start'=>$day_start, 'day_end'=>$day_end);\n}\n\n$timestamps=dateToTimestamp('15.02.1991.', '%d.%m.%Y.', 'Europe/London');\n$day_start=$timestamps['day_start'];\n" }, { "answer_id": 3669713, "author": "Victor Bojica", "author_id": 442612, "author_profile": "https://Stackoverflow.com/users/442612", "pm_score": 4, "selected": false, "text": "split mtime $date=\"30/07/2010 13:24\"; //Date example\nlist($day, $month, $year, $hour, $minute) = split('[/ :]', $date); \n\n//The variables should be arranged according to your date format and so the separators\n$timestamp = mktime($hour, $minute, 0, $month, $day, $year);\necho date(\"r\", $timestamp);\n" }, { "answer_id": 6028533, "author": "Gordon", "author_id": 208809, "author_profile": "https://Stackoverflow.com/users/208809", "pm_score": 7, "selected": false, "text": "DateTime $dateTime = new DateTime('2008-09-22'); \necho $dateTime->format('U'); \n\n// or \n\n$date = new DateTime('2008-09-22');\necho $date->getTimestamp();\n $date = date_create('2008-09-22');\necho date_format($date, 'U');\n\n// or\n\n$date = date_create('2008-09-22');\necho date_timestamp_get($date);\n $date = DateTime::createFromFormat('!d-m-Y', '22-09-2008');\necho $dateTime->format('U'); \n\n// or\n\n$date = date_parse_from_format('!d-m-Y', '22-09-2008');\necho date_format($date, 'U');\n ! IntlDateFormatter $formatter = new IntlDateFormatter(\n 'en_US',\n IntlDateFormatter::FULL,\n IntlDateFormatter::FULL,\n 'GMT',\n IntlDateFormatter::GREGORIAN,\n 'dd-MM-yyyy'\n);\necho $formatter->parse('22-09-2008');\n" }, { "answer_id": 9239828, "author": "Phil Jackson", "author_id": 201469, "author_profile": "https://Stackoverflow.com/users/201469", "pm_score": 2, "selected": false, "text": "function date_to_stamp( $date, $slash_time = true, $timezone = 'Europe/London', $expression = \"#^\\d{2}([^\\d]*)\\d{2}([^\\d]*)\\d{4}$#is\" ) {\n $return = false;\n $_timezone = date_default_timezone_get();\n date_default_timezone_set( $timezone );\n if( preg_match( $expression, $date, $matches ) )\n $return = date( \"Y-m-d \" . ( $slash_time ? '00:00:00' : \"h:i:s\" ), strtotime( str_replace( array($matches[1], $matches[2]), '-', $date ) . ' ' . date(\"h:i:s\") ) );\n date_default_timezone_set( $_timezone );\n return $return;\n}\n\n// expression may need changing in relation to timezone\necho date_to_stamp('19/03/1986', false) . '<br />';\necho date_to_stamp('19**03**1986', false) . '<br />';\necho date_to_stamp('19.03.1986') . '<br />';\necho date_to_stamp('19.03.1986', false, 'Asia/Aden') . '<br />';\necho date('Y-m-d h:i:s') . '<br />';\n\n//1986-03-19 02:37:30\n//1986-03-19 02:37:30\n//1986-03-19 00:00:00\n//1986-03-19 05:37:30\n//2012-02-12 02:37:30\n" }, { "answer_id": 10978523, "author": "Victor", "author_id": 230983, "author_profile": "https://Stackoverflow.com/users/230983", "pm_score": 3, "selected": false, "text": "strptime() strtotime() date_parse_from_format() $date = date_parse_from_format('d-m-Y', '22-09-2008');\n$timestamp = mktime(0, 0, 0, $date['month'], $date['day'], $date['year']);\n" }, { "answer_id": 13852410, "author": "insign", "author_id": 530197, "author_profile": "https://Stackoverflow.com/users/530197", "pm_score": 2, "selected": false, "text": "<?php echo date('U') ?>\n <?php $timestamp_for_mysql = date('c') ?>\n" }, { "answer_id": 13852501, "author": "Ja͢ck", "author_id": 1338292, "author_profile": "https://Stackoverflow.com/users/1338292", "pm_score": 3, "selected": false, "text": "DateTime::createFromFormat() $d = DateTime::createFromFormat('d-m-Y', '22-09-2008');\nif ($d === false) {\n die(\"Woah, that date doesn't look right!\");\n}\necho $d->format('Y-m-d'), PHP_EOL;\n// prints 2008-09-22\n 03-04-2008" }, { "answer_id": 19320524, "author": "Prof. Falken", "author_id": 193892, "author_profile": "https://Stackoverflow.com/users/193892", "pm_score": 6, "selected": false, "text": "$d = DateTime::createFromFormat('d-m-Y H:i:s', '22-09-2008 00:00:00');\nif ($d === false) {\n die(\"Incorrect date string\");\n} else {\n echo $d->getTimestamp();\n}\n $d = DateTime::createFromFormat(\n 'd-m-Y H:i:s',\n '22-09-2008 00:00:00',\n new DateTimeZone('EST')\n);\n\nif ($d === false) {\n die(\"Incorrect date string\");\n} else {\n echo $d->getTimestamp();\n}\n $d = DateTime::createFromFormat(\n 'd-m-Y H:i:s',\n '22-09-2008 00:00:00',\n new DateTimeZone('UTC')\n);\n\nif ($d === false) {\n die(\"Incorrect date string\");\n} else {\n echo $d->getTimestamp();\n}\n" }, { "answer_id": 19991236, "author": "Michael Chambers", "author_id": 2221694, "author_profile": "https://Stackoverflow.com/users/2221694", "pm_score": 2, "selected": false, "text": "<?php echo date('M j Y g:i A', strtotime('2013-11-15 13:01:02')); ?>\n" }, { "answer_id": 25053154, "author": "Praveen Srinivasan", "author_id": 3432786, "author_profile": "https://Stackoverflow.com/users/3432786", "pm_score": 2, "selected": false, "text": "$time = '22-09-2008';\necho strtotime($time);\n" }, { "answer_id": 29480669, "author": "klit67", "author_id": 4756371, "author_profile": "https://Stackoverflow.com/users/4756371", "pm_score": 4, "selected": false, "text": "<?php\n// set default timezone\ndate_default_timezone_set('America/Los_Angeles');\n\n//define date and time\n$date = date(\"d M Y H:i:s\");\n\n// output\necho strtotime($date);\n?> \n" }, { "answer_id": 35671836, "author": "ObiHill", "author_id": 310139, "author_profile": "https://Stackoverflow.com/users/310139", "pm_score": -1, "selected": false, "text": "2016-02-14T12:24:48.321Z function UTCToTimestamp($utc_datetime_str)\n{\n preg_match_all('/(.+?)T(.+?)\\.(.*?)Z/i', $utc_datetime_str, $matches_arr);\n $datetime_str = $matches_arr[1][0].\" \".$matches_arr[2][0];\n\n return strtotime($datetime_str);\n}\n\n$my_utc_datetime_str = '2016-02-14T12:24:48.321Z';\n$my_timestamp_str = UTCToTimestamp($my_utc_datetime_str);\n" }, { "answer_id": 37322349, "author": "Akam", "author_id": 3599237, "author_profile": "https://Stackoverflow.com/users/3599237", "pm_score": 0, "selected": false, "text": "timestamp strtotime function getthistime($type, $modify = null) {\n $now = new DateTime(null, new DateTimeZone('Asia/Baghdad'));\n if($modify) {\n $now->modify($modify);\n }\n if(!isset($type) || $type == 'datetime') {\n return $now->format('Y-m-d H:i:s');\n }\n if($type == 'time') {\n return $now->format('H:i:s');\n }\n if($type == 'timestamp') {\n return $now->getTimestamp();\n }\n}\nfunction timestampfromdate($date) {\n return DateTime::createFromFormat('Y-m-d H:i:s', $date, new DateTimeZone('Asia/Baghdad'))->getTimestamp();\n}\n\necho getthistime('timestamp').\"--\".\n timestampfromdate(getthistime('datetime')).\"--\".\n strtotime(getthistime('datetime'));\n\n//getthistime('timestamp') == timestampfromdate(getthistime('datetime')) (true)\n//getthistime('timestamp') == strtotime(getthistime('datetime')) (false)\n" }, { "answer_id": 48703270, "author": "Gurpreet Singh", "author_id": 8920307, "author_profile": "https://Stackoverflow.com/users/8920307", "pm_score": 3, "selected": false, "text": "strtotime() echo strtotime('2019/06/06');\n" }, { "answer_id": 71606568, "author": "Raju Ahmed", "author_id": 12174834, "author_profile": "https://Stackoverflow.com/users/12174834", "pm_score": 0, "selected": false, "text": "$date = date_parse_from_format('%Y-%m-%d', \"2022-11-15\"); //here you can give your desired date in desired format. \n //just need to keep in mind that date and format matches.\n\n$timestamp = mktime(0, 0, 0, $date['month'], $date['day'], $date['year'] + 2000); //this will return the timestamp\n\n$finalDate= date('Y-m-d H:i:s', $timestamp); //now you can convert your timestamp to desired dateTime format.\n" }, { "answer_id": 73337131, "author": "J.C.", "author_id": 7282094, "author_profile": "https://Stackoverflow.com/users/7282094", "pm_score": 0, "selected": false, "text": "$date = '22-09-2008';\n$timestamp = strtotime($date);\necho $timestamp; // 1222041600\n echo strtotime('22-09-2008');\n" } ]
2008/09/22
[ "https://Stackoverflow.com/questions/113829", "https://Stackoverflow.com", "https://Stackoverflow.com/users/205368/" ]
113,830
<p>Is there a runtime performance penalty when using interfaces (abstract base classes) in C++?</p>
[ { "answer_id": 114729, "author": "KeithB", "author_id": 2298, "author_profile": "https://Stackoverflow.com/users/2298", "pm_score": 2, "selected": false, "text": "class AbstractAlgo\n{\n virtual int func();\n};\n\nclass Algo1 : public AbstractAlgo\n{\n virtual int func();\n};\n\nclass Algo2 : public AbstractAlgo\n{\n virtual int func();\n};\n\nvoid compute(AbstractAlgo* algo)\n{\n // Use algo many times, paying virtual function cost each time\n\n} \n\nint main()\n{\n int which;\n AbstractAlgo* algo;\n\n // read which from config file\n if (which == 1)\n algo = new Algo1();\n else\n algo = new Algo2();\n compute(algo);\n}\n class Algo1\n{\n int func();\n};\n\nclass Algo2\n{\n int func();\n};\n\n\ntemplate<class ALGO> void compute()\n{\n ALGO algo;\n // Use algo many times. No virtual function cost, and func() may be inlined.\n} \n\nint main()\n{\n int which;\n // read which from config file\n if (which == 1)\n compute<Algo1>();\n else\n compute<Algo2>();\n}\n" } ]
2008/09/22
[ "https://Stackoverflow.com/questions/113830", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19863/" ]
113,845
<p>now i need to insert some data from the sqlserver into a word,i know how to use bookmark and the office interop api do that but it's slow to call the word process do that and it's coupling between the bookmark define and the code , is it possible to do this without word process start?if not are there any template engine to do this?</p>
[ { "answer_id": 124817, "author": "Mark Nold", "author_id": 4134, "author_profile": "https://Stackoverflow.com/users/4134", "pm_score": 0, "selected": false, "text": "something-uniqueid.xls <h1> <h2> <u> something.doc Content-type: application/msword Content-disposition: Attachment; filename=something-unique-id.doc .doc /listing.asp?var1=abc&var2=def&output=.doc" } ]
2008/09/22
[ "https://Stackoverflow.com/questions/113845", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20142/" ]
113,860
<p>How can I make sure that a certain OLEDB driver is installed when I start my application? I use ADO from Delphi and would like to display a descriptive error message if the driver is missing. The error that's returned from ADO isn't always that user-friendly.</p> <p>There are probably a nice little function that returns all installed drivers but I haven't found it.</p>
[ { "answer_id": 154559, "author": "Jeremy Mullin", "author_id": 7893, "author_profile": "https://Stackoverflow.com/users/7893", "pm_score": 3, "selected": true, "text": "function OleDBExists : boolean;\nvar\n reg : TRegistry;\nbegin\n Result := false;\n\n // See if Advantage OLE DB Provider is on this PC\n reg := TRegistry.Create;\n try\n reg.RootKey := HKEY_LOCAL_MACHINE;\n Result := reg.OpenKeyReadOnly( '\\SOFTWARE\\Classes\\CLSID\\{C1637B2F-CA37-11D2-AE5C-00609791DC73}' );\n finally\n reg.Free;\n end;\nend;\n" }, { "answer_id": 3363273, "author": "Adrian", "author_id": 405760, "author_profile": "https://Stackoverflow.com/users/405760", "pm_score": 0, "selected": false, "text": "namespace Common {\n public class CLSIDHelper {\n\n [DllImport(\"ole32.dll\")]\n static extern int CLSIDFromProgID([MarshalAs(UnmanagedType.LPWStr)] string lpszProgID, out Guid pclsid);\n\n\n public static Guid RetrieveGUID(string Provider) {\n Guid CLSID = Guid.Empty;\n int Ok = CLSIDFromProgID(Provider, out CLSID);\n if (Ok == 0)\n return CLSID;\n return null;\n }\n }\n}\n" }, { "answer_id": 12642324, "author": "Rogerio Ueda", "author_id": 1706541, "author_profile": "https://Stackoverflow.com/users/1706541", "pm_score": 4, "selected": false, "text": "names := TStringList.Create;\nADODB.GetProviderNames(names);\n\nif names.IndexOf('SQLNCLI10')<>-1 then\n st := 'Provider=SQLNCLI10;'\nelse if names.IndexOf('SQLNCLI')<>-1 then\n st := 'Provider=SQLNCLI;'\nelse if names.IndexOf('SQLOLEDB')<>-1 then\n st := 'Provider=SQLOLEDB;';\n" } ]
2008/09/22
[ "https://Stackoverflow.com/questions/113860", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4101/" ]
113,873
<p>I want to extend the basic <code>ControlCollection</code> in VB.NET so I can just add images and text to a self-made control, and then automaticly convert them to pictureboxes and lables.</p> <p>So I made a class that inherits from ControlCollection, overrided the add method, and added the functionality.</p> <p>But when I run the example, it gives a <code>NullReferenceException</code>.</p> <p>Here is the code:</p> <pre><code> Shadows Sub add(ByVal text As String) Dim LB As New Label LB.AutoSize = True LB.Text = text MyBase.Add(LB) 'Here it gives the exception. End Sub </code></pre> <p>I searched on Google, and someone said that the <code>CreateControlsInstance</code> method needs to be overriden. So I did that, but then it gives <code>InvalidOperationException</code> with an <code>innerException</code> message of <code>NullReferenceException</code>.</p> <p>How do I to implement this?</p>
[ { "answer_id": 113913, "author": "mattlant", "author_id": 14642, "author_profile": "https://Stackoverflow.com/users/14642", "pm_score": 0, "selected": false, "text": "puclic class MyCollection : Collection<Control>\n" }, { "answer_id": 114338, "author": "roomaroo", "author_id": 3464, "author_profile": "https://Stackoverflow.com/users/3464", "pm_score": 0, "selected": false, "text": "Public Class MyControlCollection\n Inherits Control.ControlCollection\n\n Sub New()\n 'Bad - you need to pass a valid control instance\n 'to the constructor\n MyBase.New(Nothing)\n End Sub\n\n Public Shadows Sub Add(ByVal text As String)\n Dim LB As New Label()\n LB.AutoSize = True\n LB.Text = text\n 'The next line will throw a NullReferenceException\n MyBase.Add(LB)\n End Sub\nEnd Class\n" } ]
2008/09/22
[ "https://Stackoverflow.com/questions/113873", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20261/" ]
113,883
<p>How do you determine the collation of a database in SQL 2005, for instance if you need to perform a case-insensitive search/replace?</p>
[ { "answer_id": 113913, "author": "mattlant", "author_id": 14642, "author_profile": "https://Stackoverflow.com/users/14642", "pm_score": 0, "selected": false, "text": "puclic class MyCollection : Collection<Control>\n" }, { "answer_id": 114338, "author": "roomaroo", "author_id": 3464, "author_profile": "https://Stackoverflow.com/users/3464", "pm_score": 0, "selected": false, "text": "Public Class MyControlCollection\n Inherits Control.ControlCollection\n\n Sub New()\n 'Bad - you need to pass a valid control instance\n 'to the constructor\n MyBase.New(Nothing)\n End Sub\n\n Public Shadows Sub Add(ByVal text As String)\n Dim LB As New Label()\n LB.AutoSize = True\n LB.Text = text\n 'The next line will throw a NullReferenceException\n MyBase.Add(LB)\n End Sub\nEnd Class\n" } ]
2008/09/22
[ "https://Stackoverflow.com/questions/113883", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5152/" ]
113,886
<p>I'm trying to ftp a folder using the command line ftp client, but so far I've only been able to use 'get' to get individual files. </p>
[ { "answer_id": 113892, "author": "Greg Hewgill", "author_id": 893, "author_profile": "https://Stackoverflow.com/users/893", "pm_score": 4, "selected": false, "text": "scp ftp -r" }, { "answer_id": 113900, "author": "Thibaut Barrère", "author_id": 20302, "author_profile": "https://Stackoverflow.com/users/20302", "pm_score": 10, "selected": true, "text": "wget -r ftp://user:pass@server.com/\n -m -r -N -l inf --user --password wget -r --user=\"user@login\" --password=\"Pa$$wo|^D\" ftp://server.com/\n -r -r\n--recursive\n Turn on recursive retrieving.\n\n-l depth\n--level=depth\n Specify recursion maximum depth level depth. The default maximum depth is 5.\n -m -m\n--mirror\n Turn on options suitable for mirroring. This option turns on recursion and time-stamping, sets infinite\n recursion depth and keeps FTP directory listings. It is currently equivalent to -r -N -l inf\n --no-remove-listing.\n" }, { "answer_id": 113902, "author": "Vinko Vrsalovic", "author_id": 5190, "author_profile": "https://Stackoverflow.com/users/5190", "pm_score": 5, "selected": false, "text": "ncftp -u <user> -p <pass> <server>\nncftp> mget directory\n" }, { "answer_id": 113904, "author": "Hank Gay", "author_id": 4203, "author_profile": "https://Stackoverflow.com/users/4203", "pm_score": 2, "selected": false, "text": "tar bzip gzip" }, { "answer_id": 113910, "author": "Jason Stevenson", "author_id": 13368, "author_profile": "https://Stackoverflow.com/users/13368", "pm_score": 4, "selected": false, "text": "wget -r ftp://mydomain.com/mystuff\n" }, { "answer_id": 2791934, "author": "Phillip", "author_id": 335864, "author_profile": "https://Stackoverflow.com/users/335864", "pm_score": 2, "selected": false, "text": "wget -r ftp://url" }, { "answer_id": 5297285, "author": "Rohit", "author_id": 658580, "author_profile": "https://Stackoverflow.com/users/658580", "pm_score": -1, "selected": false, "text": "ftp>cd /to/directory \nftp>prompt \nftp>mget *\n" }, { "answer_id": 5567776, "author": "Ludovic Kuty", "author_id": 452614, "author_profile": "https://Stackoverflow.com/users/452614", "pm_score": 8, "selected": false, "text": "wget -r -nH --cut-dirs=5 -nc ftp://user:pass@server//absolute/path/to/directory\n -nH -nc --cut-dirs=5 " }, { "answer_id": 13780413, "author": "Dilawar", "author_id": 1805129, "author_profile": "https://Stackoverflow.com/users/1805129", "pm_score": 5, "selected": false, "text": "lftp mirror dir" }, { "answer_id": 20035528, "author": "Tilo", "author_id": 677684, "author_profile": "https://Stackoverflow.com/users/677684", "pm_score": 2, "selected": false, "text": "ftp telnet rsync ssh ssh -r" } ]
2008/09/22
[ "https://Stackoverflow.com/questions/113886", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11708/" ]
113,897
<p>I have a quick question. How do I get the image generated by a JComponent.paint or paintComponent?</p> <p>I have a JComponent which I use as a 'workspace' and where I have overwritten the paintComponent method to my own. The thing is that my workspace JComponent also has children which has their own paintComponent methods.</p> <p>So when Swing renders my workspace component, it renders the workspace graphics and then its childrens'.</p> <p>However, I want to get the image my workspace component generates (which includes the workspace graphics and the children's graphics).</p> <p>How do I do that?</p> <p>I tried to call the paintComponent/paint-method myself by using my own Graphics, but i just returned a black image. Here is what i tried;</p> <pre><code>public void paintComponent(Graphics g) { if (bufferedImage != null) { g.drawImage(bufferedImage, 0, 0, this); } else { g.setColor(Color.WHITE); g.fillRect(0, 0, bufferedImage.getWidth(), bufferedImage.getHeight()); } } public BufferedImage getImage() { BufferedImage hello = new BufferedImage(getWidth(), getHeight(), BufferedImage.TYPE_INT_ARGB); Graphics g = hello.getGraphics(); paintComponent( g ); return hello; } </code></pre> <p>Any thoughts or comments are welcome! :)</p>
[ { "answer_id": 114026, "author": "user20298", "author_id": 20298, "author_profile": "https://Stackoverflow.com/users/20298", "pm_score": 1, "selected": false, "text": "BufferedImage hello = bufferedImage.getSubimage(0,0, getWidth(), getHeight());\n BufferedImage hello = new BufferedImage(getWidth(), getHeight(), BufferedImage.TYPE_INT_ARGB);\n" }, { "answer_id": 115019, "author": "jmagica", "author_id": 20412, "author_profile": "https://Stackoverflow.com/users/20412", "pm_score": 0, "selected": false, "text": "public class SomeApp extends JFrame {\n\n private static class ImagePanel extends JPanel {\n private BufferedImage currentImage;\n public BufferedImage getCurrentImage() {\n return currentImage;\n }\n @Override\n public void paint(Graphics g) {\n Rectangle tempBounds = g.getClipBounds();\n currentImage = new BufferedImage(tempBounds.width, tempBounds.height, BufferedImage.TYPE_INT_ARGB);\n super.paint(g);\n super.paint(currentImage.getGraphics());\n }\n }\n\n public SomeApp() {\n setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);\n setSize(800,600);\n int matrixSize = 4;\n setLayout(new BorderLayout());\n add(new JLabel(\"Wonderful Application\"), BorderLayout.NORTH);\n final ImagePanel imgPanel = new ImagePanel();\n imgPanel.setLayout(new GridLayout(matrixSize,matrixSize));\n for(int i=1; i<=matrixSize*matrixSize; i++) {\n imgPanel.add(new JButton(\"A Button\" + i));\n }\n add(imgPanel, BorderLayout.CENTER);\n final JPanel buttonPanel = new JPanel();\n buttonPanel.add(new JButton(new AbstractAction(\"get image\") {\n\n @Override\n public void actionPerformed(ActionEvent e) {\n JOptionPane.showMessageDialog(SomeApp.this, new ImageIcon(imgPanel.getCurrentImage()));\n }\n\n }));\n add(buttonPanel, BorderLayout.SOUTH);\n }\n\n public static void main(String[] args) {\n System.setProperty(\"swing.defaultlaf\", UIManager.getSystemLookAndFeelClassName());\n SwingUtilities.invokeLater(new Runnable() {\n @Override\n public void run() {\n new SomeApp().setVisible(true);\n }\n });\n }\n}\n" }, { "answer_id": 3627900, "author": "Steve McLeod", "author_id": 2959, "author_profile": "https://Stackoverflow.com/users/2959", "pm_score": 0, "selected": false, "text": "public BufferedImage getImage() {\n\n BufferedImage hello = new BufferedImage(getWidth(), getHeight(), BufferedImage.TYPE_INT_RGB);\n Graphics g = hello.getGraphics();\n paintComponent( g );\n\n return hello;\n}\n" } ]
2008/09/22
[ "https://Stackoverflow.com/questions/113897", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20298/" ]
113,899
<p>I want to create a c# application with multiple windows that are all transparent with some text on.</p> <p>The tricky part is making these forms sit on top of the desktop but under the desktop icons. Is this possible?</p>
[ { "answer_id": 113933, "author": "Jeff Hillman", "author_id": 3950, "author_profile": "https://Stackoverflow.com/users/3950", "pm_score": 3, "selected": true, "text": "this.BackColor = Color.Fuchsia;\nthis.TransparencyKey = Color.Fuchsia;\n public const int WM_NCHITTEST = 0x84;\npublic const int HTTRANSPARENT = -1;\n\nprotected override void WndProc(ref Message message)\n{\n if ( message.Msg == (int)WM_NCHITTEST )\n {\n message.Result = (IntPtr)HTTRANSPARENT;\n }\n else\n {\n base.WndProc( ref message );\n }\n}\n" } ]
2008/09/22
[ "https://Stackoverflow.com/questions/113899", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3585/" ]
113,901
<p>In order to perform a case-sensitive search/replace on a table in a SQL Server 2000/2005 database, you must use the correct collation.</p> <p>How do you determine whether the default collation for a database is case-sensitive, and if it isn't, how to perform a case-sensitive search/replace?</p>
[ { "answer_id": 113909, "author": "blowdart", "author_id": 2525, "author_profile": "https://Stackoverflow.com/users/2525", "pm_score": 5, "selected": true, "text": "SELECT testColumn FROM testTable \n WHERE testColumn COLLATE Latin1_General_CS_AS = 'example' \n\nSELECT testColumn FROM testTable\n WHERE testColumn COLLATE Latin1_General_CS_AS = 'EXAMPLE' \n\nSELECT testColumn FROM testTable \n WHERE testColumn COLLATE Latin1_General_CS_AS = 'eXaMpLe' \n" }, { "answer_id": 113912, "author": "Andrew Myhre", "author_id": 5152, "author_profile": "https://Stackoverflow.com/users/5152", "pm_score": 3, "selected": false, "text": "select charindex('RESULT', 'If the result is 0 you are in a case-sensitive collation mode') update ContentTable\nset ContentValue = replace(ContentValue COLLATE Latin1_General_BIN, 'THECONTENT', 'TheContent')\nfrom StringResource\nwhere charindex('THECONTENT', ContentValue COLLATE Latin1_General_BIN) > 0\n 'THECONTENT' 'TheContent' 'thecontent'" }, { "answer_id": 232203, "author": "nathan_jr", "author_id": 3769, "author_profile": "https://Stackoverflow.com/users/3769", "pm_score": 0, "selected": false, "text": "SELECT testColumn FROM testTable \n WHERE testColumn COLLATE Latin1_General_CS_AS = 'eXaMpLe' \n and testColumn = 'eXaMpLe'\n" }, { "answer_id": 18743898, "author": "Matas Vaitkevicius", "author_id": 827051, "author_profile": "https://Stackoverflow.com/users/827051", "pm_score": 1, "selected": false, "text": "UPDATE T SET [String] = ReplacedString\nFROM [dbo].[TranslationText] T, \n (SELECT [LanguageCode]\n ,[StringNo]\n ,REPLACE([String], 'Favourite','Favorite') ReplacedString\n FROM [dbo].[TranslationText]\n WHERE \n [String] COLLATE Latin1_General_CS_AS like '%Favourite%'\n AND [LanguageCode] = 'en-us') US_STRINGS\nWHERE \nT.[LanguageCode] = US_STRINGS.[LanguageCode] \nAND T.[StringNo] = US_STRINGS.[StringNo]\n\nUPDATE T SET [String] = ReplacedString\nFROM [dbo].[TranslationText] T, \n (SELECT [LanguageCode]\n ,[StringNo]\n , REPLACE([String], 'favourite','favorite') ReplacedString \n FROM [dbo].[TranslationText]\n WHERE \n [String] COLLATE Latin1_General_CS_AS like '%favourite%'\n AND [LanguageCode] = 'en-us') US_STRINGS\nWHERE \nT.[LanguageCode] = US_STRINGS.[LanguageCode] \nAND T.[StringNo] = US_STRINGS.[StringNo]\n" }, { "answer_id": 42433809, "author": "Sean", "author_id": 214980, "author_profile": "https://Stackoverflow.com/users/214980", "pm_score": 3, "selected": false, "text": "REPLACE UPDATE tableName\nSET fieldName = \n REPLACE(\n REPLACE(\n fieldName COLLATE Latin1_General_CS_AS,\n 'camelCase' COLLATE Latin1_General_CS_AS,\n 'changedWord'\n ),\n 'CamelCase' COLLATE Latin1_General_CS_AS,\n 'ChangedWord'\n )\n This is camelCase 1 and this is CamelCase 2\n This is changedWord 1 and this is ChangedWord 2\n" } ]
2008/09/22
[ "https://Stackoverflow.com/questions/113901", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5152/" ]
113,915
<p>I'm getting a random unreproducible Error when initializing a JSplitPane in with JDK 1.5.0_08. Note that this does not occur every time, but about 80% of the time:</p> <pre><code>Exception in thread "AWT-EventQueue-0" java.lang.ClassCastException: javax.swing.KeyStroke at java.util.TreeMap.compare(TreeMap.java:1093) at java.util.TreeMap.put(TreeMap.java:465) at java.util.TreeSet.add(TreeSet.java:210) at javax.swing.plaf.basic.BasicSplitPaneUI.installDefaults(BasicSplitPaneUI.java:364) at javax.swing.plaf.basic.BasicSplitPaneUI.installUI(BasicSplitPaneUI.java:300) at javax.swing.JComponent.setUI(JComponent.java:652) at javax.swing.JSplitPane.setUI(JSplitPane.java:350) at javax.swing.JSplitPane.updateUI(JSplitPane.java:378) at javax.swing.JSplitPane.&lt;init&gt;(JSplitPane.java:332) at javax.swing.JSplitPane.&lt;init&gt;(JSplitPane.java:287) ... </code></pre> <p>Thoughts? I've tried cleaning and rebuilding my project so as to minimize the probability of corrupted class files.</p> <p><strong>Edit #1</strong> See <a href="http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6434148" rel="nofollow noreferrer">http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6434148</a> - seems to be a JDK bug. Any known workarounds? None are listed on the bug entry page.</p>
[ { "answer_id": 34129765, "author": "Shree", "author_id": 5649198, "author_profile": "https://Stackoverflow.com/users/5649198", "pm_score": -1, "selected": false, "text": "java.lang.ClassCastException: javax.swing.KeyStroke cannot be cast to java.lang.Comparable....\n" } ]
2008/09/22
[ "https://Stackoverflow.com/questions/113915", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6583/" ]
113,916
<p>If I need to choose a collation mode to work with, how do I know what collations are available?</p>
[ { "answer_id": 118419, "author": "Constantin", "author_id": 20310, "author_profile": "https://Stackoverflow.com/users/20310", "pm_score": 3, "selected": true, "text": "select distinct COLLATION_NAME from INFORMATION_SCHEMA.COLUMNS order by 1\n" } ]
2008/09/22
[ "https://Stackoverflow.com/questions/113916", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5152/" ]
113,923
<p>We help our clients to manage and publish their media online - images, video, audio, whatever. They always ask my boss whether they can stop users from copying their media, and he asks me, and I always tell him the same thing: no. If the users can view the media, then a sufficiently determined user will always be able to make a copy. But am I right?</p> <p>I've been asked again today, and I promised my boss I'd ask about it online. So - is there a DRM scheme that will work? One that will stop users making copies without stopping legitimate viewing of the media?</p> <p>And if there isn't, how do I convince my boss?</p>
[ { "answer_id": 1452749, "author": "Mike Dunlavey", "author_id": 23771, "author_profile": "https://Stackoverflow.com/users/23771", "pm_score": 0, "selected": false, "text": "X = A; // statement 1\nX = B; // statement 2\n" } ]
2008/09/22
[ "https://Stackoverflow.com/questions/113923", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15371/" ]
113,928
<p>When I enter an object into the DB with Linq-to-SQL can I get the id that I just inserted without making another db call? I am assuming this is pretty easy, I just don't know how. </p>
[ { "answer_id": 113948, "author": "Germstorm", "author_id": 18631, "author_profile": "https://Stackoverflow.com/users/18631", "pm_score": 9, "selected": true, "text": "myObject.Field1 = \"value\";\n\n// Db is the datacontext\ndb.MyObjects.InsertOnSubmit(myObject);\ndb.SubmitChanges();\n\n// You can retrieve the id from the object\nint id = myObject.ID;\n" }, { "answer_id": 113949, "author": "Jason Stevenson", "author_id": 13368, "author_profile": "https://Stackoverflow.com/users/13368", "pm_score": 4, "selected": false, "text": "protected void btnInsertProductCategory_Click(object sender, EventArgs e)\n{\n ProductCategory productCategory = new ProductCategory();\n productCategory.Name = “Sample Category”;\n productCategory.ModifiedDate = DateTime.Now;\n productCategory.rowguid = Guid.NewGuid();\n int id = InsertProductCategory(productCategory);\n lblResult.Text = id.ToString();\n}\n\n//Insert a new product category and return the generated ID (identity value)\nprivate int InsertProductCategory(ProductCategory productCategory)\n{\n ctx.ProductCategories.InsertOnSubmit(productCategory);\n ctx.SubmitChanges();\n return productCategory.ProductCategoryID;\n}\n" }, { "answer_id": 54693243, "author": "Khalid Salameh", "author_id": 6492784, "author_profile": "https://Stackoverflow.com/users/6492784", "pm_score": 2, "selected": false, "text": "MyContext Context = new MyContext(); \nContext.YourEntity.Add(obj);\nContext.SaveChanges();\nint ID = obj._ID;\n" } ]
2008/09/22
[ "https://Stackoverflow.com/questions/113928", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14777/" ]
113,930
<p>I would like to display some memory statistics (working set, GCs etc.) on a web page using the .NET/Process performance counters. Unfortunately, if there are multiple application pools on that server, they are differentiated using an index (#1, #2 etc.) but I don't know how to match a process ID (which I have) to that #xx index. Is there a programmatic way (from an ASP.NET web page)?</p>
[ { "answer_id": 491022, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 4, "selected": false, "text": "private static string GetProcessInstanceName(int pid)\n{\n PerformanceCounterCategory cat = new PerformanceCounterCategory(\"Process\");\n\n string[] instances = cat.GetInstanceNames();\n foreach (string instance in instances)\n {\n\n using (PerformanceCounter cnt = new PerformanceCounter(\"Process\", \n \"ID Process\", instance, true))\n {\n int val = (int) cnt.RawValue;\n if (val == pid)\n {\n return instance;\n }\n }\n }\n throw new Exception(\"Could not find performance counter \" + \n \"instance name for current process. This is truly strange ...\");\n}\n" }, { "answer_id": 40597656, "author": "Akram Alhinnawi", "author_id": 5202727, "author_profile": "https://Stackoverflow.com/users/5202727", "pm_score": 0, "selected": false, "text": "public static long GetProcessPrivateWorkingSet64Size(int process_id)\n{\n long process_size = 0;\n Process process = Process.GetProcessById(process_id);\n if (process == null) return process_size;\n string instanceName = GetProcessInstanceName(process.Id);\n var counter = new PerformanceCounter(\"Process\", \"Working Set - Private\", instanceName, true);\n process_size = Convert.ToInt32(counter.NextValue()) / 1024;\n return process_size;\n}\n\npublic static string GetProcessInstanceName(int process_id)\n{\n PerformanceCounterCategory cat = new PerformanceCounterCategory(\"Process\");\n string[] instances = cat.GetInstanceNames();\n foreach (string instance in instances)\n {\n using (PerformanceCounter cnt = new PerformanceCounter(\"Process\", \"ID Process\", instance, true))\n {\n int val = (int)cnt.RawValue;\n if (val == process_id)\n return instance;\n }\n }\n throw new Exception(\"Could not find performance counter \");\n}\n public static long GetPrivateWorkingSetForAllProcesses(string ProcessName)\n{\n long totalMem = 0;\n Process[] process = Process.GetProcessesByName(ProcessName);\n foreach (Process proc in process)\n {\n long memsize = GetProcessPrivateWorkingSet64Size(proc.Id);\n totalMem += memsize;\n }\n return totalMem;\n}\n" } ]
2008/09/22
[ "https://Stackoverflow.com/questions/113930", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
113,951
<p>I am creating an appcation on Vista,which include a service and a Console application .Both running in same user account</p> <p>In service i am creating an event and waits for that event.In console application i am opening the same event (problem starts here) and calling <em>SetEvent</em> function. I can not open the event (getting error 5,Access is denied) in the console application.I searched in the net and saw something about integrity level (I am not sure that the problem is related to integrity level).Its telling that service and applicaation got differnt integrity levels.</p> <p>here is the part of the code,where IPC occures</p> <p><strong>service</strong> </p> <pre><code>DWORD WINAPI IpcThread(LPVOID lpParam) { HANDLE ghRequestEvent = NULL ; ghRequestEvent = CreateEvent(NULL, FALSE, FALSE, "Global\\Event1") ; //creating the event if(NULL == ghRequestEvent) { //error } while(1) { WaitForSingleObject(ghRequestEvent, INFINITE) //waiting for the event //here some action related to event } } </code></pre> <p><strong>Console Application</strong></p> <p>Here in application ,opening the event and seting the event</p> <pre><code>unsigned int event_notification() { HANDLE ghRequestEvent = NULL ; ghRequestEvent = OpenEvent(SYNCHRONIZE|EVENT_MODIFY_STATE, FALSE, "Global\\Event1") ; if(NULL == ghRequestEvent) { //error } SetEvent(ghRequestEvent) ; } </code></pre> <p>I am running both application (serivce and console application) with administrative privilege (i logged in as Administraor and running the console application by right clicking and using the option "run as administrator") .</p> <p>The error i am getting in console application (where i am opening the event) is error no 5(Access is denied. ) .</p> <p>So it will be very helpfull if you tell how to do the IPC between a service and an application in Vista</p> <p>Thanks in advance</p> <p>Navaneeth</p>
[ { "answer_id": 114009, "author": "1800 INFORMATION", "author_id": 3146, "author_profile": "https://Stackoverflow.com/users/3146", "pm_score": 2, "selected": false, "text": "#include <sddl.h>\n#include <AccCtrl.h>\n#include <Aclapi.h>\n\nvoid SetLowLabelToFile()\n{\n // The LABEL_SECURITY_INFORMATION SDDL SACL to be set for low integrity \n #define LOW_INTEGRITY_SDDL_SACL_W L\"S:(ML;;NW;;;LW)\"\n DWORD dwErr = ERROR_SUCCESS;\n PSECURITY_DESCRIPTOR pSD = NULL; \n\n PACL pSacl = NULL; // not allocated\n BOOL fSaclPresent = FALSE;\n BOOL fSaclDefaulted = FALSE;\n LPCWSTR pwszFileName = L\"Sample.txt\";\n\n if (ConvertStringSecurityDescriptorToSecurityDescriptorW(\n LOW_INTEGRITY_SDDL_SACL_W, SDDL_REVISION_1, &pSD;, NULL)) \n {\n if (GetSecurityDescriptorSacl(pSD, &fSaclPresent;, &pSacl;, \n &fSaclDefaulted;))\n {\n // Note that psidOwner, psidGroup, and pDacl are \n // all NULL and set the new LABEL_SECURITY_INFORMATION\n dwErr = SetNamedSecurityInfoW((LPWSTR) pwszFileName, \n SE_FILE_OBJECT, LABEL_SECURITY_INFORMATION, \n NULL, NULL, NULL, pSacl);\n }\n LocalFree(pSD);\n }\n}\n BYTE sd[SECURITY_DESCRIPTOR_MIN_LENGTH];\nSECURITY_ATTRIBUTES sa;\n\nsa.nLength = sizeof(sa);\nsa.bInheritHandle = TRUE;\nsa.lpSecurityDescriptor = &sd;\n\nInitializeSecurityDescriptor(&sd, SECURITY_DESCRIPTOR_REVISION);\nSetSecurityDescriptorDacl(&sd, TRUE, (PACL) 0, FALSE);\n\nCreateNamedPipe(..., &sa);\n" }, { "answer_id": 114091, "author": "Ignas Limanauskas", "author_id": 2877, "author_profile": "https://Stackoverflow.com/users/2877", "pm_score": 0, "selected": false, "text": "{\n HANDLE hEvent;\n hEvent = CreateEvent(null, true, false, TEXT(\"MyEvent\"));\n while (1)\n {\n WaitForSingleObject (hEvent);\n ResetEvent (hEvent);\n /* Do something -- start */\n /* Processing 1 */\n /* Processing 2 */\n /* Do something -- end */\n }\n}\n {\n HANDLE hEvent;\n hEvent = OpenEvent(0, false, TEXT(\"MyEvent\"));\n SetEvent (hEvent);\n}\n" }, { "answer_id": 121375, "author": "Jere.Jones", "author_id": 19476, "author_profile": "https://Stackoverflow.com/users/19476", "pm_score": 0, "selected": false, "text": "(SYNCHRONIZE | EVENT_MODIFY_STATE)\n" } ]
2008/09/22
[ "https://Stackoverflow.com/questions/113951", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20316/" ]
113,989
<p>Is there an easy way (in .Net) to test if a Font is installed on the current machine?</p>
[ { "answer_id": 113998, "author": "aku", "author_id": 1196, "author_profile": "https://Stackoverflow.com/users/1196", "pm_score": 5, "selected": false, "text": "var fontsCollection = new InstalledFontCollection();\nforeach (var fontFamily in fontsCollection.Families)\n{\n if (fontFamily.Name == fontName) {...} \\\\ check if font is installed\n}\n" }, { "answer_id": 114003, "author": "Jeff Hillman", "author_id": 3950, "author_profile": "https://Stackoverflow.com/users/3950", "pm_score": 6, "selected": true, "text": "string fontName = \"Consolas\";\nfloat fontSize = 12;\n\nusing (Font fontTester = new Font( \n fontName, \n fontSize, \n FontStyle.Regular, \n GraphicsUnit.Pixel)) \n{\n if (fontTester.Name == fontName)\n {\n // Font exists\n }\n else\n {\n // Font doesn't exist\n }\n}\n" }, { "answer_id": 114066, "author": "GvS", "author_id": 11492, "author_profile": "https://Stackoverflow.com/users/11492", "pm_score": 4, "selected": false, "text": " private bool IsFontInstalled(string fontName) {\n using (var testFont = new Font(fontName, 8)) {\n return 0 == string.Compare(\n fontName,\n testFont.Name,\n StringComparison.InvariantCultureIgnoreCase);\n }\n }\n" }, { "answer_id": 14653702, "author": "Hans", "author_id": 472522, "author_profile": "https://Stackoverflow.com/users/472522", "pm_score": 2, "selected": false, "text": " private static bool IsFontInstalled(string fontName)\n {\n using (var testFont = new Font(fontName, 8))\n return fontName.Equals(testFont.Name, StringComparison.InvariantCultureIgnoreCase);\n }\n" }, { "answer_id": 17596784, "author": "jltrem", "author_id": 571637, "author_profile": "https://Stackoverflow.com/users/571637", "pm_score": 3, "selected": false, "text": "Font FontStyle.Regular public static bool IsFontInstalled(string fontName)\n {\n bool installed = IsFontInstalled(fontName, FontStyle.Regular);\n if (!installed) { installed = IsFontInstalled(fontName, FontStyle.Bold); }\n if (!installed) { installed = IsFontInstalled(fontName, FontStyle.Italic); }\n\n return installed;\n }\n\n public static bool IsFontInstalled(string fontName, FontStyle style)\n {\n bool installed = false;\n const float emSize = 8.0f;\n\n try\n {\n using (var testFont = new Font(fontName, emSize, style))\n {\n installed = (0 == string.Compare(fontName, testFont.Name, StringComparison.InvariantCultureIgnoreCase));\n }\n }\n catch\n {\n }\n\n return installed;\n }\n" }, { "answer_id": 23280503, "author": "nateirvin", "author_id": 1687106, "author_profile": "https://Stackoverflow.com/users/1687106", "pm_score": 2, "selected": false, "text": "private static bool IsFontInstalled(string name)\n{\n using (InstalledFontCollection fontsCollection = new InstalledFontCollection())\n {\n return fontsCollection.Families\n .Any(x => x.Name.Equals(name, StringComparison.CurrentCultureIgnoreCase));\n }\n}\n Name IsFontInstalled(\"Arabic Typesetting Regular\") IsFontInstalled(\"Arabic Typesetting\")" }, { "answer_id": 61184284, "author": "Sourcephy", "author_id": 8196012, "author_profile": "https://Stackoverflow.com/users/8196012", "pm_score": 0, "selected": false, "text": "using System.IO;\n\nIsFontInstalled(\"verdana.ttf\")\n\npublic bool IsFontInstalled(string ContentFontName)\n{\n return File.Exists(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Fonts), ContentFontName.ToUpper()));\n}\n" } ]
2008/09/22
[ "https://Stackoverflow.com/questions/113989", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11492/" ]
113,991
<p>A heap is a list where the following applies:</p> <pre><code>l[i] &lt;= l[2*i] &amp;&amp; l[i] &lt;= [2*i+1] </code></pre> <p>for <code>0 &lt;= i &lt; len(list)</code></p> <p>I'm looking for in-place sorting.</p>
[ { "answer_id": 114071, "author": "HenryR", "author_id": 2827, "author_profile": "https://Stackoverflow.com/users/2827", "pm_score": 0, "selected": false, "text": "for (int k=len(l)-1;k>0;k--){\nswap( l, 0, k );\nwhile (i*2 < k)\n {\nint left = i*2;\nint right = l*2 + 1;\nint swapidx = i;\nif ( l[left] < l[right] )\n {\n if (l[i] > l[left])\n {\n swapidx = left;\n }\n }\nelse\n {\n if (l[i] > l[right])\n {\n swapidx = right;\n }\n }\n\nif (swapidx == i)\n {\n // Found right place in the heap, break.\n break;\n }\nswap( l, i, swapidx );\ni = swapidx;\n }}\n\n// Now reverse the list in linear time:\nint s = 0; \nint e = len(l)-1;\nwhile (e > s)\n {\n swap( l, s, e );\n s++; e--:\n }\n" } ]
2008/09/22
[ "https://Stackoverflow.com/questions/113991", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6899/" ]
113,992
<p>In what order are the following parameters tested (in C++)?</p> <pre><code>if (a || b &amp;&amp; c) { } </code></pre> <p>I've just seen this code in our application and I hate it, I want to add some brackets to just clarify the ordering. But I don't want to add the brackets until I know I'm adding them in the right place.</p> <p><strong><em>Edit: Accepted Answer &amp; Follow Up</em></strong></p> <p>This link has more information, but it's not totally clear what it means. It seems || and &amp;&amp; are the same precedence, and in that case, they are evaluated left-to-right.</p> <p><a href="http://msdn.microsoft.com/en-us/library/126fe14k.aspx" rel="nofollow noreferrer">http://msdn.microsoft.com/en-us/library/126fe14k.aspx</a></p>
[ { "answer_id": 113995, "author": "tzot", "author_id": 6899, "author_profile": "https://Stackoverflow.com/users/6899", "pm_score": 3, "selected": true, "text": "a || (b && c)\n" }, { "answer_id": 114185, "author": "efotinis", "author_id": 12320, "author_profile": "https://Stackoverflow.com/users/12320", "pm_score": 2, "selected": false, "text": "a || b && c\na || (b && c)\n a + b * c\na + (b * c)\n" } ]
2008/09/22
[ "https://Stackoverflow.com/questions/113992", "https://Stackoverflow.com", "https://Stackoverflow.com/users/986/" ]
114,010
<p>Is there any way to create C# 3.0 anonymous object via Reflection at runtime in .NET 3.5? I'd like to support them in my serialization scheme, so I need a way to manipulate them programmatically.</p> <p><em>edited later to clarify the use case</em></p> <p>An extra constraint is that I will be running all of it inside a Silverlight app, so extra runtimes are not an option, and not sure how generating code on the fly will work.</p>
[ { "answer_id": 114101, "author": "TraumaPony", "author_id": 18658, "author_profile": "https://Stackoverflow.com/users/18658", "pm_score": 2, "selected": false, "text": "public static T create<T>(T t)\n{\n return Activator.CreateInstance<T>();\n}\n\nobject anon = create(existingAnonymousType);\n" }, { "answer_id": 132589, "author": "Guvante", "author_id": 16800, "author_profile": "https://Stackoverflow.com/users/16800", "pm_score": 3, "selected": true, "text": "object anon = Activator.CreateInstance(existingObject.GetType());\n" } ]
2008/09/22
[ "https://Stackoverflow.com/questions/114010", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9777/" ]
114,054
<p>Can you please clarify the folowing query? I am not sure if the way I am trying to code is correct. Kindly advise me if I am moving in the right/wrong direction.</p> <p>I am trying to develop an automation framework using <a href="http://en.wikipedia.org/wiki/HP_QuickTest_Professional" rel="nofollow noreferrer">QuickTest Professional</a>, a testing tool.</p> <ul> <li>There is an Excel sheet from which the data is being taken for execution based on the ID's stored in an array from another Excel sheet (The same ID is available in both Excel sheets).</li> <li>I'm trying to handle the exeptional cases through a function call. This function will capture the screenshot of the page error occured and then exit the entire loop.</li> <li>I need a scenario where execution continues for the next ID stored in the array, and this needs to be handled from the function call.</li> </ul>
[ { "answer_id": 114133, "author": "Rob Cooper", "author_id": 832, "author_profile": "https://Stackoverflow.com/users/832", "pm_score": 1, "selected": false, "text": "While Not EndOfExcelSheet\n ReadDataFromExcel();\n If errOccurred Then TakeScreenPrint();\n 'NOTE: We have caught the error and requested the screen print\n 'is taken, but we have NOT bubbled the exception up!\nEnd While\n" } ]
2008/09/22
[ "https://Stackoverflow.com/questions/114054", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
114,085
<p>I have lots of unrelated named things that I'd like to do quick searches against. An "aardvark" is always an "aardvark" everywhere, so hashing the string and reusing the integer would work well to speed up comparisons. The entire set of names is unknown (and changes over time). What is a fast string hashing algorithm that will generate small (32 or 16) bit values and have a low collision rate?</p> <p>I'd like to see an optimized implementation specific to C/C++.</p>
[ { "answer_id": 372732, "author": "Bernard Igiri", "author_id": 254455, "author_profile": "https://Stackoverflow.com/users/254455", "pm_score": 2, "selected": false, "text": "#include <boost/functional/hash.hpp>\n\nint main()\n{\n boost::hash<std::string> string_hash;\n\n std::size_t h = string_hash(\"Hash me\");\n}\n" }, { "answer_id": 372996, "author": "Christoph", "author_id": 48015, "author_profile": "https://Stackoverflow.com/users/48015", "pm_score": 4, "selected": false, "text": "#include <stdint.h>\n\nuint32_t hash_string(const char * s)\n{\n uint32_t hash = 0;\n\n for(; *s; ++s)\n {\n hash += *s;\n hash += (hash << 10);\n hash ^= (hash >> 6);\n }\n\n hash += (hash << 3);\n hash ^= (hash >> 11);\n hash += (hash << 15);\n\n return hash;\n}\n" }, { "answer_id": 19028143, "author": "Antonio Morales", "author_id": 2819428, "author_profile": "https://Stackoverflow.com/users/2819428", "pm_score": 3, "selected": false, "text": " \n\nunsigned long djb_hashl(const char *clave)\n{\n unsigned long c,i,h;\n\n for(i=h=0;clave[i];i++)\n {\n c = toupper(clave[i]);\n h = ((h << 5) + h) ^ c;\n }\n return h;\n}\n\n\n unsigned long djb_hashl(const char *clave)\n{\n unsigned long c,i,h;\n\n for(i=h=0;clave[i];i++)\n {\n c = toupper(clave[i]);\n h = ((h << 5) + h) ^ c;\n }\n return h;\n}\n " } ]
2008/09/22
[ "https://Stackoverflow.com/questions/114085", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10945/" ]
114,112
<p>I have tried following guides like <a href="http://docs.djangoproject.com/en/dev/howto/deployment/modpython/" rel="nofollow noreferrer">this one</a> but it just didnt work for me.</p> <p><strong>So my question is this:</strong> What is a good guide for deploying Django, and how do you deploy your Django.</p> <p>I keep hearing that capastrano is pretty nifty to use, but i have no idea as to how to work it or what it does (apart from automation of deploying code), or even if i want/need to use it or not.</p>
[ { "answer_id": 114268, "author": "Armin Ronacher", "author_id": 19990, "author_profile": "https://Stackoverflow.com/users/19990", "pm_score": 3, "selected": false, "text": "mod_wsgi virtualenv fabric" }, { "answer_id": 1546416, "author": "che", "author_id": 7806, "author_profile": "https://Stackoverflow.com/users/7806", "pm_score": 0, "selected": false, "text": "mysite/settings.py .gitignore git checkout && git reset --hard && sudo /etc/init.d/apache2 restart" } ]
2008/09/22
[ "https://Stackoverflow.com/questions/114112", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2592/" ]
114,148
<p>On a website if I have a form where the user can input some text and then a page which displays what the user has entered. I know to html encode the values the user has entered to prevent scripting attacks. If the form was sending emails addresses I presume I would do the same but is there any special cases for emails and will email clients run the any script injected into the email?</p>
[ { "answer_id": 114791, "author": "Prestaul", "author_id": 5628, "author_profile": "https://Stackoverflow.com/users/5628", "pm_score": 1, "selected": false, "text": "<script>" } ]
2008/09/22
[ "https://Stackoverflow.com/questions/114148", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18793/" ]
114,149
<p>The point of const-correctness is to be able to provide a view of an instance that can't be altered or deleted by the user. The compiler supports this by pointing out when you break constness from within a const function, or try to use a non-const function of a const object. So without copying the const approach, is there a methodology I can use in C# that has the same ends? </p> <p>I'm aware of immutability, but that doesn't really carry over to container objects to name but one example.</p>
[ { "answer_id": 114809, "author": "Trap", "author_id": 7839, "author_profile": "https://Stackoverflow.com/users/7839", "pm_score": 7, "selected": true, "text": "public interface IReadOnlyCustomer\n{\n String Name { get; }\n int Age { get; }\n}\n\npublic class Customer : IReadOnlyCustomer\n{\n private string m_name;\n private int m_age;\n\n public string Name\n {\n get { return m_name; }\n set { m_name = value; }\n }\n\n public int Age\n {\n get { return m_age; }\n set { m_age = value; }\n }\n}\n" }, { "answer_id": 132718, "author": "Stuart McConnell", "author_id": 22111, "author_profile": "https://Stackoverflow.com/users/22111", "pm_score": 2, "selected": false, "text": " public class Customer\n {\n private readonly string m_name;\n private readonly int m_age;\n\n public Customer(string name, int age)\n {\n m_name = name;\n m_age = age;\n }\n\n public string Name\n {\n get { return m_name; }\n }\n\n public int Age\n {\n get { return m_age; }\n }\n }\n public class Customer\n {\n private string m_name;\n private int m_age;\n\n protected Customer() \n {}\n\n public Customer(string name, int age)\n {\n m_name = name;\n m_age = age;\n }\n\n public string Name\n {\n get { return m_name; }\n protected set { m_name = value; }\n }\n\n public int Age\n {\n get { return m_age; }\n protected set { m_age = value; }\n }\n }\n" } ]
2008/09/22
[ "https://Stackoverflow.com/questions/114149", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11801/" ]
114,154
<p>XAML allows you to specify an attribute value using a string that contains curly braces. Here is an example that creates a <em>Binding</em> instance and assigns it to the <em>Text</em> property of the <em>TextBox</em> element.</p> <pre><code>&lt;TextBox Text="{Binding ElementName=Foo, Path=Bar}"/&gt; </code></pre> <p>I want to extend XAML so that the developer could enter this as valid...</p> <pre><code>&lt;TextBox Text="{MyCustomObject Field1=Foo, Field2=Bar}"/&gt; </code></pre> <p>This would create an instance of my class and set the Field1/Field2 properties as appropriate. Is this possible? If so how do you do it?</p> <p>If this is possible I have a followup question. Can I take a string <em>"{Binding ElementName=Foo, Path=Bar}"</em> and ask the framework to process it and return the <em>Binding</em> instance it specified? This must be done somewhere already to make the above XAML work and so there must be a way to ask for the same thing to be processed.</p>
[ { "answer_id": 114195, "author": "Brownie", "author_id": 6600, "author_profile": "https://Stackoverflow.com/users/6600", "pm_score": 2, "selected": false, "text": "Binding System.Windows.Markup.MarkupExtension ElementName Path Binding Binding Binding" } ]
2008/09/22
[ "https://Stackoverflow.com/questions/114154", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6276/" ]
114,165
<p>At work we use <a href="http://en.wikipedia.org/wiki/WiX" rel="noreferrer">WiX</a> for building installation packages. We want that installation of product X would result in uninstall of the previous version of that product on that machine.</p> <p>I've read on several places on the Internet about a major upgrade but couldn't get it to work. Can anyone please specify the exact steps that I need to take to add uninstall previous version feature to WiX?</p>
[ { "answer_id": 114736, "author": "Dror Helper", "author_id": 11361, "author_profile": "https://Stackoverflow.com/users/11361", "pm_score": 8, "selected": false, "text": "<Property Id=\"PREVIOUSVERSIONSINSTALLED\" Secure=\"yes\" />\n<Upgrade Id=\"YOUR_GUID\"> \n <UpgradeVersion\n Minimum=\"1.0.0.0\" Maximum=\"99.0.0.0\"\n Property=\"PREVIOUSVERSIONSINSTALLED\"\n IncludeMinimum=\"yes\" IncludeMaximum=\"no\" />\n</Upgrade> \n <RemoveExistingProducts Before=\"InstallInitialize\" /> \n" }, { "answer_id": 114786, "author": "Mike Dimmick", "author_id": 6970, "author_profile": "https://Stackoverflow.com/users/6970", "pm_score": 4, "selected": false, "text": "RemoveExistingProducts <Upgrade> @Id UpgradeCode <Product> UpgradeCode UpgradeVersion/@OnlyDetect no RemoveExistingProducts UPGRADINGPRODUCTCODE Product/@Id UpgradeCode" }, { "answer_id": 214650, "author": "Brian Gillespie", "author_id": 6151, "author_profile": "https://Stackoverflow.com/users/6151", "pm_score": 5, "selected": false, "text": "<Property Id=\"PREVIOUSVERSIONSINSTALLED\" Secure=\"yes\" />\n<Upgrade Id=\"00000000-0000-0000-0000-000000000000\">\n <UpgradeVersion Minimum=\"1.0.0.0\" Maximum=\"1.0.5.0\" Property=\"PREVIOUSVERSIONSINSTALLED\" IncludeMinimum=\"yes\" IncludeMaximum=\"no\" />\n</Upgrade>\n <InstallExecuteSequence>\n <RemoveExistingProducts After=\"InstallFinalize\"></RemoveExistingProducts>\n</InstallExecuteSequence>\n" }, { "answer_id": 724098, "author": "Rob Mensching", "author_id": 23852, "author_profile": "https://Stackoverflow.com/users/23852", "pm_score": 7, "selected": false, "text": "<Product Id=\"*\" UpgradeCode=\"PUT-GUID-HERE\" Version=\"$(var.ProductVersion)\">\n <Upgrade Id=\"PUT-GUID-HERE\">\n <UpgradeVersion OnlyDetect=\"yes\" Minimum=\"$(var.ProductVersion)\" Property=\"NEWERVERSIONDETECTED\" IncludeMinimum=\"no\" />\n <UpgradeVersion OnlyDetect=\"no\" Maximum=\"$(var.ProductVersion)\" Property=\"OLDERVERSIONBEINGUPGRADED\" IncludeMaximum=\"no\" />\n</Upgrade>\n\n<InstallExecuteSequence>\n <RemoveExistingProducts After=\"InstallInitialize\" />\n</InstallExecuteSequence>\n" }, { "answer_id": 2407440, "author": "Merill Fernando", "author_id": 241338, "author_profile": "https://Stackoverflow.com/users/241338", "pm_score": 3, "selected": false, "text": "<Product Id=\"*\" UpgradeCode=\"PUT-GUID-HERE\" ... >\n\n<Upgrade Id=\"PUT-GUID-HERE\">\n <UpgradeVersion OnlyDetect=\"no\" Property=\"PREVIOUSFOUND\"\n Minimum=\"1.0.0.0\" IncludeMinimum=\"yes\"\n Maximum=\"99.0.0.0\" IncludeMaximum=\"no\" />\n</Upgrade>\n" }, { "answer_id": 3575801, "author": "Ant", "author_id": 11529, "author_profile": "https://Stackoverflow.com/users/11529", "pm_score": 9, "selected": true, "text": "<MajorUpgrade\n AllowDowngrades=\"no\" DowngradeErrorMessage=\"!(loc.NewerVersionInstalled)\"\n AllowSameVersionUpgrades=\"no\"\n />\n" }, { "answer_id": 8534048, "author": "Sasha", "author_id": 543591, "author_profile": "https://Stackoverflow.com/users/543591", "pm_score": 4, "selected": false, "text": "<MajorUpgrade Schedule=\"afterInstallInitialize\"\n DowngradeErrorMessage=\"A later version of [ProductName] is already installed. Setup will now exit.\" \n AllowDowngrades=\"no\" />\n" }, { "answer_id": 22619073, "author": "Gian Marco", "author_id": 66629, "author_profile": "https://Stackoverflow.com/users/66629", "pm_score": 1, "selected": false, "text": "<Wix ...>\n <Product ...>\n <Property Id=\"REINSTALLMODE\" Value=\"amus\" />\n <MajorUpgrade AllowDowngrades=\"yes\" />\n" }, { "answer_id": 34098823, "author": "NishantJ", "author_id": 1244334, "author_profile": "https://Stackoverflow.com/users/1244334", "pm_score": 2, "selected": false, "text": "<Product Id=\"*\" Name=\"XXXInstaller\" Language=\"1033\" Version=\"1.0.0.0\" \n Manufacturer=\"XXXX\" UpgradeCode=\"YOUR_GUID_HERE\">\n<Package InstallerVersion=\"xxx\" Compressed=\"yes\"/>\n<Upgrade Id=\"YOUR_GUID_HERE\">\n <UpgradeVersion Property=\"REMOVINGTHEOLDVERSION\" Minimum=\"1.0.0.0\" \n RemoveFeatures=\"ALL\" />\n</Upgrade>\n<InstallExecuteSequence>\n <RemoveExistingProducts After=\"InstallInitialize\" />\n</InstallExecuteSequence>\n" } ]
2008/09/22
[ "https://Stackoverflow.com/questions/114165", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11361/" ]
114,172
<p>I have a Windows executable (whoami) which is crashing every so often. It's called from another process to get details about the current user and domain. I'd like to know what parameters are passed when it fails.</p> <p>Does anyone know of an appropriate way to wrap the process and write it's command line arguments to log while still calling the process?</p> <p>Say the command is used like this: 'whoami.exe /all'</p> <p>I'd like a script to exist instead of the whoami.exe (with the same filename) which will write this invocation to log and then pass on the call to the actual process.</p>
[ { "answer_id": 114199, "author": "Milan Babuškov", "author_id": 14690, "author_profile": "https://Stackoverflow.com/users/14690", "pm_score": 1, "selected": false, "text": "int main(int argc, void **argv)\n{\n // dump contents of argv to some log file\n int i=0;\n for (i=0; i<argc; i++)\n printf(\"Argument #%d: %s\\n\", argv[i]);\n // run the 'real' program, giving it the rest of argv vector (1+)\n // for example spawn, exec or system() functions can do it\n return 0; // or you can do a blocking call, and pick the return value from the program\n}\n" }, { "answer_id": 114209, "author": "Allan Mertner", "author_id": 13394, "author_profile": "https://Stackoverflow.com/users/13394", "pm_score": 1, "selected": false, "text": "program PassThrough;\n\nuses\n Dos; // Imports the Exec routine\n\nconst\n PassTo = 'Original.exe'; // The program you really want to call\n\nvar \n CommandLine: String;\n i: Integer;\n f: Text;\n\nbegin\n CommandLine := '';\n for i := 1 to ParamCount do\n CommandLine := CommandLine + ParamStr(i) + ' ';\n\n Assign(f,'Passthrough.log');\n Append(f);\n Writeln(f, CommandLine); // Write a line in the log\n Close(f);\n\n\n Exec(PassTo, CommandLine); // Run the intended program\nend.\n" }, { "answer_id": 114235, "author": "Grey Panther", "author_id": 1265, "author_profile": "https://Stackoverflow.com/users/1265", "pm_score": 2, "selected": true, "text": "echo Parameters: %* >> logfile.txt\nwhoami.exe %*\n" } ]
2008/09/22
[ "https://Stackoverflow.com/questions/114172", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2257098/" ]
114,179
<p>I got this síngleton cache object and it exposes an IEnumerable property which just returns a private IEnumerable variable.</p> <p>I have a static method on my singleton object that updates this member variable (that exists on the single 'Instance' instance of this cache object).</p> <p>Let's say some thread is currently iterating over this IEnumerable variable/property while my cache is updating. I made it so the cache is updating on a new local variable and finally setting the exposed private variable to point to this new local variable.</p> <p>I know i'm just updating a reference, leaving the other (old) object in memory waiting to be picked up by the GC but my problem is - i'm not 100% sure what happens once i set the new reference? Would the other thread suddenly be iterating over the new object or the old one it got passed through the IEnumerable interface? If it had been a normal reference i'd say 'no'. The calling thread would be operating on the old object, but i'm not sure if this is the case for IEnumerable as well?</p> <p>Here is the class stripped down:</p> <pre><code>internal sealed class SektionCache : CacheBase { public static readonly SektionCache Instance = new SektionCache(); private static readonly object lockObject = new object(); private static bool isUpdating; private IEnumerable&lt;Sektion&gt; sektioner; static SektionCache() { UpdateCache(); } public IEnumerable&lt;Sektion&gt; Sektioner { get { return sektioner; } } public static void UpdateCache() { // SNIP - getting data, locking etc. Instance.sektioner = newSektioner; // SNIP } } </code></pre>
[ { "answer_id": 114193, "author": "configurator", "author_id": 9536, "author_profile": "https://Stackoverflow.com/users/9536", "pm_score": 2, "selected": false, "text": "{ return sektioner; } foreach (Sektion s in cache.Sektioner)" }, { "answer_id": 114462, "author": "TcKs", "author_id": 20382, "author_profile": "https://Stackoverflow.com/users/20382", "pm_score": 0, "selected": false, "text": "internal sealed class SektionCache : CacheBase\n{\n //public static readonly SektionCache Instance = new SektionCache();\n\n // this template is better ( safer ) than the previous one, for thread-safe singleton patter >>>\n private static SektionCache defaultInstance;\n private static object readonly lockObject = new object();\n public static SektionCach Default {\n get {\n SektionCach result = defaultInstance;\n if ( null == result ) {\n lock( lockObject ) {\n if ( null == result ) {\n defaultInstance = result = new SektionCache();\n }\n }\n }\n\n return result;\n }\n }\n // <<< this template is better ( safer ) than the previous one\n\n //private static readonly object lockObject = new object();\n //private static bool isUpdating;\n //private IEnumerable<Sektion> sektioner;\n\n // this declaration is enough\n private volatile IEnumerable<Sektion> sektioner;\n\n // no static constructor is required >>>\n //static SektionCache()\n //{\n // UpdateCache();\n //}\n // <<< no static constructor is required\n\n // I think, you can use getter and setter for reading & changing a collection\n public IEnumerable<Sektion> Sektioner {\n get {\n IEnumerable<Sektion> result = this.sektioner;\n // i don't know, if you need this functionality >>>\n // if ( null == result ) { result = new Sektion[0]; }\n // <<< i don't know, if you need this functionality\n return result;\n }\n set { this.sektion = value; }\n }\n\n //public static void UpdateCache()\n //{\n //// SNIP - getting data, locking etc.\n //Instance.sektioner = newSektioner;\n //// SNIP\n //}\n}\n" } ]
2008/09/22
[ "https://Stackoverflow.com/questions/114179", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11619/" ]
114,180
<p>What would be better practice when giving a function the original variable to work with:</p> <pre><code>unsigned long x = 4; void func1(unsigned long&amp; val) { val = 5; } func1(x); </code></pre> <p>or:</p> <pre><code>void func2(unsigned long* val) { *val = 5; } func2(&amp;x); </code></pre> <p>IOW: Is there any reason to pick one over another?</p>
[ { "answer_id": 114351, "author": "Johann Gerell", "author_id": 6345, "author_profile": "https://Stackoverflow.com/users/6345", "pm_score": 6, "selected": false, "text": "const const" }, { "answer_id": 213963, "author": "Kiley Hykawy", "author_id": 22727, "author_profile": "https://Stackoverflow.com/users/22727", "pm_score": 3, "selected": false, "text": "// Sample method using optional as input parameter\nvoid PrintOptional(const boost::optional<std::string>& optional_str)\n{\n if (optional_str)\n {\n cout << *optional_str << std::endl;\n }\n else\n {\n cout << \"(no string)\" << std::endl;\n }\n}\n\n// Sample method using optional as return value\nboost::optional<int> ReturnOptional(bool return_nothing)\n{\n if (return_nothing)\n {\n return boost::optional<int>();\n }\n\n return boost::optional<int>(42);\n}\n" }, { "answer_id": 19659142, "author": "Germán Diago", "author_id": 429879, "author_profile": "https://Stackoverflow.com/users/429879", "pm_score": 2, "selected": false, "text": "nullptr NULL & &" }, { "answer_id": 49256541, "author": "Saurabh Raoot", "author_id": 2519258, "author_profile": "https://Stackoverflow.com/users/2519258", "pm_score": 4, "selected": false, "text": "BaseType* ptrBaseType;\nBaseType objBaseType;\nptrBaseType = &objBaseType;\n int nVar = 7;\n int* ptrVar = &nVar;\n int nVar2 = *ptrVar;\n int i = 3; //integer declaration\nint * pi = &i; //pi points to the integer i\nint& ri = i; //ri is refers to integer i – creation of reference and initialization\n" } ]
2008/09/22
[ "https://Stackoverflow.com/questions/114180", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20349/" ]
114,192
<p>Imagine a web application written in Ruby on Rails. Part of the state of that application is represented in a piece of data which doesn't fit the description of a model. This state descriptor needs to be persisted in the same database as the models. Where it differs from a model is that there needs to be only one instance of its class and it doesn't have relationships with other classes.</p> <p>Has anyone come across anything like this?</p>
[ { "answer_id": 114317, "author": "Toby Hede", "author_id": 14971, "author_profile": "https://Stackoverflow.com/users/14971", "pm_score": 1, "selected": false, "text": "class ApplicationController < ActionController::Base\n helper :all \n @data = \"YOUR DATA HERE\" \nend\n" }, { "answer_id": 114843, "author": "webmat", "author_id": 6349, "author_profile": "https://Stackoverflow.com/users/6349", "pm_score": 0, "selected": false, "text": "ComplexThing.data = complex_hash.inspect\n complex_hash = eval ComplexThing.data\n" } ]
2008/09/22
[ "https://Stackoverflow.com/questions/114192", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8683/" ]
114,194
<p>My app is installed via NSIS.</p> <p>I want the installer to install the program for all users.</p> <p>I can do this, by installing to the 'program files' directory.</p> <p>There is a database file (firebird), that all user accounts on the system should share. </p> <p>If I store this database file in the 'program files' directory it will be read only.</p> <p>If I store it in the users APPDATA directory they will each have a different copy, when one user adds data the others wont see it.</p> <p>Option 1 - In my app directory under 'program files' create a 'Data' directory, in my installer make this dir read-writeable by all, that way the user 'program files' virtualisation won't kick in and all users can update the file and see each others changes.</p> <p>Any other options ? </p>
[ { "answer_id": 835131, "author": "Kyle Gagnet", "author_id": 101915, "author_profile": "https://Stackoverflow.com/users/101915", "pm_score": 0, "selected": false, "text": "SetShellVarContext all\nSetOutPath $APPDATA\nFile \"MyInsecurelySharedFile.txt\"\n" } ]
2008/09/22
[ "https://Stackoverflow.com/questions/114194", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1724/" ]
114,196
<p>I'm using <a href="http://erlang.org/doc/man/httpc.html#request-1" rel="nofollow noreferrer"><code>httpc:request</code></a> to post some data to a remote service. I have the post working but the data in the body() of the post comes through as is, without any URL-encoding which causes the post to fail when parsed by the remote service.</p> <p>Is there a function in Erlang that is similar to <a href="https://apidock.com/ruby/CGI/escape/class" rel="nofollow noreferrer"><code>CGI.escape</code></a> in Ruby for this purpose?</p>
[ { "answer_id": 114223, "author": "tonys", "author_id": 35439, "author_profile": "https://Stackoverflow.com/users/35439", "pm_score": 0, "selected": false, "text": "% Utility function to convert a 'form' of name-value pairs into a URL encoded\n% content string.\n\nurlencode(Form) ->\n RevPairs = lists:foldl(fun({K,V},Acc) -> [[quote_plus(K),$=,quote_plus(V)] | Acc] end, [],Form),\n lists:flatten(revjoin(RevPairs,$&,[])).\n\nquote_plus(Atom) when is_atom(Atom) ->\n quote_plus(atom_to_list(Atom));\n\nquote_plus(Int) when is_integer(Int) ->\n quote_plus(integer_to_list(Int));\n\nquote_plus(String) ->\n quote_plus(String, []).\n\nquote_plus([], Acc) ->\n lists:reverse(Acc);\n\nquote_plus([C | Rest], Acc) when ?QS_SAFE(C) ->\n quote_plus(Rest, [C | Acc]);\n\nquote_plus([$\\s | Rest], Acc) ->\n quote_plus(Rest, [$+ | Acc]);\n\nquote_plus([C | Rest], Acc) ->\n <<Hi:4, Lo:4>> = <<C>>,\n quote_plus(Rest, [hexdigit(Lo), hexdigit(Hi), ?PERCENT | Acc]).\n\nrevjoin([], _Separator, Acc) ->\n Acc;\n\nrevjoin([S | Rest],Separator,[]) ->\n revjoin(Rest,Separator,[S]);\n\nrevjoin([S | Rest],Separator,Acc) ->\n revjoin(Rest,Separator,[S,Separator | Acc]).\n\nhexdigit(C) when C < 10 -> $0 + C;\nhexdigit(C) when C < 16 -> $A + (C - 10).\n" }, { "answer_id": 114273, "author": "davidsmalley", "author_id": 20345, "author_profile": "https://Stackoverflow.com/users/20345", "pm_score": 2, "selected": false, "text": "url_encode/1\n\nurl_encode(Str) -> UrlEncodedStr\n\nStr = string()\nUrlEncodedStr = string()\n" }, { "answer_id": 501244, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 5, "selected": false, "text": "> edoc_lib:escape_uri(\"luca+more@here.com\").\n\"luca%2bmore%40here.com\"\n > CGI.escape(\"luca+more@here.com\")\n => \"luca%2Bmore%40here.com\" \n> URI.escape(\"luca+more@here.com\")\n => \"luca+more@here.com\" \n" }, { "answer_id": 3504624, "author": "Rick Moynihan", "author_id": 224432, "author_profile": "https://Stackoverflow.com/users/224432", "pm_score": 3, "selected": false, "text": "%% @doc A function to URL encode form data.\n%% @spec url_encode(formdata()).\n\n-spec(url_encode(formdata()) -> string()).\nurl_encode(Data) ->\n url_encode(Data,\"\").\n\nurl_encode([],Acc) ->\n Acc;\n\nurl_encode([{Key,Value}|R],\"\") ->\n url_encode(R, edoc_lib:escape_uri(Key) ++ \"=\" ++ edoc_lib:escape_uri(Value));\nurl_encode([{Key,Value}|R],Acc) ->\n url_encode(R, Acc ++ \"&\" ++ edoc_lib:escape_uri(Key) ++ \"=\" ++ edoc_lib:escape_uri(Value)).\n httpc:request(post, {\"http://localhost:3000/foo\", [], \n \"application/x-www-form-urlencoded\",\n url_encode([{\"username\", \"bob\"}, {\"password\", \"123456\"}])}\n ,[],[]).\n" }, { "answer_id": 3743323, "author": "gdamjan", "author_id": 230917, "author_profile": "https://Stackoverflow.com/users/230917", "pm_score": 1, "selected": false, "text": "edoc_lib:escape_uri escape_uri(S) when is_list(S) ->\n escape_uri(unicode:characters_to_binary(S));\nescape_uri(<<C:8, Cs/binary>>) when C >= $a, C =< $z ->\n [C] ++ escape_uri(Cs);\nescape_uri(<<C:8, Cs/binary>>) when C >= $A, C =< $Z ->\n [C] ++ escape_uri(Cs);\nescape_uri(<<C:8, Cs/binary>>) when C >= $0, C =< $9 ->\n [C] ++ escape_uri(Cs);\nescape_uri(<<C:8, Cs/binary>>) when C == $. ->\n [C] ++ escape_uri(Cs);\nescape_uri(<<C:8, Cs/binary>>) when C == $- ->\n [C] ++ escape_uri(Cs);\nescape_uri(<<C:8, Cs/binary>>) when C == $_ ->\n [C] ++ escape_uri(Cs);\nescape_uri(<<C:8, Cs/binary>>) ->\n escape_byte(C) ++ escape_uri(Cs);\nescape_uri(<<>>) ->\n \"\".\n\nescape_byte(C) ->\n \"%\" ++ hex_octet(C).\n\nhex_octet(N) when N =< 9 ->\n [$0 + N];\nhex_octet(N) when N > 15 ->\n hex_octet(N bsr 4) ++ hex_octet(N band 15);\nhex_octet(N) ->\n [N - 10 + $a].\n 9> httpc:request(\"http://httpbin.org/get?q=\" ++ mylib_app:escape_uri(\"☺\")).\n{ok,{{\"HTTP/1.1\",200,\"OK\"},\n [{\"connection\",\"keep-alive\"},\n {\"date\",\"Sat, 09 Nov 2019 21:51:54 GMT\"},\n {\"server\",\"nginx\"},\n {\"content-length\",\"178\"},\n {\"content-type\",\"application/json\"},\n {\"access-control-allow-credentials\",\"true\"},\n {\"access-control-allow-origin\",\"*\"},\n {\"referrer-policy\",\"no-referrer-when-downgrade\"},\n {\"x-content-type-options\",\"nosniff\"},\n {\"x-frame-options\",\"DENY\"},\n {\"x-xss-protection\",\"1; mode=block\"}],\n \"{\\n \\\"args\\\": {\\n \\\"q\\\": \\\"\\\\u263a\\\"\\n }, \\n \\\"headers\\\": {\\n \\\"Host\\\": \\\"httpbin.org\\\"\\n }, \\n \\\"origin\\\": \\\"11.111.111.111, 11.111.111.111\\\", \\n \\\"url\\\": \\\"https://httpbin.org/get?q=\\\\u263a\\\"\\n}\\n\"}}\n\n" }, { "answer_id": 12648499, "author": "Renato Albano", "author_id": 113112, "author_profile": "https://Stackoverflow.com/users/113112", "pm_score": 3, "selected": false, "text": "Eshell V5.9.1 (abort with ^G)\n\n1> c(encode_uri_rfc3986).\n{ok,encode_uri_rfc3986}\n\n2> encode_uri_rfc3986:encode(\"テスト\").\n\"%e3%83%86%e3%82%b9%e3%83%88\"\n\n3> edoc_lib:escape_uri(\"テスト\").\n\"%c3%86%c2%b9%c3%88\" # output wrong: ƹÈ\n" } ]
2008/09/22
[ "https://Stackoverflow.com/questions/114196", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20345/" ]
114,207
<p>I just want my apache to register some of my predefined environment so that i can retrieve it using getenv function in php. How can i do this? I tried adding /etc/profile.d/foo.sh with export FOO=/bar/baz using root and restarted apache.</p>
[ { "answer_id": 114231, "author": "Torsten Marek", "author_id": 9567, "author_profile": "https://Stackoverflow.com/users/9567", "pm_score": 4, "selected": true, "text": "# . /etc/profile.d/foo.sh /etc/profile.d/ init" }, { "answer_id": 26251452, "author": "Don Grem", "author_id": 468282, "author_profile": "https://Stackoverflow.com/users/468282", "pm_score": 0, "selected": false, "text": "/etc/apache2/envvars export LANG='en_US.UTF-8'\nexport LC_ALL='en_US.UTF-8'\n" } ]
2008/09/22
[ "https://Stackoverflow.com/questions/114207", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20300/" ]
114,208
<p>Let me explain: this is path to this folder: > <code>www.my_site.com/images</code></p> <p>And images are created by <code>user_id</code>, and for example, images of <code>user_id = 27</code> are, <code>27_1.jpg</code>, <code>27_2.jpg</code>, <code>27_3.jpg</code>! How to list and print images which start with <code>27_%.jpg</code>? I hope You have understood me! PS. I am totally beginmer in ASP.NET (VB) and please give me detailed information</p> <p>Here starts my loop</p> <pre><code>while dbread.Read() 'and then id user_id dbread('user_id') </code></pre> <p>NEXT???</p> <hr> <p>I nedd to create XML, till now I created like this:</p> <p>act.WriteLine("") act.WriteLine("<a href="http://www.my_site.com/images/" rel="nofollow noreferrer">http://www.my_site.com/images/</a>"&amp;dbread("user_id")&amp;"_1.jpg") act.WriteLine("")</p> <p>But this is not answer because I need to create this nodes how many images of this user exist?</p> <p>In database doesn't exist list of this images so that is reason why I must count them in folder. (this is not my site exacly, but I need to create XMl on this site)</p> <p>Do you understand me?</p>
[ { "answer_id": 114231, "author": "Torsten Marek", "author_id": 9567, "author_profile": "https://Stackoverflow.com/users/9567", "pm_score": 4, "selected": true, "text": "# . /etc/profile.d/foo.sh /etc/profile.d/ init" }, { "answer_id": 26251452, "author": "Don Grem", "author_id": 468282, "author_profile": "https://Stackoverflow.com/users/468282", "pm_score": 0, "selected": false, "text": "/etc/apache2/envvars export LANG='en_US.UTF-8'\nexport LC_ALL='en_US.UTF-8'\n" } ]
2008/09/22
[ "https://Stackoverflow.com/questions/114208", "https://Stackoverflow.com", "https://Stackoverflow.com/users/205368/" ]
114,214
<p>What is the difference between the following class methods?</p> <p>Is it that one is static and the other is not?</p> <pre><code>class Test(object): def method_one(self): print "Called method_one" def method_two(): print "Called method_two" a_test = Test() a_test.method_one() a_test.method_two() </code></pre>
[ { "answer_id": 114232, "author": "Justin Poliey", "author_id": 6967, "author_profile": "https://Stackoverflow.com/users/6967", "pm_score": 4, "selected": false, "text": "self gargaloo method_two TypeError method_two = staticmethod(method_two)\n @staticmethod" }, { "answer_id": 114250, "author": "Jon Cage", "author_id": 15369, "author_profile": "https://Stackoverflow.com/users/15369", "pm_score": 2, "selected": false, "text": ">>> a_test.method_two()\nTraceback (most recent call last):\n File \"<stdin>\", line 1, in <module>\nTypeError: method_two() takes no arguments (1 given)\n" }, { "answer_id": 114251, "author": "MvdD", "author_id": 18044, "author_profile": "https://Stackoverflow.com/users/18044", "pm_score": 1, "selected": false, "text": "staticmethod decorator Class Test(Object):\n @staticmethod\n def method_two():\n print \"Called method_two\"\n\nTest.method_two()\n" }, { "answer_id": 114267, "author": "Torsten Marek", "author_id": 9567, "author_profile": "https://Stackoverflow.com/users/9567", "pm_score": 10, "selected": true, "text": "method_one a_test.method_one()\n Test.method_one(a_test)\n method_two TypeError >>> a_test = Test() \n>>> a_test.method_two()\nTraceback (most recent call last):\n File \"<stdin>\", line 1, in <module>\nTypeError: method_two() takes no arguments (1 given) \n class Test(object):\n def method_one(self):\n print \"Called method_one\"\n\n @staticmethod\n def method_two():\n print \"Called method two\"\n type method_two >>> a_test = Test()\n>>> a_test.method_one()\nCalled method_one\n>>> a_test.method_two()\nCalled method_two\n>>> Test.method_two()\nCalled method_two\n" }, { "answer_id": 114281, "author": "hayalci", "author_id": 16084, "author_profile": "https://Stackoverflow.com/users/16084", "pm_score": 1, "selected": false, "text": "class Test(object):\n >>> a.method_two()\nTraceback (most recent call last):\nFile \"<stdin>\", line 1, in <module>\nTypeError: method_two() takes no arguments (1 given)\n" }, { "answer_id": 114289, "author": "Armin Ronacher", "author_id": 19990, "author_profile": "https://Stackoverflow.com/users/19990", "pm_score": 8, "selected": false, "text": "class C(object):\n def foo(self):\n pass\n >>> C.foo\n<unbound method C.foo>\n>>> C.__dict__['foo']\n<function foo at 0x17d05b0>\n foo __getattribute__ C.foo >>> C.__dict__['foo'].__get__(None, C)\n<unbound method C.foo>\n __get__ None >>> c = C()\n>>> C.__dict__['foo'].__get__(c, C)\n<bound method C.foo of <__main__.C object at 0x17bd4d0>>\n staticmethod class C(object):\n @staticmethod\n def foo():\n pass\n staticmethod __get__ >>> C.__dict__['foo'].__get__(None, C)\n<function foo at 0x17d0c30>\n" }, { "answer_id": 2696019, "author": "kzh", "author_id": 143739, "author_profile": "https://Stackoverflow.com/users/143739", "pm_score": 4, "selected": false, "text": ">>> class Class(object):\n... def __init__(self):\n... self.i = 0\n... def instance_method(self):\n... self.i += 1\n... print self.i\n... c = 0\n... @classmethod\n... def class_method(cls):\n... cls.c += 1\n... print cls.c\n... @staticmethod\n... def static_method(s):\n... s += 1\n... print s\n... \n>>> a = Class()\n>>> a.class_method()\n1\n>>> Class.class_method() # The class shares this value across instances\n2\n>>> a.instance_method()\n1\n>>> Class.instance_method() # The class cannot use an instance method\nTraceback (most recent call last):\n File \"<stdin>\", line 1, in <module>\nTypeError: unbound method instance_method() must be called with Class instance as first argument (got nothing instead)\n>>> Class.instance_method(a)\n2\n>>> b = 0\n>>> a.static_method(b)\n1\n>>> a.static_method(a.c) # Static method does not have direct access to \n>>> # class or instance properties.\n3\n>>> Class.c # a.c above was passed by value and not by reference.\n2\n>>> a.c\n2\n>>> a.c = 5 # The connection between the instance\n>>> Class.c # and its class is weak as seen here.\n2\n>>> Class.class_method()\n3\n>>> a.c\n5\n" }, { "answer_id": 39563369, "author": "supi", "author_id": 923372, "author_profile": "https://Stackoverflow.com/users/923372", "pm_score": 2, "selected": false, "text": "class C:\n a = [] \n def foo(self):\n pass\n\nC # this is the class object\nC.a # is a list object (class property object)\nC.foo # is a function object (class property object)\nc = C() \nc # this is the class instance\n __dict__ >>> C.__dict__['foo']\n<function foo at 0x17d05b0>\n __get__() def __get__(self, instance, owner)\ndef __set__(self, instance, value)\ndef __delete__(self, instance)\n >>> C.__dict__['foo'].__get__(c, C)\n self instance owner value >>> C.__dict__['foo'].__get__(None, C)\n<function C.foo at 0x10a72f510> \n>>> C.__dict__['a'].__get__(None, C)\nTraceback (most recent call last):\n File \"<stdin>\", line 1, in <module>\nAttributeError: 'list' object has no attribute '__get__'\n c.foo(self) C.__dict__['foo'].__get__(c, C) __get__() @staticmethod class C(object):\n @staticmethod\n def foo():\n pass\n foo >>> C.__dict__['foo'].__get__(None, C)\n<function foo at 0x17d0c30>\n" }, { "answer_id": 54260080, "author": "Yossarian42", "author_id": 9905745, "author_profile": "https://Stackoverflow.com/users/9905745", "pm_score": 0, "selected": false, "text": "method_two method_two TypeError: method_two() takes 0 positional arguments but 1 was given a_test.method_two() self Test self" }, { "answer_id": 60205635, "author": "Öykü", "author_id": 9616459, "author_profile": "https://Stackoverflow.com/users/9616459", "pm_score": 0, "selected": false, "text": "class MyClass: \n def some_method(self):\n return self # For the sake of the example\n\n>>> MyClass().some_method()\n<__main__.MyClass object at 0x10e8e43a0># This can also be written as:>>> obj = MyClass()\n\n>>> obj.some_method()\n<__main__.MyClass object at 0x10ea12bb0>\n\n# Bound method call:\n>>> obj.some_method(10)\nTypeError: some_method() takes 1 positional argument but 2 were given\n\n# WHY IT DIDN'T WORK?\n# obj.some_method(10) bound call translated as\n# MyClass.some_method(obj, 10) unbound method and it takes 2 \n# arguments now instead of 1 \n\n# ----- USING THE UNBOUND METHOD ------\n>>> MyClass.some_method(10)\n10\n obj MyClass.some_method(10) @staticmethod @staticmethod class MyClass: \n def some_method(self):\n return self \n\n @staticmethod\n def some_static_method(number):\n return number\n\n>>> MyClass.some_static_method(10) # without an instance\n10\n>>> MyClass().some_static_method(10) # Calling through an instance\n10\n MyClass.some_method(obj, 10) TypeError MyClass.some_static_method MyClass().some_static_method" } ]
2008/09/22
[ "https://Stackoverflow.com/questions/114214", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16070/" ]
114,222
<p>With the introduction of .NET 3.5 and the <code>IQueryable&lt;T&gt;</code> interface, new patterns will emerge. While I have seen a number of implementations of the Specification pattern, I have not seen many other patterns using this technology. Rob Conery's Storefront application is another concrete example using <code>IQueryable&lt;T&gt;</code> which may lead to some new patterns.</p> <p><strong>What patterns have emerged from the useful <code>IQueryable&lt;T&gt;</code> interface?</strong></p>
[ { "answer_id": 114609, "author": "Fredrik Kalseth", "author_id": 1710, "author_profile": "https://Stackoverflow.com/users/1710", "pm_score": 3, "selected": false, "text": "public class LinqToSqlRepository : IRepository\n{\n private readonly DataContext _context;\n\n public LinqToSqlRepository(DataContext context)\n {\n _context = context;\n }\n\n public IQueryable<T> Find<T>()\n {\n return _dataContext.GetTable<T>(); // linq 2 sql\n }\n\n /** snip: Insert, Update etc.. **/\n}\n var query = from customers in _repository.Find<Customer>() \n select customers;\n" }, { "answer_id": 645970, "author": "BC.", "author_id": 54838, "author_profile": "https://Stackoverflow.com/users/54838", "pm_score": 3, "selected": false, "text": "public class ThingRepository : IThingRepository\n{\n public IQueryable<Thing> GetThings()\n {\n return from m in context.Things\n select m; // Really simple!\n }\n}\n public static class ServiceExtensions\n{\n public static IQueryable<Thing> ForUserID(this IQueryable<Thing> qry, int userID)\n {\n return from a in qry\n where a.UserID == userID\n select a;\n }\n}\n public GetThingsForUserID(int userID)\n{\n return repository.GetThings().ForUserID(userID);\n}\n" } ]
2008/09/22
[ "https://Stackoverflow.com/questions/114222", "https://Stackoverflow.com", "https://Stackoverflow.com/users/708/" ]
114,229
<p>I'm trying to write a function that formats every (string) member/variable in an object, for example with a callback function. The variable names are unknown to me, so it must work with objects of all classes.</p> <p>How can I achieve something similar to <code>array_map</code> or <code>array_walk</code> with objects?</p>
[ { "answer_id": 114271, "author": "tpk", "author_id": 8437, "author_profile": "https://Stackoverflow.com/users/8437", "pm_score": 1, "selected": false, "text": "get_object_vars() get_object_vars() get_class_methods()" } ]
2008/09/22
[ "https://Stackoverflow.com/questions/114229", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12534/" ]
114,236
<p>I use pstack to analyze core dump files in Solaris</p> <p>How else can I analyze the core dump from solaris?</p> <p>What commands can be used to do this?</p> <p>What other information will be available from the dump? </p>
[ { "answer_id": 252715, "author": "Chris Quenelle", "author_id": 32470, "author_profile": "https://Stackoverflow.com/users/32470", "pm_score": 2, "selected": false, "text": "% dbx a.out core\n(dbx) where\n(dbx) threads\n(dbx) thread t@3\n(dbx) where\n" }, { "answer_id": 21462854, "author": "Will Charlton", "author_id": 2517989, "author_profile": "https://Stackoverflow.com/users/2517989", "pm_score": 1, "selected": false, "text": "/opt/SUNWspro/bin/dbx\n" } ]
2008/09/22
[ "https://Stackoverflow.com/questions/114236", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20357/" ]
114,237
<p>When a getter returns a property, such as returning a <code>List</code> of other related objects, should that list and it's objects be immutable to prevent code outside of the class, changing the state of those objects, without the main parent object knowing?</p> <p>For example if a <code>Contact</code> object, has a <code>getDetails</code> getter, which returns a <code>List</code> of <code>ContactDetails</code> objects, then any code calling that getter:</p> <ol> <li>can remove <code>ContactDetail</code> objects from that list without the <code>Contact</code> object knowing of it.</li> <li>can change each <code>ContactDetail</code> object without the <code>Contact</code> object knowing of it.</li> </ol> <p>So what should we do here? Should we just trust the calling code and return easily mutable objects, or go the hard way and make a immutable class for each mutable class?</p>
[ { "answer_id": 114444, "author": "Martin Spamer", "author_id": 15527, "author_profile": "https://Stackoverflow.com/users/15527", "pm_score": 1, "selected": false, "text": "contact.print( printer ) ; // or\ncontact.show( new Dialog() ) ; // or\ncontactList.findByName( searchName ).print( printer ) ;\n" }, { "answer_id": 114920, "author": "Kip", "author_id": 18511, "author_profile": "https://Stackoverflow.com/users/18511", "pm_score": 2, "selected": false, "text": "return Collections.unmodifiableList(list);" } ]
2008/09/22
[ "https://Stackoverflow.com/questions/114237", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19888/" ]
114,242
<p>Previously I have asked to strip text from a field and convert it to an int, this works successfully. But now, I would like to do an INNER JOIN on this new value.</p> <p>So I have this:</p> <pre><code>SELECT CONVERT(int, SUBSTRING(accountingTab.id, PATINDEX('%[0-9]%', accountingTab.id), 999)) AS 'memId', userDetails.title, userDetails.lname FROM accountingTab INNER JOIN (SELECT id, title, first, last FROM memDetTab) AS userDetails ON memID = userDetails.id </code></pre> <p>And then I get the Invalid Column Name <code>memID</code> error.</p> <p>How can I fix this?</p>
[ { "answer_id": 114280, "author": "Chris Shaffer", "author_id": 6744, "author_profile": "https://Stackoverflow.com/users/6744", "pm_score": 3, "selected": false, "text": "\nSELECT *\nFROM memDetTab\n JOIN (SELECT CONVERT(int, SUBSTRING(accountingTab.id, PATINDEX('%[0-9]%', accountingTab.id), 999)) AS 'memId', userDetails.title, userDetails.lname\nFROM accountingTab) subquery\n ON subquery.memID = memDetTab.ID\n" } ]
2008/09/22
[ "https://Stackoverflow.com/questions/114242", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1841427/" ]
114,260
<p>I've created an <code>IHttpHandler</code> in .NET C# which returns pieces of html to a classic asp page.</p> <p>The classic asp page communicates with the <code>IHttpHandler</code> through basic http requests using <code>ServerXMLHTTP</code> in vbscript or Ajax Calls in JavaScript.</p> <p>Now, I need a way to share a variable which I have in vbscript but not in javascript with the .NET application.</p> <p>The first bit, sharing a variable between classic asp and .net is not a problem as I can just add it onto the http request. Because the variable is not available in javascript however I can't do this in that case.</p> <p>I had the idea that I could maybe cache the variable in the .NET application and use the cached version for javascript calls. But for this to work I would need a way to uniquely identify the "client" in .NET...</p> <p>I tried to add <code>System.Web.SessionState.IRequiresSessionState</code> to my HttpHandler and use the SessionId but this didn't work because every single call to the HttpHandler seems to get a new ID.</p> <p>Am I thinking the right way? What are my options here?</p>
[ { "answer_id": 156597, "author": "Ben", "author_id": 5005, "author_profile": "https://Stackoverflow.com/users/5005", "pm_score": 0, "selected": false, "text": "<meta>" } ]
2008/09/22
[ "https://Stackoverflow.com/questions/114260", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5005/" ]
114,283
<p>I want to emulate the delete confirmation page behavior before saving certain models in the admin. In my case if I change one object, certain others should be deleted as they depend upon the object's now out-of-date state. </p> <p>I understand where to implement the actual cascaded updates (inside the parent model's save method), but I don't see a quick way to ask the user for confirmation (and then rollback if they decide not to save). I suppose I could implement some weird confirmation logic directly inside the save method (sort of a two phase save) but that seems...ugly. </p> <p>Any thoughts, even general pointers into the django codebase? </p> <p>Thanks!</p>
[ { "answer_id": 114348, "author": "Tomo", "author_id": 9622, "author_profile": "https://Stackoverflow.com/users/9622", "pm_score": 1, "selected": false, "text": "django.contrib.admin.options.ModelAdmin render_change_form response_change" }, { "answer_id": 114373, "author": "Armin Ronacher", "author_id": 19990, "author_profile": "https://Stackoverflow.com/users/19990", "pm_score": 2, "selected": false, "text": "get_form change_view" } ]
2008/09/22
[ "https://Stackoverflow.com/questions/114283", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5357/" ]
114,284
<p>First of all, this question regards MySQL 3.23.58, so be advised.</p> <p>I have 2 tables with the following definition:</p> <pre><code>Table A: id INT (primary), customer_id INT, offlineid INT Table B: id INT (primary), name VARCHAR(255) </code></pre> <p>Now, table A contains in the range of 65k+ records, while table B contains ~40 records. In addition to the 2 primary key indexes, there is also an index on the <em>offlineid</em> field in table A. There are more fields in each table, but they are not relevant (as I see it, ask if necessary) for this query.</p> <p>I was first presented with the following query (<em>query time: ~22 seconds</em>):</p> <pre><code>SELECT b.name, COUNT(*) AS orders, COUNT(DISTINCT(a.kundeid)) AS leads FROM katalogbestilling_katalog a, medie b WHERE a.offlineid = b.id GROUP BY b.name </code></pre> <p>Now, each id in medie is associated with a different name, meaning you could group by id as well as name. A bit of testing back and forth settled me on this (<em>query time: ~6 seconds</em>):</p> <pre><code>SELECT a.name, COUNT(*) AS orders, COUNT(DISTINCT(b.kundeid)) AS leads FROM medie a INNER JOIN katalogbestilling_katalog b ON a.id = b.offline GROUP BY b.offline; </code></pre> <p>Is there any way to crank it down to "instant" time (max 1 second at worst)? I added the index on offlineid, but besides that and the re-arrangement of the query, I am at a loss for what to do. The EXPLAIN query shows me the query is using fileshort (the original query also used temp tables). All suggestions are welcome!</p>
[ { "answer_id": 114350, "author": "tpk", "author_id": 8437, "author_profile": "https://Stackoverflow.com/users/8437", "pm_score": 0, "selected": false, "text": "SELECT b.name, COUNT(*) AS orders, COUNT(DISTINCT(a.kundeid)) AS leads\nFROM katalogbestilling_katalog a, medie b\nWHERE a.offlineid = b.id\nGROUP BY b.name\n SELECT b.name, COUNT(DISTINCT(a.kundeid)) AS leads\nFROM katalogbestilling_katalog a, medie b\nWHERE a.offlineid = b.id\nGROUP BY b.name\n SELECT b.name, COUNT(*) AS orders\nFROM katalogbestilling_katalog a, medie b\nWHERE a.offlineid = b.id\nGROUP BY b.name\n SELECT b.name\nFROM katalogbestilling_katalog a, medie b\nWHERE a.offlineid = b.id\nGROUP BY b.name\n EXPLAIN SELECT b.name\nFROM katalogbestilling_katalog a, medie b\nWHERE a.offlineid = b.id\nGROUP BY b.name\n" }, { "answer_id": 114423, "author": "Marcus King", "author_id": 19840, "author_profile": "https://Stackoverflow.com/users/19840", "pm_score": 0, "selected": false, "text": "SELECT a.name, COUNT(*) AS orders, COUNT(DISTINCT(b.kundeid)) AS leads\nFROM medie aINNER JOIN katalogbestilling_katalog b ON a.id = b.offline \nGROUP BY b.offline; SELECT a.name, \n COUNT(a.id) AS orders, \n (SELECT COUNT(kundeid) FROM katalogbestilling_katalog b WHERE b.offline = a.id) AS Leads\nFROM medie a;" }, { "answer_id": 115409, "author": "enobrev", "author_id": 14651, "author_profile": "https://Stackoverflow.com/users/14651", "pm_score": 0, "selected": false, "text": "CREATE TABLE `katalogbestilling_katalog` (\n `id` int(11) NOT NULL auto_increment,\n `offlineid` int(11) NOT NULL,\n `kundeid` int(11) NOT NULL,\n PRIMARY KEY (`id`),\n KEY `offline_id` (`offlineid`,`kundeid`)\n) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=60001 ;\n\nCREATE TABLE `medie` (\n `id` int(11) NOT NULL auto_increment,\n `name` varchar(255) NOT NULL,\n PRIMARY KEY (`id`)\n) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=30001 ;\n SELECT b.name, COUNT(*) AS orders, COUNT(DISTINCT(a.kundeid)) AS leads\nFROM medie b\nINNER JOIN katalogbestilling_katalog a ON b.id = a.offlineid\nGROUP BY a.offlineid\nLIMIT 0 , 30\n\n\n\"Showing rows 0 - 29 (30,000 total, Query took 0.0018 sec)\"\n id: 1\nselect_type: SIMPLE\ntable: a\ntype: index\npossible_keys: NULL\nkey: offline_id\nkey_len: 8\nref: NULL\nrows: 180000\nExtra: Using index\n\nid: 1\nselect_type: SIMPLE\ntable: b\ntype: eq_ref\npossible_keys: PRIMARY\nkey: PRIMARY\nkey_len: 4\nref: test.a.offlineid\nrows: 1\nExtra:\n" } ]
2008/09/22
[ "https://Stackoverflow.com/questions/114284", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9479/" ]