qid int64 4 19.1M | question stringlengths 18 48.3k | answers list | date stringlengths 10 10 | metadata list |
|---|---|---|---|---|
355,318 | <ol>
<li><p><strong>How do i redirect a url to domain .</strong>
eg. <a href="http://www.mydomain.com/index.php=HairThing" rel="nofollow noreferrer">http://www.mydomain.com/index.php=HairThing</a> --> <a href="http://www.mydomain.com" rel="nofollow noreferrer">http://www.mydomain.com</a></p></li>
<li><p><strong>How do i redirect a non-www to www WITHOUT a slash at end ?</strong></p></li>
</ol>
<p>eg <a href="http://mydomain.com" rel="nofollow noreferrer">http://mydomain.com</a> ---> <a href="http://www.mydomain.com" rel="nofollow noreferrer">http://www.mydomain.com</a></p>
| [
{
"answer_id": 355339,
"author": "Kent Fredric",
"author_id": 15614,
"author_profile": "https://Stackoverflow.com/users/15614",
"pm_score": 2,
"selected": false,
"text": "#1\nRewriteRule /index.php=HairThing$ http://www.mydomain.com [R=301]\n\n#2\nRewriteCond %{HTTP_HOST} ^mydomain.com \nRewriteRule .* http://www.mydomain.com [R=301] \n / mydomain.com # impossible \nmydomain.com/ # possible\nmydomain.com/foo #possible\nmydomain.com/foo/ #possible\n"
},
{
"answer_id": 705092,
"author": "Gabriel Solomon",
"author_id": 65503,
"author_profile": "https://Stackoverflow.com/users/65503",
"pm_score": 0,
"selected": false,
"text": "RewriteCond %{HTTP_HOST} !^www\\.[a-z0-9-]+\\.[a-z]{2,6} [NC]\nRewriteCond %{HTTP_HOST} ([a-z0-9-]+\\.[a-z]{2,6})$ [NC]\nRewriteRule (.*) http://www.%1/$1 [L,R=301]\n"
}
] | 2008/12/10 | [
"https://Stackoverflow.com/questions/355318",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
355,327 | <p>Does thread-safety of SQLite3 mean different threads can modify the same table of a database concurrently?</p>
| [
{
"answer_id": 2894848,
"author": "Jeremiah Rose",
"author_id": 234383,
"author_profile": "https://Stackoverflow.com/users/234383",
"pm_score": 2,
"selected": false,
"text": "check_same_thread"
}
] | 2008/12/10 | [
"https://Stackoverflow.com/questions/355327",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/26404/"
] |
355,333 | <p>I have a client that thought a highly dynamic ASP.NET application was a very simple sytem, yet to implement it in the manner in which they needed for future grown it has grown to well over 100 different code files.</p>
<p>I am looking for a way, most likely with some sort of static code analysis tool to put some numbers that might "make sense" to a non-technical person. I fully understand that Lines of Code and other metrics are not really "valid" items to evaluate, but in this case this is the type of thing I need, Lines of Code, Number of XML comments, Total Files, Total Folders. </p>
<p>I know I can look some of these up, but I'm looking for an easy way to get these values in bulk! I found a few old posts here, but nothing that specifically talked about .NET (Current versions) and/or C#.</p>
<p>Ideally I want something that can investigate a C# WAP project. SQL Server would be an AWESOME value add, but not a 100% needed item!</p>
| [
{
"answer_id": 2894848,
"author": "Jeremiah Rose",
"author_id": 234383,
"author_profile": "https://Stackoverflow.com/users/234383",
"pm_score": 2,
"selected": false,
"text": "check_same_thread"
}
] | 2008/12/10 | [
"https://Stackoverflow.com/questions/355333",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13279/"
] |
355,343 | <p>Does anyone know how to acess a url from a windows application?.</p>
<p>I have an address <a href="http://serverport/Page.I" rel="nofollow noreferrer">http://serverport/Page.I</a> want to acess this page from my windows application.</p>
<p>Regards,
Harsh Suman</p>
| [
{
"answer_id": 355348,
"author": "mmx",
"author_id": 33708,
"author_profile": "https://Stackoverflow.com/users/33708",
"pm_score": 2,
"selected": false,
"text": "WebBrowser System.Net.WebClient"
},
{
"answer_id": 355380,
"author": "Stein G. Strindhaug",
"author_id": 26115,
"author_profile": "https://Stackoverflow.com/users/26115",
"pm_score": 0,
"selected": false,
"text": "string targeturl= \"http://stackoverflow.com\";\n\ntry\n {\n System.Diagnostics.Process.Start(targeturl);\n }\ncatch\n ( \n System.ComponentModel.Win32Exception noBrowser) \n {\n if (noBrowser.ErrorCode==-2147467259)\n MessageBox.Show(noBrowser.Message);\n }\ncatch (System.Exception other)\n {\n MessageBox.Show(other.Message);\n }\n"
},
{
"answer_id": 355407,
"author": "Germstorm",
"author_id": 18631,
"author_profile": "https://Stackoverflow.com/users/18631",
"pm_score": 1,
"selected": false,
"text": " /// <summary>\n /// Downloads a file from the given location\n /// </summary>\n /// <param name=\"url\">Location of the file</param>\n /// <param name=\"dest\">The destination of the downloaded file</param>\n /// <returns>False if there was an error, else True</returns>\n public bool DownLoad(string url, string dest)\n {\n WebClient client = new WebClient();\n try\n {\n //Downloads the file from the given url to the given destination \n client.DownloadFile(url, dest);\n return true;\n }\n catch (WebException)\n {\n // Handle exception\n return false;\n }\n catch (System.Security.SecurityException)\n {\n // Handle exception\n return false;\n }\n catch (Exception)\n {\n // Handle exception\n return false;\n }\n }\n"
}
] | 2008/12/10 | [
"https://Stackoverflow.com/questions/355343",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
355,355 | <p>I am using <a href="http://www.svnkit.com" rel="nofollow noreferrer">SVNKit</a> in my application. I have a scenario wherein certain files should be ignored when doing svn operations. i.e. I need to set the svn:ignore property for certain patterns.</p>
<p>How do I do that using SVNKit?</p>
| [
{
"answer_id": 355363,
"author": "VonC",
"author_id": 6309,
"author_profile": "https://Stackoverflow.com/users/6309",
"pm_score": 3,
"selected": true,
"text": "addIgnorePattern() svn:ignore File dir = file.getParentFile().getAbsoluteFile();\nourClientManager.getWCClient().doSetProperty(dir, SVNProperty.IGNORE,\n file.getName(), false, false, null);\n svn:ignore a\\n\nb\\n\n*.bin\n"
}
] | 2008/12/10 | [
"https://Stackoverflow.com/questions/355355",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/35392/"
] |
355,358 | <p>I can't connect to the default web site in IIS 6.0 using localhost or 127.0.0.1 or by server name. When I telnet to port 80 with one of these names, there's no connection.</p>
<p>However other web sites are running and I can telnet using any of the ip addresses.
I can ping to localhost where 127.0.0.1 is responding.
The default web site is running. It's not stopped.</p>
| [
{
"answer_id": 356083,
"author": "Samiksha",
"author_id": 29515,
"author_profile": "https://Stackoverflow.com/users/29515",
"pm_score": 0,
"selected": false,
"text": "*.(your site url)"
}
] | 2008/12/10 | [
"https://Stackoverflow.com/questions/355358",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5232/"
] |
355,365 | <p>The Java AtomicInteger class has a method -</p>
<pre><code>boolean weakCompareAndSet(int expect,int update)
</code></pre>
<p>Its documnentation says:</p>
<blockquote>
<p>May fail spuriously.</p>
</blockquote>
<p>What does 'failing spuriously' here mean?</p>
| [
{
"answer_id": 355374,
"author": "Michael Burr",
"author_id": 12711,
"author_profile": "https://Stackoverflow.com/users/12711",
"pm_score": 3,
"selected": false,
"text": "CompareAndSet()"
},
{
"answer_id": 355392,
"author": "VonC",
"author_id": 6309,
"author_profile": "https://Stackoverflow.com/users/6309",
"pm_score": 4,
"selected": false,
"text": "atomic"
}
] | 2008/12/10 | [
"https://Stackoverflow.com/questions/355365",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14316/"
] |
355,386 | <p>Please let me know why there is lot of white space below the page content and also why horizontal scroll bar is displayed. Attaching link to zip folder below. Unzip and open index.html.<br />
<a href="http://shivanand.in/tmp/Basic_Profile.zip" rel="nofollow noreferrer">link text</a></p>
| [
{
"answer_id": 355421,
"author": "VonC",
"author_id": 6309,
"author_profile": "https://Stackoverflow.com/users/6309",
"pm_score": 3,
"selected": true,
"text": "div#content content div#content { margin: 3px 3px 3px 188px; background: rgb(255, 255, 255) none \n repeat; min-height: 392px; }\n container div#container { margin: auto; padding: 10px; background: rgb(255, 255, 255) \n none repeat; position: relative; min-height: 400px; \n max-width: 100%; min-width: 750px; }\n overflow: hidden div#container"
}
] | 2008/12/10 | [
"https://Stackoverflow.com/questions/355386",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/34642/"
] |
355,398 | <p>How do I segment a 2D image into blobs of similar values efficiently? The given input is a n array of integer, which includes hue for non-gray pixels and brightness of gray pixels.</p>
<p>I am writing a virtual mobile robot using Java, and I am using segmentation to analyze the map and also the image from the camera. This is a well-known problem in <a href="http://en.wikipedia.org/wiki/Computer_vision" rel="nofollow noreferrer">Computer Vision</a>, but when it's on a robot performance does matter so I wanted some inputs. Algorithm is what matters, so you can post code in any language.</p>
<ul>
<li>Wikipedia article: <a href="http://en.wikipedia.org/wiki/Segmentation_%28image_processing%29" rel="nofollow noreferrer">Segmentation (image processing)</a></li>
<li><a href="http://robots.stanford.edu/cs223b04/CS%20223-B%20L11%20Segmentation.ppt" rel="nofollow noreferrer">[PPT] Stanford CS-223-B Lecture 11 Segmentation and Grouping</a> (which says Mean Shift is perhaps the best technique to date)</li>
<li><a href="http://www.caip.rutgers.edu/~comanici/MSPAMI/msPamiResults.html" rel="nofollow noreferrer">Mean Shift Pictures</a> (paper is also available from <a href="http://www.caip.rutgers.edu/~comanici/" rel="nofollow noreferrer">Dorin Comaniciu</a>)</li>
</ul>
| [
{
"answer_id": 355417,
"author": "Eugene Yokota",
"author_id": 3827,
"author_profile": "https://Stackoverflow.com/users/3827",
"pm_score": 0,
"selected": false,
"text": "UNSEGMENTED UNSEGMENTED EPSILON private boolean isValuesCloseEnough(int a_lhs, int a_rhs) {\n return Math.abs(a_lhs - a_rhs) <= EPSILON;\n}\n UNSEGMENTED"
}
] | 2008/12/10 | [
"https://Stackoverflow.com/questions/355398",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3827/"
] |
355,425 | <p>I need to write a script to change a filename from aDate.txt to bDate.txt where:</p>
<ul>
<li>aDate is the current system date in <em>yyyymmdd</em> format and </li>
<li>bDate is the current system date - 1 in <em>yyyymmdd</em> format.</li>
</ul>
<p>I currently have:</p>
<pre><code>set yy=%date:~6,2%
set mm=%date:~3,2%
set dd=%date:~0,2%
if "%date:~6,1%"==" " set yy=0%yy:~1,1%
if "%date:~3,1%"==" " set mm=0%mm:~1,1%
if "%date:~0,1%"==" " set dd=0%dd:~1,1%
SET sys_date=20%yy%%mm%%dd%
ECHO %sys_date%
REM still have to do this bit properly
SET sys_date_yesterday=%sys_date%a
move %sys_date%.txt %sys_date_yesterday%.txt
</code></pre>
<p>but I have no idea how to do the date -1 thing (other than the long winded) subtract 1 from the day and if that is = 0 then subtract one from the month and set the day = to the last day of the new month and so on for years.</p>
<p>Any ideas?</p>
| [
{
"answer_id": 355561,
"author": "wimh",
"author_id": 33499,
"author_profile": "https://Stackoverflow.com/users/33499",
"pm_score": 3,
"selected": false,
"text": "@echo off\n\nset yyyy=\n\nset $tok=1-3\nfor /f \"tokens=1 delims=.:/-, \" %%u in ('date /t') do set $d1=%%u\nif \"%$d1:~0,1%\" GTR \"9\" set $tok=2-4\nfor /f \"tokens=%$tok% delims=.:/-, \" %%u in ('date /t') do (\n for /f \"skip=1 tokens=2-4 delims=/-,().\" %%x in ('echo.^|date') do (\n set %%x=%%u\n set %%y=%%v\n set %%z=%%w\n set $d1=\n set $tok=))\n\nif \"%yyyy%\"==\"\" set yyyy=%yy%\nif /I %yyyy% LSS 100 set /A yyyy=2000 + 1%yyyy% - 100\n\nset CurDate=%mm%/%dd%/%yyyy%\n\nset dayCnt=%1\n\nif \"%dayCnt%\"==\"\" set dayCnt=1\n\nREM Substract your days here\nset /A dd=1%dd% - 100 - %dayCnt%\nset /A mm=1%mm% - 100\n\n:CHKDAY\n\nif /I %dd% GTR 0 goto DONE\n\nset /A mm=%mm% - 1\n\nif /I %mm% GTR 0 goto ADJUSTDAY\n\nset /A mm=12\nset /A yyyy=%yyyy% - 1\n\n:ADJUSTDAY\n\nif %mm%==1 goto SET31\nif %mm%==2 goto LEAPCHK\nif %mm%==3 goto SET31\nif %mm%==4 goto SET30\nif %mm%==5 goto SET31\nif %mm%==6 goto SET30\nif %mm%==7 goto SET31\nif %mm%==8 goto SET31\nif %mm%==9 goto SET30\nif %mm%==10 goto SET31\nif %mm%==11 goto SET30\nREM ** Month 12 falls through\n\n:SET31\n\nset /A dd=31 + %dd%\n\ngoto CHKDAY\n\n:SET30\n\nset /A dd=30 + %dd%\n\ngoto CHKDAY\n\n:LEAPCHK\n\nset /A tt=%yyyy% %% 4\n\nif not %tt%==0 goto SET28\n\nset /A tt=%yyyy% %% 100\n\nif not %tt%==0 goto SET29\n\nset /A tt=%yyyy% %% 400\n\nif %tt%==0 goto SET29\n\n:SET28\n\nset /A dd=28 + %dd%\n\ngoto CHKDAY\n\n:SET29\n\nset /A dd=29 + %dd%\n\ngoto CHKDAY\n\n:DONE\n\nif /I %mm% LSS 10 set mm=0%mm%\nif /I %dd% LSS 10 set dd=0%dd%\n\necho Date %dayCnt% day(s) before %CurDate% is %mm%/%dd%/%yyyy%\n"
},
{
"answer_id": 10475805,
"author": "Batch Scripter",
"author_id": 1378821,
"author_profile": "https://Stackoverflow.com/users/1378821",
"pm_score": 1,
"selected": false,
"text": "IF \"%1\"==\"\" goto modifydate\n\n:modifydate\nSET subtractdays=5\nSET ModDateScript=\\\\servershare\\path\\Called_Scripts\\ModDate.cmd\nCALL \"%ModDateScript%\" %subtractdays% \"%~fnx0\"\n SET moddate=%mm%/%dd%/%yyyy%\nCall %2 %moddate%\nGOTO EOF\n set yyyy=\nset $tok=1-3\nfor /f \"tokens=1 delims=.:/-, \" %%u in ('date /t') do set $d1=%%u\nif \"%$d1:~0,1%\" GTR \"9\" set $tok=2-4\nfor /f \"tokens=%$tok% delims=.:/-, \" %%u in ('date /t') do (\nfor /f \"skip=1 tokens=2-4 delims=/-,().\" %%x in ('echo.^|date') do (\n set %%x=%%u\n set %%y=%%v\n set %%z=%%w\n set $d1=\n set $tok=))\nif \"%yyyy%\"==\"\" set yyyy=%yy%\nif /I %yyyy% LSS 100 set /A yyyy=2000 + 1%yyyy% - 100\n FOR /F \"tokens=2-4 delims=/ \" %%A IN (\"%date%\") DO SET \"mm=%%A\" DO (& SET \"dd=%%B\") DO (& SET \"yyyy=%%C\")\n"
},
{
"answer_id": 10974401,
"author": "Batch Scripter",
"author_id": 1448123,
"author_profile": "https://Stackoverflow.com/users/1448123",
"pm_score": 1,
"selected": false,
"text": ":: Pass 1st parameter as number of days (whole numbers) to subtract from current day in date\n:: This script is able to subtract days to any date of the current date\n:: This script will check for leap years, etc. as well\n@echo on\n::for /f \"tokens=2-4 delims=/ \" %%A in (\"%date%\") do set \"mm=%%A\" do & set \"dd=%%B\" do & set \"yyyy=%%C\"\nset \"mm=%date:~4,2%\" & set \"dd=%date:~7,2%\" & set \"yyyy=%date:~10,4%\"\nset CurDate=%mm%/%dd%/%yyyy%\nset dayCnt=%1\nif \"%dayCnt%\"==\"\" set dayCnt=1\n:: Substract your days here\nset /A dd=1%dd% - 100 - %dayCnt%\nset /A mm=1%mm% - 100\n:CHKDAY\nif /I %dd% GTR 0 goto DONE\nset /A mm=%mm% - 1\nif /I %mm% GTR 0 goto ADJUSTDAY\nset /A mm=12\nset /A yyyy=%yyyy% - 1\n:ADJUSTDAY\nif %mm%==1 goto SET31\nif %mm%==2 goto LEAPCHK\nif %mm%==3 goto SET31\nif %mm%==4 goto SET30\nif %mm%==5 goto SET31\nif %mm%==6 goto SET30\nif %mm%==7 goto SET31\nif %mm%==8 goto SET31\nif %mm%==9 goto SET30\nif %mm%==10 goto SET31\nif %mm%==11 goto SET30\n:: ** Month 12 falls through\n:SET31\nset /A dd=31 + %dd%\ngoto CHKDAY\n:SET30\nset /A dd=30 + %dd%\ngoto CHKDAY\n:LEAPCHK\nset /A tt=%yyyy% %% 4\nif not %tt%==0 goto SET28\nset /A tt=%yyyy% %% 100\nif not %tt%==0 goto SET29\nset /A tt=%yyyy% %% 400\nif %tt%==0 goto SET29\n:SET28\nset /A dd=28 + %dd%\ngoto CHKDAY\n:SET29\nset /A dd=29 + %dd%\ngoto CHKDAY\n:DONE\nif /I %mm% LSS 10 set mm=0%mm%\nif /I %dd% LSS 10 set dd=0%dd%\necho Date %dayCnt% day(s) before %CurDate% is %mm%/%dd%/%yyyy%\nSET DirDate=%mm%/%dd%/%yyyy%\n:: The %2 parameter is passed from the calling script as the full path and name of the file to call back\n:: %2 equals %~fnx0\n:: The dirdate variable is passed as parameter %1 back to the calling script\nCall %2 %dirdate%\nGOTO EOF\n"
},
{
"answer_id": 38531649,
"author": "Bitcoin Murderous Maniac",
"author_id": 5458310,
"author_profile": "https://Stackoverflow.com/users/5458310",
"pm_score": 2,
"selected": false,
"text": "- :DynamicVBSScriptBuild ,-%MinusDay%, ,%MinusDay%, MinusDay= 99999 MinusDays= 999999 MinusDays= @ECHO ON\n\n::// Minus days is the number of days to subtract from the CURRENT DAY i.e. 2 for minus 2 days or 99999 for minus 99999 days from when it's run\nSET MinusDay=2\n\n:: This calls the temp vbs script routine that will be used to set YYYY-MM-DD values for the subtracted days date you specify\nCALL :DynamicVBSScriptBuild\n\nFOR /F \"TOKENS=*\" %%A IN ('cscript//nologo \"%YYYYTmpVBS%\"') DO SET YYYY=%%A\nFOR /F \"TOKENS=*\" %%A IN ('cscript//nologo \"%MMTmpVBS%\"') DO SET MM=%%A\nFOR /F \"TOKENS=*\" %%A IN ('cscript//nologo \"%DDTmpVBS%\"') DO SET DD=%%A\n\n::// Set your web server log file path in the below variable\nSET WebServerLogPath=C:\\WebServer\\Logs\n\n::// Set web server log file name where YYYY MM DD variables are set to the values after the day numbers setup above are subtracted\nSET YYYY=%YYYY%\nSET MM=%MM%\nSET DD=%DD%\n\nECHO %YYYY%%MM%%DD%\nPAUSE\n\nGOTO EOF\n\n:DynamicVBSScriptBuild\nSET YYYYTmpVBS=%temp%\\~tmp_yyyy.vbs\nSET MMTmpVBS=%temp%\\~tmp_mm.vbs\nSET DDTmpVBS=%temp%\\~tmp_dd.vbs\nIF EXIST \"%YYYYTmpVBS%\" DEL /Q /F \"%YYYYTmpVBS%\"\nIF EXIST \"%MMTmpVBS%\" DEL /Q /F \"%MMTmpVBS%\"\nIF EXIST \"%DDTmpVBS%\" DEL /Q /F \"%DDTmpVBS%\"\nECHO dt = DateAdd(\"d\",-%MinusDay%,date) >> \"%YYYYTmpVBS%\"\nECHO yyyy = Year(dt) >> \"%YYYYTmpVBS%\"\nECHO WScript.Echo yyyy >> \"%YYYYTmpVBS%\"\nECHO dt = DateAdd(\"d\",-%MinusDay%,date) >> \"%MMTmpVBS%\"\nECHO mm = Right(\"0\" ^& Month(dt),2) >> \"%MMTmpVBS%\"\nECHO WScript.Echo mm >> \"%MMTmpVBS%\"\nECHO dt = DateAdd(\"d\",-%MinusDay%,date) >> \"%DDTmpVBS%\"\nECHO dd = Right(\"0\" ^& Day(dt),2) >> \"%DDTmpVBS%\"\nECHO WScript.Echo dd >> \"%DDTmpVBS%\"\nGOTO EOF\n"
},
{
"answer_id": 59104992,
"author": "f.cipriani",
"author_id": 599072,
"author_profile": "https://Stackoverflow.com/users/599072",
"pm_score": 1,
"selected": false,
"text": "set YY=%date:~-4,4%\nset MM=%date:~-7,2%\nset DD=%date:~-10,2\ncall datemath.bat %YY% %MM% %DD% - 1\necho year=%_yy_int%, month=%_mm_int%, day=%_dd_int%\necho padded date:%_ymd_str%, padded month:%_mm_str%, padded day:%_dd_str%\n @ECHO off\n SETLOCAL\n :: DateMath, a general purpose date math routine\n\n :: If DateMath detects an error, variable _dd_int is set to 999999.\n SET v_dd_int=0\n SET v_mm_int=0 \n SET v_yy_int=0\n SET v_ymd_str=\n SET v_mm_str=\n SET v_dd_str=\n\n IF \"%3\"==\"\" goto s_syntax\n IF \"%4\"==\"+\" goto s_validate_year\n IF \"%4\"==\"-\" goto s_validate_year\n IF \"%4\"==\"\" goto s_validate_year\n\n :s_syntax\n echo:\n echo DATEMATH SYNTAX:\n echo _______________\n echo:\n echo DateMath will set the variables as listed below\n echo 'str' variables include leading zeros e.g. \"01\"\n echo 'int' variables leading zeros are stripped e.g. \"1\"\n echo:\n echo CALL DateMath YY MM DD - YY2 MM2 DD2 \n echo:\n echo Will set variable _dd_int to the signed difference\n echo between the 2 dates (measured in days)\n echo:\n echo:\n echo CALL DateMath YY MM DD +/- Days \n echo:\n echo Will set the following variables to the result of \n echo adding or substracting days from the initial date:\n echo _ymd_str, _yy_int\n echo _mm_str, _mm_int,\n echo _dd_str, _dd_int\n echo:\n echo:\n echo ___________________________________\n pause\n\n echo:\n echo:\n echo CALL DateMath YY MM DD\n echo:\n echo Will set the following variables:\n echo _ymd_str, _yy_int\n echo _mm_str, _mm_int,\n echo _dd_str, _dd_int\n echo:\n echo ___________________________________\n echo:\n echo _ymd_str is in YYYYMMDD format.\n echo:\n echo _yy_int is in YYYY format, even if YY format was originally supplied.\n echo This conversion is useful for FAT/NTFS file dates which are in YY format.\n echo:\n\n ENDLOCAL & SET /a _dd_int=999999\n goto :eof\n\n :s_validate_year\n ::strip leading zeros\n SET v_yy=%1\n if %v_yy:~0,1% EQU 0 set v_yy=%v_yy:~1%\n\n :: Check for Y2K\n IF %v_yy% LSS 100 IF %v_yy% GEQ 80 SET /A v_yy += 1900\n IF %v_yy% LSS 80 SET /A v_yy += 2000\n\n :: at this point v_yy contains a 4 digit year\n\n ::validate month and day\n if %2 GTR 12 goto s_syntax\n if %3 GTR 31 goto s_syntax\n\n SET v_mm=%2\n SET v_dd=%3\n\n ::strip leading zeros\n if %v_mm:~0,1% EQU 0 set v_mm=%v_mm:~1%\n if %v_dd:~0,1% EQU 0 set v_dd=%v_dd:~1%\n\n :: Set the int variables\n SET /a v_dd_int=%v_dd%\n SET /a v_yy_int=%v_yy%\n SET /a v_mm_int=%v_mm%\n\n :: Determine which function to perform - ADD, SUBTRACT or CONVERT\n\n If not \"%6\"==\"\" goto s_validate_2nd_date \n if \"%4\"==\"\" goto s_convert_only\n\n :: Add or subtract days to a date\n SET /a v_number_of_days=%5\n goto s_add_or_subtract_days\n\n :s_convert_only\n\n SET /a v_dd_int=%v_dd%\n IF %v_dd% LEQ 9 (SET v_dd_str=0%v_dd%) ELSE (SET v_dd_str=%v_dd%)\n IF %v_mm% LEQ 9 (SET v_mm_str=0%v_mm%) ELSE (SET v_mm_str=%v_mm%)\n SET v_ymd_str=%v_yy%%v_mm_str%%v_dd_str%\n\n ECHO DATEMATH - Convert date only (no maths)\n goto s_end\n ::::::::::::::::::::::::::::::::::::::::::::::::::\n\n :s_validate_2nd_date\n If \"%4\"==\"+\" goto s_syntax\n :: Subtracting one date from another ::::::\n :: strip leading zero\n SET v_yy2=%5\n if %v_yy2:~0,1% EQU 0 set v_yy2=%v_yy2:~1%\n\n if %v_yy2% GTR 99 goto s_validate2nd_month\n if %v_yy2% GTR 49 goto s_prefix_2_1950_1999\n if %v_yy2% LSS 10 goto s_prefix_2_2000_2009\n SET v_yy2=20%v_yy2%\n goto s_validate2nd_month\n\n :s_prefix_2_2000_2009\n SET v_yy2=200%v_yy2%\n goto s_validate2nd_month\n\n :s_prefix_2_1950_1999\n SET v_yy2=19%v_yy2%\n\n :s_validate2nd_month\n ::strip leading zeros\n ::SET /a v_yy2=%v_yy2%\n if %v_yy2:~0,1% EQU 0 set v_yy2=%v_yy2:~1%\n ::v_yy2 now contains a 4 digit year\n\n if %6 GTR 12 goto s_syntax\n SET v_mm2=%6\n\n if %7 GTR 31 goto s_syntax\n SET v_dd2=%7\n\n ::strip leading zeros\n ::SET /a v_mm2=%v_mm2%\n if %v_mm2:~0,1% EQU 0 set v_mm2=%v_mm2:~1%\n ::SET /a v_dd2=%v_dd2%\n if %v_dd2:~0,1% EQU 0 set v_dd2=%v_dd2:~1%\n\n call :s_julian_day %v_yy_int% %v_mm_int% %v_dd_int%\n SET v_sumdays1=%v_JulianDay%\n\n call :s_julian_day %v_yy2% %v_mm2% %v_dd2%\n SET v_sumdays2=%v_JulianDay%\n\n SET /a v_dd_int=%v_sumdays1% - %v_sumdays2%\n\n ECHO DATEMATH - Subtracting one date from another = days difference\n ECHO ~~~~~~\n ECHO %v_dd_int%\n ECHO ~~~~~~\n goto s_end_days\n ::::::::::::::::::::::::::::::::::::::::::::::::::\n\n :s_add_or_subtract_days\n if /i \"%4\"==\"+\" goto s_add_up_days\n\n :: Subtract all days ::::::\n SET /a v_dd=%v_dd% - %v_number_of_days%\n\n :s_adjust_month_year\n if %v_dd% GEQ 1 goto s_add_subtract_days_DONE\n SET /a v_mm=%v_mm% - 1\n if %v_mm% GEQ 1 goto s_add_days_%v_mm%\n SET /a v_yy=%v_yy% - 1\n SET /a v_mm=%v_mm% + 12\n goto s_add_days_%v_mm%\n\n :s_add_days_2\n SET /a v_dd=%v_dd% + 28\n SET /a v_leapyear=%v_yy% / 4\n SET /a v_leapyear=%v_leapyear% * 4\n if %v_leapyear% NEQ %v_yy% goto s_adjust_month_year\n SET /a v_dd=%v_dd% + 1\n goto s_adjust_month_year\n\n :s_add_days_4\n :s_add_days_6\n :s_add_days_9\n :s_add_days_11\n SET /a v_dd=%v_dd% + 30\n goto s_adjust_month_year\n\n :s_add_days_1\n :s_add_days_3\n :s_add_days_5\n :s_add_days_7\n :s_add_days_8\n :s_add_days_10\n :s_add_days_12\n SET /a v_dd=%v_dd% + 31\n goto s_adjust_month_year\n\n :s_add_up_days\n :: add all days ::::::\n SET /a v_dd=%v_dd% + %v_number_of_days%\n\n :s_subtract_days_\n goto s_subtract_days_%v_mm%\n\n :s_adjust_mth_yr\n SET /a v_mm=%v_mm% + 1\n if %v_mm% LEQ 12 goto s_subtract_days_%v_mm%\n SET /a v_yy=%v_yy% + 1\n SET /a v_mm=%v_mm% - 12\n goto s_subtract_days_%v_mm%\n\n :s_subtract_days_2\n SET /a v_leapyear=%v_yy% / 4\n SET /a v_leapyear=%v_leapyear% * 4\n If %v_leapyear% EQU %v_yy% goto s_subtract_leapyear\n\n if %v_dd% LEQ 28 goto s_add_subtract_days_DONE\n SET /a v_dd=%v_dd% - 28\n goto s_adjust_mth_yr\n\n :s_subtract_leapyear\n if %v_dd% LEQ 29 goto s_add_subtract_days_DONE\n SET /a v_dd=%v_dd% - 29\n goto s_adjust_mth_yr\n\n :s_subtract_days_4\n :s_subtract_days_6\n :s_subtract_days_9\n :s_subtract_days_11\n if %v_dd% LEQ 30 goto s_add_subtract_days_DONE\n SET /a v_dd=%v_dd% - 30\n goto s_adjust_mth_yr\n\n :s_subtract_days_1\n :s_subtract_days_3\n :s_subtract_days_5\n :s_subtract_days_7\n :s_subtract_days_8\n :s_subtract_days_10\n :s_subtract_days_12\n if %v_dd% LEQ 31 goto s_add_subtract_days_DONE\n SET /a v_dd=%v_dd% - 31\n goto s_adjust_mth_yr\n\n :s_add_subtract_days_DONE\n SET /a v_dd_int=%v_dd%\n SET /a v_mm_int=%v_mm%\n SET /a v_yy_int=%v_yy%\n IF %v_dd% GTR 9 (SET v_dd_str=%v_dd%) ELSE (SET v_dd_str=0%v_dd%)\n IF %v_mm% GTR 9 (SET v_mm_str=%v_mm%) ELSE (SET v_mm_str=0%v_mm%)\n SET v_ymd_str=%v_yy%%v_mm_str%%v_dd_str%\n\n ECHO DATEMATH - add or subtract days from a date = new date\n goto s_end\n ::::::::::::::::::::::::::::::::::::::::::::::::::\n\n :s_julian_day\n SET v_year=%1\n SET v_month=%2\n SET v_day=%3\n\n SET /a v_month=v_month\n SET /a v_day=v_day\n\n SET /A a = 14 - v_month\n SET /A a /= 12\n SET /A y = v_year + 4800 - a\n SET /A m = v_month + 12 * a - 3\n SET /A m = 153 * m + 2\n SET /A m /= 5\n SET /A v_JulianDay = v_day + m + 365 * y + y / 4 - y / 100 + y / 400 - 32045\n\n ECHO The Julian Day is [%v_JulianDay%]\n goto :eof\n ::::::::::::::::::::::::::::::::::::::::::::::::::\n\n :s_end\n ECHO ~~~~~~~~~~~~\n ECHO [%v_ymd_str%] YY=[%v_yy_int%] MM=[%v_mm_str%] DD=[%v_dd_str%]\n ECHO ~~~~~~~~~~~~\n :s_end_days\n ENDLOCAL&SET /a _yy_int=%v_yy_int%&SET /a _mm_int=%v_mm_int%&SET /a _dd_int=%v_dd_int%&SET _ymd_str=%v_ymd_str%&SET _mm_str=%v_mm_str%&SET _dd_str=%v_dd_str%\n"
},
{
"answer_id": 64677803,
"author": "npocmaka",
"author_id": 388389,
"author_profile": "https://Stackoverflow.com/users/388389",
"pm_score": 0,
"selected": false,
"text": "dayAdder.bat @if (@X) == (@Y) @end /* JScript comment \n @echo off \n cscript //E:JScript //nologo \"%~f0\" %*\n exit /b %errorlevel% \n@if (@X)==(@Y) @end JScript comment */\n\nvar days=parseInt(WScript.Arguments.Item(0));\n\n\nDate.prototype.addDays = function(days) {\n var date = new Date(this.valueOf());\n date.setDate(date.getDate() + days);\n return date;\n}\n\nvar date = new Date();\n\nWScript.Echo(date.addDays(5));\nWScript.Echo(\"Year: \" + date.getFullYear());\nWScript.Echo(\"Month: \" + date.getMonth());\nWScript.Echo(\"DayOfTeWEek: \" + date.getDay());\n E:\\scripts>dayAdder.bat 7\nSun Nov 8 16:27:48 UTC+0200 2020\nYear: 2020\nMonth: 10\nDayOfTeWEek: 2\nDayOfTheMonth: 3\n"
}
] | 2008/12/10 | [
"https://Stackoverflow.com/questions/355425",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/939/"
] |
355,447 | <p>I have some documentation written in OpenOffice, and I would like to include some of it as PDF files in the final build deliveries. I would like to do this with the automated build script.</p>
<p>Is there a way to create a PDF file from OpenOffice with a command line command?</p>
| [
{
"answer_id": 355470,
"author": "OscarRyz",
"author_id": 20654,
"author_profile": "https://Stackoverflow.com/users/20654",
"pm_score": 5,
"selected": true,
"text": " File inputFile = new File(\"C:\\\\oreyes\\\\hola.doc\"); \n File outputFile = new File(\"C:\\\\oreyes\\\\hola.pdf\"); \n OpenOfficeConnection connection = new SocketOpenOfficeConnection(8100);\n try { \n connection.connect(); \n } catch(Exception e) {}\n\n DocumentConverter converter = new OpenOfficeDocumentConverter(connection);\n converter.convert(inputFile, outputFile); \n connection.disconnect(); \n"
},
{
"answer_id": 12508753,
"author": "Eineki",
"author_id": 29125,
"author_profile": "https://Stackoverflow.com/users/29125",
"pm_score": 5,
"selected": false,
"text": "lowriter --headless --convert-to pdf yourfile.odt\n lowriter --headless --convert-to pdf yourfiles*.odt\n"
},
{
"answer_id": 23736944,
"author": "Michael Helwig",
"author_id": 3114552,
"author_profile": "https://Stackoverflow.com/users/3114552",
"pm_score": 2,
"selected": false,
"text": "lowriter libreoffice loffice loffice --headless --convert-to pdf yourfile.odt Error: Please reverify input parameters..."
}
] | 2008/12/10 | [
"https://Stackoverflow.com/questions/355447",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6482/"
] |
355,449 | <p>Hey folks - I'm writing a pretty simple iPhone application. The data comes from a plist file (NSDictionary basically), that I'm trying to load into a singleton class and use across my various view controllers to access the data.</p>
<p>Here's the implementation for my singleton (heavily modeled after <a href="https://stackoverflow.com/questions/145154/what-does-your-objective-c-singleton-look-like">this thread</a>)</p>
<pre><code>@implementation SearchData
@synthesize searchDict;
@synthesize searchArray;
- (id)init {
if (self = [super init]) {
NSString *path = [[NSBundle mainBundle] bundlePath];
NSString *finalPath = [path stringByAppendingPathComponent:@"searches.plist"];
searchDict = [NSDictionary dictionaryWithContentsOfFile:finalPath];
searchArray = [searchDict allKeys];
}
return self;
}
- (void)dealloc {
[searchDict release];
[searchArray release];
[super dealloc];
}
static SearchData *sharedSingleton = NULL;
+ (SearchData *)sharedSearchData {
@synchronized(self) {
if (sharedSingleton == NULL)
sharedSingleton = [[self alloc] init];
}
return(sharedSingleton);
}
@end
</code></pre>
<p>So whenever I try to access the searchDict or searchArray properties elsewhere in my application (like a TableView delegate) like so:</p>
<pre><code>[[[SearchData sharedSearchData] searchArray] objectAtIndex:indexPath.row]
</code></pre>
<p>I get an exception stating *** -[NSCFSet objectAtIndex:]: unrecognized selector sent to instance 0x5551f0</p>
<p>I'm not really sure why the objectAtIndex message is being sent to an NSCFSet object, I feel like my singleton is implemented wrong or something. I also tried a more complex singleton implementation like the one recommended by apple in the <a href="https://stackoverflow.com/questions/145154/what-does-your-objective-c-singleton-look-like">aforementioned thread</a> and had the same problem. Thanks for any insight you can provide.</p>
| [
{
"answer_id": 355461,
"author": "Ashley Clark",
"author_id": 4556,
"author_profile": "https://Stackoverflow.com/users/4556",
"pm_score": 5,
"selected": true,
"text": "-init searchDict = [[NSDictionary alloc] initWithContentsOfFile:finalPath];\nsearchArray = [[searchDict allKeys] retain];\n"
},
{
"answer_id": 356125,
"author": "Chris Jefferson",
"author_id": 27074,
"author_profile": "https://Stackoverflow.com/users/27074",
"pm_score": 1,
"selected": false,
"text": "- (id)init {\n if (self = [super init]) {\n NSString *path = [[NSBundle mainBundle] bundlePath];\n NSString *finalPath = [path stringByAppendingPathComponent:@\"searches.plist\"];\n self.searchDict = [NSDictionary dictionaryWithContentsOfFile:finalPath];\n self.searchArray = [searchDict allKeys];\n }\n\n return self;\n"
}
] | 2008/12/10 | [
"https://Stackoverflow.com/questions/355449",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/44858/"
] |
355,456 | <p>Is it possible to get the current source line number in Perl?
The equivalent in C++ is <code>__LINE__</code>.</p>
| [
{
"answer_id": 355464,
"author": "Eugene Yokota",
"author_id": 3827,
"author_profile": "https://Stackoverflow.com/users/3827",
"pm_score": 7,
"selected": true,
"text": "__LINE__ print \"File: \", __FILE__, \" Line: \", __LINE__, \"\\n\";\n warn(\"foo\");\n"
},
{
"answer_id": 358293,
"author": "bigiain",
"author_id": 11590,
"author_profile": "https://Stackoverflow.com/users/11590",
"pm_score": 3,
"selected": false,
"text": "$ perl -e'warn(\"foo\")'\nfoo at -e line 1.\n $ perl -e'warn(\"foo\\n\")'\nfoo\n perldoc -f die perldoc -f warn die"
},
{
"answer_id": 9453458,
"author": "cnd",
"author_id": 1233840,
"author_profile": "https://Stackoverflow.com/users/1233840",
"pm_score": 2,
"selected": false,
"text": "while(my @where=caller($frame++)) { print \"$frame:\" . join(\",\",@where) . \"\\n\"; }\n"
}
] | 2008/12/10 | [
"https://Stackoverflow.com/questions/355456",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/259/"
] |
355,459 | <p>I have a big red button and I'm trying to use javascript to perform the following: -</p>
<ol>
<li>OnMouseDown change image so the button looks depressed</li>
<li>OnMouseUp return to the initial image AND reveal a hidden div</li>
</ol>
<p>I can get the onMouse Down and onMouseUp image changes part to work.</p>
<p>I can also get the hidden div to reveal by using OnClick</p>
<p>The problem is I can't get it all to work together. </p>
<p>How do I do this?</p>
<p>BTW, I'm sure its obvious, but I'm fairly new to javascript, so I appreciate your help</p>
| [
{
"answer_id": 355484,
"author": "Jonathan Lonowski",
"author_id": 15031,
"author_profile": "https://Stackoverflow.com/users/15031",
"pm_score": 2,
"selected": true,
"text": "<img src=\"...\" alt=\"...\"\n onmousedown=\"depressed();\"\n onmouseup=\"undepressed(); revealDiv();\" />\n <img src=\"...\" alt=\"...\"\n onmousedown=\"depressed();\"\n onmouseup=\"undepressed();\"\n onclick=\"revealDiv();\" />\n"
},
{
"answer_id": 360547,
"author": "Andreas Grech",
"author_id": 44084,
"author_profile": "https://Stackoverflow.com/users/44084",
"pm_score": 0,
"selected": false,
"text": "<img id=\"abut\" />\n\n<script>\nvar thebutton = document.getElementById('abut'); //Retrieve the button from the page \nthebutton.onmousedown = depressed; //depressed is a function that you declare earlier on...here, you are just passing a reference to it\nthebutton.onmouseup = function () {\n undepressed();\n revealDiv(); //Invoke the two functions when the 'onmouseup' is triggered'\n};\n</script>\n"
}
] | 2008/12/10 | [
"https://Stackoverflow.com/questions/355459",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
355,473 | <p>I want to handle different types of docs the same way in my application
Therefore:
I have a generic interface like this.</p>
<pre><code>public interface IDocHandler<T>where T: class
{
T Document { get;set;}
void Load(T doc);
void Load(string PathToDoc);
void Execute();
void Execute(T doc);
}
</code></pre>
<p>And for different types of documents I implement this interface.</p>
<p>for example:</p>
<pre><code>public class FinanceDocumentProcessor:IDocumentHandler<ReportDocument>
{}
public class MarketingDocumentProcessor:IDocumentHandler<MediaDocument>
{}
</code></pre>
<p>Then I can do of course something like this:</p>
<pre><code>IDocumentHandler<ReportDocument> docProc= new FinanceDocumentProcessor();
</code></pre>
<p>It would be interessting to know how I could inject T at runtime to make the line above loosly coupled...</p>
<pre><code>IDocumentHandler<ReportDocument> docProc = container.resolve("FinanceDocumentProcessor());
</code></pre>
<p>but I want to decide per Configuration wether I want to have my FinanceDomcumentProcessor or my MarketingDocumentProcessor... therefore I would have to inject T on the left site, too ...
Since I have to use c# 2.0 I can not use the magic word "var" which would help a lot in this case... but how can I design this to be open and flexible...</p>
<hr>
<p>Sorry for the misunderstanding and thanks for all the comments but I have another example for my challenge (maybe I am using the wrong design for that) ...
But I give it a try: Same situation but different Explanation</p>
<p>Example Image I have:</p>
<p>ReportingService, Crystal, ListAndLabel
Three different Reporting Document types. I have a generic Handler <code>IReportHandler<T></code> (would be the same as above) this Handler provides all the functionality for handling a report Document.
for Example </p>
<pre><code>ChrystalReportHandler:IReportHandler<CrystalReportDocument>
</code></pre>
<p>Now I want to use a Framework like Unity (or some else framework) for dependency injection to decide via configuration whether I want to use Crystal, <code>Reportingservices</code> or List and Label.</p>
<p>When I specify my mapping I can inject my <code>ChrystalReportHandler</code> but how can I inject T on the left side or in better word The Type of <code>ReportDocument</code>.</p>
<pre><code>IReportHandler<T (this needs also to be injected)> = IOContainer.Resolve(MyMappedType here)
</code></pre>
<p>my Problem is the left Site of course because it is coupled to the type but I have my mapping ... would it be possible to generate a object based on Mapping and assign the mapped type ? or basically inject T on the left side, too?
Or is this approach not suitable for this situation.</p>
| [
{
"answer_id": 355525,
"author": "Lasse V. Karlsen",
"author_id": 267,
"author_profile": "https://Stackoverflow.com/users/267",
"pm_score": 1,
"selected": false,
"text": "public interface IDocumentHandler { }\npublic interface IDocumentHandler<T> : IDocumentHandler { }\n"
},
{
"answer_id": 355606,
"author": "bruno conde",
"author_id": 31136,
"author_profile": "https://Stackoverflow.com/users/31136",
"pm_score": 2,
"selected": false,
"text": "IDocumentHandler ReportDocument MediaDocument IDocumentHandler<ReportDocument or MediaDocument> public interface IDocumentHandler\n{\n IDocument Document { get; set; }\n\n void Load(IDocument doc);\n\n void Load(string PathToDoc);\n\n void Execute();\n\n void Execute(IDocument doc);\n\n}\n\npublic class IDocument { }\npublic class ReportDocument : IDocument { }\npublic class MediaDocument : IDocument { }\npublic class FinanceDocumentProcessor : IDocumentHandler { }\npublic class MarketingDocumentProcessor : IDocumentHandler { }\n"
}
] | 2008/12/10 | [
"https://Stackoverflow.com/questions/355473",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
355,477 | <p>In Silverlight (and I guess WPF) why are the properties x:name x:fieldmodifier x:uid the only ones with the prefix x. </p>
<p>I understand the x prefix is used to refer to the XML namespace but there are a number of other properties that do not use a prefix such as width. Identifying a control is such a common task it seems odd to require a prefix?</p>
| [
{
"answer_id": 355503,
"author": "DaniCE",
"author_id": 19046,
"author_profile": "https://Stackoverflow.com/users/19046",
"pm_score": 2,
"selected": false,
"text": "xmlns=\"http://schemas.microsoft.com/winfx/2006/xaml/presentation\" \nxmlns:x=\"http://schemas.microsoft.com/winfx/2006/xaml\" \n"
}
] | 2008/12/10 | [
"https://Stackoverflow.com/questions/355477",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23066/"
] |
355,486 | <p>I've got a Core Data application that has an Event class, which has a start date and a finish date. It's trivial to bind these to a pair of NSDatePicker widgets, but I wanted to make it work with the NSRangeDateMode available in Leopard.</p>
<p>The NSDatePicker has a pair of methods that deal with timeInterval, but I don't seem to be able to bind to this.</p>
<p><strong>Update</strong>: I've used a manual call to do the binding, and it half works:</p>
<pre><code>[picker bind:@"timeInterval"
toObject:array
withKeyPath:@"selection.timeInterval"
options:options];
</code></pre>
<p>It sets the timeInterval in the NSDatePicker when the underlying object is changed, but does not set the underlying object when the NSDatePicker's timeInterval is changed.</p>
| [
{
"answer_id": 357758,
"author": "Ashley Clark",
"author_id": 4556,
"author_profile": "https://Stackoverflow.com/users/4556",
"pm_score": 1,
"selected": false,
"text": "timeInterval"
}
] | 2008/12/10 | [
"https://Stackoverflow.com/questions/355486",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/188/"
] |
355,492 | <p>I have read the following properties from AD,</p>
<pre><code>TerminalServicesProfilePath
TerminalServicesHomeDirectory
TerminalServicesHomeDrive
</code></pre>
<p>I've tried DirectoryEntry and DirectorySearcher. But they does not include the properties.</p>
<p>I found some example in vbscript and VC to read them.
However I failed to make it working in C#. Am I missing some tricky thing?</p>
<p>EDIT: Am I have to run it on "Windows Server" to make it works? Can it be read from win XP?</p>
| [
{
"answer_id": 355513,
"author": "chriscena",
"author_id": 32671,
"author_profile": "https://Stackoverflow.com/users/32671",
"pm_score": 2,
"selected": true,
"text": "//user is a DirectoryEntry\nIADsTSUserEx adsiUser = (IADsTSUserEx)user.NativeObject; \n"
},
{
"answer_id": 355545,
"author": "Arnout",
"author_id": 3496,
"author_profile": "https://Stackoverflow.com/users/3496",
"pm_score": 2,
"selected": false,
"text": "InvokeGet DirectoryEntry using (DirectorySearcher searcher = new DirectorySearcher(\"(cn=Test)\"))\n{\n SearchResult result = searcher.FindOne();\n if (result != null)\n {\n DirectoryEntry entry = result.GetDirectoryEntry();\n string s = entry.InvokeGet(\"TerminalServicesHomeDrive\") as string;\n MessageBox.Show(s ?? \"null\");\n }\n}\n"
},
{
"answer_id": 1538838,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": " DirectoryEntry user = new DirectoryEntry(\"LDAP://\" + sLDAP_SERVER + \"/cn=\" + SAMAccount + \",\" + sLdapFullPath, sUser, sPwd);\n\n //ActiveDs.IADsUser iADsUser = (ActiveDs.IADsUser)user.NativeObject;\n ActiveDs.IADsUser cont = null;\n\n cont = user.NativeObject as ActiveDs.IADsUser;\n\n TSUSEREXLib.IADsTSUserEx m_TsUser = (TSUSEREXLib.IADsTSUserEx)cont;\n int m_TSLogonDisabled = 0;\n\n m_TsUser.AllowLogon = m_TSLogonDisabled;\n"
}
] | 2008/12/10 | [
"https://Stackoverflow.com/questions/355492",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/40214/"
] |
355,508 | <p>Sorry about the vague subject but I couldn't think what to put.</p>
<p>Here's my problem, I'm doing a query on a table that returns me a count of items related to a day. I want to make sure that if I do a query on the DB, I always get a set number of rows. For example, imagine I have the following table that contains a log of when people log into a website:</p>
<pre><code>**WebsiteLogin**
id: Integer
login_date: Datetime
</code></pre>
<p>I can then get counts of the logins for each date by doing something like:</p>
<pre><code>SELECT DATE(login_date), COUNT(*) FROM WebsiteLogin GROUP BY DATE(login_date)
</code></pre>
<p>Which works great and will return me the data I want. But imagine my website was quite unpopular on the weekends. The data returned would look like:</p>
<pre><code>2008-12-10, 100
2008-12-11, 124
2008-12-12, 151
2008-12-15, 141
2008-12-16, 111
</code></pre>
<p>The 13th & 14th are missing because there was no data for those dates. Is there any way I can change my query so that I get data that includes all the dates I query on. E.g.</p>
<pre><code>2008-12-10, 100
2008-12-11, 124
2008-12-12, 151
2008-12-13, 0
2008-12-14, 0
2008-12-15, 141
2008-12-16, 111
</code></pre>
<p>I imagine I could do this if I set up a table containing all the dates in a year and then using a left/right join but that's really messy way of doing it.</p>
<p>So any clues on a nice way to do this in SQL? Or is programmatically my only choice? Cheers for any input.</p>
| [
{
"answer_id": 355625,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "select d login_date, count(login_date) count\nfrom\n websitelogin wsl\n right outer join (\n select start_date+l-1 d from (select start_date, level l\n from (select min(login_date) start_date, max(login_date)-min(login_date)+1 num_days\n from websitelogin) connect by level <= num_days)) v on d=login_date\ngroup by d\n/\n select d login_date, count(login_date) count\nfrom\n websitelogin wsl\n right outer join (select start_date+rownum-1 d from\n(\nselect \n min(login_date) start_date, \n max(login_date)-min(login_date)+1 num_days\nfrom websitelogin)v,all_objects\nwhere rownum<=num_days\n) v on d=login_date\ngroup by d\n"
},
{
"answer_id": 355862,
"author": "Jonathan",
"author_id": 6910,
"author_profile": "https://Stackoverflow.com/users/6910",
"pm_score": 0,
"selected": false,
"text": "CREATE FUNCTION dbo.DatesBetween (@start_date datetime, @end_date datetime)\nRETURNS @DateTable TABLE (gen_date datetime)\nAS \nBEGIN\n DECLARE @num_dates int\n DECLARE @tmpVal TABLE (a_count int identity(0,1))\n\n SELECT @num_dates = datediff(day, @start_date, @end_date)\n WHILE (select isnull(max(a_count), 0) from @tmpVal) < @num_dates\n INSERT @tmpVal DEFAULT VALUES\n\n INSERT @DateTable (gen_date) \n SELECT dateadd(day, a_count, @start_date) FROM @tmpVal\n\n RETURN\nEND\n DECLARE @min_date datetime, @max_date datetime\nSELECT @min_date = min(login_date), @max_date = max(login_date) \nFROM WebsiteLogin\n\nSELECT m.gen_date 'login_date', isnull(l.num_visits, 0) 'num_visits'\nFROM dbo.DatesBetween(@min_date, @max_date) as d\nLEFT OUTER JOIN (SELECT DATE(login_date) 'login_date', COUNT(*) 'num_visits'\n FROM WebsiteLogin \n GROUP BY DATE(login_date)) AS l ON d.gen_date = l.login_date\n DECLARE @LowDate DATETIME\nSET @LowDate = '01-01-2006'\n\nDECLARE @HighDate DATETIME\nSET @HighDate = '12-31-2016'\n\nSELECT DISTINCT DATEADD(dd, Days.Row, DATEADD(mm, Months.Row, DATEADD(yy, Years.Row, @LowDate))) AS Date\nFROM\n(SELECT 0 AS Row UNION ALL SELECT 1 UNION ALL SELECT 2 UNION ALL SELECT 3 UNION ALL SELECT 4\n UNION ALL SELECT 5 UNION ALL SELECT 6 UNION ALL SELECT 7 UNION ALL SELECT 8 UNION ALL SELECT 9\n UNION ALL SELECT 10 UNION ALL SELECT 11 UNION ALL SELECT 12 UNION ALL SELECT 13 UNION ALL SELECT 14\n UNION ALL SELECT 15 UNION ALL SELECT 16 UNION ALL SELECT 17 UNION ALL SELECT 18 UNION ALL SELECT 19\n UNION ALL SELECT 20 UNION ALL SELECT 21 UNION ALL SELECT 22 UNION ALL SELECT 23 UNION ALL SELECT 24\n UNION ALL SELECT 25 UNION ALL SELECT 26 UNION ALL SELECT 27 UNION ALL SELECT 28 UNION ALL SELECT 29\n UNION ALL SELECT 30 -- add more years here...\n) AS Years\nINNER JOIN\n(SELECT 0 AS Row UNION ALL SELECT 1 UNION ALL SELECT 2 UNION ALL SELECT 3 UNION ALL SELECT 4\n UNION ALL SELECT 5 UNION ALL SELECT 6 UNION ALL SELECT 7 UNION ALL SELECT 8 UNION ALL SELECT 9\n UNION ALL SELECT 10 UNION ALL SELECT 11\n) AS Months\nON DATEADD(mm, Months.Row, DATEADD(yy, Years.Row, @LowDate)) <= @HighDate \nINNER JOIN\n(SELECT 0 AS Row UNION ALL SELECT 1 UNION ALL SELECT 2 UNION ALL SELECT 3 UNION ALL SELECT 4\n UNION ALL SELECT 5 UNION ALL SELECT 6 UNION ALL SELECT 7 UNION ALL SELECT 8 UNION ALL SELECT 9\n UNION ALL SELECT 10 UNION ALL SELECT 11 UNION ALL SELECT 12 UNION ALL SELECT 13 UNION ALL SELECT 14\n UNION ALL SELECT 15 UNION ALL SELECT 16 UNION ALL SELECT 17 UNION ALL SELECT 18 UNION ALL SELECT 19\n UNION ALL SELECT 20 UNION ALL SELECT 21 UNION ALL SELECT 22 UNION ALL SELECT 23 UNION ALL SELECT 24\n UNION ALL SELECT 25 UNION ALL SELECT 26 UNION ALL SELECT 27 UNION ALL SELECT 28 UNION ALL SELECT 29\n UNION ALL SELECT 30\n) AS Days\nON DATEADD(dd, Days.Row, DATEADD(mm, Months.Row, DATEADD(yy, Years.Row, @LowDate))) <= @HighDate\nWHERE DATEADD(yy, Years.Row, @LowDate) <= @HighDate\nORDER BY 1\n"
}
] | 2008/12/10 | [
"https://Stackoverflow.com/questions/355508",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1900/"
] |
355,516 | <p>When accessing my site, the user has to enter his credentials. They are basically plain directory access credentials.
At a certain point I check if a certain file they want to download exists by calling</p>
<pre><code>WebRequest req = HttpWebRequest.Create(checkUri.AbsoluteUri);
WebResponse res = req.GetResponse();
</code></pre>
<p>Although I can access the checkUri from the browser, I get a 401 when doing the above check. I think I have to set the</p>
<pre><code>req.Credentials
</code></pre>
<p>But I don't know where the current credentials are stored...</p>
<p>Any ideas?</p>
<p><strong>--Update--</strong> </p>
<ul>
<li>Integrated Windows Authentication: No</li>
<li>Allow Anonymous: Off</li>
<li>Caler: Link on page of same site (GET)</li>
<li>Impersonation: default is off (don't even know how to enable it in asp.net mvc)</li>
</ul>
| [
{
"answer_id": 355522,
"author": "mookid8000",
"author_id": 6560,
"author_profile": "https://Stackoverflow.com/users/6560",
"pm_score": 3,
"selected": false,
"text": "req.Credentials = CredentialCache.DefaultCredentials;\n"
},
{
"answer_id": 356308,
"author": "Dave Markle",
"author_id": 24995,
"author_profile": "https://Stackoverflow.com/users/24995",
"pm_score": 1,
"selected": false,
"text": "<identity impersonate=\"true\"> \n"
},
{
"answer_id": 1589723,
"author": "David",
"author_id": 21909,
"author_profile": "https://Stackoverflow.com/users/21909",
"pm_score": 3,
"selected": false,
"text": "HttpWebRequest req = (HttpWebRequest)WebRequest.Create(uri);\n// Add the current authentication cookie to the request\nHttpCookie cookie = HttpContext.Current.Request.Cookies[FormsAuthentication.FormsCookieName];\nCookie authenticationCookie = new Cookie(\n FormsAuthentication.FormsCookieName,\n cookie.Value,\n cookie.Path,\n HttpContext.Current.Request.Url.Authority);\n\nreq.CookieContainer = new CookieContainer();\nreq.CookieContainer.Add(authenticationCookie);\n\nWebResponse res = req.GetResponse();\n"
}
] | 2008/12/10 | [
"https://Stackoverflow.com/questions/355516",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11333/"
] |
355,526 | <p>HI,</p>
<p>I have a large table from which i can query to get the following table</p>
<pre><code>type no of times type occurs
101 450
102 562
103 245
</code></pre>
<p>also i can get another table</p>
<pre><code>code no of times code occurs
0 1222
1 750
2 355
</code></pre>
<p>but now i want to write a query which could get me the following table</p>
<pre><code>type no of timescode1occurs %of timescode1 occurs out of %of times code1 occurs out of
no of times type occurs no of times code occcurs
101 50 11% 6%
102 75 13% 10%
</code></pre>
<p>How can i write a query to get this?</p>
<p>Thanks</p>
| [
{
"answer_id": 355522,
"author": "mookid8000",
"author_id": 6560,
"author_profile": "https://Stackoverflow.com/users/6560",
"pm_score": 3,
"selected": false,
"text": "req.Credentials = CredentialCache.DefaultCredentials;\n"
},
{
"answer_id": 356308,
"author": "Dave Markle",
"author_id": 24995,
"author_profile": "https://Stackoverflow.com/users/24995",
"pm_score": 1,
"selected": false,
"text": "<identity impersonate=\"true\"> \n"
},
{
"answer_id": 1589723,
"author": "David",
"author_id": 21909,
"author_profile": "https://Stackoverflow.com/users/21909",
"pm_score": 3,
"selected": false,
"text": "HttpWebRequest req = (HttpWebRequest)WebRequest.Create(uri);\n// Add the current authentication cookie to the request\nHttpCookie cookie = HttpContext.Current.Request.Cookies[FormsAuthentication.FormsCookieName];\nCookie authenticationCookie = new Cookie(\n FormsAuthentication.FormsCookieName,\n cookie.Value,\n cookie.Path,\n HttpContext.Current.Request.Url.Authority);\n\nreq.CookieContainer = new CookieContainer();\nreq.CookieContainer.Add(authenticationCookie);\n\nWebResponse res = req.GetResponse();\n"
}
] | 2008/12/10 | [
"https://Stackoverflow.com/questions/355526",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/31132/"
] |
355,531 | <p>I am trying to understand if I really have any case for using git/mercurial.</p>
<p>The projects I work are java and c# projects, usually with 5-20 people working towards
a common goal (the "release"). Most of the developers are professional developers who
refactor code <em>all of the time</em>. So where the typical linux kernel has a large number of
relatively independent changes in separate files, we have a constant flux of refactoring changes -
often hitting a <em>lot</em> of files and a <em>lot</em> of code. No-one's scared of changing code here.</p>
<p>Now with subversion we solve this by staying extremely close to SVN HEAD. Some of us even have
automated svn up's that trigger on the build server's jabber broadcast. Most of us have also learned
(or learn really quickly) how to plan our work to stay close to SVN HEAD. If you're doing a major refactoring we
incrementally bend the source tree in a new direction instead of going away for too long. Sometimes you just plan the
refactoring operation and start off in the less contended areas. After some years
of working this way it becomes second nature. Most of us simply never leave the "comfort zone" of being less than
2 hours away from svn head. The automated build and svn head is the project "pulse" and we like it.</p>
<p>Of course we branch off each release, but the number of backmerges from the release-branch back to trunk dwindle
down quickly enough to be insignificant (we've got decent test coverage). Running off for days/weeks with private branches of the source sounds
like something we actively want to discourage, and it simply doesn't happen very frequently.</p>
<p>Both git and mercurial sound way cool, git slightly more so since I'm more a McGyver type than a James Bond type.
But when it comes to building a case for actually switching, it feels like Linus and I are living on two different planets.
Most of the time we <em>want</em> our teams to stay focused on HEAD. </p>
<p>How can GIT make my version control better ? How would GIT let me improve my process ? Am I a subversion dinosaur ?</p>
| [
{
"answer_id": 355686,
"author": "Kent Fredric",
"author_id": 15614,
"author_profile": "https://Stackoverflow.com/users/15614",
"pm_score": 5,
"selected": true,
"text": "a b center\n |\n |\n / Key: / - | \\ = Flow\n/----<---| < > = Flow Directions\n| /--<--/ * = Commit \n* | | T = Test\n| * | M = Merging with \"Current\" state of common branch\n* | | C = Tests Complete and Current state is \"sane\"\n| * |\nT | |\n| T |\n| C |\n| |/-<--/\n* M |\n| T |\n* C |\n| \\--->-\\\n* /---<-/\nT | |\nC * |\n|/-----<-/\nM | |\nT * |\n| T |\n* C |\n| |/-<--/\n* M |\nT T |\nC \\-->--\\\n|/---<---/\nM |\nT |\nC |\n\\---->---\\\n |\n a b center\n| | |\nT | |\nC * |\n|/</ |\nM | |\n| * |\nT |\nC |\n|/----<--/\nM |\nT |\nC |\n\\-->-----\\\n |\n"
}
] | 2008/12/10 | [
"https://Stackoverflow.com/questions/355531",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23691/"
] |
355,533 | <p>I have two unix partitions under debian which I would like to merge (disk space problems :/). What would be the easiest way to do it? I think it would be best to tar or copy files from one partition to the other, delete one and resize the other. I will use parted to resize but how should I copy the files? There are links, permissions and devices which need to be moved without change.</p>
| [
{
"answer_id": 355591,
"author": "Anders Westrup",
"author_id": 36845,
"author_profile": "https://Stackoverflow.com/users/36845",
"pm_score": 3,
"selected": true,
"text": "cd /partition2\ntar cf - . | ( cd /partition1 && tar xf - )\n"
},
{
"answer_id": 440800,
"author": "Teddy",
"author_id": 54435,
"author_profile": "https://Stackoverflow.com/users/54435",
"pm_score": 2,
"selected": false,
"text": "cp --archive cp --archive --sparse=always --verbose --one-file-system --target-directory=/TARGET /ORIGIN\n tar cd /origin\nfind . -xdev -depth -not -path ./lost+found -print0 \\\n | tar --create --atime-preserve=system --null --files-from=- \\\n --format=posix --no-recursion --sparse \\\n | { cd /target; tar --extract --overwrite --preserve-permissions --sparse; }\n tar cp --archive mkdir /target\ncd /origin\nfind . -xdev -depth -not -path ./lost+found -print0 \\\n | bsdtar -c -n --null -T - --format pax \\\n | { cd /target; bsdtar -x -pS -f -; }\n"
}
] | 2008/12/10 | [
"https://Stackoverflow.com/questions/355533",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/26943/"
] |
355,538 | <p>The client has asked for a number of tables to be extracted into csv's, all done no problem. They've just asked we make sure the files are always in UTF 8 format.</p>
<p>How do I check this is actually the case. Or even better force it to be so, is it something i can set in a procedure before running a query perhaps?</p>
<p>The data is extracted from an Oracle 10g database.</p>
<p>What should I be checking?</p>
<p>Thanks</p>
| [
{
"answer_id": 355575,
"author": "rics",
"author_id": 21047,
"author_profile": "https://Stackoverflow.com/users/21047",
"pm_score": 4,
"selected": true,
"text": "select value from nls_database_parameters \nwhere parameter='NLS_CHARACTERSET'\n"
},
{
"answer_id": 356211,
"author": "Justin Cave",
"author_id": 10397,
"author_profile": "https://Stackoverflow.com/users/10397",
"pm_score": 1,
"selected": false,
"text": "NLS_LANG NLS_LANG"
}
] | 2008/12/10 | [
"https://Stackoverflow.com/questions/355538",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/27412/"
] |
355,539 | <p>If I had a dictionary <code>dict</code> and I wanted to check for <code>dict['key']</code> I could either do so in a <code>try</code> block (bleh!) or use the <code>get()</code> method, with <code>False</code> as a default value.</p>
<p>I'd like to do the same thing for <code>object.attribute</code>. That is, I already have object to return <code>False</code> if it hasn't been set, but then that gives me errors like</p>
<blockquote>
<p>AttributeError: 'bool' object has no attribute 'attribute'</p>
</blockquote>
| [
{
"answer_id": 355562,
"author": "Zoomulator",
"author_id": 44563,
"author_profile": "https://Stackoverflow.com/users/44563",
"pm_score": 4,
"selected": false,
"text": "hasattr() hasattr(object, \"attribute name\") #Returns True or False\n \"attribute\" in obj.__dict__\n"
},
{
"answer_id": 355571,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 3,
"selected": false,
"text": "in 'key' in dictionary hasattr() hasattr(obj, 'attribute')"
},
{
"answer_id": 356227,
"author": "Brian",
"author_id": 9493,
"author_profile": "https://Stackoverflow.com/users/9493",
"pm_score": 8,
"selected": true,
"text": "dict.get(key, default) hasattr getattr val = getattr(obj, 'attr_to_check', default_value)\n default_value False"
}
] | 2008/12/10 | [
"https://Stackoverflow.com/questions/355539",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9106/"
] |
355,540 | <p>I have a special url which I would want only few people to have access to. I have a list of super users stored as an array in the app.yml. How can I use this array in :requirements section of a specific route in the routes.rb file to allow only those super users access to this route? Thanks a lot.</p>
| [
{
"answer_id": 355562,
"author": "Zoomulator",
"author_id": 44563,
"author_profile": "https://Stackoverflow.com/users/44563",
"pm_score": 4,
"selected": false,
"text": "hasattr() hasattr(object, \"attribute name\") #Returns True or False\n \"attribute\" in obj.__dict__\n"
},
{
"answer_id": 355571,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 3,
"selected": false,
"text": "in 'key' in dictionary hasattr() hasattr(obj, 'attribute')"
},
{
"answer_id": 356227,
"author": "Brian",
"author_id": 9493,
"author_profile": "https://Stackoverflow.com/users/9493",
"pm_score": 8,
"selected": true,
"text": "dict.get(key, default) hasattr getattr val = getattr(obj, 'attr_to_check', default_value)\n default_value False"
}
] | 2008/12/10 | [
"https://Stackoverflow.com/questions/355540",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/44916/"
] |
355,550 | <p>I have two arrays in PHP. The first array ($author_array) is comprised of user_ids in a particular order, like so: (8, 1, 6)</p>
<p>The second array ($user_results) is comprised of an array of objects like so:</p>
<pre><code>Array
(
[0] => stdClass Object
(
[ID] => 1
[user_login] => user1
)
[1] => stdClass Object
(
[ID] => 6
[user_login] => user6
)
[2] => stdClass Object
(
[ID] => 8
[user_login] => user8
)
)
</code></pre>
<p>I'd like to "sort" the second array so it's in this order, which matches the order of the values in the first array of (8, 1, 6). So it'd look like this:</p>
<pre><code>Array
(
[0] => stdClass Object
(
[ID] => 8
[user_login] => user8
)
[1] => stdClass Object
(
[ID] => 1
[user_login] => user1
)
[2] => stdClass Object
(
[ID] => 6
[user_login] => user6
)
)
</code></pre>
<p>I'm weak on data structures. How could I do this? :-)</p>
<p>Thanks in advance for your help!</p>
<p>-Bob</p>
| [
{
"answer_id": 355583,
"author": "Paul Dixon",
"author_id": 6521,
"author_profile": "https://Stackoverflow.com/users/6521",
"pm_score": 6,
"selected": true,
"text": "function cmp($a, $b) \n{\n global $author_array;\n\n $pos1=array_search ($a->ID, $author_array);\n $pos2=array_search ($b->ID, $author_array);\n\n if ($pos1==$pos2)\n return 0;\n else\n return ($pos1 < $pos2 ? -1 : 1);\n\n}\n\n\nusort($user_results, \"cmp\");\n"
},
{
"answer_id": 355592,
"author": "Tom Haigh",
"author_id": 22224,
"author_profile": "https://Stackoverflow.com/users/22224",
"pm_score": 2,
"selected": false,
"text": "$hash = array();\n$result = array();\n\nforeach ($user_results as $obj) {\n $hash[$obj->ID] = $obj;\n}\n\nforeach ($author_array as $id) {\n $result[] = $hash[$id];\n}\n"
},
{
"answer_id": 5130068,
"author": "David",
"author_id": 309320,
"author_profile": "https://Stackoverflow.com/users/309320",
"pm_score": 1,
"selected": false,
"text": "$sort_array= array(11, 4, 16, 19, 23);\n$myobject = sort_categories($myobject)\n\nfunction cmp($a, $b) { \n if ($a->sort_key == $b->sort_key) { return 0; }\n return ($a->sort_key < $b->sort_key) ? -1 : 1;\n}\nfunction sort_categories($obj) {\n global $sort_array;\n\n foreach($obj as $cat) {\n $cat->sort_key = 999;\n for ($i=0;$i<count($sort_array);$i++) {\n if ($sort_array[$i] == $cat->term_id) $cat->sort_key = $i;\n }\n }\n usort($obj,'cmp');\n return $obj;\n}\n"
},
{
"answer_id": 10254262,
"author": "morecer",
"author_id": 1347583,
"author_profile": "https://Stackoverflow.com/users/1347583",
"pm_score": 0,
"selected": false,
"text": "public static function reorganizeBykey ($objects, array $keys){\n $results = array();\n foreach($keys as $key){\n $i=0;\n foreach($objects as $object){\n if($object->sourceName==$key){\n $results[$i] = $object;\n }\n $i++;\n }\n }\n $others = (array_diff_assoc($objects,$results));\n $results = array_merge($results,$others);\n return $results;\n}\n array() keys()"
}
] | 2008/12/10 | [
"https://Stackoverflow.com/questions/355550",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/44919/"
] |
355,560 | <p>I have these values: <code>d1, d45, d79, d33, d100</code></p>
<p>I want to sort these variables in ascending order from my table.</p>
<p>What is the query to get the output as:</p>
<pre><code>d1
d33
d45
d79
d100
</code></pre>
| [
{
"answer_id": 355611,
"author": "annakata",
"author_id": 13018,
"author_profile": "https://Stackoverflow.com/users/13018",
"pm_score": 0,
"selected": false,
"text": "select foo from bar order by cast(substring(foo from 2) as int)\n ..order by char_length(foo),foo\n"
},
{
"answer_id": 356619,
"author": "Jonathan",
"author_id": 6910,
"author_profile": "https://Stackoverflow.com/users/6910",
"pm_score": 0,
"selected": false,
"text": "select column from YourTable\norder by convert(int, replace(column, 'd', ''))\n select column from YourTable\norder by convert(int, \n replace(replace(replace(replace(replace(\n column, 'a', ''),\n 'b', ''),\n 'c', ''),\n 'd', ''), \n 'e', '')\n )\n"
}
] | 2008/12/10 | [
"https://Stackoverflow.com/questions/355560",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
355,576 | <p>I would like to get Binding object from web.config or app.config.</p>
<p>So, this code works:</p>
<pre><code>wcfTestClient = new TestServiceClient("my_endpoint", Url + "/TestService.svc");
</code></pre>
<p>but I would like to do the following:</p>
<pre><code>Binding binding = DoSomething();
wcfTestClient = new TestServiceClient(binding, Url + "/TestService.svc");
</code></pre>
<p>I am interested in DoSomething() method, of course.</p>
| [
{
"answer_id": 355709,
"author": "Marc Gravell",
"author_id": 23354,
"author_profile": "https://Stackoverflow.com/users/23354",
"pm_score": 3,
"selected": false,
"text": "Binding defaultBinding;\nusing(TestServiceClient client = new TestServiceClient()) {\n defaultBinding = client.Endpoint.Binding;\n}\n"
},
{
"answer_id": 370785,
"author": "Philippe",
"author_id": 920,
"author_profile": "https://Stackoverflow.com/users/920",
"pm_score": 4,
"selected": true,
"text": "// Set the IssuerBinding to a WSHttpBinding loaded from config\nb.Security.Message.IssuerBinding = new WSHttpBinding(\"Issuer\");\n"
},
{
"answer_id": 2740276,
"author": "Jason Gerard",
"author_id": 185606,
"author_profile": "https://Stackoverflow.com/users/185606",
"pm_score": 3,
"selected": false,
"text": "return (Binding)Activator.CreateInstance(bindingType, endpointConfigName);\n"
},
{
"answer_id": 33242499,
"author": "daniloquio",
"author_id": 354756,
"author_profile": "https://Stackoverflow.com/users/354756",
"pm_score": 3,
"selected": false,
"text": "private BindingsSection GetBindingsSection(string path)\n{\n System.Configuration.Configuration config = \n System.Configuration.ConfigurationManager.OpenMappedExeConfiguration(\n new System.Configuration.ExeConfigurationFileMap() { ExeConfigFilename = path },\n System.Configuration.ConfigurationUserLevel.None);\n\n var serviceModel = ServiceModelSectionGroup.GetSectionGroup(config);\n return serviceModel.Bindings;\n}\n Binding public Binding ResolveBinding(string name)\n{\n BindingsSection section = GetBindingsSection(path);\n\n foreach (var bindingCollection in section.BindingCollections)\n {\n if (bindingCollection.ConfiguredBindings.Count > 0 \n && bindingCollection.ConfiguredBindings[0].Name == name)\n {\n var bindingElement = bindingCollection.ConfiguredBindings[0];\n var binding = (Binding)Activator.CreateInstance(bindingCollection.BindingType);\n binding.Name = bindingElement.Name;\n bindingElement.ApplyConfiguration(binding);\n\n return binding;\n }\n }\n\n return null;\n}\n"
}
] | 2008/12/10 | [
"https://Stackoverflow.com/questions/355576",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/28912/"
] |
355,602 | <p>I've had to create a custom membership provider for my current ASP .Net project in order to fit in with our database schema, and am having problems configuring it to lockout a user if they get their password wrong three times, as is supported by the standard providers.</p>
<p>Is this something I need to implement myself, or should it be supported inherently?</p>
<p>I have no code that specifically deals with it (and none of the interface members seem to deal with it specifically), but if I need to implement it myself, how do I go about informing the user they are locked out? Do I need to raise some sort of exception in ValidateUser?</p>
<p><strong>Solution</strong></p>
<p>Shame I can't mark two answers, the links provided by Dave R give a great in depth look at how membership works, and what Zhaph pointed out was just what I ended up doing, handling the locked out logic in the custom membership provider.</p>
<p>I then handled the error condition by using the Login control's LoginError event and checked in there to see if the user was locked out in order to show the appropriate error message.</p>
| [
{
"answer_id": 356106,
"author": "Zhaph - Ben Duguid",
"author_id": 33051,
"author_profile": "https://Stackoverflow.com/users/33051",
"pm_score": 2,
"selected": false,
"text": "IsLockedOut\nFailedPasswordAttemptCount\nFailedPasswordAttemptWindowStart\n maxInvalidPasswordAttempts=\"5\"\npasswordAttemptWindow=\"10\"\n"
},
{
"answer_id": 2064058,
"author": "Samo Fabčič",
"author_id": 250705,
"author_profile": "https://Stackoverflow.com/users/250705",
"pm_score": 2,
"selected": false,
"text": "if (0 < Membership.MaxInvalidPasswordAttempts && Membership.MaxInvalidPasswordAttempts < 100)\n {\n for(int i = 0; i <= Membership.MaxInvalidPasswordAttempts; i++)\n {\n Membership.ValidateUser(userName, \"jfdlsjflksjlkfjsdlkfjsdl\");\n }\n }\n"
}
] | 2008/12/10 | [
"https://Stackoverflow.com/questions/355602",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/40848/"
] |
355,619 | <p>The common sense tells that the Doxygen comment blocks have to be put in the header files where the classes, structs, enums, functions, declarations are. I agree that this is a sound argument for a libraries that are mean to be distributed without its source (only headers and libs with object code).</p>
<p>BUT...I've been thinking of the exact opposite approach when I'm developing an internal to the company (or as a side project for myself) library that will be used with its full source code. What I propose is to put the large comment blocks in the implementations files (HPP, INL, CPP, etc) in order NOT to clutter the inteface of the classes and functions declared in the header.</p>
<p><strong>Pros:</strong></p>
<ul>
<li>Less clutter in the header files, only categorizing of the functions can be added.</li>
<li>The comment blocks that are previewed when Intellisense for example is used doesn't clash - this is a defect that I have observed when I have a comment block for a function in the .H file and have its inline definition in the same .H file but included from .INL file.</li>
</ul>
<p><strong>Cons:</strong></p>
<ul>
<li>(The obvious one) The comment blocks are not in the header files where the declarations are.</li>
</ul>
<p>So, what do you think and possibly suggest?</p>
| [
{
"answer_id": 355646,
"author": "eaanon01",
"author_id": 36986,
"author_profile": "https://Stackoverflow.com/users/36986",
"pm_score": 4,
"selected": false,
"text": "/**\n * \\brief Short about function\n *\n * More about function\n */\nWORD my_fync1(BYTE*);\n /** \\copydoc my_func1 */\nWORD my_fync1(BYTE* data){/*code*/}\n"
},
{
"answer_id": 7737162,
"author": "Daniel Buckmaster",
"author_id": 945863,
"author_profile": "https://Stackoverflow.com/users/945863",
"pm_score": 7,
"selected": false,
"text": "/// @brief This method adds two integers.\n/// @param a First integer to add.\n/// @param b Second integer to add.\n/// @return The sum of both parameters.\nint add(int a, int b);\n /// This method uses a little-known variant of integer addition known as\n/// Sophocles' Scissors. It optimises the function's performance on many\n/// platforms that we may or may not choose to target in the future.\n/// @TODO make sure I implemented the algorithm correctly with some unit tests.\nint add(int a, int b) {\n return b + a;\n}\n"
}
] | 2008/12/10 | [
"https://Stackoverflow.com/questions/355619",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/34752/"
] |
355,632 | <p>On a website I'm working we have an onsite login and a private login, the problem I'm having is that Firefox doesn't seem to be able to differentiate between these login forms.</p>
<p>Does anybody know how I can make clear that these are different logins?</p>
<p>I already tried giving the form fields different names and ids, ex: onsite_login and login but without success.</p>
<p><strong>edit:</strong> my form-tags are not being mixed up, they aren't even on the same page</p>
<p>The two forms on the different pages</p>
<pre><code><form method="post" action="/en/login/1">
<fieldset>
<p>
<input type="hidden" value="login" name="form"/>
<input type="hidden" value="en" name="redirect"/>
<label for="onsite_username">Username<abbr title="Required ">*</abbr></label>
<input type="text" class="input-text" maxlength="255" value="" name="onsite_username" id="onsite_username"/>
<label for="onsite_password">Password<abbr title="Required ">*</abbr></label>
<input type="password" class="input-password" maxlength="255" value="" name="onsite_password" id="onsite_password"/>
<input type="submit" value="Log in" name="submit" class="input-submit"/>
</p>
</fieldset>
</form>
</code></pre>
<p>and</p>
<pre><code><form method="post" action="">
<fieldset>
<input type="hidden" value="login" name="form"/>
<div>
<label for="username">Username</label>
<input type="text" class="input-text" value="" name="username" id="username"/>
</div><div>
<label for="password">Password</label>
<input type="password" class="input-password" value="" name="password" id="password"/>
</div>
<input type="submit" value="Aanmelden" class="input-submit"/>
</fieldset>
</form>
</code></pre>
| [
{
"answer_id": 355734,
"author": "dragonlord21",
"author_id": 44931,
"author_profile": "https://Stackoverflow.com/users/44931",
"pm_score": 1,
"selected": false,
"text": "<p> <div>"
},
{
"answer_id": 355856,
"author": "Polichism",
"author_id": 44544,
"author_profile": "https://Stackoverflow.com/users/44544",
"pm_score": 0,
"selected": false,
"text": "<form method=\"POST\" action=\"#\" id=\"login1\">"
}
] | 2008/12/10 | [
"https://Stackoverflow.com/questions/355632",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1074/"
] |
355,633 | <p>I was reading up on Ruby, and learned about its mixins pattern, but couldn't think of many useful mixin functionality (because I'm not used to thinking that way most likely). So I was wondering what would be good examples of useful Mixin functionality?</p>
<p>Thanks</p>
<p>Edit: A bit of background. I'm Coming from C++, and other Object languages, but my doubt here is that Ruby says it's not inheriting mixins, but I keep seeing mixins as Multiple inheritance, so I fear I'm trying to categorize them too soon into my comfort zone, and not really grok what a mixin is.</p>
| [
{
"answer_id": 355698,
"author": "Gishu",
"author_id": 1695,
"author_profile": "https://Stackoverflow.com/users/1695",
"pm_score": 4,
"selected": true,
"text": "module Persistence\n def load sFileName\n puts \"load code to read #{sFileName} contents into my_data\"\n end\n def save sFileName\n puts \"Uber code to persist #{@my_data} to #{sFileName}\"\n end\n\nend\n\nclass BrandNewClass\n include Persistence\n attr :my_data\n\n def data=(someData)\n @my_data = someData\n end\nend\n\nb = BrandNewClass.new\nb.data = \"My pwd\"\nb.save \"MyFile.secret\"\nb.load \"MyFile.secret\"\n include ModuleILike"
},
{
"answer_id": 356114,
"author": "rampion",
"author_id": 9859,
"author_profile": "https://Stackoverflow.com/users/9859",
"pm_score": 2,
"selected": false,
"text": "include Module#append_features Module#append_features method_added Module#inherit include Enumerable #each Enumerable"
}
] | 2008/12/10 | [
"https://Stackoverflow.com/questions/355633",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15124/"
] |
355,636 | <p>I have a problem that I feel is best implimented in a stand alone windows application, but needs to pass data to a web page that is already open. </p>
<p>Is it possible to pass the data directly to the web page?</p>
<p>If so, what is the best way to go about it?</p>
<p>(Its my first question, so go easy on me!)</p>
| [
{
"answer_id": 355698,
"author": "Gishu",
"author_id": 1695,
"author_profile": "https://Stackoverflow.com/users/1695",
"pm_score": 4,
"selected": true,
"text": "module Persistence\n def load sFileName\n puts \"load code to read #{sFileName} contents into my_data\"\n end\n def save sFileName\n puts \"Uber code to persist #{@my_data} to #{sFileName}\"\n end\n\nend\n\nclass BrandNewClass\n include Persistence\n attr :my_data\n\n def data=(someData)\n @my_data = someData\n end\nend\n\nb = BrandNewClass.new\nb.data = \"My pwd\"\nb.save \"MyFile.secret\"\nb.load \"MyFile.secret\"\n include ModuleILike"
},
{
"answer_id": 356114,
"author": "rampion",
"author_id": 9859,
"author_profile": "https://Stackoverflow.com/users/9859",
"pm_score": 2,
"selected": false,
"text": "include Module#append_features Module#append_features method_added Module#inherit include Enumerable #each Enumerable"
}
] | 2008/12/10 | [
"https://Stackoverflow.com/questions/355636",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/44914/"
] |
355,638 | <p>I'm using Jquery's toggle event to do some stuff when a user clicks a checkbox, like this:</p>
<pre><code>$('input#myId').toggle(
function(){
//do stuff
},
function(){
//do other stuff
}
);
</code></pre>
<p>The problem is that the checkbox isn't being ticked when I click on the checkbox. (All the stuff I've put into the toggle event is working properly.)</p>
<p>I've tried the following:</p>
<pre><code>$('input#myId').attr('checked', 'checked');
</code></pre>
<p>and</p>
<pre><code>$(this).attr('checked', 'checked');
</code></pre>
<p>and even simply</p>
<pre><code>return true;
</code></pre>
<p>But nothing is working. Can anyone tell me where I'm going wrong?</p>
<p>Edit - thanks to all who replied. Dreas' answer very nearly worked for me, except for the part that checked the attribute. This works perfectly (although it's a bit hacky)</p>
<pre><code>$('input#myInput').change(function ()
{
if(!$(this).hasClass("checked"))
{
//do stuff if the checkbox isn't checked
$(this).addClass("checked");
return;
}
//do stuff if the checkbox isn't checked
$(this).removeClass('checked');
});
</code></pre>
<p>Thanks again to all who replied.</p>
| [
{
"answer_id": 355664,
"author": "Andreas Grech",
"author_id": 44084,
"author_profile": "https://Stackoverflow.com/users/44084",
"pm_score": 7,
"selected": true,
"text": "change toggle $('input#myId').change(function () {\n if ($(this).attr(\"checked\")) {\n //do the stuff that you would do when 'checked'\n\n return;\n }\n //Here do the stuff you want to do when 'unchecked'\n});\n"
},
{
"answer_id": 355672,
"author": "adam",
"author_id": 33604,
"author_profile": "https://Stackoverflow.com/users/33604",
"pm_score": 1,
"selected": false,
"text": "$('input#myId').toggle(\n function(e){\n e.preventDefault();\n //do stuff \n $(this).attr('checked', 'true');\n },\n function(e){\n e.preventDefault();\n //do other stuff \n $(this).attr('checked', 'false');\n }\n);\n"
},
{
"answer_id": 431606,
"author": "dubek",
"author_id": 884,
"author_profile": "https://Stackoverflow.com/users/884",
"pm_score": 4,
"selected": false,
"text": "change change click keyup checked checked $('input#myInput').change(function () {\n if ($(this).attr(\"checked\")) {\n //do stuff if the checkbox is checked\n } else {\n //do stuff if the checkbox isn't checked\n }\n});\n checked input \"checked\" null"
},
{
"answer_id": 802236,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": " //toggles checkbox on/off\n $(\"input:checkbox\").change(\n function(){\n if(!this.checked){\n this.checked=true;\n }\n else{\n this.checked=false;\n }\n }\n );\n //end toggle\n"
},
{
"answer_id": 1325943,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "function chkboxToggle() {\n if ($('input#chkbox').attr('checked'))\n // do something\n else\n // do something else\n}\n <input id=\"chkbox\" type=\"checkbox\" onclick=\"chkboxToggle()\" />\n"
},
{
"answer_id": 1829263,
"author": "Richard",
"author_id": 68940,
"author_profile": "https://Stackoverflow.com/users/68940",
"pm_score": 2,
"selected": false,
"text": "checkbox.checked .checked checkbox[0].checked change() $(this)[0].checked\n"
},
{
"answer_id": 2627425,
"author": "Harikrishnan",
"author_id": 315171,
"author_profile": "https://Stackoverflow.com/users/315171",
"pm_score": 1,
"selected": false,
"text": "$(\":checkbox\").click(function(){\nif($(this).attr(\"id\").split(\"chk_all\")[1])\n {\n var ty = \"sel\"+$(this).attr(\"id\").split(\"chk_all\")[1]+\"[]\";\n if($(this).attr(\"checked\"))\n {\n $('input[name=\"'+ty+'\"]').attr(\"checked\", \"checked\");\n }\n else\n {\n $('input[name=\"'+ty+'\"]').removeAttr(\"checked\");\n }\n }\n})\n"
},
{
"answer_id": 2627612,
"author": "Harikrishnan",
"author_id": 315171,
"author_profile": "https://Stackoverflow.com/users/315171",
"pm_score": 0,
"selected": false,
"text": "$(\":checkbox\").click(function(){\n if($(this).attr(\"checked\"))\n {\n $('input[name=\"name[]\"]').attr(\"checked\", \"checked\");\n }\n else\n {\n $('input[name=\"name[]\"]').removeAttr(\"checked\");\n }\n})\n"
},
{
"answer_id": 3880871,
"author": "solsTiCe",
"author_id": 283067,
"author_profile": "https://Stackoverflow.com/users/283067",
"pm_score": 3,
"selected": false,
"text": "$('input#myId').change(\n function() {\n if ($(this).is(':checked')) {\n // do stuff here \n } else {\n // do other stuff here\n }\n});\n"
},
{
"answer_id": 4341615,
"author": "philljohn",
"author_id": 528772,
"author_profile": "https://Stackoverflow.com/users/528772",
"pm_score": 0,
"selected": false,
"text": " $(\"input[type=checkbox][checked=false]\")// be shure to set to false on ready\n $(\"input#Checkbox1\").change(function() {\n if ($(this).attr(\"checked\")) {\n $(\"#chk1\").html(\"you just selected me\")//the lable\n } else {$(\"#chk1\").html(\"you just un selected me\") } \n });\n"
}
] | 2008/12/10 | [
"https://Stackoverflow.com/questions/355638",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/22946/"
] |
355,650 | <p>I am looking for template/generator libraries for C++ that are similar to eg. Ruby's Erb, Haml, PHP's Smarty, etc.</p>
<p>It would be great if I it would sport some basic features like loops, if/else, int conversion to strings, etc.</p>
<p>Parameter passing to template rendering engine is also important if I could pass all of them in a hash map instead of calling some function for each of parameters.</p>
<p>Do you have any recommendations?</p>
<p>I can see also the possibility of embedding languages like Lua, however I haven't found a templatizing library for that either.</p>
| [
{
"answer_id": 15592275,
"author": "kirill_igum",
"author_id": 390066,
"author_profile": "https://Stackoverflow.com/users/390066",
"pm_score": 2,
"selected": false,
"text": "std::cout << format(\"The answers are {} and {}\", 23, 42); \n// => \"The answers are 23 and 42\"\n\nstd::map<std::string, std::string> m { {\"what\", \"answer\"}, {\"value\", \"42\"} }; \nstd::cout << vformat(\"The only {what} is {value}\", m); \n// => \"The only answer is 42\"\n"
},
{
"answer_id": 30281734,
"author": "burner",
"author_id": 2261889,
"author_profile": "https://Stackoverflow.com/users/2261889",
"pm_score": 1,
"selected": false,
"text": "< html\n < h1 The title is ${{ params[\"title\"] }}& >\n < ul >\n & for(int i = 0; i < boost::get<int>(params[\"items\"]); ++i) {\n < li Item ${{ i }}$ >\n & }\n>\n"
},
{
"answer_id": 31909485,
"author": "trodevel",
"author_id": 4833314,
"author_profile": "https://Stackoverflow.com/users/4833314",
"pm_score": 1,
"selected": false,
"text": "using namespace templtext;\n\nTempl * t = new Templ( \"Dear %SALUTATION %NAME. I would like to invite you for %TEXT. Sincerely yours, %MYNAME.\" );\n\nstd::map<std::string, std::string> tokens01 =\n{\n { \"SALUTATION\", \"Mr.\" },\n { \"NAME\", \"John Doe\" },\n { \"TEXT\", \"an interview\" },\n { \"MYNAME\", \"Ty Coon\" }\n};\n\nstd::map<std::string, std::string> tokens02 =\n{\n { \"SALUTATION\", \"Sweetheart\" },\n { \"NAME\", \"Mary\" },\n { \"TEXT\", \"a cup of coffee\" },\n { \"MYNAME\", \"Bob\" }\n};\n\nstd::cout << t->format( tokens01 ) << std::endl;\nstd::cout << t->format( tokens02 ) << std::endl;\n Dear Mr. John Doe. I would like to invite you for an interview. Sincerely yours, Ty Coon.\nDear Sweetheart Mary. I would like to invite you for a cup of coffee. Sincerely yours, Bob.\n using namespace templtext;\n\nstd::unique_ptr<Templ> tf1( new Templ( \"You have got an $decode( 1 ).\" ) );\nstd::unique_ptr<Templ> tf2( new Templ( \"You have got an $decode( 2 ).\" ) );\nstd::unique_ptr<Templ> tf3( new Templ( \"English version - $decode_loc( 1, EN ).\" ) );\nstd::unique_ptr<Templ> tf4( new Templ( \"German version - $decode_loc( 1, DE ).\" ) );\nstd::unique_ptr<Templ> tf5( new Templ( \"Flexible version - $decode_loc( 1, %LANG ).\" ) );\n\ntf1->set_func_proc( func );\ntf2->set_func_proc( func );\ntf3->set_func_proc( func );\ntf4->set_func_proc( func );\ntf5->set_func_proc( func );\n\nTempl::MapKeyValue map1 =\n{\n { \"LANG\", \"EN\" }\n};\n\nTempl::MapKeyValue map2 =\n{\n { \"LANG\", \"DE\" }\n};\n\nstd::cout << tf1->format() << std::endl;\nstd::cout << tf2->format() << std::endl;\nstd::cout << tf3->format() << std::endl;\nstd::cout << tf4->format() << std::endl;\nstd::cout << tf5->format( map1 ) << std::endl;\nstd::cout << tf5->format( map2 ) << std::endl;\n You have got an apple.\nYou have got an orange.\nEnglish version - apple.\nGerman version - Apfel.\nFlexible version - apple.\nFlexible version - Apfel.\n"
}
] | 2008/12/10 | [
"https://Stackoverflow.com/questions/355650",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5731/"
] |
355,670 | <p>Myself and a colleague have a dispute about which of the following is more elegant. I won't say who's who, so it is impartial. Which is more elegant?</p>
<pre><code>public function set hitZone(target:DisplayObject):void
{
if(_hitZone != target)
{
_hitZone.removeEventListener(MouseEvent.ROLL_OVER, onBtOver);
_hitZone.removeEventListener(MouseEvent.ROLL_OUT, onBtOut);
_hitZone.removeEventListener(MouseEvent.MOUSE_DOWN, onBtDown);
_hitZone = target;
_hitZone.addEventListener(MouseEvent.ROLL_OVER, onBtOver, false, 0, true);
_hitZone.addEventListener(MouseEvent.ROLL_OUT, onBtOut, false, 0, true);
_hitZone.addEventListener(MouseEvent.MOUSE_DOWN, onBtDown, false, 0, true);
}
}
</code></pre>
<p>...or...</p>
<pre><code>public function set hitZone(target:DisplayObject):void
{
if(_hitZone == target)return;
_hitZone.removeEventListener(MouseEvent.ROLL_OVER, onBtOver);
_hitZone.removeEventListener(MouseEvent.ROLL_OUT, onBtOut);
_hitZone.removeEventListener(MouseEvent.MOUSE_DOWN, onBtDown);
_hitZone = target;
_hitZone.addEventListener(MouseEvent.ROLL_OVER, onBtOver, false, 0, true);
_hitZone.addEventListener(MouseEvent.ROLL_OUT, onBtOut, false, 0, true);
_hitZone.addEventListener(MouseEvent.MOUSE_DOWN, onBtDown, false, 0, true);
}
</code></pre>
| [
{
"answer_id": 355684,
"author": "xsl",
"author_id": 11387,
"author_profile": "https://Stackoverflow.com/users/11387",
"pm_score": 5,
"selected": false,
"text": "return return continue break"
},
{
"answer_id": 355812,
"author": "Zarkonnen",
"author_id": 15255,
"author_profile": "https://Stackoverflow.com/users/15255",
"pm_score": 2,
"selected": false,
"text": "return return return"
},
{
"answer_id": 358167,
"author": "joel.neely",
"author_id": 3525,
"author_profile": "https://Stackoverflow.com/users/3525",
"pm_score": 0,
"selected": false,
"text": "public function setHitZone(target:DisplayObject):void\n {\n if(_hitZone != target)\n setHitZoneUnconditionally(target);\n\n }\n\npublic function setHitZoneUnconditionally(target:DisplayObject):void\n {\n _hitZone.removeEventListener(MouseEvent.ROLL_OVER, onBtOver);\n _hitZone.removeEventListener(MouseEvent.ROLL_OUT, onBtOut);\n _hitZone.removeEventListener(MouseEvent.MOUSE_DOWN, onBtDown);\n\n _hitZone = target;\n\n _hitZone.addEventListener(MouseEvent.ROLL_OVER, onBtOver, false, 0, true);\n _hitZone.addEventListener(MouseEvent.ROLL_OUT, onBtOut, false, 0, true);\n _hitZone.addEventListener(MouseEvent.MOUSE_DOWN, onBtDown, false, 0, true);\n\n }\n"
}
] | 2008/12/10 | [
"https://Stackoverflow.com/questions/355670",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11911/"
] |
355,673 | <p>This is probably a simple question but I am not an ASP.NET developer and I am quite stuck.</p>
<p>I have a simple search routine that returns between zero and several hundred results. Each of these must be added to the page as a button and I want to set the text of the button and the CommandArgument property so that when the button is clicked I can read the CommandArgument back and react accordingly.</p>
<p>However, when I click the button the event does not run at all. How can I get it to run?</p>
<p>The code for building the button list (simplified for readability) is as follows:</p>
<pre><code> foreach (SearchResult sr in searchResults)
{
Button result = new Button();
result.Text = sr.name;
result.CommandArgument = sr.ID.ToString();
AccountSearchResults.Controls.Add(result);
result.Click += new EventHandler(SearchResultClicked);
AccountSearchResults.Controls.Add(new LiteralControl("<br/>"));
}
</code></pre>
<p>At the minute to test, I have popped a label on the form to put the CommandArgument in. This code is never executed though.</p>
<pre><code> void SearchResultClicked(object sender, EventArgs e)
{
Label1.Text = ((Button)sender).CommandArgument;
}
</code></pre>
| [
{
"answer_id": 355683,
"author": "Ian Oxley",
"author_id": 1904,
"author_profile": "https://Stackoverflow.com/users/1904",
"pm_score": 0,
"selected": false,
"text": "result.Click += new EventHandler(SearchResultClicked);\n result.Command += new EventHandler(SearchResultClicked);\n result.CommandName = \"foo\";\n"
}
] | 2008/12/10 | [
"https://Stackoverflow.com/questions/355673",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/44938/"
] |
355,691 | <p>I've got an extremely long XML file, like</p>
<pre><code><Root>
<ele1>
<child1>context1</child1>
<child2>test1</child2>
<child1>context1</child1>
</ele1>
<ele2>
<child1>context2</child1>
<child2>test2</child2>
<child1>context2</child1>
</ele2>
<ele3>...........<elen>
</Root>
</code></pre>
<p>Now I want to remove all the second <code><child1></code> in each <code><ele></code> using xslt, is it possible?
The result would be like this:</p>
<pre><code><Root>
<ele1>
<child1>context1</child1>
<child2>test1</child2>
</ele1>
<ele2>
<child1>context2</child1>
<child2>test2</child2>
</ele2>
<ele3>...........<elen>
</Root>
</code></pre>
<p>Thank u, BR</p>
<p>Allen</p>
| [
{
"answer_id": 10670314,
"author": "ABach",
"author_id": 327179,
"author_profile": "https://Stackoverflow.com/users/327179",
"pm_score": 2,
"selected": false,
"text": "<child1> <ele*> <?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<xsl:stylesheet xmlns:xsl=\"http://www.w3.org/1999/XSL/Transform\" version=\"1.0\">\n <xsl:output omit-xml-declaration=\"no\" indent=\"yes\"/>\n <xsl:strip-space elements=\"*\"/>\n\n <!-- Identity Template: copies everything as-is -->\n <xsl:template match=\"node()|@*\">\n <xsl:copy>\n <xsl:apply-templates select=\"node()|@*\"/>\n </xsl:copy>\n </xsl:template>\n\n <!-- Remove the 2nd <child1> element from each <ele*> element -->\n <xsl:template match=\"*[starts-with(name(), 'ele')]/child1[2]\" />\n\n</xsl:stylesheet>\n <?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<Root>\n <ele1>\n <child1>context1</child1>\n <child2>test1</child2>\n <child1>context1</child1>\n </ele1>\n <ele2>\n <child1>context2</child1>\n <child2>test2</child2>\n <child1>context2</child1>\n </ele2>\n</Root>\n <?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<Root>\n <ele1>\n <child1>context1</child1>\n <child2>test1</child2>\n </ele1>\n <ele2>\n <child1>context2</child1>\n <child2>test2</child2>\n </ele2>\n</Root>\n"
}
] | 2008/12/10 | [
"https://Stackoverflow.com/questions/355691",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
355,700 | <p>I want to embed a link to a controller action in my page so I can use it from javascript. Something like</p>
<pre><code>var pollAction = '/Mycontroller/CheckStatus'
</code></pre>
<p>Now I am happy to hardcode it, but it would be really nice if there were a method I could use to create the URL. The AjaxHelper/HtmlExtensions contain methods to create hyperlinks (.ActionLink(...) and so on), but if you look into the guts of them, they rely on a method called UrlHelper.GenerateUrl() to resolve a controller and action into a url. This is internal so I can't really get at this.</p>
<p>Anyone found a good method in the framework to do this? Or must I roll my own?</p>
| [
{
"answer_id": 355736,
"author": "mapache",
"author_id": 41422,
"author_profile": "https://Stackoverflow.com/users/41422",
"pm_score": 5,
"selected": true,
"text": "var pollAction = '<%=Url.Action(\"CheckStatus\", \"MyController\") %>';\n"
},
{
"answer_id": 355824,
"author": "Michiel",
"author_id": 44954,
"author_profile": "https://Stackoverflow.com/users/44954",
"pm_score": 4,
"selected": false,
"text": "ViewPage ViewUserControl Url.Action String url = RouteTable.Routes.GetVirtualPath\n (\n ((MvcHandler) HttpContext.Current.CurrentHandler).RequestContext,\n new RouteValueDictionary\n (\n new \n { \n controller = \"MyController\", \n action = \"CheckState\", \n id = idParameter \n }\n )\n ).VirtualPath;\n"
}
] | 2008/12/10 | [
"https://Stackoverflow.com/questions/355700",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/22360/"
] |
355,723 | <p>I'm trying in vain to write a regular expression to match valid ssh connection strings.</p>
<p>I really only need to recognise strings of the format:</p>
<ul>
<li>user@hostname:/some/path</li>
</ul>
<p>but it would be nice to also match an implicit home directory:</p>
<ul>
<li>user@hostname:</li>
</ul>
<p>I've so-far come up with this regex:</p>
<pre><code>/^[:alnum:]+\@\:(\/[:alnum:]+)*$/
</code></pre>
<p>which doesn't work as intended.</p>
<p>Any suggestions welcome before my brain explodes and I start speaking in line noise :)</p>
| [
{
"answer_id": 355750,
"author": "paxdiablo",
"author_id": 14860,
"author_profile": "https://Stackoverflow.com/users/14860",
"pm_score": 2,
"selected": false,
"text": "/^[:alnum:]+\\@[:alnum:\\.]\\:(\\/[:alnum:]+)*$/\n /^[A-Za-z][A-Za-z0-9_]*\\@[A-Za-z][A-Za-z0-9_\\.]*\\:(\\/[A-Za-z][A-Za-z0-9_]*)*$/\n"
},
{
"answer_id": 355753,
"author": "Kent Fredric",
"author_id": 15614,
"author_profile": "https://Stackoverflow.com/users/15614",
"pm_score": 0,
"selected": false,
"text": "/^[:alnum:]+\\@\\:(\\/[:alnum:]+)*$/\n /^[[:alnum:]]+\\@\\:(\\/[[:alnum:]]+)*$/\n my $at = q{@};\nmy @res = (\n qr/^[:alnum:]+${at}[:alnum:]+:(\\/[:alnum:]+)*$/,\n qr/^[[:alnum:]]+${at}[[:alnum:]]+:(\\/[[:alnum:]]+)*$/,\n qr/^[a-z][[:alnum:]_]*${at}[a-z][[:alnum:]_.]*:(\\/[^\\/]*)*$/i,\n);\n\nmy @u = qw{\n user@hostname:/some/path\n bob_foo@bobs.fish.stores.com:/foo/bar/baz/quux_\n 9foo@9foo.org:/9foo/9foo\n baz@foo.org:/9foo/_#_numerics_are_fine_in_URI_and_so_is_anything_else_(virtually)\n};\n\nfor my $str (@u) {\n for my $re (@res) {\n if ( $str =~ $re ) {\n print \"$str =~ $re\\n\";\n }\n else {\n print \"NOT $str =~ $re\\n\";\n }\n }\n}\n POSIX syntax [: :] belongs inside character classes in regex; marked by <-- HERE in m/^[:alnum:] <-- HERE +@[:alnum:]+:(/[:alnum:]+)*$/ at /tmp/egl.pl line 27.\nPOSIX syntax [: :] belongs inside character classes in regex; marked by <-- HERE in m/^[:alnum:]+@[:alnum:] <-- HERE +:(/[:alnum:]+)*$/ at /tmp/egl.pl line 27.\nPOSIX syntax [: :] belongs inside character classes in regex; marked by <-- HERE in m/^[:alnum:]+@[:alnum:]+:(/[:alnum:] <-- HERE +)*$/ at /tmp/egl.pl line 27.\nNOT user@hostname:/some/path =~ (?-xism:^[:alnum:]+@[:alnum:]+:(/[:alnum:]+)*$)\nuser@hostname:/some/path =~ (?-xism:^[[:alnum:]]+@[[:alnum:]]+:(/[[:alnum:]]+)*$)\nuser@hostname:/some/path =~ (?i-xsm:^[a-z][[:alnum:]_]*@[a-z][[:alnum:]_.]*:(/[^/]*)*$)\nNOT bob_foo@bobs.fish.stores.com:/foo/bar/baz/quux_ =~ (?-xism:^[:alnum:]+@[:alnum:]+:(/[:alnum:]+)*$)\nNOT bob_foo@bobs.fish.stores.com:/foo/bar/baz/quux_ =~ (?-xism:^[[:alnum:]]+@[[:alnum:]]+:(/[[:alnum:]]+)*$)\nbob_foo@bobs.fish.stores.com:/foo/bar/baz/quux_ =~ (?i-xsm:^[a-z][[:alnum:]_]*@[a-z][[:alnum:]_.]*:(/[^/]*)*$)\nNOT 9foo@9foo.org:/9foo/9foo =~ (?-xism:^[:alnum:]+@[:alnum:]+:(/[:alnum:]+)*$)\nNOT 9foo@9foo.org:/9foo/9foo =~ (?-xism:^[[:alnum:]]+@[[:alnum:]]+:(/[[:alnum:]]+)*$)\nNOT 9foo@9foo.org:/9foo/9foo =~ (?i-xsm:^[a-z][[:alnum:]_]*@[a-z][[:alnum:]_.]*:(/[^/]*)*$)\nNOT baz@foo.org:/9foo/_#_numerics_are_fine_in_URI_and_so_is_anything_else_(virtually) =~ (?-xism:^[:alnum:]+@[:alnum:]+:(/[:alnum:]+)*$)\nNOT baz@foo.org:/9foo/_#_numerics_are_fine_in_URI_and_so_is_anything_else_(virtually) =~ (?-xism:^[[:alnum:]]+@[[:alnum:]]+:(/[[:alnum:]]+)*$)\nbaz@foo.org:/9foo/_#_numerics_are_fine_in_URI_and_so_is_anything_else_(virtually) =~ (?i-xsm:^[a-z][[:alnum:]_]*@[a-z][[:alnum:]_.]*:(/[^/]*)*$)\n"
},
{
"answer_id": 355800,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "/^\\w+\\@(\\w|\\.)+\\:(\\/\\w+)*$/\n"
},
{
"answer_id": 355843,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "/^\\w+\\@(\\w|\\.)+\\:(\\/(\\w|.)+)*$/\n"
},
{
"answer_id": 356322,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "/^\\w+\\@(\\w|\\.)+\\:(\\/(\\w|.)+\\/?)*$/\n"
},
{
"answer_id": 26078633,
"author": "Derrek Bertrand",
"author_id": 4086828,
"author_profile": "https://Stackoverflow.com/users/4086828",
"pm_score": 0,
"selected": false,
"text": "stackoverflow.com \\w #should match 99.9% of SSH users\nuser_regex='[a-zA-Z][a-zA-Z0-9_]+'\n#match domains\nhost_regex='([a-zA-Z][a-zA-Z0-9\\-]*\\.)*[a-zA-Z][a-zA-Z0-9\\-]*'\n#match paths starting with / and empty strings (which is valid for our use!)\npath_regex='(\\/[A-Za-z0-9_\\-\\.]+)*\\/?'\n#the complete regex\nmaster_regex=\"^$user_regex\\@$host_regex\\:$path_regex\\$\"\n 0-9"
}
] | 2008/12/10 | [
"https://Stackoverflow.com/questions/355723",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
355,724 | <p>Is it possible to embed a DOS console in a Windows Form or User Control in C# 2.0?</p>
<p>We have a legacy DOS product that my Windows app has to interact with, and it's been requested that an instance of the legacy product should run within the Windows application.</p>
<p>At the moment, I'm using the user32.dll to locate the window that the DOS product is running in, minimising then maximising the window, and typing characters into the window. This isn't a very good solution to the problem, as it means my application has to store the window name in application settings, and requires that the user returns to the correct page of the DOS app before using the interaction function.</p>
<p>EDIT: Some more information</p>
<p>The legacy app needs to be visible to the user, but not in a separate window.</p>
<p>I've tried TimothyP's answer and it works very well, but is it possible to achieve the same functionality, but with the DOS window visually embedded in a windows form or user control instead of popping up in it's own window? Preferably in a ShowDialog() way so that the user cannot interact with the app wile they are in 'Legacy Mode', so to speak.</p>
| [
{
"answer_id": 355749,
"author": "TimothyP",
"author_id": 28149,
"author_profile": "https://Stackoverflow.com/users/28149",
"pm_score": 6,
"selected": true,
"text": "var processStartInfo = new ProcessStartInfo(\"someoldapp.exe\", \"-p someparameters\");\n\nprocessStartInfo.UseShellExecute = false;\nprocessStartInfo.ErrorDialog = false;\n\nprocessStartInfo.RedirectStandardError = true;\nprocessStartInfo.RedirectStandardInput = true;\nprocessStartInfo.RedirectStandardOutput = true;\nprocessStartInfo.CreateNoWindow = true;\n\nProcess process = new Process();\nprocess.StartInfo = processStartInfo;\nbool processStarted = process.Start();\n\nStreamWriter inputWriter = process.StandardInput;\nStreamReader outputReader = process.StandardOutput;\nStreamReader errorReader = process.StandardError;\nprocess.WaitForExit();\n"
}
] | 2008/12/10 | [
"https://Stackoverflow.com/questions/355724",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18895/"
] |
355,730 | <p>What is the best way to store instances of a class to file/database?</p>
<p>We have a base class called Command and loads of derived classes.
Users create instances of these classes by adding commands to a graphical designer
where they can configure them. (Set the properties).</p>
<p>We then need a way to store these "commands" to a file without losing
any information.</p>
<p>One idea was to use db4o, but the GPL license is not acceptable for this project.</p>
<p>Any suggestions or code samples?</p>
<p>Update:</p>
<p>(In order to "de-blurryfie" my question :p)</p>
<p>The generated code might look something like:</p>
<pre><code> command[i++] = new DelayInSecondsCommand(2);
command[i++] = new DaliRequestCommand(1, false, 254);
command[i++] = new DaliRequestCommand(2, false, 254);
command[i++] = new DaliRequestCommand(3, false, 254);
command[i++] = new WaitInSecondsCommand(2);
command[i++] = new DaliRequestCommand(1, false, 0);
command[i++] = new DaliRequestCommand(2, false, 0);
command[i++] = new DaliRequestCommand(3, false, 0);
command[i++] = new JumpCommand(0);
</code></pre>
<p>But then with loads of different commands.</p>
<p>I know it's possible with .NET serialization, altough I've never used it before,
but I was wondering if there are better alternatives, like I said db4o seems nice but the license doesn't fit the project.</p>
<p>Update 2:</p>
<p>Thank you for the replies. I'll probably go with the serialization solution now,
but I'll look into the other options as well. F.Y.I. data is stored in a SQL Compact database.</p>
| [
{
"answer_id": 355838,
"author": "Marc Gravell",
"author_id": 23354,
"author_profile": "https://Stackoverflow.com/users/23354",
"pm_score": 2,
"selected": false,
"text": "DataContractSerializer BinaryFormatter XmlSerializer"
}
] | 2008/12/10 | [
"https://Stackoverflow.com/questions/355730",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/28149/"
] |
355,732 | <p>For example, java.io.File is just a concrete class. My replacement for it supports resolving Windows shortcuts. I need to preprocess constructor parameters to resolve possible .lnk files because the FileSystem object that does normalizing/canonicalision/resolving on the abstract paths is not accessible. The need for preprocessing rules out pure subclassing - can't do preprocessing before calling super(...) and File is immutable. So I extend File and use a delegate, overriding all of File's constructors and methods (calling super("") in all constructors).</p>
<p>This works nicely, but is obviously not ideal - if File changes, I will not have overridden any new methods or constructors and this will expose the underlying empty abstract pathname. Am I missing something obvious? It seems like there should be a simpler/better way.</p>
| [
{
"answer_id": 355754,
"author": "Dan Vinton",
"author_id": 21849,
"author_profile": "https://Stackoverflow.com/users/21849",
"pm_score": 2,
"selected": false,
"text": "super() public class MyFile extends File {\n\n public MyFile(String path) {\n\n // static blocks aren't ideal, this is just for demo purposes:\n super(cleanPath(path)); \n }\n\n private static String cleanPath(String uncleanPath) {...}\n\n}\n"
},
{
"answer_id": 355774,
"author": "bruno conde",
"author_id": 31136,
"author_profile": "https://Stackoverflow.com/users/31136",
"pm_score": 2,
"selected": false,
"text": "public class FileWrapper {\n\n private File file;\n private String path;\n\n private FileWrapper(String path) {\n this.path = path;\n file = new File(preProcess(path));\n }\n\n private String preProcess(String path) {\n // process\n return path;\n }\n\n public File getFile() {\n return file;\n }\n\n public String getPath() {\n return path;\n }\n}\n"
}
] | 2008/12/10 | [
"https://Stackoverflow.com/questions/355732",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2492/"
] |
355,737 | <p>How can I rotate the Apache Access and Error logs on a Window 2000 box?</p>
<p>I include my batch file below as an answer.</p>
<p>Is there a way of doing this directly via the Apache config file? I'm currently using the following customlog command to generate daily logs.</p>
<p>CustomLog '|" "*Apache-Path/bin/rotatelogs.exe" "*Apache-Path/logs/backup/internet_access_%d-%m-%y.log" 86400' combined</p>
| [
{
"answer_id": 355792,
"author": "Adam Bellaire",
"author_id": 21632,
"author_profile": "https://Stackoverflow.com/users/21632",
"pm_score": 0,
"selected": false,
"text": "logrotate"
},
{
"answer_id": 355857,
"author": "alimack",
"author_id": 39447,
"author_profile": "https://Stackoverflow.com/users/39447",
"pm_score": 4,
"selected": true,
"text": "@echo off\n\n:: Name - svrlogmng.bat\n:: Description - Server Log File Manager\n::\n:: History\n:: Date Authory Change\n:: 22-May-2005 AGButler Original\n:: 14-Jan-2008 AIMackenzie Changed net stops and paths where necessary\n\n:: ========================================================\n:: setup variables and parameters\n:: ========================================================\n\n:: generate date and time variables\nfor /f \"tokens=2,3,4 delims=/ \" %%i in ('date /T') do set trdt=%%k%%j%%i\nfor /f \"tokens=1,2 delims=: \" %%i in ('time /T') do set trtt=%%i%%j\nset nftu=%trdt%%trtt%\n\n:: set the Number Of Archives To Keep\nset /a noatk=8\n\n:: ========================================================\n:: turn over log files\n:: ========================================================\n\n:: change to the apache log file directory\ncd /D \"D:\\Program Files\\Apache Software Foundation\\Apache2.2\\logs\\\"\n\n:: stop Apache Service, Move log files and restart Apache Service\n\"D:\\Program Files\\Apache Software Foundation\\Apache2.2\\bin\\httpd.exe\" -k stop\n\necho %nftu% >> access.log\nmove \"D:\\Program Files\\Apache Software Foundation\\Apache2.2\\logs\\access.log\" \"D:\\Program Files\\Apache Software Foundation\\Apache2.2\\logs\\%nftu%_access.log\"\n\necho %nftu% >> error.log\nmove \"D:\\Program Files\\Apache Software Foundation\\Apache2.2\\logs\\error.log\" \"D:\\Program Files\\Apache Software Foundation\\Apache2.2\\logs\\%nftu%_error.log\"\n\n\"D:\\Program Files\\Apache Software Foundation\\Apache2.2\\bin\\httpd.exe\" -k start\n\n:: ========================================================\n:: zip todays Access and Error log files, then delete old logs\n:: ========================================================\n\n:: zip the files\n\"D:\\Program Files\\7-Zip\\7z.exe\" a -tzip %nftu%_logs.zip %nftu%_access.log %nftu%_error.log\n\n:: del the files\ndel /Q %nftu%_*.log\n\n:: ========================================================\n:: rotate the zip files\n:: ========================================================\n\n:: make list of archive zip files\ntype NUL > arclist.dat\nfor /F \"tokens=1,2 delims=[] \" %%i in ('dir /B *_logs.zip ^| find /N \"_logs.zip\"') do echo %%i = %%j>> arclist.dat\n\n:: count total number of files\nfor /F \"tokens=1 delims=\" %%i in ('type arclist.dat ^| find /C \"_logs.zip\"') do set tnof=%%i\n\n:: setup for and create the deletion list\nset /a negtk=%noatk%*-1\nset /a tntd=%tnof% - %noatk%\n\ntype NUL>dellist.dat\nfor /L %%i in (%negtk%,1,%tntd%) do find \" %%i = \" arclist.dat >> dellist.dat\n\n:: del the old files\nfor /F \"tokens=3 delims= \" %%i in ('find \"_logs.zip\" dellist.dat') do del /Q %%i\n\n:: remove temp files\ndel /Q arclist.dat\ndel /Q dellist.dat\n"
},
{
"answer_id": 355929,
"author": "chriscena",
"author_id": 32671,
"author_profile": "https://Stackoverflow.com/users/32671",
"pm_score": 1,
"selected": false,
"text": "option explicit\n\nconst DEBUG_MODE = false\nconst MAX_ROTATIONS = 10\nconst MAX_SIZE = 2097152 ' 2MB\nconst WEB_LOGS = \"c:\\path\\to\\site\\logs\"\nconst PHP_LOG = \"c:\\path\\to\\phplog\"\nconst APACHE_LOGS = \"C:\\path\\to\\Apache2\\logs\"\nconst APACHE_SERVICE =\"Apache2.2\" ' Name of the apache service for restart\nconst ZIP_APP = \"c:\\path\\to\\zip.exe\"\nconst LOGROTATE_LOG = \"c:\\tmp\\logrotate.log\"\n\ndim aLogs\naLogs = Array(\"\\error.log\",\"\\transfer.log\",\"\\sec.log\",\"\\phperror.log\") \n\ndim oFSO\nset oFSO = CreateObject(\"Scripting.FileSystemObject\")\n\nif (not DEBUG_MODE) then\n dim oLogFile\n set oLogFile = oFSO.CreateTextFile(LOGROTATE_LOG, 2, True)\nend if\n\ndim bHasRotated\nbHasRotated = false\n\nPrint \"Starting log rotation\"\nPrint \"=====================\"\nManageWebLogs()\nManageApacheLogs()\nManagePhpLog()\n\nif (bHasRotated = true) then\n Print \"=====================\"\n RestartService APACHE_SERVICE\nend if\n\nPrint \"=====================\"\nPrint \"Log rotation finished\"\n\nif (not DEBUG_MODE) then\n oLogFile.Close\n set oLogFile = nothing\nend if\nset oFSO = nothing\n\n'*****************************************************************************\n' Loop through all the subfolders in the weblog directory\nsub ManageWebLogs()\n dim oLogDirs\n set oLogDirs = oFSO.GetFolder(WEB_LOGS)\n dim oLogDir\n for each oLogDir in oLogDirs.SubFolders\n Print \"In \" & oLogDir.Name\n RotateLogs(oLogDir)\n next \n set oLogDir = nothing\nend sub\n\n'*****************************************************************************\n' Loop through the log files in the Apache logs directory\nsub ManageApacheLogs()\n dim oLogDir\n set oLogDir = oFSO.GetFolder(APACHE_LOGS)\n Print \"In \" & oLogDir.Name\n RotateLogs(oLogDir)\n set oLogDir = nothing\nend sub\n\n'*****************************************************************************\n' Loop through the log files in the Apache logs directory\nsub ManagePhpLog()\n dim oLogDir\n set oLogDir = oFSO.GetFolder(PHP_LOG)\n Print \"In \" & oLogDir.Name\n RotateLogs(oLogDir)\n set oLogDir = nothing\nend sub\n\n\n'*****************************************************************************\n' Traverse through each of the log file types and check if they need rotation\nsub RotateLogs(ByVal oFolder)\n dim sLog\n dim oLog\n for each sLog in aLogs\n if oFSO.FileExists(oFolder.Path & sLog) then\n set oLog = oFSO.GetFile(oFolder.Path & sLog)\n if (oLog.Size > MAX_SIZE) then\n RotateLog oFolder.Path & sLog\n ArchiveLog oFolder.Path & sLog\n bHasRotated = true\n end if\n end if\n next\n set oLog = nothing\nend sub\n\n\n'*****************************************************************************\n' Rotates the given log, by incrementing the file name\nsub RotateLog(ByVal sLog)\n dim i\n dim sOldFile, sNewFile\n for i = MAX_ROTATIONS to 1 step -1\n sOldFile = sLog & \".\" & i & \".zip\"\n sNewFile = sLog & \".\" & (i+1) & \".zip\"\n if oFSO.FileExists(sOldFile) and i = MAX_ROTATIONS then\n ' Delete zipfile \n Print \"-- Deleting \" & sOldFile\n oFSO.DeleteFile(sOldFile)\n elseif oFSO.FileExists(sOldFile) then\n ' Rename zipfile\n Print \"-- Renaming \" & sOldFile & \" to \" & sNewFile\n oFSO.MoveFile sOldFile, sNewFile\n end if\n next\nend sub\n\n\n'*****************************************************************************\n' Zips the current log\nsub ArchiveLog(ByVal sLog)\n Dim oShell\n Set oShell = CreateObject(\"WScript.Shell\")\n dim sZipFile \n sZipFile = sLog & \".1.zip\"\n Print \"-- Archiving \" & sLog & \" to \" & sZipFile\n oShell.Run \"cmd /c \" & ZIP_APP & \" -jq \" & sZipFile & \" \" & sLog, 0, true\n oFSO.DeleteFile(sLog)\n set oShell = nothing\nend sub\n\n\n' ****************************************************************************\n' Restarts a given service (in our case Apache)\nprivate sub RestartService( _\n ByVal sService _\n)\n\n Dim oShell\n Set oShell = CreateObject(\"WScript.Shell\")\n\n ' Service stopped with 'Net' command\n oShell.Run \"cmd /c net stop \" & sService, 0, true\n Print sService & \" service stopped\"\n\n ' Service started with 'Net' command\n oShell.Run \"cmd /c net start \" & sService, 0, true\n Print sService & \" service restarted\"\n\n set oShell = nothing\nend sub\n\n\n'*****************************************************************************\n' Echoes out the given message if in debug mode\nsub Print(ByVal sMsg)\n if (DEBUG_MODE) then\n wscript.echo sMsg\n else\n oLogFile.WriteLine sMsg\n end if\nend sub\n"
},
{
"answer_id": 8171413,
"author": "sas900",
"author_id": 1052314,
"author_profile": "https://Stackoverflow.com/users/1052314",
"pm_score": 2,
"selected": false,
"text": "@echo off\nSETLOCAL ENABLEEXTENSIONS ENABLEDELAYEDEXPANSION\n:: ========================================================\n:: setup variables and parameters\n:: ========================================================\n\n:: USE Service Display Name, Services are space-separated -> Syntax: \"Display Name 1\" \"Display Name 2\"\nSET ROTATE_SERVICES=\"Apache2.2\"\n\n:: setting LOG-directory, log-files in this directory should be rotate\nSET ROTATE_LOGDIR=F:\\xampp\\apache\\logs\n\n:: files which should rotate (space separated)\nSET ROTATE_FILES=access.log error.log ssl_request.log\n\n:: SET the Number Of Archives To Keep\nSET /a keptarchives=5\n\n:: SET delimiter for date format (english \"/\", german \".\")\nSET DATEDEL=.\n:: ========================================================\n:: DO NOT CHANGE ANYTHING\n:: ========================================================\n\n:: Check for existing Log-directory\nIF NOT EXIST \"%ROTATE_LOGDIR%\" (\n CALL :LOG Please check your paths to Log Directory\n PAUSE\n GOTO :EOF\n)\n\n:: Check for existing Log-files\nFOR %%d IN (%ROTATE_FILES%) DO (\n IF NOT EXIST \"%ROTATE_LOGDIR%\\%%d\" (\n CALL :LOG File %ROTATE_LOGDIR%\\%ROTATE_LOGFILES% does not exist!\n PAUSE\n GOTO :EOF\n )\n)\n\n:: generate date and time variables for execution\nFOR /f \"tokens=1,2,3 delims=%DATEDEL% \" %%i IN ('date /T') DO SET execdate=%%k%%j%%i\nFOR /f \"tokens=1,2 delims=: \" %%i IN ('time /T') DO SET exectime=%%i%%j\nSET fullexectime=%execdate%_%exectime%\n:: ========================================================\n\n\n:: ========================================================\n:: Operations\n:: ========================================================\n\nFOR %%d IN (%ROTATE_SERVICES%) DO (\n NET STOP %%d\n)\n\nFOR %%d IN (%ROTATE_FILES%) DO (\n cd /d %ROTATE_LOGDIR%\n IF NOT EXIST OLD (MKDIR OLD) \n move %%d %ROTATE_LOGDIR%\\OLD\\%fullexectime%_%%d\n)\n\nFOR %%d IN (%ROTATE_SERVICES%) DO (\n NET START %%d\n)\n\n:: ========================================================\n:: ZIP - LOGFILES\n:: ========================================================\ncd /d %ROTATE_LOGDIR%\\OLD\nCALL \"%~dp0\\7za.exe\" a %ROTATE_LOGDIR%\\OLD\\%fullexectime%_log.zip %ROTATE_LOGDIR%\\OLD\\%fullexectime%_*.log\n IF %ERRORLEVEL% NEQ 0 (\n CALL :LOG Error while compressing log-file. Log will not deleted and not rotated. Check your OLD-directory!\n PAUSE\n GOTO :EOF\n )\ndel /Q %fullexectime%_*.log\n\n:: ========================================================\n:: ROTATE - ZIPPED LOGFILES\n:: ========================================================\n\n:: make list of archive zip files\ntype NUL > arclist.dat\nfor /F \"tokens=1,2 delims=[] \" %%i in ('dir /B *_log.zip ^| find /N \"_log.zip\"') do echo %%i = %%j>> arclist.dat\n\n:: count total number of files\nfor /F \"tokens=1 delims=\" %%i in ('type arclist.dat ^| find /C \"_log.zip\"') do set tnof=%%i\n\n:: setup for and create the deletion list\nset /a negtk=%keptarchives%*-1\nset /a tntd=%tnof% - %keptarchives%\n\ntype NUL>dellist.dat\nfor /L %%i in (%negtk%,1,%tntd%) do find \" %%i = \" arclist.dat >> dellist.dat\n\n:: del the old files\nfor /F \"tokens=3 delims= \" %%i in ('find \"_log.zip\" dellist.dat') do del /Q %%i\n\n:: remove temp files\ndel /Q arclist.dat\ndel /Q dellist.dat\n\n\nGOTO :EOF\n\n:LOG\n SET MSG=[%DATE%, %TIME: =0%] %*\n ECHO.%MSG%\n SET MSG=\n GOTO :EOF\npause\n"
}
] | 2008/12/10 | [
"https://Stackoverflow.com/questions/355737",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/39447/"
] |
355,775 | <p>I'm writing a JavaSCript class that has a method that recursively calls itself.</p>
<pre><code>Scheduler.prototype.updateTimer = function () {
document.write( this._currentTime );
this._currentTime -= 1000;
// recursively calls itself
this._updateUITimerHandler = window.setTimeout( arguments.callee , 1000 );
}
</code></pre>
<p>Property description:</p>
<pre><code>_currentTime: the currentTime of the timer in miliseconds.
_updateUITimerHandler: stores the reference so can be used later with clearTimeout().
</code></pre>
<p>my problem is where I'm using recursion with setTimeout(). I know setTimeout() will accept some string to execute, or a reference to a function. since this function is method of an object, I don't know how to call it from outside. so I used the second format of setTimeout() and passed in a reference to the method itself. but it does not work.</p>
| [
{
"answer_id": 355790,
"author": "annakata",
"author_id": 13018,
"author_profile": "https://Stackoverflow.com/users/13018",
"pm_score": 1,
"selected": false,
"text": "function f() \n{\n alert('foo');\n window.setTimeout(arguments.callee,5000);\n}\n\nf();\n"
},
{
"answer_id": 355825,
"author": "Pablo Cabrera",
"author_id": 12540,
"author_profile": "https://Stackoverflow.com/users/12540",
"pm_score": 0,
"selected": false,
"text": "/* ... */\nvar func = arguments.callee;\nthis._updateUITimerHandler = window.setTimeout(function() { func(); }, 1000);\n/* ... */\n"
},
{
"answer_id": 355826,
"author": "AnthonyWJones",
"author_id": 17516,
"author_profile": "https://Stackoverflow.com/users/17516",
"pm_score": 4,
"selected": true,
"text": "Scheduler.prototype.startTimer = function() {\n var self = this;\n function updateTimer() {\n this._currentTime -= 1000;\n self.hTimer = window.setTimeout(updateTimer, 1000)\n self.tick()\n }\n this.hTimer = window.setTimeout(updateTimer, 1000)\n}\nScheduler.prototype.stopTimer = function() {\n if (this.hTimer != null) window.clearTimeout(this.hTimer)\n this.hTimer = null;\n}\nScheduler.prototype.tick = function() {\n //Do stuff on timer update\n}\n"
}
] | 2008/12/10 | [
"https://Stackoverflow.com/questions/355775",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9394/"
] |
355,787 | <p>This is something I'm not much consistent about and always curious about what other people do.</p>
<p>How do you access internal properties (private or public)? </p>
<p>For example you've got this property :</p>
<pre><code>Private _Name As String
Public Property Name() As String
Get
Return _Name
End Get
Set(ByVal value As String)
_Name = value
End Set
End Property
</code></pre>
<p>In the same class within another function which one do you prefer? and why?</p>
<pre><code>_Name = "Johnny"
</code></pre>
<p>or </p>
<pre><code>Name = "Johnny"
</code></pre>
<p><strong>Ignore the fact that I used Name instead of Me.Name.</strong></p>
| [
{
"answer_id": 355797,
"author": "bezmax",
"author_id": 43677,
"author_profile": "https://Stackoverflow.com/users/43677",
"pm_score": 1,
"selected": false,
"text": "Name = \"Johny\"\n"
},
{
"answer_id": 355806,
"author": "Jon Skeet",
"author_id": 22656,
"author_profile": "https://Stackoverflow.com/users/22656",
"pm_score": 5,
"selected": true,
"text": "min <= max public void SetMinMax(int min, int max)\n{\n if (max > min)\n {\n throw new ArgumentOutOfRangeException(\"max\";\n }\n // We're okay now - no need to validate, so go straight to fields\n this.min = min;\n this.max = max;\n}\n public string Name\n{\n string name;\n\n get { return name; }\n set\n {\n if (value == null)\n {\n throw new ArgumentNullException(\"value\");\n } \n name = value;\n }\n}\n name Name"
},
{
"answer_id": 355807,
"author": "finnsson",
"author_id": 24044,
"author_profile": "https://Stackoverflow.com/users/24044",
"pm_score": 2,
"selected": false,
"text": "Name = \"Johnny\"\n"
},
{
"answer_id": 355845,
"author": "dr. evil",
"author_id": 40322,
"author_profile": "https://Stackoverflow.com/users/40322",
"pm_score": 0,
"selected": false,
"text": "Me.Name = \"Johnny\"\n Name = \"Johnny\"\n _Name = \"Jonny\"\n"
}
] | 2008/12/10 | [
"https://Stackoverflow.com/questions/355787",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/40322/"
] |
355,796 | <p>My relative is studying programming and has a hard time understanding classes. He has trouble understanding for example that you need to instantiate it, that methods cannot access variables in other methods and if you change a variable in one instance of a class it doesn't change for other instances.</p>
<p>I've tried to use analogies like a class definition is like a blueprint of a house. And instances are houses made from that blueprint.</p>
<p>How do you explain classes and OO in general?</p>
| [
{
"answer_id": 355810,
"author": "Robert Gould",
"author_id": 15124,
"author_profile": "https://Stackoverflow.com/users/15124",
"pm_score": 5,
"selected": true,
"text": " // Assembly: Common Classes\n // Namespace: CommonClasses\n\n public interface IAnimal\n {\n string Name\n { \n get; \n }\n string Talk();\n }\n\n // Assembly: Animals\n // Namespace: Animals\n\n public class AnimalBase\n {\n private string _name;\n AnimalBase(string name)\n {\n _name = name;\n }\n public string Name\n {\n get\n {\n return _name;\n }\n }\n }\n\n // Assembly: Animals\n // Namespace: Animals\n\n public class Cat : AnimalBase, IAnimal\n {\n public Cat(String name) :\n base(name)\n {\n }\n\n public string Talk() {\n return \"Meowww!\";\n }\n }\n\n // Assembly: Animals\n // Namespace: Animals\n\n public class Dog : AnimalBase, IAnimal\n {\n public Dog(string name) : \n base(name)\n {\n }\n\n public string Talk() {\n return \"Arf! Arf!\";\n }\n }\n\n // Assembly: Program\n // Namespace: Program\n // References and Uses Assemblies: Common Classes, Animals\n\n public class TestAnimals\n {\n // prints the following:\n //\n // Missy: Meowww!\n // Mr. Bojangles: Meowww!\n // Lassie: Arf! Arf!\n //\n public static void Main(String[] args)\n {\n List<IAnimal> animals = new List<IAnimal>();\n animals.Add(new Cat(\"Missy\"));\n animals.Add(new Cat(\"Mr. Bojangles\"));\n animals.Add(new Dog(\"Lassie\"));\n\n foreach(IAnimal animal in animals)\n {\n Console.WriteLine(animal.Name + \": \" + animal.Talk());\n } \n }\n }\n"
}
] | 2008/12/10 | [
"https://Stackoverflow.com/questions/355796",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/33468/"
] |
355,802 | <p>Is there some standard way or has anyone written something that allows you to log a message and have it be displayed either in a small scrolling section on the iphone screen or in a separate window in the iphone simulator?</p>
<p>Update:
For noobs like me and don't know, use the NSLog methods as decribed below and make sure you select Run->Console to display the console.</p>
<p>Would still like to know if anyone has written a simple logger that displays on the iphone itself....</p>
| [
{
"answer_id": 355861,
"author": "adam",
"author_id": 33604,
"author_profile": "https://Stackoverflow.com/users/33604",
"pm_score": 4,
"selected": true,
"text": "NSLog(@\"message\");\n printf(\"message\");\n"
},
{
"answer_id": 358233,
"author": "Rob",
"author_id": 386102,
"author_profile": "https://Stackoverflow.com/users/386102",
"pm_score": 4,
"selected": false,
"text": "NSLog(@\"My int: %d my BOOL: %d\", myInt, myBOOL);\nNSLog(@\"My object of any NSObject: %@\", anObjectOfAnyKind);\nNSLog(@\"My float: %f\",myFloat);\n"
},
{
"answer_id": 33746816,
"author": "nevster",
"author_id": 36510,
"author_profile": "https://Stackoverflow.com/users/36510",
"pm_score": 0,
"selected": false,
"text": "print(\"log msg\")\n"
}
] | 2008/12/10 | [
"https://Stackoverflow.com/questions/355802",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/36510/"
] |
355,813 | <p>I've got some entities which have decimal properties on them. These entities' properties are displayed in multiple places throughout my UI.</p>
<p>Currently I'm finding myself doing:</p>
<pre><code>litWeight.Text = person.Weight.ToString("0.00");
</code></pre>
<p>all over the place.
Now I know for a fact that in several instances, and am suspicious of many others that the client is likely to want the values to 3d.p. in the future.</p>
<p>Is there some pattern I can employ to handle the formatting of this Weight property (and other properties; not just decimals, perhaps dates etc.) so that I can have this formatting in a single place?</p>
<p>I know could use a formatstring in the webconfig, or write some extension methods in the UI but these don't seem very elegant solutions.</p>
<p>It would be nice to have some formatting objects which are tied to my entities, so its inherently obvious which formatter to use.</p>
<p>Thanks,</p>
<p>Andrew</p>
| [
{
"answer_id": 355852,
"author": "Toni Ruža",
"author_id": 6267,
"author_profile": "https://Stackoverflow.com/users/6267",
"pm_score": 3,
"selected": true,
"text": "litWeight.Text = Utility.FormatWeight(person.Weight);\n"
},
{
"answer_id": 355854,
"author": "The Archetypal Paul",
"author_id": 21755,
"author_profile": "https://Stackoverflow.com/users/21755",
"pm_score": 1,
"selected": false,
"text": "PersonView pv = new PersonView(person)\n\nlitWeight.Text = pv.format_weight();\n"
},
{
"answer_id": 356481,
"author": "Garry Shutler",
"author_id": 6369,
"author_profile": "https://Stackoverflow.com/users/6369",
"pm_score": 1,
"selected": false,
"text": "weightValue.DisplayValue(person.Weight);\n public void DisplayValue(decimal weight)\n{\n this.Text = weight.ToString(\"0.00\");\n}\n"
}
] | 2008/12/10 | [
"https://Stackoverflow.com/questions/355813",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/28543/"
] |
355,816 | <p>I am using a global named mutex for file access synchronization between an ASP.NET application and a console application.</p>
<p>While running the ASP.NET application, the console application fails to acquire mutex - as expected. While running the console application, the ASP.NET application throws <code>UnauthorizedAccessException: Access to the path 'Global\TheNameOfTheMutex' is denied.</code> </p>
<p>I will try to catch the exception and treat it like it failed to acquire the mutex, but I want to know why is it behaving like this? The ASP.NET application runs as expected if it is accessed from two different browsers and the console applications also runs as expected when running multiple instances.</p>
<p><strong>Update:</strong> on Windows XP the exception is also thrown when the ASP.NET application is running and I try to start the console application.</p>
<p>The code used for synchronization is in a common assembly:</p>
<pre><code>using (Mutex m = new Mutex(false, "Global\\TheNameOfTheMutex")) // exception thrown
{
try
{
lock = m.WaitOne(0, false);
}
catch (AbandonedMutexException)
{
// ...
}
if(lock)
{
// ...
m.ReleaseMutex();
}
}
</code></pre>
<p>Environment: Windows Server 2008, IIS 7, ASP.NET 2.0</p>
| [
{
"answer_id": 355829,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 5,
"selected": true,
"text": "MutexSecurity and MutexAccessRule ?\n"
},
{
"answer_id": 3456066,
"author": "Vladislav",
"author_id": 155687,
"author_profile": "https://Stackoverflow.com/users/155687",
"pm_score": 3,
"selected": false,
"text": " var sid = new SecurityIdentifier(WellKnownSidType.WorldSid, null);\n var mutexsecurity = new MutexSecurity();\n mutexsecurity.AddAccessRule(new MutexAccessRule(sid, MutexRights.FullControl, AccessControlType.Allow));\n mutexsecurity.AddAccessRule(new MutexAccessRule(sid, MutexRights.ChangePermissions, AccessControlType.Deny));\n mutexsecurity.AddAccessRule(new MutexAccessRule(sid, MutexRights.Delete, AccessControlType.Deny));\n _mutex = new Mutex(false, \"Global\\\\YourAppName-{add-your-random-chars}\", out created, mutexsecurity);\n"
}
] | 2008/12/10 | [
"https://Stackoverflow.com/questions/355816",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19756/"
] |
355,818 | <pre><code>ScalarQuery<int> query = new ScalarQuery<int>(typeof(Role),
"select count(role.RoleId) from Role as role");
return query.Execute();
</code></pre>
<p>It fails with the invalidcast exception but succeeds when count is replaced with max. </p>
| [
{
"answer_id": 355837,
"author": "gcores",
"author_id": 40256,
"author_profile": "https://Stackoverflow.com/users/40256",
"pm_score": 2,
"selected": true,
"text": "ScalarQuery<long> query = new ScalarQuery<long>(typeof(Role), \n \"select count(r) from Role r\");\nreturn query.Execute();\n"
},
{
"answer_id": 357182,
"author": "Neil Hewitt",
"author_id": 22178,
"author_profile": "https://Stackoverflow.com/users/22178",
"pm_score": 0,
"selected": false,
"text": "ActiveRecordMediator<T>.Count() int"
},
{
"answer_id": 3127457,
"author": "Michael Maddox",
"author_id": 12712,
"author_profile": "https://Stackoverflow.com/users/12712",
"pm_score": 0,
"selected": false,
"text": "// Option 1\nint result = ActiveRecordMediator<Post>.Count(\"BlogId = ?\", blogId);\n\n// Option 2\nCountQuery query = new CountQuery(typeof(Post), \"BlogId = ?\", blogId);\nint result = ActiveRecordMediator.ExecuteQuery(query);\n\n// Option 3\nScalarQuery<long> query= new ScalarQuery<long>(typeof(Post),\n \"SELECT COUNT(*) FROM Post WHERE BlogId = ?\", blogId);\nlong result = query.Execute();\n"
}
] | 2008/12/10 | [
"https://Stackoverflow.com/questions/355818",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/38807/"
] |
355,830 | <p>I would like to create a cache for my php pages on my site. I did find too many solutions but what I want is a script which can generate an HTML page from my database ex:</p>
<p>I have a page for categories which grabs all the categories from the DB, so the script should be able to generate an HTML page of the sort: my-categories.html. then if I choose a category I should get a my-x-category.html page and so on and so forth for other categories and sub categories.</p>
<p>I can see that some web sites have got URLs like: wwww.the-web-site.com/the-page-ex.html</p>
<p>even though they are dynamic.</p>
<p>thanks a lot for help</p>
| [
{
"answer_id": 355860,
"author": "Irmantas",
"author_id": 43182,
"author_profile": "https://Stackoverflow.com/users/43182",
"pm_score": 4,
"selected": false,
"text": "ob_start();\necho 'some_output';\n$content = ob_get_contents();\nob_end_clean();\n\necho 'Content generated :'.$content;\n"
},
{
"answer_id": 356750,
"author": "TravisO",
"author_id": 35116,
"author_profile": "https://Stackoverflow.com/users/35116",
"pm_score": 2,
"selected": false,
"text": "$cache_filename = basename($_SERVER['PHP_SELF']) . \"?\" . $_SERVER['QUERY_STRING'];\n$cache_limit_in_mins = 60 * 32; // this forms 32hrs\n// check if we have a cached file already\nif ( file_exists($cache_filename) )\n{\n $secs_in_min = 60;\n $diff_in_secs = (time() - ($secs_in_min * $cache_limit_in_mins)) - filemtime($cache_filename);\n // check if the cached file is older than our limit\n if ( $diff_in_secs < 0 )\n {\n // it isn't, so display it to the user and stop\n print file_get_contents($cache_filename);\n exit();\n }\n}\n\n// create an array to hold your HTML output, this is where you generate your HTML\n$output = array();\n$output[] = '<table>';\n$output[] = '<tr>';\n// etc\n\n// Save the output as manual cache\n$file = fopen ( $cache_filename, 'w' );\nfwrite ( $file, implode($output,'') );\nfclose ( $file );\n\nprint implode($output,'');\n"
},
{
"answer_id": 32818294,
"author": "Eliasz Kubala",
"author_id": 2273794,
"author_profile": "https://Stackoverflow.com/users/2273794",
"pm_score": 2,
"selected": false,
"text": "cache cache_start.php <?php\nheader(\"HTTP/1.1 200 OK\");\n//header(\"Content-Type: application/json\"); \nheader(\"Content-Encoding: gzip\");\n\n$cache_filename = basename($_SERVER['PHP_SELF']) . \"?\" . $_SERVER['QUERY_STRING'];\n$cache_filename = \"./cache/\".md5($cache_filename);\n$cache_limit_in_mins = 60 * 60; // It's one hour\n\n\nif (file_exists($cache_filename))\n{\n $secs_in_min = 60;\n $diff_in_secs = (time() - ($secs_in_min * $cache_limit_in_mins)) - filemtime($cache_filename);\n if ( $diff_in_secs < 0 )\n {\n print file_get_contents($cache_filename);\n exit();\n }\n}\nob_start(\"ob_gzhandler\");\n?>\n cache_end.php <?php\n$content = ob_get_contents();\nob_end_clean();\n$file = fopen ( $cache_filename, 'w' );\nfwrite ( $file, $content );\nfclose ( $file );\necho gzencode($content);\n?>\n index.php <?php\ninclude \"cache_start.php\";\necho \"Hello Compress Cache World!\";\ninclude \"cache_end.php\";\n?>\n"
}
] | 2008/12/10 | [
"https://Stackoverflow.com/questions/355830",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
355,833 | <p>I have been searching for a simple way to convert a dataset from a <a href="http://en.wikipedia.org/wiki/PostgreSQL" rel="nofollow noreferrer">PostgreSQL</a> database to JSON for use in a project that I am building.</p>
<p>This is my first time using JSON, and I have found it really tricky to find a simple way of doing this. I have been using a StringBuilder at the moment to create a JSON string from the information in the dataset, but I have heard that it is possible to do this very simply with <a href="http://en.wikipedia.org/wiki/.NET_Framework" rel="nofollow noreferrer">.NET</a> 3.5 using the <code>System.Runtime.Serialization</code> namespace, though I have yet to find a simple article or blog on how this is done! What is the easiest way to do this?</p>
| [
{
"answer_id": 5727183,
"author": "DineshHona",
"author_id": 404315,
"author_profile": "https://Stackoverflow.com/users/404315",
"pm_score": 0,
"selected": false,
"text": "public static string GetJSONString(DataTable Dt)\n{\n string[] StrDc = new string[Dt.Columns.Count];\n string HeadStr = string.Empty;\n\n for (int i = 0; i < Dt.Columns.Count; i++)\n {\n StrDc[i] = Dt.Columns[i].Caption;\n HeadStr += \"\\\"\" + StrDc[i] + \"\\\" : \\\"\" + StrDc[i] + i.ToString() + \"¾\" + \"\\\",\";\n }\n\n HeadStr = HeadStr.Substring(0, HeadStr.Length - 1);\n\n StringBuilder Sb = new StringBuilder();\n Sb.Append(\"{\\\"\" + Dt.TableName + \"\\\" : [\");\n\n for (int i = 0; i < Dt.Rows.Count; i++)\n {\n string TempStr = HeadStr;\n Sb.Append(\"{\");\n\n for (int j = 0; j < Dt.Columns.Count; j++)\n {\n TempStr = TempStr.Replace(Dt.Columns[j] + j.ToString() + \"¾\", Dt.Rows[i][j].ToString());\n }\n Sb.Append(TempStr + \"},\");\n }\n\n Sb = new StringBuilder(Sb.ToString().Substring(0, Sb.ToString().Length - 1));\n Sb.Append(\"]}\");\n\n return Sb.ToString();\n}\n var JObject = eval('(' + JSONString + ');');\nfor(var i = 0; i < JObject .Employees.length; i++)\n{\n\nvar val1 = JObject.Employees[i].EmployeeID;\n\nvar val2 = JObject.Employees[i].NationalIDNumber;\n\nvar val3 = JObject.Employees[i].Title;\n\nvar val4 = JObject.Employees[i].BirthDate;\n\nvar val5 = JObject .Employees[i].HireDate ;\n\n}\n"
},
{
"answer_id": 16985568,
"author": "dvdmn",
"author_id": 770446,
"author_profile": "https://Stackoverflow.com/users/770446",
"pm_score": 3,
"selected": false,
"text": "json_encode using Newtonsoft.Json;\n\npublic static string ds2json(DataSet ds) {\n return JsonConvert.SerializeObject(ds, Formatting.Indented);\n}\n"
},
{
"answer_id": 64329781,
"author": "Srinivasulareddy Mallela",
"author_id": 13503284,
"author_profile": "https://Stackoverflow.com/users/13503284",
"pm_score": -1,
"selected": false,
"text": "public static T WriteJson<T>(this System.Data.DataSet dataSet)\n{\n try\n {\n XmlDocument doc = new XmlDocument();\n doc.LoadXml(dataSet.GetXml());\n return (T)Convert.ChangeType(JsonConvert.SerializeXmlNode(doc).Replace(\"null\", \"\\\"\\\"\").Replace(\"'\", \"\\'\"), typeof(T));\n }\n catch (Exception ex)\n {\n throw ex;\n }\n}\n"
},
{
"answer_id": 73253860,
"author": "HOUSES",
"author_id": 19557627,
"author_profile": "https://Stackoverflow.com/users/19557627",
"pm_score": 0,
"selected": false,
"text": "public static string dataSetToJsonSt(DataSet dataDs)\n{\n\n int rowsCountIn = dataDs.Tables[0].Rows.Count;\n int colsCountIn = dataDs.Tables[0].Columns.Count;\n string[] columnNamesAr = new string[dataDs.Tables[0].Columns.Count];\n\n for (int i = 0; i < colsCountIn; i++){\n\n columnNamesAr[i] = dataDs.Tables[0].Columns[i].ColumnName;\n }\n\n string jsonSt = \"[\";\n\n for (int i = 0; i < rowsCountIn; i++)\n {\n jsonSt += \"{\";\n\n for (int j = 0; j < colsCountIn; j++)\n {\n jsonSt += ((jsonSt.Substring(jsonSt.Length - 1) == \"{\" ? \"\" : \",\") + \"\\\"\" + columnNamesAr[j] + \"\\\":\" + (dataDs.Tables[0].Rows[i][j] == DBNull.Value ? \"null\" : (\"\\\"\" + dataDs.Tables[0].Rows[i][j] + \"\\\"\")));\n }\n\n jsonSt += (\"}\" + (i < (rowsCountIn - 1) ? \",\" : \"\"));\n }\n\n jsonSt += \"]\";\n\n return jsonSt;\n}\n"
}
] | 2008/12/10 | [
"https://Stackoverflow.com/questions/355833",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
355,842 | <p>I have the following HandleError filter on my controller:</p>
<pre>[HandleError(ExceptionType = typeof(ArgumentException), View = "DestinationError")]</pre>
<p>I've set-up the Web.Config so that customErrors are on. The problem I'm having is that the HandleError filter is working fine, when I run the app locally out of Visual Studio, but when I deploy it to the server all I get is a 500 Internal Server Error, indicating the Error view cannot be found.</p>
<p>Has anyone come across this before, I'm suspicious that routing may be the root cause of the problem (hoho). The site gets deployed into a directory in the web root, rather than into the wwwroot itself, so perhaps IIS cannot locate the error file.</p>
| [
{
"answer_id": 1230927,
"author": "labilbe",
"author_id": 1195872,
"author_profile": "https://Stackoverflow.com/users/1195872",
"pm_score": 0,
"selected": false,
"text": "Response.TrySkipIisCustomErrors = true;\n"
},
{
"answer_id": 1236497,
"author": "labilbe",
"author_id": 1195872,
"author_profile": "https://Stackoverflow.com/users/1195872",
"pm_score": 2,
"selected": false,
"text": " <customErrors mode=\"On\" defaultRedirect=\"/Error\">\n <error statusCode=\"404\" redirect=\"/Error/NotFound\"/>\n </customErrors>\n public class ErrorController : Controller\n{\n [AcceptVerbs(HttpVerbs.Get)]\n public ActionResult Index()\n {\n Response.StatusCode = (int)HttpStatusCode.InternalServerError;\n return View(\"Index\");\n }\n\n [AcceptVerbs(HttpVerbs.Get)]\n public ActionResult NotFound()\n {\n Response.StatusCode = (int)HttpStatusCode.NotFound;\n return View(\"NotFound\");\n }\n}\n"
},
{
"answer_id": 4386107,
"author": "Geert Doornbos",
"author_id": 533701,
"author_profile": "https://Stackoverflow.com/users/533701",
"pm_score": 0,
"selected": false,
"text": "@inherits System.Web.Mvc.WebViewPage<System.Web.Mvc.HandleErrorInfo>\n\n@{\n View.Title = \"Error\";\n Layout = \"~/Views/Shared/_Layout.cshtml\";\n}\n"
}
] | 2008/12/10 | [
"https://Stackoverflow.com/questions/355842",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
355,848 | <p>How can I emulate classes (and namespaces) in JavaScript?</p>
<p>I need to create a JavaScript library and have limited experience with the language. I always thought that it had native support for classes, but it is less related to Java than I had assumed. It seems that everything in JavaScript is actually a function.</p>
<p>What I have found out so far makes a lot of sense with it being a dynamic weakly typed language, but this makes it a bit of a departure for people who are used to having a strongly typed language and using a compiler to spot our errors :)</p>
<p>I mainly work in C# and Java, and was hoping for something syntacticaly similar so the library would look familiar for our other C# developers that will have to maintain it.</p>
<p>I have the following sort of code which works, but I was wondering what other developer's takes would be on this. What are the alternatives? Is there a way that is better? Is there a way that is more readable?</p>
<p>I understand that what I want is something similar to C# or Java when I should just accept the fact that this <strong>is JavaScript</strong>, but my aim is to try to ease the learning curve for other developers by making it more familiar and intuitive for them.</p>
<pre><code>//Perform the namespace setup (this will actually be done with checking
//in real life so we don't overwrite definitions, but this is kept short
//for the code sample).
var DoctaJonez = new function();
DoctaJonez.Namespace1 = new function();
/**
* Class description.
*/
DoctaJonez.Namespace1.SomeClass = function()
{
/**
* Public functions listed at the top to act like a "header".
*/
this.publicFunction = privateFunction;
/**
* Private variables next.
*/
var privateVariable;
/**
* Finally private functions.
*/
function privateFunction()
{
}
}
//Create an instance of the class
var myClass = new DoctaJonez.SomeClass();
//Do some stuff with the instance
myClass.publicFunction();
</code></pre>
| [
{
"answer_id": 355889,
"author": "annakata",
"author_id": 13018,
"author_profile": "https://Stackoverflow.com/users/13018",
"pm_score": 1,
"selected": false,
"text": "DoctaJonez.Namespace1 = {};"
},
{
"answer_id": 356343,
"author": "Eugene Lazutkin",
"author_id": 26394,
"author_profile": "https://Stackoverflow.com/users/26394",
"pm_score": 3,
"selected": false,
"text": "// Let's define a super simple class (doesn't inherit anything).\ndojo.declare(\"Person\", null, {\n // Class-level property\n answer: 42,\n\n // Class-level object property\n name: {first: \"Ford\", last: \"Prefect\"},\n\n // The constructor, duh!\n constructor: function(age){\n this.age = age; // instance-level property\n },\n\n // A method\n saySomething: function(verb){\n console.log(\"I \" + verb + \" \" +\n this.name.first + \" \" + this.name.last + \"!\" +\n \" -- \" + this.answer);\n },\n\n // Another method\n passportControl: function(){\n console.log(\"I am \" + this.age);\n }\n});\n // A fan of Ford Perfect\nvar fan = new Person(18);\nfan.saySomething(\"love\"); // I love Ford Perfect! -- 42\nfan.passportControl(); // I am 18\n // Let's create a derived class inheriting Person\ndojo.declare(\"SuperAgent\", Person, {\n // Redefine class-level property\n answer: \"shaken, not stirred\",\n\n // Redefine class-level object property\n name: {first: \"James\", last: \"Bond\"},\n\n // The constructor\n constructor: function(age, drink){\n // We don't need to call the super class because\n // it would be done automatically for us passing\n // all arguments to it.\n\n // At this point \"age\" is already assigned.\n\n this.drink = drink; // Instance-level property\n },\n\n // Let's redefine the method\n saySomething: function(verb){\n // Let's call the super class first\n this.inherited(arguments);\n // Pay attention: no need for extra parameters, or any extra code,\n // we don't even name the class we call --- it is all automatic.\n // We can call it any time in the body of redefined method\n\n console.log(\"Yeah, baby!\");\n },\n\n shoot: function(){ console.log(\"BAM!!!\"); }\n});\n // Let's create a James Bond-wannabe\nvar jb007 = new SuperAgent(45, \"Martini\");\njb007.saySomething(\"dig\"); // I dig James Bond! -- shaken, not stirred\n // Yeah, baby!\njb007.passportControl(); // I am 45\njb007.shoot(); // BAM!!!\n\n// Constructors were called in this order: Person, SuperAgent\n// saySomething() came from SuperAgent, which called Person\n// passportControl() came from Person\n// shoot() came from SuperAgent.\n // Let's define one more super simple class\ndojo.define(\"SharpShooter\", null, {\n // For simplicity no constructor\n\n // One method to clash with SuperAgent\n shoot: function(){\n console.log(\"It's jammed! Shoot!\");\n }\n});\n // Multiple inheritance\ndojo.declare(\"FakeAgent\", [\"SuperAgent\", \"SharpShooter\"], {\n // Let's do it with no constructor\n\n // Redefine the method\n saySomething: function(verb){\n // We don't call super here --- a complete redefinition\n\n console.log(\"What is \" + verb \"? I want my \" + this.drink + \"!\");\n },\n});\n // A fake agent coming up\nvar ap = new FakeAgent(40, \"Kool-Aid\");\nap.saySomething(\"hate\"); // What is hate? I want my Kool-Aid!\nap.passportControl(); // I am 40\nap.shoot(); // It's jammed! Shoot!\n\n// Constructors were called in this order: Person, SuperAgent\n// saySomething() came from FakeAgent\n// passportControl() came from Person\n// shoot() came from SharpShooter.\n dojo.declare()"
}
] | 2008/12/10 | [
"https://Stackoverflow.com/questions/355848",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/39277/"
] |
355,865 | <p>I have the following code, which is the core part of my small AJAX application. I am not getting any errors, it is just that nothing happens. I am guessing there is a more efficient way to do what I am trying to do.</p>
<p>Here is the code:</p>
<pre><code>var xmlHttp
var layername
function update(layer, part, pk, query)
{
if (part=="1")
{
$url "get_auction.php?cmd=GetAuctionData&pk="+pk+"&sid="+Math.random()
}
else if (part=="2")
{
var url "get_records.php?cmd=GetRecordSet&query="+query+"&sid="+Math.random()
}
xmlHttp=GetXmlHttpObject()
if(xmlHttp==null)
{
alert("Your browser is not supported?")
}
xmlHttp.onreadystatechange = function() {
if(xmlHttp.readyState==4 || xmlHttp.readyState=="complete") {
document.getElementById(layer).innerHTML=xmlHttp.responseText
} else if (xmlHttp.readyState==1 || xmlHttp.readyState=="loading") {
document.getElementById(layer).innerHTML="loading"
}
};
xmlHttp.open("GET",url,true)
xmlHttp.send(null)
}
function GetXmlHttpObject()
{
var xmlHttp=null;
try
{
xmlHttp=new XMLHttpRequest();
}catch (e)
{
try
{
xmlHttp =new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e) {}
}
return xmlHttp;
}
function makewindows(){
child1 = window.open ("about:blank");
child1.document.write(json_encode(<?php echo $row2["ARTICLE_DESC"]; ?>));
child1.document.close();
}
</code></pre>
<p>and an example of how I am calling the function from php</p>
<pre><code>onclick="update(\'Layer3\',\'2\','.$pk.'\',\'0\',)">'
</code></pre>
<p>pk or query will never be passed at the same time, only one of them will ever be passed.</p>
<p>edit: I am also wondering if it would make more sense for the makewindows function to take a parameter, or stay as it is. Are there advantages and disadvantages for each approach?</p>
| [
{
"answer_id": 355935,
"author": "Stoo",
"author_id": 27425,
"author_profile": "https://Stackoverflow.com/users/27425",
"pm_score": 1,
"selected": false,
"text": "onclick=\"update(\\'Layer3\\',\\'2\\',\\''.$pk.'\\',\\'0\\',)\">\n"
},
{
"answer_id": 356282,
"author": "Andreas Grech",
"author_id": 44084,
"author_profile": "https://Stackoverflow.com/users/44084",
"pm_score": 0,
"selected": false,
"text": "json_encode child1.document.write(<?php echo json_encode($row2[\"ARTICLE_DESC\"]); ?>);\n"
},
{
"answer_id": 356356,
"author": "Kieveli",
"author_id": 15852,
"author_profile": "https://Stackoverflow.com/users/15852",
"pm_score": 2,
"selected": true,
"text": "if (part==\"1\")\n{\n $url \"get_auction.php?cmd=GetAuctionData&pk=\"+pk+\"&sid=\"+Math.random()\n}\nelse if (part==\"2\")\n{\n var url \"get_records.php?cmd=GetRecordSet&query=\"+query+\"&sid=\"+Math.random()\n}\n"
}
] | 2008/12/10 | [
"https://Stackoverflow.com/questions/355865",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1246613/"
] |
355,875 | <p>I think I am having a mental block but can someone please enlighten me on how to combine these two LINQ statements into one? </p>
<pre><code>/// <summary>
/// Returns an array of Types that implement the supplied generic interface in the
/// current AppDomain.
/// </summary>
/// <param name="interfaceType">Type of generic interface implemented</param>
/// <param name="includeAbstractTypes">Include Abstract class types in the search</param>
/// <param name="includeInterfaceTypes">Include Interface class types in the search</param>
/// <returns>Array of Types that implement the supplied generic interface</returns>
/// <remarks>
/// History.<br/>
/// 10/12/2008 davide Method creation.<br/>
/// </remarks>
public static Type[] GetTypesImplementingGenericInterface(Type interfaceType, bool includeAbstractTypes, bool includeInterfaceTypes)
{
// Use linq to find types that implement the supplied interface.
var allTypes = AppDomain.CurrentDomain.GetAssemblies().ToList()
.SelectMany(s => s.GetTypes())
.Where(p => p.IsAbstract == includeAbstractTypes
&& p.IsInterface == includeInterfaceTypes);
var implementingTypes = from type in allTypes
from intf in type.GetInterfaces().ToList()
where intf.FullName != null && intf.FullName.Contains(interfaceType.FullName)
select type;
return implementingTypes.ToArray<Type>();
}
</code></pre>
<p>I am avoiding IsAssignableFrom as its seems to fail when not supplying the specific type of the generic interface therefore I believe using FullName caparison over IsAssignableFrom should suffice, for example:</p>
<pre><code>namespace Davide
{
interface IOutput<TOutputType> { }
class StringOutput : IOutput<string> { }
}
</code></pre>
<p>typeof(IOutput<>).FullName will return "Davide+IOutput`1"</p>
<p>typeof(StringOutput).GetInterfaces()[0].FullName will return "Davide+IOutput`1[[System.String, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]"</p>
<p>Therefore using FullName.Contains should suffice</p>
| [
{
"answer_id": 355936,
"author": "Hath",
"author_id": 5186,
"author_profile": "https://Stackoverflow.com/users/5186",
"pm_score": 1,
"selected": false,
"text": " public static Type[] GetTypesImplementingGenericInterface(Type interfaceType, bool includeAbstractTypes, bool includeInterfaceTypes)\n {\n // Use linq to find types that implement the supplied interface.\n var allTypes = AppDomain.CurrentDomain.GetAssemblies().ToList()\n .SelectMany(s => s.GetTypes())\n .Where(p => p.IsAbstract == includeAbstractTypes\n && p.IsInterface == includeInterfaceTypes\n && p.GetInterfaces().Any(i=>i.FullName != null && i.FullName.Contains(interfaceType.FullName))\n );\n\n //var implementingTypes = from type in allTypes\n // from intf in type.GetInterfaces().ToList()\n // where intf.FullName != null && intf.FullName.Contains(interfaceType.FullName)\n // select type;\n\n //return implementingTypes.ToArray<Type>();\n\n return allTypes.ToArray();\n }\n"
},
{
"answer_id": 355953,
"author": "bruno conde",
"author_id": 31136,
"author_profile": "https://Stackoverflow.com/users/31136",
"pm_score": 1,
"selected": false,
"text": " public static Type[] GetTypesImplementingGenericInterface(Type interfaceType, bool includeAbstractTypes, bool includeInterfaceTypes)\n {\n // Use linq to find types that implement the supplied interface.\n var implementingTypes = AppDomain.CurrentDomain.GetAssemblies()\n .SelectMany(s => s.GetTypes())\n .Where(p => interfaceType.IsAssignableFrom(p)\n && (\n (p.IsAbstract && includeAbstractTypes) \n || (p.IsInterface && includeInterfaceTypes)\n || (!p.IsAbstract && !p.IsInterface)\n )\n );\n\n return implementingTypes.ToArray<Type>();\n }\n"
},
{
"answer_id": 355989,
"author": "Jon Skeet",
"author_id": 22656,
"author_profile": "https://Stackoverflow.com/users/22656",
"pm_score": 2,
"selected": false,
"text": "var implementors = from assembly in AppDomain.CurrentDomain.GetAssemblies()\n from type in assembly.GetTypes()\n where type.IsAbstract == includeAbstractTypes\n where type.IsInterface == includeInterfaceTypes\n from intf in type.GetInterfaces()\n where intf.FullName != null && \n intf.FullName.Contains(interfaceType.FullName)\n select type;\n var implementors = from assembly in AppDomain.CurrentDomain.GetAssemblies()\n from type in assembly.GetTypes()\n where type.IsAbstract == includeAbstractTypes\n where type.IsInterface == includeInterfaceTypes\n where interfaceType.IsAssignableFrom(type)\n select type;\n"
},
{
"answer_id": 359466,
"author": "Student for Life",
"author_id": 38041,
"author_profile": "https://Stackoverflow.com/users/38041",
"pm_score": 1,
"selected": true,
"text": "/// <summary>\n/// Returns an array of Types that implement the supplied generic interface in the\n/// current AppDomain.\n/// </summary>\n/// <param name=\"interfaceType\">Type of generic interface implemented</param>\n/// <param name=\"excludeAbstractTypes\">Exclude Abstract class types in the search</param>\n/// <param name=\"excludeInterfaceTypes\">Exclude Interface class types in the search</param>\n/// <returns>Array of Types that implement the supplied generic interface</returns>\n/// <remarks>\n/// History.<br/>\n/// 11/12/2008 davide Created method.<br/>\n/// 11/12/2008 davide Altered method to use a two LINQ query pass.<br/>\n/// 11/12/2008 davide Altered method to use optimised combined LINQ query.<br/>\n/// 12/12/2008 davide Altered method and replaced FullName criteria match with GetGenericTypeDefinition.<br/>\n/// </remarks>\npublic static Type[] GetTypesImplementingGenericInterface(Type interfaceType, bool excludeAbstractTypes, bool excludeInterfaceTypes)\n{\n if (!interfaceType.IsGenericType)\n {\n throw new ArgumentException(\"Supplied interface is not a Generic type\");\n }\n\n if (interfaceType.ContainsGenericParameters)\n {\n interfaceType = interfaceType.GetGenericTypeDefinition();\n }\n\n // Use linq to find types that implement the supplied generic interface.\n var implementingTypes = from assembly in AppDomain.CurrentDomain.GetAssemblies()\n from type in assembly.GetTypes()\n where (type.IsAbstract != excludeAbstractTypes) || (!excludeAbstractTypes)\n where (type.IsInterface != excludeInterfaceTypes) || (!excludeInterfaceTypes)\n from intf in type.GetInterfaces()\n where intf.IsGenericType && intf.GetGenericTypeDefinition() == interfaceType\n select type;\n\n return implementingTypes.ToArray<Type>();\n}\n"
}
] | 2008/12/10 | [
"https://Stackoverflow.com/questions/355875",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/38041/"
] |
355,876 | <p>I'm working on an ASP .NET 2.0 site which uses a Web Application project file, and therefore compiles to a dll rather than deploying the source code as you do with the older style Web Site projects.</p>
<p>The site works fine on my test server (Windows Server 2003 R2, IIS6) when it runs in the root of a website. However I need to run it under a virtual directory instead. When I switch over to that, I get the following error on browsing to any of the pages in the site</p>
<p>CS1519: Invalid token ',' in class, struct, or interface member declaration</p>
<p>The error message goes onto tell me the line number and code file, however the code file is under the Temporary ASP .NET files folder and when I try to find it, it's not there.</p>
<p>As such I'm unable to work out which page is causing the issue although I suspect it could be the master page, if this error occurs on all pages. Has anyone else seen this before or found a solution?</p>
| [
{
"answer_id": 48753390,
"author": "noemi",
"author_id": 9351451,
"author_profile": "https://Stackoverflow.com/users/9351451",
"pm_score": -1,
"selected": false,
"text": "namespace Rectangle\n{\n class Name\n {\n int length1;\n int width1;\n int sum;\n\n Console.Write(\"Enter the length: \");\n length = int.Parse(Console.ReadLine());\n\n Console.Write(\"Enter the width: \");\n width = int.Parse(Console.ReadLine());\n\n sum = length1* width1;\n\n Console.WriteLine($\"Sumis {sum}\");\n\n }\n}\n"
}
] | 2008/12/10 | [
"https://Stackoverflow.com/questions/355876",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12277/"
] |
355,879 | <p>I have the following code:</p>
<p><a href="http://www.nomorepasting.com/getpaste.php?pasteid=22615" rel="nofollow noreferrer">http://www.nomorepasting.com/getpaste.php?pasteid=22615</a></p>
<p>Which is called by the javascript mentioned in <a href="https://stackoverflow.com/questions/355865/javascript-function-not-responsive">this question</a>:</p>
<p>My problem is that I do not seem to be able to pass $query, as in nothing seemingly happens when I call this file by itself.</p>
<p>I am unsure what the best way to control the flow of information is. Is my logic ok? Passing the query through javascript to the php file, and then returning it with the function? </p>
<p>I am also concerned about my use of $rows, as it does not seem to be required.</p>
| [
{
"answer_id": 356019,
"author": "spelley",
"author_id": 41654,
"author_profile": "https://Stackoverflow.com/users/41654",
"pm_score": 0,
"selected": false,
"text": "$query ='';\nif (isset($_GET[\"query\"]))\n$query = $_GET[\"query\"];\n $table = 'Auctions';\n$rows = getRowsByArticleSearch($searchString, $table);\n $result = mysql_query(\"SELECT ARTICLE_NO, USERNAME, ACCESSSTARTS, ARTICLE_NAME \n FROM {$table} \n WHERE upper ARTICLE_NAME LIKE '%\" . $searchString . \"%'\");\n $result = mysql_query(\"SELECT ARTICLE_NO, USERNAME, ACCESSSTARTS, ARTICLE_NAME \n FROM {$table} \n WHERE upper ARTICLE_NAME LIKE '%\" . mysql_real_escape_string($searchString) . \"%'\");\n"
},
{
"answer_id": 356085,
"author": "Karsten",
"author_id": 28144,
"author_profile": "https://Stackoverflow.com/users/28144",
"pm_score": 2,
"selected": true,
"text": "$rows = getRowsByArticleSearch($searchString, $table);\n $rows = getRowsByArticleSearch($query, $table);\n"
}
] | 2008/12/10 | [
"https://Stackoverflow.com/questions/355879",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1246613/"
] |
355,899 | <pre><code> String fullName = PATH + "." + name;
Class cl= Class.forName(fullName);
if(name.equalsIgnoreCase("MobileSearch")){
if(msearchType==null){
msearchType=(SearchInterface)cl.newInstance();
}
return msearchType;
}
if(name.equalsIgnoreCase("BookSearch")){
if(bsearchType==null){
bsearchType=(SearchInterface)cl.newInstance();
}
return bsearchType;
}
</code></pre>
<p>How do I get rid of the <code>if</code> statements here.<br>
I am using reflection.<br>
Please help. Thanks in advance.</p>
| [
{
"answer_id": 355922,
"author": "Jacob Schoen",
"author_id": 3340,
"author_profile": "https://Stackoverflow.com/users/3340",
"pm_score": 0,
"selected": false,
"text": "String fullName = PATH + \".\" + name;\n\nClass cl= Class.forName(fullName); \nif(searchType==null){ \n searchType=(SearchInterface)cl.newInstance();\n} \nreturn searchType;\n"
},
{
"answer_id": 355928,
"author": "Nick Holt",
"author_id": 41423,
"author_profile": "https://Stackoverflow.com/users/41423",
"pm_score": 2,
"selected": false,
"text": "if (!searchInstances.containsKey(name)) \n{\n searchInstances.put(\n name, \n (SearchInterface)Class.forName(PATH + \".\" + name).newInstance()\n );\n}\n\nreturn searchInstances.get(name); \n"
}
] | 2008/12/10 | [
"https://Stackoverflow.com/questions/355899",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
355,903 | <p>I have a website setup in IIS 6, let's say it's called <strong><a href="http://www.this.com" rel="nofollow noreferrer">http://www.this.com</a></strong>.</p>
<p>I have setup a redirection for this website to <strong><a href="http://www.that.com" rel="nofollow noreferrer">http://www.that.com</a></strong> which maintains the directory structure and query parameters as follows:</p>
<p><strong><a href="http://www.that.com" rel="nofollow noreferrer">http://www.that.com</a>$S$Q - using the option "The exact URL entered above"</strong></p>
<p>This works great, whenever someone requests, for example:</p>
<p><strong><a href="http://www.this.com/subfolder/page.aspx?Id=1" rel="nofollow noreferrer">http://www.this.com/subfolder/page.aspx?Id=1</a></strong></p>
<p>then they end up at:</p>
<p><strong><a href="http://www.that.com/subfolder/page.aspx?Id=1" rel="nofollow noreferrer">http://www.that.com/subfolder/page.aspx?Id=1</a></strong></p>
<p>Now, I have one page, actually a handler, <strong><a href="http://www.this.com/image.axd" rel="nofollow noreferrer">http://www.this.com/image.axd</a></strong>, which I do not want to redirect.</p>
<p>What is the syntax for that? I've read the <strong>Redirection Using Wildcards</strong> section <a href="http://www.microsoft.com/technet/prodtechnol/WindowsServer2003/Library/IIS/41c238b2-1188-488f-bf2d-464383b1bb08.mspx?mfr=true" rel="nofollow noreferrer">here</a>, but I can't work out how to do what seems to be something straight forward.</p>
<p>Note that <strong>image.axd</strong> is a handler so I can't just "right click" on it and set the redirection properties as it doesn't physically exist.</p>
<p>I also have a couple of other pages in subfolders which I do not want to redirect, for example:</p>
<p><strong><a href="http://www.this.com/subfolder/donotredirectthispage.aspx" rel="nofollow noreferrer">http://www.this.com/subfolder/donotredirectthispage.aspx</a></strong></p>
<p>Any help would be appreciated.</p>
<p><strong>Edit:</strong> A couple of people have mentioned using ISAPI_Rewrite, for which I'm grateful, but I really don't want to introduce another complexity into the website configuration. IIS seems to imply I can acheive what I want using the ! and 0 through 9 variables. </p>
<p>Is it really not possible to do this using IIS?</p>
<p>My current workaround is to set the redirection properties on ALL folders and pages that I want to redirect except those I do not, but this is a management nightmare.</p>
| [
{
"answer_id": 355912,
"author": "tvanfosson",
"author_id": 12950,
"author_profile": "https://Stackoverflow.com/users/12950",
"pm_score": 1,
"selected": false,
"text": "page not found"
},
{
"answer_id": 355956,
"author": "Tomalak",
"author_id": 18771,
"author_profile": "https://Stackoverflow.com/users/18771",
"pm_score": 0,
"selected": false,
"text": "image.axd # image.axd stays unchanged (\"L\" is the \"last rule\" flag)\nRewriteCond Host: www.\\this\\.com\nRewriteRule ^.*?\\bimage\\.axd\\b.* $0 [L]\n\n# all requests that have not been stopped by an earlier rule\n# end up here (\"RP\" is the \"permanent redirect\" flag)\nRewriteCond Host: www.\\this\\.com\nRewriteRule .* http://www.that.com$0 [RP,L]\n"
}
] | 2008/12/10 | [
"https://Stackoverflow.com/questions/355903",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5449/"
] |
355,907 | <p>I'm aware that in Vim I can often repeat a command by simply adding a number in front of it. For example, one can delete 5 lines by:</p>
<pre><code>5dd
</code></pre>
<p>It's also often possible to specify a range of lines to apply a command to, for example</p>
<pre><code>:10,20s:hello:goodbye:gc
</code></pre>
<p>How can I perform a 'vertical edit'? I'd like to, for example, insert a particular symbol, say a comma, at the beggining (skipping whitespace, i.e. what you'd get if you type a comma after Shift-I in command mode) of every line in a given range. How can this be achieved (without resorting to down-period-down-period-down-period)?</p>
| [
{
"answer_id": 355921,
"author": "Svante",
"author_id": 31615,
"author_profile": "https://Stackoverflow.com/users/31615",
"pm_score": 8,
"selected": true,
"text": ":10,20s/^/,/ q a i , ESC j h q @ a q a a q a z"
},
{
"answer_id": 355923,
"author": "wimh",
"author_id": 33499,
"author_profile": "https://Stackoverflow.com/users/33499",
"pm_score": 4,
"selected": false,
"text": "q a I , ESC j q\n 5 @ a\n"
},
{
"answer_id": 355970,
"author": "Paolo Tedesco",
"author_id": 15622,
"author_profile": "https://Stackoverflow.com/users/15622",
"pm_score": 2,
"selected": false,
"text": ":10,20s/\\(.*\\)/,\\1\n"
},
{
"answer_id": 356059,
"author": "rampion",
"author_id": 9859,
"author_profile": "https://Stackoverflow.com/users/9859",
"pm_score": 7,
"selected": false,
"text": "abc123abc\ndef456def\nghi789ghi\n abc,123abc\ndef,456def\nghi,789ghi\n"
},
{
"answer_id": 1812290,
"author": "Albert",
"author_id": 187352,
"author_profile": "https://Stackoverflow.com/users/187352",
"pm_score": 5,
"selected": false,
"text": ":'<,'>norm@a\n"
},
{
"answer_id": 8064607,
"author": "emboss",
"author_id": 827060,
"author_profile": "https://Stackoverflow.com/users/827060",
"pm_score": 6,
"selected": false,
"text": "\" allow the . to execute once for each line of a visual selection\nvnoremap . :normal .<CR>\n"
},
{
"answer_id": 54695291,
"author": "Noah",
"author_id": 1480787,
"author_profile": "https://Stackoverflow.com/users/1480787",
"pm_score": 4,
"selected": false,
"text": ". :norm ."
}
] | 2008/12/10 | [
"https://Stackoverflow.com/questions/355907",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/37984/"
] |
355,908 | <p>For tasks that will take more than a few seconds, a good user interface, in my opinion, should provide a progress bar along with appropriate information on the progress of the operation. (Microsoft kindly provide <a href="http://msdn.microsoft.com/en-us/library/aa511486.aspx" rel="nofollow noreferrer">User Interface Guidelines</a> on this topic, but I want a status panel that is a bit more advanced.)</p>
<p>The "task" class I am using is able to log messages, and if the messages are important enough (warning or error), I would like to display them on the progress panel. It would also be nice with a graphical indication when warnings or errors have occured (a warning or error icon perhaps). If there are many such messages, a text box, a list view or perhaps some <a href="http://www.codejock.com/products/reportcontrol/" rel="nofollow noreferrer">report control</a> could be appropriate here.</p>
<p>There could be a cancel button while the task is running, and after the task has been completed, a "View log" button would also be nice.</p>
<p>To summarise, I have a good idea how to implement my status panel, but I would really like some input on this. Did I miss something important? Am I going overboard on this? Are there perhaps any components like this already available out there?</p>
| [
{
"answer_id": 357137,
"author": "Greg",
"author_id": 42882,
"author_profile": "https://Stackoverflow.com/users/42882",
"pm_score": 1,
"selected": false,
"text": "StartNewTask(Caption,NumberOfSubtasks)\nEndTask \nSetProgress(Caption,NumberOfSubtasksFinished)\n StartNewTask EndTask StartNewTask('Doing 2 things',2)\n SetProgress('Done 1 now',1)\n StartNewTask('Big Subtask',40)\n ...\n SetProgress('Done some subtasks',10)\n StartNewTask(Caption,[ListOfSubTaskWeightings])\n"
}
] | 2008/12/10 | [
"https://Stackoverflow.com/questions/355908",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18651/"
] |
355,909 | <p>(All of the following is to be written in Java)</p>
<p>I have to build an application that will take as input XML documents that are, potentially, very large. The document is encrypted -- not with XMLsec, but with my client's preexisting encryption algorithm -- will be processed in three phases:</p>
<p>First, the stream will be decrypted according to the aforementioned algorithm.</p>
<p>Second, an extension class (written by a third party to an API I am providing) will read some portion of the file. The amount that is read is not predictable -- in particular it is not guaranteed to be in the header of the file, but might occur at any point in the XML.</p>
<p>Lastly, another extension class (same deal) will subdivide the input XML into 1..n subset documents. It is possible that these will in some part overlap the portion of the document dealt with by the second operation, ie: I believe I will need to rewind whatever mechanism I am using to deal with this object.</p>
<p>Here is my question:</p>
<p>Is there a way to do this without ever reading the entire piece of data into memory at one time? Obviously I can implement the decryption as an input stream filter, but I'm not sure if it's possible to parse XML in the way I'm describing; by walking over as much of the document is required to gather the second step's information, and then by rewinding the document and passing over it again to split it into jobs, ideally releasing all of the parts of the document that are no longer in use after they have been passed.</p>
| [
{
"answer_id": 355962,
"author": "Joachim Sauer",
"author_id": 40342,
"author_profile": "https://Stackoverflow.com/users/40342",
"pm_score": 2,
"selected": false,
"text": "BufferedInputStream mark() reset() BufferedInputStream"
},
{
"answer_id": 356111,
"author": "Nick Holt",
"author_id": 41423,
"author_profile": "https://Stackoverflow.com/users/41423",
"pm_score": 2,
"selected": false,
"text": "InputStream SAXParserFactory.newInstance().newSAXParser().parse(\n new DecryptingInputStream(), \n new MyHandler()\n);\n"
},
{
"answer_id": 5266023,
"author": "NickV",
"author_id": 8322,
"author_profile": "https://Stackoverflow.com/users/8322",
"pm_score": 0,
"selected": false,
"text": "StreamingExampleExtractor.java"
}
] | 2008/12/10 | [
"https://Stackoverflow.com/questions/355909",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23309/"
] |
355,916 | <p>Please if you have used NHibernate and Entity Frameworks, please contrast your experiences.</p>
| [
{
"answer_id": 355962,
"author": "Joachim Sauer",
"author_id": 40342,
"author_profile": "https://Stackoverflow.com/users/40342",
"pm_score": 2,
"selected": false,
"text": "BufferedInputStream mark() reset() BufferedInputStream"
},
{
"answer_id": 356111,
"author": "Nick Holt",
"author_id": 41423,
"author_profile": "https://Stackoverflow.com/users/41423",
"pm_score": 2,
"selected": false,
"text": "InputStream SAXParserFactory.newInstance().newSAXParser().parse(\n new DecryptingInputStream(), \n new MyHandler()\n);\n"
},
{
"answer_id": 5266023,
"author": "NickV",
"author_id": 8322,
"author_profile": "https://Stackoverflow.com/users/8322",
"pm_score": 0,
"selected": false,
"text": "StreamingExampleExtractor.java"
}
] | 2008/12/10 | [
"https://Stackoverflow.com/questions/355916",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19799/"
] |
355,917 | <p>I have a web app that uses log4net to log errors to a log file.
It works well when I publish my website via xcopy but when I build a package installer, log4net does not appear to work when remote users access my site.</p>
<p>I use <em>impersonate=true</em> in my web.config and log4net only logs errors when I am the logged user.</p>
<p>I have another app that works fine in all cases but was not package deployed.</p>
<p>Does anyone have any thoughts?</p>
| [
{
"answer_id": 356205,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": " <!-- log4net -->\n <log4net debug=\"false\">\n <appender name=\"RollingFileAppender\" type=\"log4net.Appender.RollingFileAppender\">\n <file value=\"D:\\\\WSBank\\\\Solution\\\\Logs\\\\Solution.log\" />\n <appendToFile value=\"true\" />\n <rollingStyle value=\"Size\" />\n <maxSizeRollBackups value=\"10\" />\n <maximumFileSize value=\"1024KB\" />\n <staticLogFileName value=\"true\" />\n <layout type=\"log4net.Layout.PatternLayout\">\n <conversionPattern value=\"%date [%thread] %-5level %logger [%property{NDC}] - %message%newline\" />\n </layout>\n </appender>\n <root>\n <level value=\"ALL\" />\n <appender-ref ref=\"RollingFileAppender\" />\n </root>\n </log4net>\n"
}
] | 2008/12/10 | [
"https://Stackoverflow.com/questions/355917",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
355,933 | <p>I have a ASP.NET project, in which I have a method with 10 local variables. This method calls about 10 other methods. 3 of the called methods need all the variables. Is it considered good practice to turn all those variables into global members, and then they don't have to passed as parameters?</p>
| [
{
"answer_id": 355954,
"author": "Marc Gravell",
"author_id": 23354,
"author_profile": "https://Stackoverflow.com/users/23354",
"pm_score": 3,
"selected": false,
"text": "public class Foo {\n public string Key {get;set;}\n public decimal Quantity {get;set;}\n // etc\n}\n"
},
{
"answer_id": 355982,
"author": "Samiksha",
"author_id": 29515,
"author_profile": "https://Stackoverflow.com/users/29515",
"pm_score": 3,
"selected": true,
"text": "public struct user \n{ \n public string FirstName; \n public string LastName; \n public string zilionotherproperties; \n public bool SearchByLastNameOnly; \n public datetime date1;\n} \n"
}
] | 2008/12/10 | [
"https://Stackoverflow.com/questions/355933",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/278/"
] |
355,937 | <p>I have Widget.title, Widget.publish_ at, and Widget.unpublish_ at. It's a rails app with thinking_sphinx running, indexing once a night. I want to find all Widgets that have 'foo' in the title, and are published (publish _at < Time.now, unpublish _at > Time.now). </p>
<p>To get pagination to work properly, I really want to do this in a sphinx query. I have
'has :publish_at, :unpublish_at' to get the attributes, but what's the syntax for 'Widget.search("foo @publish_ at > #{Time.now}",:match _mode=>:extended'? Is this even possible? </p>
| [
{
"answer_id": 356028,
"author": "Michael",
"author_id": 35500,
"author_profile": "https://Stackoverflow.com/users/35500",
"pm_score": 3,
"selected": false,
"text": "class Widget < ActiveRecord::Base\n define_index do\n indexes title\n has publish_at\n has unpublish_at\n ...\n end\n min_time = Time.now.advance(:years => -10)\nmax_time = Time.now.advance(:years => 10)\ntitle = \"foo\"\n\nWidget.search title, :with => {:publish_at => min_time..Time.now, :unpublish_at => Time.now..max_time}\n"
}
] | 2008/12/10 | [
"https://Stackoverflow.com/questions/355937",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18666/"
] |
355,942 | <p>I am getting an error while porting my application from VC6 to Visual Studio 2005.</p>
<p>Does anyone have any idea what this means?</p>
<blockquote>
<p>mfcs80.lib(dllmodul.obj) : error
LNK2005: _DllMain@12 already defined
in MSVCRT.lib(dllmain.obj)</p>
</blockquote>
| [
{
"answer_id": 2093094,
"author": "Ruddy",
"author_id": 229904,
"author_profile": "https://Stackoverflow.com/users/229904",
"pm_score": 2,
"selected": false,
"text": "#ifdef OMUTILITIES_LINK_STATIC\n #undef AfxGetStaticModuleState\n #define AfxGetStaticModuleState AfxGetModuleState\n#endif\n"
}
] | 2008/12/10 | [
"https://Stackoverflow.com/questions/355942",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/43596/"
] |
355,945 | <p>Is there a quick and nice way using linq?</p>
| [
{
"answer_id": 355977,
"author": "Marc Gravell",
"author_id": 23354,
"author_profile": "https://Stackoverflow.com/users/23354",
"pm_score": 8,
"selected": true,
"text": "var most = list.GroupBy(i=>i).OrderByDescending(grp=>grp.Count())\n .Select(grp=>grp.Key).First();\n var most = (from i in list\n group i by i into grp\n orderby grp.Count() descending\n select grp.Key).First();\n public static T MostCommon<T>(this IEnumerable<T> list)\n{\n return ... // previous code\n}\n var most = list.MostCommon();\n"
},
{
"answer_id": 356453,
"author": "Amy B",
"author_id": 8155,
"author_profile": "https://Stackoverflow.com/users/8155",
"pm_score": 0,
"selected": false,
"text": "int indicator = 0\n\nvar result =\n list.GroupBy(i => i)\n .Select(g => new {i = g.Key, count = g.Count()}\n .OrderByDescending(x => x.count)\n .TakeWhile(x =>\n {\n if (x.count == indicator || indicator == 0)\n {\n indicator = x.count;\n return true;\n }\n return false;\n })\n .Select(x => x.i);\n"
},
{
"answer_id": 16850071,
"author": "nawfal",
"author_id": 661933,
"author_profile": "https://Stackoverflow.com/users/661933",
"pm_score": 2,
"selected": false,
"text": "public static IEnumerable<T> Mode<T>(this IEnumerable<T> input)\n{ \n var dict = input.ToLookup(x => x);\n if (dict.Count == 0)\n return Enumerable.Empty<T>();\n var maxCount = dict.Max(x => x.Count());\n return dict.Where(x => x.Count() == maxCount).Select(x => x.Key);\n}\n\nvar modes = { }.Mode().ToArray(); //returns { }\nvar modes = { 1, 2, 3 }.Mode().ToArray(); //returns { 1, 2, 3 }\nvar modes = { 1, 1, 2, 3 }.Mode().ToArray(); //returns { 1 }\nvar modes = { 1, 2, 3, 1, 2 }.Mode().ToArray(); //returns { 1, 2 }\n TakeWhile"
},
{
"answer_id": 16853299,
"author": "Jodrell",
"author_id": 659190,
"author_profile": "https://Stackoverflow.com/users/659190",
"pm_score": 1,
"selected": false,
"text": "public static IEnumerable<T> Mode<T>(\n this IEnumerable<T> source,\n IEqualityComparer<T> comparer = null)\n{\n var counts = source.GroupBy(t => t, comparer)\n .Select(g => new { g.Key, Count = g.Count() })\n .ToList();\n\n if (counts.Count == 0)\n {\n return Enumerable.Empty<T>();\n }\n\n var maxes = new List<int>(5);\n int maxCount = 1;\n\n for (var i = 0; i < counts.Count; i++)\n {\n if (counts[i].Count < maxCount)\n {\n continue;\n }\n\n if (counts[i].Count > maxCount)\n {\n maxes.Clear();\n maxCount = counts[i].Count;\n }\n\n maxes.Add(i);\n }\n\n return maxes.Select(i => counts[i].Key);\n}\n"
},
{
"answer_id": 72791647,
"author": "Paulius Lapienis",
"author_id": 19437709,
"author_profile": "https://Stackoverflow.com/users/19437709",
"pm_score": 0,
"selected": false,
"text": "public static List<T> MostCommonP<T>(this IEnumerable<T> list)\n {\n return list.GroupBy(element => element)\n .GroupBy(group => group.Count())\n .MaxBy(groups => groups.Key)\n .Select(group => group.Key)\n .ToList();\n }\n"
}
] | 2008/12/10 | [
"https://Stackoverflow.com/questions/355945",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
355,958 | <p>i have little problem with boost::asio library. My app receive and process data asynchronously, it create threads and run io_service.run() on each of them.</p>
<pre><code>boost::asio::io_service io;
boost::thread_group thread_pool;
...
int cpu_cnt = get_cpu_count();
for (int i = 0; i < cpu_cnt; ++i)
{
thread_pool.create_thread( boost::bind(&run_service, &io) );
}
void run_service(boost::asio::io_service* io)
{
try
{
io->run();//make fun
}
catch(const std::exception& e)
{ //process error
}
catch(...)
{ //process error
}
}
</code></pre>
<p>Time after time, my application receives message(across windows messaging system) from some supervisor application that checks is my program alive or not. If my application wont reply, it will be restarted. The tricky part here is to check, that threads is running and not deadlocked. I can post handler to io_service like this:</p>
<pre><code>io.post( &reply_to_supervisor );
</code></pre>
<p>but this method affects only one thread.
How can i check that all threads is running and not deadlocked?</p>
| [
{
"answer_id": 416820,
"author": "Vlagged",
"author_id": 6727,
"author_profile": "https://Stackoverflow.com/users/6727",
"pm_score": 3,
"selected": true,
"text": "cpu_cnt reply_to_supervisor sleep()"
}
] | 2008/12/10 | [
"https://Stackoverflow.com/questions/355958",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/42371/"
] |
355,967 | <p>The following code calls the builtin functions for clz/ctz in GCC and, on other systems, has C versions. Obviously, the C versions are a bit suboptimal if the system has a builtin clz/ctz instruction, like x86 and ARM.</p>
<pre><code>#ifdef __GNUC__
#define clz(x) __builtin_clz(x)
#define ctz(x) __builtin_ctz(x)
#else
static uint32_t ALWAYS_INLINE popcnt( uint32_t x )
{
x -= ((x >> 1) & 0x55555555);
x = (((x >> 2) & 0x33333333) + (x & 0x33333333));
x = (((x >> 4) + x) & 0x0f0f0f0f);
x += (x >> 8);
x += (x >> 16);
return x & 0x0000003f;
}
static uint32_t ALWAYS_INLINE clz( uint32_t x )
{
x |= (x >> 1);
x |= (x >> 2);
x |= (x >> 4);
x |= (x >> 8);
x |= (x >> 16);
return 32 - popcnt(x);
}
static uint32_t ALWAYS_INLINE ctz( uint32_t x )
{
return popcnt((x & -x) - 1);
}
#endif
</code></pre>
<p>What functions do I need to call, which headers do I need to include, etc to add a proper ifdef for MSVC here? I've already looked at <a href="https://msdn.microsoft.com/en-us/library/wfd9z0bb.aspx" rel="noreferrer">this page</a>, but I'm not entirely sure what the #pragma is for (is it required?) and what restrictions it puts on MSVC version requirements for compilation. As someone who doesn't really use MSVC, I also don't know whether these intrinsics have C equivalents on other architectures, or whether I have to #ifdef x86/x86_64 as well when #defining them.</p>
| [
{
"answer_id": 5468852,
"author": "sh0dan",
"author_id": 681490,
"author_profile": "https://Stackoverflow.com/users/681490",
"pm_score": -1,
"selected": false,
"text": "#ifdef _MSC_VER\n#include <intrin.h>\n\nstatic uint32_t __inline ctz( uint32_t x )\n{\n int r = 0;\n _BitScanReverse(&r, x);\n return r;\n}\n\nstatic uint32_t __inline clz( uint32_t x )\n{\n int r = 0;\n _BitScanForward(&r, x);\n return r;\n}\n#endif\n"
},
{
"answer_id": 20468180,
"author": "crazyjul",
"author_id": 547807,
"author_profile": "https://Stackoverflow.com/users/547807",
"pm_score": 5,
"selected": false,
"text": "#ifdef _MSC_VER\n#include <intrin.h>\n\nuint32_t __inline ctz( uint32_t value )\n{\n DWORD trailing_zero = 0;\n\n if ( _BitScanForward( &trailing_zero, value ) )\n {\n return trailing_zero;\n }\n else\n {\n // This is undefined, I better choose 32 than 0\n return 32;\n }\n}\n\nuint32_t __inline clz( uint32_t value )\n{\n DWORD leading_zero = 0;\n\n if ( _BitScanReverse( &leading_zero, value ) )\n {\n return 31 - leading_zero;\n }\n else\n {\n // Same remarks as above\n return 32;\n }\n}\n#endif\n __builtin_clz(value) (value?__builtin_clz(value):32)"
},
{
"answer_id": 25823147,
"author": "Tanguy",
"author_id": 293527,
"author_profile": "https://Stackoverflow.com/users/293527",
"pm_score": -1,
"selected": false,
"text": "#ifdef WIN32\n #include <intrin.h>\n static uint32_t __inline __builtin_clz(uint32_t x) {\n unsigned long r = 0;\n _BitScanReverse(&r, x);\n return (31-r);\n }\n#endif\n\nuint32_t clz64(const uint64_t x)\n{\n uint32_t u32 = (x >> 32);\n uint32_t result = u32 ? __builtin_clz(u32) : 32;\n if (result == 32) {\n u32 = x & 0xFFFFFFFFUL;\n result += (u32 ? __builtin_clz(u32) : 32);\n }\n return result;\n}\n"
},
{
"answer_id": 64398388,
"author": "Jebearssica",
"author_id": 13618304,
"author_profile": "https://Stackoverflow.com/users/13618304",
"pm_score": 1,
"selected": false,
"text": "__lzcnt(unsigned int) __builtin_clz(unsigned int)"
}
] | 2008/12/10 | [
"https://Stackoverflow.com/questions/355967",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11206/"
] |
355,986 | <p>How do we assign null value to int column in LINQ.
eg.</p>
<pre><code> SQLDBDataContext sqlD = new SQLDBDataContext();
var result = from p in sqlD.loadsRadius(Convert.ToInt32(Request["radius"]), .....
</code></pre>
<p>here if Request["radius"] is null gives an error.</p>
<p>I could pass 0 via this but I need to change in many already existing procedures.</p>
<p>Thanks in advance.<br>
<a href="http://www.ade-technologies.com" rel="nofollow noreferrer">Anil</a></p>
| [
{
"answer_id": 356158,
"author": "Pradeep Kumar Mishra",
"author_id": 22710,
"author_profile": "https://Stackoverflow.com/users/22710",
"pm_score": 0,
"selected": false,
"text": "int radius = -1;\nint.TryParse(Request[\"radius\"],out radius)\nif(radius > 0) // you can remove this clause if you don't want this\n{\nSQLDBDataContext sqlD = new SQLDBDataContext();\n var result = from p in sqlD.loadsRadius(radius)\n}\n"
},
{
"answer_id": 361979,
"author": "Alexander Prokofyev",
"author_id": 11256,
"author_profile": "https://Stackoverflow.com/users/11256",
"pm_score": 0,
"selected": false,
"text": "Convert.ToInt32(Request[\"radius\"] ?? \"0\")\n"
},
{
"answer_id": 361980,
"author": "Aaron Powell",
"author_id": 11388,
"author_profile": "https://Stackoverflow.com/users/11388",
"pm_score": 2,
"selected": false,
"text": "var result = from p in sqlD.loadsRadius(string.IsNullOrEmpty(Request[\"radius\"]) ? (int?)null : int.Parse(Request[\"radius\"]);\n"
}
] | 2008/12/10 | [
"https://Stackoverflow.com/questions/355986",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
355,988 | <p>I'm trying to do this:</p>
<pre><code>cmd.exe /C "C:\Program Files\Somewhere\SomeProgram.exe" > "C:\temp\Folder Containing Spaces\SomeProgram.out"
</code></pre>
<p>However, I have problems which are down to the way cmd.exe works. If you read the help for it, it handles " characters in a special way. See the help at the end of question. So, this doesn't execute correctly... I'm guessing cmd.exe strips some quotes which makes the statement ill-formed.</p>
<p>I can do this successfully:</p>
<pre><code>// quotes not required around folder with no spaces
cmd.exe /C "C:\Program Files\Somewhere\SomeProgram.exe" > C:\temp\FolderWithNoSpaces\SomeProgram.out
</code></pre>
<p>But, I really need the first one to work. Is there away around the strange quote processing that cmd.exe uses? I want it to preserve all of the quotes, but there doesn't appear to be an option to make it do that.</p>
<hr>
<p><strong>Help taken from output of: cmd /?</strong></p>
<p>If /C or /K is specified, then the remainder of the command line after
the switch is processed as a command line, where the following logic is
used to process quote (") characters:</p>
<pre><code>1. If all of the following conditions are met, then quote characters
on the command line are preserved:
- no /S switch
- exactly two quote characters
- no special characters between the two quote characters,
where special is one of: &<>()@^|
- there are one or more whitespace characters between the
the two quote characters
- the string between the two quote characters is the name
of an executable file.
2. Otherwise, old behavior is to see if the first character is
a quote character and if so, strip the leading character and
remove the last quote character on the command line, preserving
any text after the last quote character.
</code></pre>
| [
{
"answer_id": 356014,
"author": "Scott Langham",
"author_id": 11898,
"author_profile": "https://Stackoverflow.com/users/11898",
"pm_score": 8,
"selected": true,
"text": "cmd.exe /S /C \" do what you like here, quotes within the outermost quotes will be preserved \"\n"
},
{
"answer_id": 13939310,
"author": "barlop",
"author_id": 385907,
"author_profile": "https://Stackoverflow.com/users/385907",
"pm_score": 4,
"selected": false,
"text": "cmd.exe /C \"C:\\Program Files\\Somewhere\\SomeProgram.exe\" > \"C:\\temp\\Folder Containing Spaces\\SomeProgram.out\"\n C:\\>cmd /c \"c:\\Program Files\\my folder\\my long program.exe\" > \"c:\\temp\\spaces are here\\a.a\"\n\nC:\\>type \"c:\\temp\\spaces are here\\a.a\"\nmy long program.exe has run\n\nC:\\>\n\nfurther example demonstrating it works with \"my long program.exe\", removing cmd /c, it operates fine too.\n\nC:\\>\"c:\\Program Files\\my folder\\my long program.exe\" > \"c:\\temp\\spaces are here\\\na.a\"\n\nC:\\>type \"c:\\temp\\spaces are here\\a.a\"\nmy long program.exe has run\n\nC:\\>\n\n\n\nAnother example, but with replace. replace with no parameters says \"source path required\" \"no files replaced\"\n\nC:\\>replace > a.a\nSource path required\n\nC:\\>type a.a\nNo files replaced\n\nExactly the same effect when they're in folders with spaces.\n\nC:\\>cmd /c \"c:\\Program Files\\my folder\\replace.exe\" > \"c:\\temp\\spaces are here\\r.r\"\nSource path required\n\nC:\\>type \"c:\\temp\\spaces are here\\r.r\"\nNo files replaced\n\nC:\\>\n\nfurther demonstration with replace\nwithout cmd /c works fine too.\n\nC:\\>\"c:\\Program Files\\my folder\\replace.exe\" > \"c:\\temp\\spaces are here\\r.r\"\nSource path required\n\nC:\\>type \"c:\\temp\\spaces are here\\r.r\"\nNo files replaced\n\nC:\\>\n cmd.exe /C \"C:\\Program Files\\Somewhere\\SomeProgram.exe\" > \"C:\\temp\\Folder Containing Spaces\\SomeProgram.out\"\n cmd.exe /C \"C:\\Program Files\\Somewhere\\SomeProgram.exe\" If /C or /K is specified, then the remainder of the command line after\nthe switch is processed as a command line, where the following logic is\nused to process quote (\") characters:\n\n 1. If all of the following conditions are met, then quote characters\n on the command line are preserved:\n\n - no /S switch\n - exactly two quote characters\n - no special characters between the two quote characters,\n where special is one of: &<>()@^|\n - there are one or more whitespace characters between the\n two quote characters\n - the string between the two quote characters is the name\n of an executable file.\n\n 2. Otherwise, old behavior is to see if the first character is\n a quote character and if so, strip the leading character and\n remove the last quote character on the command line, preserving\n any text after the last quote character.\n C:\\>cmd /c \"c:\\Program Files\\my folder\\replace.exe\"\nSource path required\nNo files replaced\n\nC:\\>cmd /s /c \"c:\\Program Files\\my folder\\replace.exe\"\n'c:\\Program' is not recognized as an internal or external command,\noperable program or batch file.\n\nC:\\>cmd /c \"\"c:\\Program Files\\my folder\\replace.exe\"\"\nSource path required\nNo files replaced\n\nC:\\>cmd /s /c \"\"c:\\Program Files\\my folder\\replace.exe\"\"\nSource path required\nNo files replaced\n\nC:\\>\n cmd.exe /C \"C:\\Program Files\\Somewhere\\SomeProgram.exe\" > \"C:\\temp\\Folder Containing Spaces\\SomeProgram.out\"\n cmd.exe /S /C \"\"C:\\Program Files\\Somewhere\\SomeProgram.exe\" > \"C:\\temp\\Folder Containing Spaces\\SomeProgram.out\"\"\n cmd.exe /C \"\"C:\\Program Files\\Somewhere\\SomeProgram.exe\" > \"C:\\temp\\Folder Containing Spaces\\SomeProgram.out\"\"\n"
}
] | 2008/12/10 | [
"https://Stackoverflow.com/questions/355988",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11898/"
] |
355,994 | <p>I have two medium-sized web applications that I'm merging into one. They are both localized with <code>GetText</code> and have large amout of common strings, so merging them manually would be extremely annoying. What is the fastest way to merge the two <code>PO</code> files?</p>
| [
{
"answer_id": 356001,
"author": "mat",
"author_id": 42083,
"author_profile": "https://Stackoverflow.com/users/42083",
"pm_score": 3,
"selected": true,
"text": "msgmerge"
},
{
"answer_id": 7643286,
"author": "seanf",
"author_id": 14379,
"author_profile": "https://Stackoverflow.com/users/14379",
"pm_score": 4,
"selected": false,
"text": "msgcat msgmerge"
}
] | 2008/12/10 | [
"https://Stackoverflow.com/questions/355994",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/38256/"
] |
356,000 | <p>I'd like to drop a user in a SQL Server script but I'll need to test for existence first or I'll get script errors. When dropping tables or stored procs, I check the sysobjects table like so:</p>
<pre><code>IF EXISTS (
SELECT *
FROM sysobjects
WHERE id = object_id(N'[dbo].[up_SetMedOptions]')
AND OBJECTPROPERTY(id, N'IsProcedure') = 1
)
Drop Procedure up_SetMedOptions;
GO
</code></pre>
<p>What is the corollary for checking for a user? Note that I am NOT asking about a database login to the server! The question pertains to a User in a specific database.</p>
| [
{
"answer_id": 356021,
"author": "edosoft",
"author_id": 6399,
"author_profile": "https://Stackoverflow.com/users/6399",
"pm_score": 2,
"selected": false,
"text": "select * from sys.sysusers\n select * from sysusers\n"
},
{
"answer_id": 356030,
"author": "Ed Harper",
"author_id": 27825,
"author_profile": "https://Stackoverflow.com/users/27825",
"pm_score": 6,
"selected": true,
"text": "IF EXISTS (SELECT * FROM sys.database_principals WHERE name = N'username')\nDROP USER [username]\n IF EXISTS (SELECT * FROM dbo.sysusers WHERE name = N'username')\nEXEC dbo.sp_revokedbaccess N'username'\n"
},
{
"answer_id": 19759759,
"author": "Diganta Kumar",
"author_id": 798727,
"author_profile": "https://Stackoverflow.com/users/798727",
"pm_score": -1,
"selected": false,
"text": "IF EXISTS (SELECT * FROM sys.syslogins WHERE name = N'MyUserName') \nDROP LOGIN [MyUserName]\n"
}
] | 2008/12/10 | [
"https://Stackoverflow.com/questions/356000",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15592/"
] |
356,002 | <p>So I'm trying to get rid of my std::vector's by using boost::ptr_vector. Now I'm trying to remove an element from one, and have the removed element deleted as well. The most obvious thing to me was to do:</p>
<pre><code>class A
{ int m; };
boost::ptr_vector<A> vec;
A* a = new A;
vec.push_back(a);
vec.erase(a);
</code></pre>
<p>But this won't even compile (see below for the full error message). I've tried the erase/remove idiom like I would on a std::vector but all the algorithms of boost::ptr_vector turn out to be slightly different from those in std::vector.</p>
<p>So my questions:</p>
<ul>
<li>How do I remove a pointer from a ptr_vector?</li>
<li>Do I still need to manually delete() that element that I removed?</li>
</ul>
<p>Compiler error:</p>
<pre><code>1>------ Build started: Project: ptr_vector_test, Configuration: Debug Win32 ------
1>Compiling...
1>ptr_vector_test.cpp
1>c:\users\rvanhout\svn\trunk\thirdparty\boost\range\const_iterator.hpp(37) : error C2825: 'C': must be a class or namespace when followed by '::'
1> c:\users\rvanhout\svn\trunk\thirdparty\boost\mpl\eval_if.hpp(63) : see reference to class template instantiation 'boost::range_const_iterator<C>' being compiled
1> with
1> [
1> C=A *
1> ]
1> c:\users\rvanhout\svn\trunk\thirdparty\boost\range\iterator.hpp(63) : see reference to class template instantiation 'boost::mpl::eval_if_c<C,F1,F2>' being compiled
1> with
1> [
1> C=true,
1> F1=boost::range_const_iterator<A *>,
1> F2=boost::range_mutable_iterator<A *const >
1> ]
1> c:\users\rvanhout\svn\trunk\thirdparty\boost\ptr_container\detail\reversible_ptr_container.hpp(506) : see reference to class template instantiation 'boost::range_iterator<C>' being compiled
1> with
1> [
1> C=A *const
1> ]
1> c:\tmp\ptr_vector_test\ptr_vector_test.cpp(21) : see reference to function template instantiation 'boost::void_ptr_iterator<VoidIter,T> boost::ptr_container_detail::reversible_ptr_container<Config,CloneAllocator>::erase<A*>(const Range &)' being compiled
1> with
1> [
1> VoidIter=std::_Vector_iterator<void *,std::allocator<void *>>,
1> T=A,
1> Config=boost::ptr_container_detail::sequence_config<A,std::vector<void *,std::allocator<void *>>>,
1> CloneAllocator=boost::heap_clone_allocator,
1> Range=A *
1> ]
1>c:\users\rvanhout\svn\trunk\thirdparty\boost\range\const_iterator.hpp(37) : error C2039: 'const_iterator' : is not a member of '`global namespace''
1>c:\users\rvanhout\svn\trunk\thirdparty\boost\range\const_iterator.hpp(37) : error C2146: syntax error : missing ';' before identifier 'type'
1>c:\users\rvanhout\svn\trunk\thirdparty\boost\range\const_iterator.hpp(37) : error C2208: 'boost::type' : no members defined using this type
1>c:\users\rvanhout\svn\trunk\thirdparty\boost\range\const_iterator.hpp(37) : fatal error C1903: unable to recover from previous error(s); stopping compilation
1>Build log was saved at "file://c:\tmp\ptr_vector_test\Debug\BuildLog.htm"
1>ptr_vector_test - 5 error(s), 0 warning(s)
========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========
</code></pre>
| [
{
"answer_id": 356016,
"author": "Evgeny Lazin",
"author_id": 42371,
"author_profile": "https://Stackoverflow.com/users/42371",
"pm_score": 1,
"selected": false,
"text": "vec.erase_if( predicate() );\n"
},
{
"answer_id": 356046,
"author": "Pieter",
"author_id": 5822,
"author_profile": "https://Stackoverflow.com/users/5822",
"pm_score": 0,
"selected": false,
"text": "struct delete_a {\n bool operator()(boost::ptr_vector<A>::value_type inA) {\n return inA == a;\n }\n}\n\nvec.erase_if(delete_a());\n"
},
{
"answer_id": 356166,
"author": "James Hopkin",
"author_id": 11828,
"author_profile": "https://Stackoverflow.com/users/11828",
"pm_score": 1,
"selected": false,
"text": "ptr_vector vector"
},
{
"answer_id": 357043,
"author": "Martin York",
"author_id": 14065,
"author_profile": "https://Stackoverflow.com/users/14065",
"pm_score": 4,
"selected": true,
"text": " std::vector<A> x;\n std::ptr_vector<A> y;\n\n // These two object should behave in exactly the same way.\n // The ONLY difference is inserting values which for y are pointers.\n // Y take ownership of the pointer and all subsequent acesses to the\n // members of y look like they are objects\n #include <boost/ptr_container/ptr_vector.hpp>\n#include <vector>\n\nclass A\n{ int m;\n public:\n A(int x):m(x) {}\n bool operator==(A const& rhs) {return m = rhs.m;}\n};\n\nint main()\n{\n boost::ptr_vector<A> x;\n x.push_back(new A(1));\n x.erase(std::find(x.begin(),x.end(),A(1)));\n\n\n std::vector<A> y;\n y.push_back(A(2));\n y.erase(std::find(y.begin(),y.end(),A(2)));\n\n // To find an exact pointer don't modify the equality.\n // Use find_if and pass a predicate that tests for a pointer\n A* a = new A(3);\n boost:ptr_Vector<A> z;\n z.push_back(a);\n z.erase(std::find_if(y.begin(),y.end(),CheckPointerValue(a));\n}\n\nstruct CheckPointerValue\n{\n CheckPointerValue(A* a):anA(a) {}\n bool operator()(A const& x) { return &X == anA;}\n private:\n A* anA;\n};\n"
}
] | 2008/12/10 | [
"https://Stackoverflow.com/questions/356002",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11449/"
] |
356,004 | <p>Is it possible to have a singleton in a factory method? I have many domains using the factory method. How do I work around with this. Please help me with an example.</p>
| [
{
"answer_id": 356018,
"author": "mepcotterell",
"author_id": 43312,
"author_profile": "https://Stackoverflow.com/users/43312",
"pm_score": 2,
"selected": false,
"text": "/**\n * An interface defining objects that can create Singleton\n * instances.\n */\npublic interface SingletonFactoryFunctor {\n /**\n * @return An instance of the Singleton.\n */\n public Singleton makeInstance();\n}\n"
},
{
"answer_id": 356020,
"author": "Bill the Lizard",
"author_id": 1288,
"author_profile": "https://Stackoverflow.com/users/1288",
"pm_score": 2,
"selected": false,
"text": "getInstance() getInstance()"
},
{
"answer_id": 357406,
"author": "Markus Lausberg",
"author_id": 39062,
"author_profile": "https://Stackoverflow.com/users/39062",
"pm_score": 2,
"selected": false,
"text": "public class Singleton {\n\nprivate static Singleton mInstance;\n\nprivate Singleton(){}\n\npublic static Singleton getInstance()\n{\n if(mInstance==null){\n mInstance=new Singleton();\n }\nreturn mInstance;\n}\n\n}\n"
},
{
"answer_id": 358100,
"author": "Chris B.",
"author_id": 45176,
"author_profile": "https://Stackoverflow.com/users/45176",
"pm_score": 3,
"selected": false,
"text": "public static synchronized Singleton getInstance()\n{\n // since whole method is synchronized only 1 thread can \n // enter the following block ensuring only one instance \n // is ever created. however we pay a synchronization\n // penalty every time this method is called.\n if(mInstance==null) { \n mInstance=new Singleton();\n }\n return mInstance;\n}\n // no synchronization penalty, but penalty for eager init\nprivate static Singleton mInstance = new Singleton(); \n\npublic static Singleton getInstance()\n{\n return mInstance;\n}\n private volatile static Singleton mInstance;\n\nprivate Singleton(){}\n\npublic static Singleton getInstance()\n{\n if(mInstance==null) {\n synchronized (Singleton.class) { \n // only pay synchronization penalty once\n if(mInstance==null){\n mInstance=new Singleton();\n }\n }\n }\n return mInstance;\n}\n"
},
{
"answer_id": 13090544,
"author": "Gabriel Ramirez",
"author_id": 1046489,
"author_profile": "https://Stackoverflow.com/users/1046489",
"pm_score": 0,
"selected": false,
"text": "abstract class Product {}\n\nclass ConcreteProduct extends Product{}\n\nclass ProductSupportFactory {\n private static ProductSupportFactory instance = null;\n private ConcreteProduct product = null;\n\n static {\n instance = new ProductSupportFactory();\n }\n private ProductSupportFactory() {\n product = new ConcreteProduct(); //object initialization\n }\n public static ProductSupportFactory getInstance(){\n return instance;\n }\n public ConcreteProduct getProduct() {\n return product;\n }\n public void setProduct(ConcreteProduct product) {\n this.product = product;\n }\n}\n\npublic class ProductConsumer { \n public static void main(String args[]){ //client\n ConcreteProduct uniqueInstance = ProductSupportFactory.getInstance().getProduct();\n ConcreteProduct sharedInstance = ProductSupportFactory.getInstance().getProduct(); //same object hash\n }\n}\n"
}
] | 2008/12/10 | [
"https://Stackoverflow.com/questions/356004",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
356,010 | <p>I was wondering if there is some option to keep ReSharper from removing just the <code>using System;</code> directive? Perhaps this is configurable somewhere?</p>
<p>Also, is there a way to have ReSharper sort the remaining directives just as Visual Studio 2008 does it (alphabetically, I think)?</p>
<p>Thanks.</p>
| [
{
"answer_id": 356032,
"author": "Garry Shutler",
"author_id": 6369,
"author_profile": "https://Stackoverflow.com/users/6369",
"pm_score": 3,
"selected": false,
"text": "Resharper Options Languages C# Namespace Imports System"
}
] | 2008/12/10 | [
"https://Stackoverflow.com/questions/356010",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8205/"
] |
356,035 | <p>I have a 2D area with "dots" distributed on this area. I now am trying to detect "clusters" of dots, that is, areas with a certain high density of dots.</p>
<p>Any thoughts on (or links to articles with thoughts on) how to elegantly detect these areas?</p>
| [
{
"answer_id": 356069,
"author": "krusty.ar",
"author_id": 43981,
"author_profile": "https://Stackoverflow.com/users/43981",
"pm_score": 6,
"selected": true,
"text": "//load the image\nPImage sample;\nsample = loadImage(\"test.png\");\nsize(sample.width, sample.height);\nimage(sample, 0, 0);\nint[][] heat = new int[width][height];\n\n//parameters\nint resolution = 5; //distance between points in the gridq\nint distance = 8; //distance at wich two points are considered near\nfloat threshold = 0.5;\nint level = 240; //leven to detect the dots\nint sensitivity = 1; //how much does each dot matters\n\n//calculate the \"heat\" on each point of the grid\ncolor black = color(0,0,0);\nloadPixels();\nfor(int a=0; a<width; a+=resolution){\n for(int b=0; b<height; b+=resolution){\n for(int x=0; x<width; x++){\n for(int y=0; y<height; y++){\n color c = sample.pixels[y*sample.width+x]; \n /**\n * the heat should be a function of the brightness and the distance, \n * but this works (tm)\n */\n if(brightness(c)<level && dist(x,y,a,b)<distance){\n heat[a][b] += sensitivity;\n }\n }\n }\n }\n}\n\n//render the output\nfor(int a=0; a<width; ++a){\n for(int b=0; b<height; ++b){\n pixels[b*sample.width+a] = color(heat[a][b],0,0);\n }\n}\nupdatePixels();\nfilter(THRESHOLD,threshold);\n //load the image\nPImage sample;\nsample = loadImage(\"test.png\");\nsize(sample.width, sample.height);\nimage(sample, 0, 0);\nint[][] heat = new int[width][height];\nint dotQ = 0;\nint[][] dots = new int[width*height][2];\nint X = 0;\nint Y = 1;\n\n\n//parameters\nint resolution = 1; //distance between points in the grid\nint distance = 20; //distance at wich two points are considered near\nfloat threshold = 0.6;\nint level = 240; //minimum brightness to detect the dots\nint sensitivity = 1; //how much does each dot matters\n\n//detect all dots in the sample\nloadPixels();\nfor(int x=0; x<width; x++){\n for(int y=0; y<height; y++){\n color c = pixels[y*sample.width+x];\n if(brightness(c)<level) {\n dots[dotQ][X] += x;\n dots[dotQ++][Y] += y;\n }\n }\n}\n\n//calculate heat\nfor(int x=0; x<width; x+=resolution){\n for(int y=0; y<height; y+=resolution){\n for(int d=0; d<dotQ; d++){\n if(dist(x,y,dots[d][X],dots[d][Y]) < distance)\n heat[x][y]+=sensitivity;\n }\n }\n}\n\n//render the output\nfor(int a=0; a<width; ++a){\n for(int b=0; b<height; ++b){\n pixels[b*sample.width+a] = color(heat[a][b],0,0);\n }\n}\nupdatePixels();\nfilter(THRESHOLD,threshold);\n\n/** This smooths the ouput with low resolutions\n* for(int i=0; i<10; ++i) filter(DILATE);\n* for(int i=0; i<3; ++i) filter(BLUR);\n* filter(THRESHOLD);\n*/\n"
},
{
"answer_id": 356109,
"author": "P Daddy",
"author_id": 36388,
"author_profile": "https://Stackoverflow.com/users/36388",
"pm_score": 4,
"selected": false,
"text": "1 2 3 2 1\n2 4 6 4 2\n3 6 9 6 3\n2 4 6 4 2\n1 2 3 2 1\n"
},
{
"answer_id": 414042,
"author": "Ivan",
"author_id": 50135,
"author_profile": "https://Stackoverflow.com/users/50135",
"pm_score": 5,
"selected": false,
"text": "int cvMeanShift( const CvArr* prob_image, CvRect window,\n CvTermCriteria criteria, CvConnectedComp* comp );\n"
}
] | 2008/12/10 | [
"https://Stackoverflow.com/questions/356035",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6583/"
] |
356,039 | <p>For a stylesheet I'm writing (actually for a set of them, each generating a different output format), I have the need to evaluate whether a certain value is present in a list of values. In this case, the value being tested is taken from an element's attribute. The list it is to be tested against comes from the invocation of the stylesheet, and is taken as a top-level <code><xsl:param></code> (to be provided on the command-line when I call <code>xsltproc</code> or a Saxon equivalent invocation). For example, the input value may be:</p>
<pre><code>v0_01,v0_10,v0_99
</code></pre>
<p>while the attribute values will each look very much like <em>one</em> such value. (Whether a comma is used to separate values, or a space, is not important-- I chose a comma for now because I plan on passing the value via command-line switch to <code>xsltproc</code>, and using a space would require quoting the argument, and I'm lazy-enough to not want to type the extra two characters.)</p>
<p>What I am looking for is something akin to Perl's <code>grep</code>, wherein I can see if the value I currently have is contained in the list. It can be done with sub-string tests, but this would have to be clever so as not to get a false-positive (<code>v0_01</code> should not match a string that contains <code>v0_011</code>). It seems that the only non-scalar data-type that XSL/XSLT supports is a node-set. I suppose it's possible to convert the list into a set of text nodes, but that seems like over-kill, even compared to making a sub-string test with extra boundaries-checking to prevent false matches.</p>
| [
{
"answer_id": 356077,
"author": "Tomalak",
"author_id": 18771,
"author_profile": "https://Stackoverflow.com/users/18771",
"pm_score": 3,
"selected": false,
"text": "contains(concat(',' $list, ','), concat(',', $value, ','))\n substring-before(concat('|,' $list, ',|'), concat(',', $value, ','))\n substring-after(concat('|,' $list, ',|'), concat(',', $value, ','))\n $value substring-before() substring-after() contains()"
},
{
"answer_id": 356777,
"author": "Dimitre Novatchev",
"author_id": 36305,
"author_profile": "https://Stackoverflow.com/users/36305",
"pm_score": 2,
"selected": false,
"text": "exists(tokenize($list, ',')[. = $value]) true() $value $list"
}
] | 2008/12/10 | [
"https://Stackoverflow.com/questions/356039",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6421/"
] |
356,060 | <p>I have using the following code for developing tabs.</p>
<pre><code>$(document).ready(function() {
$('#container-1').tabs();
}
....
<div id="container-1">
<ul>
<li><a href="#fragment-1"><span>Home</span></a></li>
<li><a href="#fragment-2"><span>Contact</span></a></li>
</ul>
</div>
...
</code></pre>
<p>It works fine! I need the tab click event. If it is the <em>Home</em> tab click, I have to do <code>alert();</code>. How do I achieve this?</p>
| [
{
"answer_id": 356136,
"author": "adam",
"author_id": 33604,
"author_profile": "https://Stackoverflow.com/users/33604",
"pm_score": 0,
"selected": false,
"text": "$(\"#tabid\").click(function(e) {\n e.preventDefault();\n // Do tab click logic\n});\n $(\".tabclass\").click(function(e) {\n e.preventDefault();\n // Do tab click logic\n});\n"
},
{
"answer_id": 356152,
"author": "Alexander Prokofyev",
"author_id": 11256,
"author_profile": "https://Stackoverflow.com/users/11256",
"pm_score": 2,
"selected": false,
"text": "<li><a href=\"#fragment-1\"><span id=\"home\">Home</span></a></li> \n $(\"#home\").click(function()\n{\n alert(\"Home tab is selected!\");\n});\n"
},
{
"answer_id": 357432,
"author": "Manik",
"author_id": 41381,
"author_profile": "https://Stackoverflow.com/users/41381",
"pm_score": 2,
"selected": true,
"text": " $(document).ready(function() {\n $('#container-1').tabs({\n selected : function(e, ui) {\n if (ui.index == 0) {\n alert('Home clicked!');\n }\n } \n }); \n });\n ....\n <div id=\"container-1\">\n <ul>\n <li><a href=\"#fragment-1\"><span>Home</span></a></li>\n <li><a href=\"#fragment-2\"><span>Contact</span></a></li>\n\n </ul>\n </div>\n"
}
] | 2008/12/10 | [
"https://Stackoverflow.com/questions/356060",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/44984/"
] |
356,090 | <p>I need a way to compute the nth root of a long integer in Python. </p>
<p>I tried <code>pow(m, 1.0/n)</code>, but it doesn't work:</p>
<blockquote>
<p>OverflowError: long int too large to convert to float</p>
</blockquote>
<p>Any ideas?</p>
<p>By long integer I mean REALLY long integers like:</p>
<blockquote>
<p>11968003966030964356885611480383408833172346450467339251
196093144141045683463085291115677488411620264826942334897996389
485046262847265769280883237649461122479734279424416861834396522
819159219215308460065265520143082728303864638821979329804885526
557893649662037092457130509980883789368448042961108430809620626
059287437887495827369474189818588006905358793385574832590121472
680866521970802708379837148646191567765584039175249171110593159
305029014037881475265618958103073425958633163441030267478942720
703134493880117805010891574606323700178176718412858948243785754
898788359757528163558061136758276299059029113119763557411729353
915848889261125855717014320045292143759177464380434854573300054
940683350937992500211758727939459249163046465047204851616590276
724564411037216844005877918224201569391107769029955591465502737
961776799311859881060956465198859727495735498887960494256488224
613682478900505821893815926193600121890632</p>
</blockquote>
| [
{
"answer_id": 356110,
"author": "Brian",
"author_id": 18192,
"author_profile": "https://Stackoverflow.com/users/18192",
"pm_score": 0,
"selected": false,
"text": "1/3 1/3 1//3 1/3.0"
},
{
"answer_id": 356187,
"author": "gimel",
"author_id": 6491,
"author_profile": "https://Stackoverflow.com/users/6491",
"pm_score": 4,
"selected": false,
"text": "root >>> import gmpy\n>>> i0=11968003966030964356885611480383408833172346450467339251 \n>>> m0=gmpy.mpz(i0)\n>>> m0\nmpz(11968003966030964356885611480383408833172346450467339251L)\n>>> m0.root(20)\n(mpz(567), 0)\n"
},
{
"answer_id": 356206,
"author": "Markus Jarderot",
"author_id": 22364,
"author_profile": "https://Stackoverflow.com/users/22364",
"pm_score": 5,
"selected": false,
"text": "def find_invpow(x,n):\n \"\"\"Finds the integer component of the n'th root of x,\n an integer such that y ** n <= x < (y + 1) ** n.\n \"\"\"\n high = 1\n while high ** n <= x:\n high *= 2\n low = high/2\n while low < high:\n mid = (low + high) // 2\n if low < mid and mid**n < x:\n low = mid\n elif high > mid and mid**n > x:\n high = mid\n else:\n return mid\n return mid + 1\n >>> x = 237734537465873465\n>>> n = 5\n>>> y = find_invpow(x,n)\n>>> y\n2986\n>>> y**n <= x <= (y+1)**n\nTrue\n>>>\n>>> x = 119680039660309643568856114803834088331723464504673392511960931441>\n>>> n = 45\n>>> y = find_invpow(x,n)\n>>> y\n227661383982863143360L\n>>> y**n <= x < (y+1)**n\nTrue\n>>> find_invpow(y**n,n) == y\nTrue\n>>>\n"
},
{
"answer_id": 356235,
"author": "Jim Carroll",
"author_id": 35922,
"author_profile": "https://Stackoverflow.com/users/35922",
"pm_score": 2,
"selected": false,
"text": "ns = \"11968003966030964356885611480383408833172346450467339251196093144141045683463085291115677488411620264826942334897996389485046262847265769280883237649461122479734279424416861834396522819159219215308460065265520143082728303864638821979329804885526557893649662037092457130509980883789368448042961108430809620626059287437887495827369474189818588006905358793385574832590121472680866521970802708379837148646191567765584039175249171110593159305029014037881475265618958103073425958633163441030267478942720703134493880117805010891574606323700178176718412858948243785754898788359757528163558061136758276299059029113119763557411729353915848889261125855717014320045292143759177464380434854573300054940683350937992500211758727939459249163046465047204851616590276724564411037216844005877918224201569391107769029955591465502737961776799311859881060956465198859727495735498887960494256488224613682478900505821893815926193600121890632\"\nfrom decimal import Decimal\nd = Decimal(ns)\none_third = Decimal(\"0.3333333333333333\")\nprint d ** one_third\n from decimal import Decimal\n\ndef nth_root(num_decimal, n_integer):\n exponent = Decimal(\"1.0\") / Decimal(n_integer)\n return num_decimal ** exponent\n\ndef test():\n ns = \"11968003966030964356885611480383408833172346450467339251196093144141045683463085291115677488411620264826942334897996389485046262847265769280883237649461122479734279424416861834396522819159219215308460065265520143082728303864638821979329804885526557893649662037092457130509980883789368448042961108430809620626059287437887495827369474189818588006905358793385574832590121472680866521970802708379837148646191567765584039175249171110593159305029014037881475265618958103073425958633163441030267478942720703134493880117805010891574606323700178176718412858948243785754898788359757528163558061136758276299059029113119763557411729353915848889261125855717014320045292143759177464380434854573300054940683350937992500211758727939459249163046465047204851616590276724564411037216844005877918224201569391107769029955591465502737961776799311859881060956465198859727495735498887960494256488224613682478900505821893815926193600121890632\"\n nd = Decimal(ns)\n cube_root = nth_root(nd, 3)\n print (cube_root ** Decimal(\"3.0\")) - nd\n\nif __name__ == \"__main__\":\n test()\n"
},
{
"answer_id": 358026,
"author": "Calyth",
"author_id": 45144,
"author_profile": "https://Stackoverflow.com/users/45144",
"pm_score": 2,
"selected": false,
"text": "x^n - 11968003.... = 0 mod p"
},
{
"answer_id": 358134,
"author": "Brian",
"author_id": 18192,
"author_profile": "https://Stackoverflow.com/users/18192",
"pm_score": 4,
"selected": true,
"text": "from timeit import Timer\n\ndef find_invpow(x,n):\n \"\"\"Finds the integer component of the n'th root of x,\n an integer such that y ** n <= x < (y + 1) ** n.\n \"\"\"\n high = 1\n while high ** n < x:\n high *= 2\n low = high/2\n while low < high:\n mid = (low + high) // 2\n if low < mid and mid**n < x:\n low = mid\n elif high > mid and mid**n > x:\n high = mid\n else:\n return mid\n return mid + 1\n\ndef find_invpowAlt(x,n):\n \"\"\"Finds the integer component of the n'th root of x,\n an integer such that y ** n <= x < (y + 1) ** n.\n \"\"\"\n low = 10 ** (len(str(x)) / n)\n high = low * 10\n\n while low < high:\n mid = (low + high) // 2\n if low < mid and mid**n < x:\n low = mid\n elif high > mid and mid**n > x:\n high = mid\n else:\n return mid\n return mid + 1\n\nx = 237734537465873465\nn = 5\ntests = 10000\n\nprint \"Norm\", Timer('find_invpow(x,n)', 'from __main__ import find_invpow, x,n').timeit(number=tests)\nprint \"Alt\", Timer('find_invpowAlt(x,n)', 'from __main__ import find_invpowAlt, x,n').timeit(number=tests)\n"
},
{
"answer_id": 637321,
"author": "Mahmoud Kassem",
"author_id": 77038,
"author_profile": "https://Stackoverflow.com/users/77038",
"pm_score": 3,
"selected": false,
"text": "from decimal import *\n\nx = '11968003966030964356885611480383408833172346450467339251\\\n196093144141045683463085291115677488411620264826942334897996389\\\n485046262847265769280883237649461122479734279424416861834396522\\\n819159219215308460065265520143082728303864638821979329804885526\\\n557893649662037092457130509980883789368448042961108430809620626\\\n059287437887495827369474189818588006905358793385574832590121472\\\n680866521970802708379837148646191567765584039175249171110593159\\\n305029014037881475265618958103073425958633163441030267478942720\\\n703134493880117805010891574606323700178176718412858948243785754\\\n898788359757528163558061136758276299059029113119763557411729353\\\n915848889261125855717014320045292143759177464380434854573300054\\\n940683350937992500211758727939459249163046465047204851616590276\\\n724564411037216844005877918224201569391107769029955591465502737\\\n961776799311859881060956465198859727495735498887960494256488224\\\n613682478900505821893815926193600121890632'\n\nminprec = 27\nif len(x) > minprec: getcontext().prec = len(x)\nelse: getcontext().prec = minprec\n\nx = Decimal(x)\npower = Decimal(1)/Decimal(3)\n\nanswer = x**power\nranswer = answer.quantize(Decimal('1.'), rounding=ROUND_UP)\n\ndiff = x - ranswer**Decimal(3)\nif diff == Decimal(0):\n print(\"x is the cubic number of\", ranswer)\nelse:\n print(\"x has a cubic root of \", answer)\n"
},
{
"answer_id": 37171151,
"author": "Elias Zamaria",
"author_id": 28324,
"author_profile": "https://Stackoverflow.com/users/28324",
"pm_score": 1,
"selected": false,
"text": "def cube_root(x):\n return decimal.Decimal(x) ** (decimal.Decimal(1) / decimal.Decimal(3))\n power decimal with decimal.localcontext() as context:\n context.prec = 50\n print(cube_root(42))\n"
},
{
"answer_id": 71530812,
"author": "Arty",
"author_id": 941531,
"author_profile": "https://Stackoverflow.com/users/941531",
"pm_score": 1,
"selected": false,
"text": "Opt [hi / 2, hi) hi 2^(num_bit_length / k) y = n (x0, n) n = x0 ^ k test() k = 3 def binary_search(begin, end, f, *, niter = [0]):\n while begin < end:\n niter[0] += 1\n mid = (begin + end) >> 1\n if f(mid):\n begin = mid + 1\n else:\n end = mid\n return begin\n\ndef binary_search_kth_root(n, k, *, verbose = False):\n # https://en.wikipedia.org/wiki/Binary_search_algorithm\n niter = [0]\n res = binary_search(0, n + 1, lambda root: root ** k < n, niter = niter)\n if verbose:\n print('Binary Search iterations:', niter[0])\n return res\n\ndef binary_search_opt_kth_root(n, k, *, verbose = False):\n # https://en.wikipedia.org/wiki/Binary_search_algorithm\n niter = [0]\n hi = 1 << (n.bit_length() // k - 1)\n while hi ** k <= n:\n niter[0] += 1\n hi <<= 1\n res = binary_search(hi >> 1, hi, lambda root: root ** k < n, niter = niter)\n if verbose:\n print('Binary Search Opt iterations:', niter[0])\n return res\n\ndef newton_kth_root(n, k, *, verbose = False):\n # https://en.wikipedia.org/wiki/Newton%27s_method\n f = lambda x: x ** k - n\n df = lambda x: k * x ** (k - 1)\n x, px, niter = n, 2 * n, [0]\n while abs(px - x) > 1:\n niter[0] += 1\n px = x\n x -= f(x) // df(x)\n if verbose:\n print('Newton Method iterations:', niter[0])\n mini, minv = None, None\n for i in range(-2, 3):\n v = abs(f(x + i))\n if minv is None or v < minv:\n mini, minv = i, v\n return x + mini\n\ndef shifting_kth_root(n, k, *, verbose = False):\n # https://en.wikipedia.org/wiki/Shifting_nth_root_algorithm\n B_bits = 64\n \n r, y = 0, 0\n B = 1 << B_bits\n Bk_bits = B_bits * k\n Bk_mask = (1 << Bk_bits) - 1\n niter = [0]\n \n for i in range((n.bit_length() + Bk_bits - 1) // Bk_bits - 1, -1, -1):\n alpha = (n >> (i * Bk_bits)) & Bk_mask\n B_y = y << B_bits\n Bk_yk = (y ** k) << Bk_bits\n Bk_r_alpha = (r << Bk_bits) + alpha\n Bk_yk_Bk_r_alpha = Bk_yk + Bk_r_alpha\n beta = binary_search(1, B, lambda beta: (B_y + beta) ** k <= Bk_yk_Bk_r_alpha, niter = niter) - 1\n y, r = B_y + beta, Bk_r_alpha - ((B_y + beta) ** k - Bk_yk)\n\n if verbose:\n print('Shifting Method iterations:', niter[0])\n\n return y\n\ndef chord_tangent_kth_root(n, k, *, verbose = False):\n niter = [0]\n hi = 1 << (n.bit_length() // k - 1)\n while hi ** k <= n:\n niter[0] += 1\n hi <<= 1\n f = lambda x: x ** k\n df = lambda x: k * x ** (k - 1)\n # https://i.stack.imgur.com/et9O0.jpg\n x_begin, x_end = hi >> 1, hi\n y_begin, y_end = f(x_begin), f(x_end)\n for icycle in range(1 << 30):\n if x_end - x_begin <= 1:\n break\n niter[0] += 1\n if 0: # Do Binary Search step if needed\n x_mid = (x_begin + x_end) >> 1\n y_mid = f(x_mid)\n if y_mid > n:\n x_end, y_end = x_mid, y_mid\n else:\n x_begin, y_begin = x_mid, y_mid\n # (y_end - y_begin) / (x_end - x_begin) = (n - y_begin) / (x_n - x_begin) ->\n x_n = x_begin + (n - y_begin) * (x_end - x_begin) // (y_end - y_begin)\n y_n = f(x_n)\n tangent_x = x_n + (n - y_n) // df(x_n) + 1\n \n chord_x = x_n + (n - y_n) * (x_end - x_n) // (y_end - y_n)\n \n assert chord_x <= tangent_x, (chord_x, tangent_x)\n x_begin, x_end = chord_x, tangent_x\n y_begin, y_end = f(x_begin), f(x_end)\n assert y_begin <= n, (chord_x, y_begin, n, n - y_begin)\n assert y_end > n, (icycle, tangent_x - binary_search_kth_root(n, k), y_end, n, y_end - n)\n if verbose:\n print('Chord Tangent Method iterations:', niter[0])\n return x_begin\n\ndef test():\n import random, timeit\n \n nruns = 3\n bits = 8192\n n = random.randrange(1 << (bits - 1), 1 << bits)\n \n a = binary_search_kth_root(n, 3, verbose = True)\n b = binary_search_opt_kth_root(n, 3, verbose = True)\n c = newton_kth_root(n, 3, verbose = True)\n d = shifting_kth_root(n, 3, verbose = True)\n e = chord_tangent_kth_root(n, 3, verbose = True)\n assert abs(a - b) <= 0 and abs(a - c) <= 1 and abs(a - d) <= 1 and abs(a - e) <= 1, (a - b, a - c, a - d, a - e)\n\n print()\n print('Binary Search timing:', round(timeit.timeit(lambda: binary_search_kth_root(n, 3), number = nruns) / nruns, 3), 'sec')\n print('Binary Search Opt timing:', round(timeit.timeit(lambda: binary_search_opt_kth_root(n, 3), number = nruns) / nruns, 3), 'sec')\n print('Newton Method timing:', round(timeit.timeit(lambda: newton_kth_root(n, 3), number = nruns) / nruns, 3), 'sec')\n print('Shifting Method timing:', round(timeit.timeit(lambda: shifting_kth_root(n, 3), number = nruns) / nruns, 3), 'sec')\n print('Chord Tangent Method timing:', round(timeit.timeit(lambda: chord_tangent_kth_root(n, 3), number = nruns) / nruns, 3), 'sec')\n\nif __name__ == '__main__':\n test()\n Binary Search iterations: 8192\nBinary Search Opt iterations: 2732\nNewton Method iterations: 9348\nShifting Method iterations: 2752\nChord Tangent Method iterations: 8\n\nBinary Search timing: 0.506 sec\nBinary Search Opt timing: 0.05 sec\nNewton Method timing: 2.09 sec\nShifting Method timing: 0.03 sec\nChord Tangent Method timing: 0.001 sec\n"
}
] | 2008/12/10 | [
"https://Stackoverflow.com/questions/356090",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/44988/"
] |
356,100 | <p>How to wait in a bash script for several subprocesses spawned from that script to finish, and then return exit code <code>!=0</code> when any of the subprocesses ends with code <code>!=0</code>?</p>
<p>Simple script:</p>
<pre><code>#!/bin/bash
for i in `seq 0 9`; do
doCalculations $i &
done
wait
</code></pre>
<p>The above script will wait for all 10 spawned subprocesses, but it will always give exit status <code>0</code> (see <code>help wait</code>). How can I modify this script so it will discover exit statuses of spawned subprocesses and return exit code <code>1</code> when any of subprocesses ends with code <code>!=0</code>?</p>
<p>Is there any better solution for that than collecting PIDs of the subprocesses, wait for them in order and sum exit statuses?</p>
| [
{
"answer_id": 356154,
"author": "Luca Tettamanti",
"author_id": 42448,
"author_profile": "https://Stackoverflow.com/users/42448",
"pm_score": 10,
"selected": true,
"text": "wait PID $! PID PID PID # run processes and store pids in array\nfor i in $n_procs; do\n ./procs[${i}] &\n pids[${i}]=$!\ndone\n\n# wait for all pids\nfor pid in ${pids[*]}; do\n wait $pid\ndone\n"
},
{
"answer_id": 356229,
"author": "Alnitak",
"author_id": 6782,
"author_profile": "https://Stackoverflow.com/users/6782",
"pm_score": 3,
"selected": false,
"text": "#!/bin/sh\nset -o monitor # enable script job control\ntrap 'echo \"child died\"' CHLD\n wait waitpid(-1)"
},
{
"answer_id": 356398,
"author": "Nietzche-jou",
"author_id": 39892,
"author_profile": "https://Stackoverflow.com/users/39892",
"pm_score": -1,
"selected": false,
"text": "doCalculations; echo \"$?\" >>/tmp/acc wait /tmp/acc #!/bin/sh\n\nrandom -e 20\nsleep $?\nrandom -e 10\n #!/bin/sh\n\nrm /tmp/acc\n\nfor i in $( seq 0 20 ) \ndo\n ( ./doCalculations \"$i\"; echo \"$?\" >>/tmp/acc ) &\ndone\n\nwait\n\ncat /tmp/acc | fmt\nrm /tmp/acc\n ./try 5 1 9 6 8 1 2 0 9 6 5 9 6 0 0 4 9 5 5 9 8\n"
},
{
"answer_id": 515170,
"author": "HoverHell",
"author_id": 62821,
"author_profile": "https://Stackoverflow.com/users/62821",
"pm_score": 8,
"selected": false,
"text": "#!/bin/bash\n\nFAIL=0\n\necho \"starting\"\n\n./sleeper 2 0 &\n./sleeper 2 1 &\n./sleeper 3 0 &\n./sleeper 2 0 &\n\nfor job in `jobs -p`\ndo\necho $job\n wait $job || let \"FAIL+=1\"\ndone\n\necho $FAIL\n\nif [ \"$FAIL\" == \"0\" ];\nthen\necho \"YAY!\"\nelse\necho \"FAIL! ($FAIL)\"\nfi\n"
},
{
"answer_id": 1048390,
"author": "Mark Edgar",
"author_id": 129332,
"author_profile": "https://Stackoverflow.com/users/129332",
"pm_score": 5,
"selected": false,
"text": "WAITALL_DELAY waitall() { # PID...\n ## Wait for children to exit and indicate whether all exited with 0 status.\n local errors=0\n while :; do\n debug \"Processes remaining: $*\"\n for pid in \"$@\"; do\n shift\n if kill -0 \"$pid\" 2>/dev/null; then\n debug \"$pid is still alive.\"\n set -- \"$@\" \"$pid\"\n elif wait \"$pid\"; then\n debug \"$pid exited with zero exit status.\"\n else\n debug \"$pid exited with non-zero exit status.\"\n ((++errors))\n fi\n done\n ((\"$#\" > 0)) || break\n # TODO: how to interrupt this sleep when a child terminates?\n sleep ${WAITALL_DELAY:-1}\n done\n ((errors == 0))\n}\n\ndebug() { echo \"DEBUG: $*\" >&2; }\n\npids=\"\"\nfor t in 3 5 4; do \n sleep \"$t\" &\n pids=\"$pids $!\"\ndone\nwaitall $pids\n"
},
{
"answer_id": 7639942,
"author": "errr",
"author_id": 977327,
"author_profile": "https://Stackoverflow.com/users/977327",
"pm_score": 3,
"selected": false,
"text": "#!/bin/bash\nfor i in $(seq 0 9); do\n (doCalculations $i >&2 & wait %1; echo $?) &\ndone | grep -qv 0 && exit 1\n"
},
{
"answer_id": 9311102,
"author": "Ole Tange",
"author_id": 452012,
"author_profile": "https://Stackoverflow.com/users/452012",
"pm_score": 6,
"selected": false,
"text": "# If doCalculations is a function\nexport -f doCalculations\nseq 0 9 | parallel doCalculations {}\n"
},
{
"answer_id": 9786094,
"author": "estani",
"author_id": 1182464,
"author_profile": "https://Stackoverflow.com/users/1182464",
"pm_score": 3,
"selected": false,
"text": "#!/bin/bash\ntmp=/tmp/results\n\n: > $tmp #clean the file\n\nfor i in `seq 0 9`; do\n (doCalculations $i; echo $i:$?>>$tmp)&\ndone #iterate\n\nwait #wait until all ready\n\nsort $tmp | grep -v ':0' #... handle as required\n"
},
{
"answer_id": 17079664,
"author": "Brent Bradburn",
"author_id": 86967,
"author_profile": "https://Stackoverflow.com/users/86967",
"pm_score": 5,
"selected": false,
"text": "for i in $(whatever_list) ; do\n do_something $i\ndone\n for i in $(whatever_list) ; do echo $i ; done | ## execute in parallel...\n (\n export -f do_something ## export functions (if needed)\n export PATH ## export any variables that are required\n xargs -I{} --max-procs 0 bash -c ' ## process in batches...\n {\n echo \"processing {}\" ## optional\n do_something {}\n }' \n )\n --max-procs 0 xargs for echo $i $(whatever_list for for i in {0..5} ; do echo $i ; done |xargs -I{} --max-procs 2 bash -c '\n {\n echo sleep {}\n sleep 2s\n }'\n"
},
{
"answer_id": 18666536,
"author": "stefanct",
"author_id": 1905491,
"author_profile": "https://Stackoverflow.com/users/1905491",
"pm_score": 3,
"selected": false,
"text": "#! /bin/bash\n\nmain () {\n local -A pids=()\n local -A tasks=([task1]=\"echo 1\"\n [task2]=\"echo 2\"\n [task3]=\"echo 3\"\n [task4]=\"false\"\n [task5]=\"echo 5\"\n [task6]=\"false\")\n local max_concurrent_tasks=2\n\n for key in \"${!tasks[@]}\"; do\n while [ $(jobs 2>&1 | grep -c Running) -ge \"$max_concurrent_tasks\" ]; do\n sleep 1 # gnu sleep allows floating point here...\n done\n ${tasks[$key]} &\n pids+=([\"$key\"]=\"$!\")\n done\n\n errors=0\n for key in \"${!tasks[@]}\"; do\n pid=${pids[$key]}\n local cur_ret=0\n if [ -z \"$pid\" ]; then\n echo \"No Job ID known for the $key process\" # should never happen\n cur_ret=1\n else\n wait $pid\n cur_ret=$?\n fi\n if [ \"$cur_ret\" -ne 0 ]; then\n errors=$(($errors + 1))\n echo \"$key (${tasks[$key]}) failed.\"\n fi\n done\n\n return $errors\n}\n\nmain\n"
},
{
"answer_id": 19024802,
"author": "Lloeki",
"author_id": 368409,
"author_profile": "https://Stackoverflow.com/users/368409",
"pm_score": 1,
"selected": false,
"text": "#!/bin/bash\n# activate child monitoring\nset -o monitor\n\n# locking subprocess\n(while true; do sleep 0.001; done) &\npid=$!\n\n# count, and kill when all done\nc=0\nfunction kill_on_count() {\n # you could kill on whatever criterion you wish for\n # I just counted to simulate bash's wait with no args\n [ $c -eq 9 ] && kill $pid\n c=$((c+1))\n echo -n '.' # async feedback (but you don't know which one)\n}\ntrap \"kill_on_count\" CHLD\n\nfunction save_status() {\n local i=$1;\n local rc=$2;\n # do whatever, and here you know which one stopped\n # but remember, you're called from a subshell\n # so vars have their values at fork time\n}\n\n# care must be taken not to spawn more than one child per loop\n# e.g don't use `seq 0 9` here!\nfor i in {0..9}; do\n (doCalculations $i; save_status $i $?) &\ndone\n\n# wait for locking subprocess to be killed\nwait $pid\necho\n"
},
{
"answer_id": 19788022,
"author": "troelskn",
"author_id": 18180,
"author_profile": "https://Stackoverflow.com/users/18180",
"pm_score": 2,
"selected": false,
"text": "wait $PID while [ -e /proc/$PID ]; do sleep 0.1 ; done\n while ps -p $PID >/dev/null ; do sleep 0.1 ; done\n"
},
{
"answer_id": 21034504,
"author": "Jayen",
"author_id": 192798,
"author_profile": "https://Stackoverflow.com/users/192798",
"pm_score": 3,
"selected": false,
"text": "#!/bin/bash\nset -m\nfor i in `seq 0 9`; do\n doCalculations $i &\ndone\nwhile fg; do true; done\n set -m fg while fg fg"
},
{
"answer_id": 21750255,
"author": "michaelt",
"author_id": 901643,
"author_profile": "https://Stackoverflow.com/users/901643",
"pm_score": 3,
"selected": false,
"text": "checkpids #!/bin/bash\n\nset -o monitor\n\nsleep 2 &\nsleep 4 && exit 1 &\nsleep 6 &\n\npids=`jobs -p`\n\ncheckpids() {\n for pid in $pids; do\n if kill -0 $pid 2>/dev/null; then\n echo $pid is still alive.\n elif wait $pid; then\n echo $pid exited with zero exit status.\n else\n echo $pid exited with non-zero exit status.\n fi\n done\n echo\n}\n\ntrap checkpids CHLD\n\nwait\n"
},
{
"answer_id": 26240420,
"author": "patapouf_ai",
"author_id": 3990607,
"author_profile": "https://Stackoverflow.com/users/3990607",
"pm_score": 6,
"selected": false,
"text": "#!/bin/bash\n\npids=\"\"\n\nfor i in `seq 0 9`; do\n doCalculations $i &\n pids=\"$pids $!\"\ndone\n\nwait $pids\n\n...code continued here ...\n #!/bin/bash\n\npids=\"\"\nRESULT=0\n\n\nfor i in `seq 0 9`; do\n doCalculations $i &\n pids=\"$pids $!\"\ndone\n\nfor pid in $pids; do\n wait $pid || let \"RESULT=1\"\ndone\n\nif [ \"$RESULT\" == \"1\" ];\n then\n exit 1\nfi\n\n...code continued here ...\n"
},
{
"answer_id": 27272418,
"author": "Tosh",
"author_id": 4320122,
"author_profile": "https://Stackoverflow.com/users/4320122",
"pm_score": 2,
"selected": false,
"text": "$ sleep 20 && exit 1 &\n$ sleep 10 && exit 2 &\n$ wait\n[1]- Exit 2 sleep 20 && exit 2\n[2]+ Exit 1 sleep 10 && exit 1\n $ sleep 20 && exit 1 &\n$ sleep 10 && exit 2 &\n$ wait\n[1]+ Done(2) sleep 20 && exit 2\n[2]+ Done(1) sleep 10 && exit 1\n #!/bin/bash\n\ntrap \"rm -f /tmp/x.$$\" EXIT\n\nfor i in `seq 0 9`; do\n doCalculations $i &\ndone\n\nwait 2> /tmp/x.$$\nif [ `wc -l /tmp/x.$$` -gt 0 ] ; then\n exit 1\nfi\n wait 2> >(wc -l)\n wait 2> >(if [ `wc -l` -gt 0 ] ; then echo \"ERROR\"; fi)\n"
},
{
"answer_id": 31044460,
"author": "mug896",
"author_id": 1330706,
"author_profile": "https://Stackoverflow.com/users/1330706",
"pm_score": 1,
"selected": false,
"text": "#!/bin/bash\n\ntrap 'rm -f $tmpfile' EXIT\n\ntmpfile=$(mktemp)\n\ndoCalculations() {\n echo start job $i...\n sleep $((RANDOM % 5)) \n echo ...end job $i\n exit $((RANDOM % 10))\n}\n\nnumber_of_jobs=10\n\nfor i in $( seq 1 $number_of_jobs )\ndo\n ( trap \"echo job$i : exit value : \\$? >> $tmpfile\" EXIT; doCalculations ) &\ndone\n\nwait \n\ni=0\nwhile read res; do\n echo \"$res\"\n let i++\ndone < \"$tmpfile\"\n\necho $i jobs done !!!\n"
},
{
"answer_id": 35613617,
"author": "Jason Slobotski",
"author_id": 5665753,
"author_profile": "https://Stackoverflow.com/users/5665753",
"pm_score": 3,
"selected": false,
"text": "#! /bin/bash\n\nitems=\"1 2 3 4 5 6\"\npids=\"\"\n\nfor item in $items; do\n sleep $item &\n pids+=\"$! \"\ndone\n\nfor pid in $pids; do\n wait $pid\n if [ $? -eq 0 ]; then\n echo \"SUCCESS - Job $pid exited with a status of $?\"\n else\n echo \"FAILED - Job $pid exited with a status of $?\"\n fi\ndone\n"
},
{
"answer_id": 36038185,
"author": "kenorb",
"author_id": 55075,
"author_profile": "https://Stackoverflow.com/users/55075",
"pm_score": 7,
"selected": false,
"text": "wait $ sleep 10 &\n$ sleep 10 &\n$ sleep 20 &\n$ sleep 20 &\n wait $ wait < <(jobs -p)\n wait -n help wait help jobs $ sleep 20 && true || tee fail &\n$ sleep 20 && false || tee fail &\n$ wait < <(jobs -p)\n$ test -f fail && echo Calculation failed.\n"
},
{
"answer_id": 38017902,
"author": "Yajo",
"author_id": 1468388,
"author_profile": "https://Stackoverflow.com/users/1468388",
"pm_score": 2,
"selected": false,
"text": "set -e\nfail () {\n touch .failure\n}\nexpect () {\n wait\n if [ -f .failure ]; then\n rm -f .failure\n exit 1\n fi\n}\n\nsleep 2 || fail &\nsleep 2 && false || fail &\nsleep 2 || fail\nexpect\n set -e expect 1"
},
{
"answer_id": 38755268,
"author": "Orsiris de Jong",
"author_id": 2635443,
"author_profile": "https://Stackoverflow.com/users/2635443",
"pm_score": 3,
"selected": false,
"text": "function WaitForTaskCompletion {\n local pids=\"${1}\" # pids to wait for, separated by semi-colon\n local soft_max_time=\"${2}\" # If execution takes longer than $soft_max_time seconds, will log a warning, unless $soft_max_time equals 0.\n local hard_max_time=\"${3}\" # If execution takes longer than $hard_max_time seconds, will stop execution, unless $hard_max_time equals 0.\n local caller_name=\"${4}\" # Who called this function\n local exit_on_error=\"${5:-false}\" # Should the function exit program on subprocess errors \n\n Logger \"${FUNCNAME[0]} called by [$caller_name].\"\n\n local soft_alert=0 # Does a soft alert need to be triggered, if yes, send an alert once \n local log_ttime=0 # local time instance for comparaison\n\n local seconds_begin=$SECONDS # Seconds since the beginning of the script\n local exec_time=0 # Seconds since the beginning of this function\n\n local retval=0 # return value of monitored pid process\n local errorcount=0 # Number of pids that finished with errors\n\n local pidCount # number of given pids\n\n IFS=';' read -a pidsArray <<< \"$pids\"\n pidCount=${#pidsArray[@]}\n\n while [ ${#pidsArray[@]} -gt 0 ]; do\n newPidsArray=()\n for pid in \"${pidsArray[@]}\"; do\n if kill -0 $pid > /dev/null 2>&1; then\n newPidsArray+=($pid)\n else\n wait $pid\n result=$?\n if [ $result -ne 0 ]; then\n errorcount=$((errorcount+1))\n Logger \"${FUNCNAME[0]} called by [$caller_name] finished monitoring [$pid] with exitcode [$result].\"\n fi\n fi\n done\n\n ## Log a standby message every hour\n exec_time=$(($SECONDS - $seconds_begin))\n if [ $((($exec_time + 1) % 3600)) -eq 0 ]; then\n if [ $log_ttime -ne $exec_time ]; then\n log_ttime=$exec_time\n Logger \"Current tasks still running with pids [${pidsArray[@]}].\"\n fi\n fi\n\n if [ $exec_time -gt $soft_max_time ]; then\n if [ $soft_alert -eq 0 ] && [ $soft_max_time -ne 0 ]; then\n Logger \"Max soft execution time exceeded for task [$caller_name] with pids [${pidsArray[@]}].\"\n soft_alert=1\n SendAlert\n\n fi\n if [ $exec_time -gt $hard_max_time ] && [ $hard_max_time -ne 0 ]; then\n Logger \"Max hard execution time exceeded for task [$caller_name] with pids [${pidsArray[@]}]. Stopping task execution.\"\n kill -SIGTERM $pid\n if [ $? == 0 ]; then\n Logger \"Task stopped successfully\"\n else\n errrorcount=$((errorcount+1))\n fi\n fi\n fi\n\n pidsArray=(\"${newPidsArray[@]}\")\n sleep 1\n done\n\n Logger \"${FUNCNAME[0]} ended for [$caller_name] using [$pidCount] subprocesses with [$errorcount] errors.\"\n if [ $exit_on_error == true ] && [ $errorcount -gt 0 ]; then\n Logger \"Stopping execution.\"\n exit 1337\n else\n return $errorcount\n fi\n}\n\n# Just a plain stupid logging function to be replaced by yours\nfunction Logger {\n local value=\"${1}\"\n\n echo $value\n}\n function something {\n\n sleep 10 &\n pids=\"$!\"\n sleep 12 &\n pids=\"$pids;$!\"\n sleep 9 &\n pids=\"$pids;$!\"\n\n WaitForTaskCompletion $pids 5 120 ${FUNCNAME[0]} false\n}\n# Launch the function\nsometing\n \n"
},
{
"answer_id": 40310072,
"author": "FreelanceConsultant",
"author_id": 893254,
"author_profile": "https://Stackoverflow.com/users/893254",
"pm_score": 2,
"selected": false,
"text": "n=10 # run 10 jobs\nc=0\nPIDS=()\n\nwhile true\n\n my_function_or_command &\n PID=$!\n echo \"Launched job as PID=$PID\"\n PIDS+=($PID)\n\n (( c+=1 ))\n\n # required to prevent any exit due to error\n # caused by additional commands run which you\n # may add when modifying this example\n true\n\ndo\n\n if (( c < n ))\n then\n continue\n else\n break\n fi\ndone \n\n\n# collect launched jobs\n\nfor pid in \"${PIDS[@]}\"\ndo\n wait $pid || echo \"failed job PID=$pid\"\ndone\n"
},
{
"answer_id": 42202064,
"author": "Alexander Mills",
"author_id": 1223975,
"author_profile": "https://Stackoverflow.com/users/1223975",
"pm_score": 2,
"selected": false,
"text": "#!/usr/bin/env bash\n\nset -m # allow for job control\nEXIT_CODE=0; # exit code of overall script\n\nfunction foo() {\n echo \"CHLD exit code is $1\"\n echo \"CHLD pid is $2\"\n echo $(jobs -l)\n\n for job in `jobs -p`; do\n echo \"PID => ${job}\"\n wait ${job} || echo \"At least one test failed with exit code => $?\" ; EXIT_CODE=1\n done\n}\n\ntrap 'foo $? $$' CHLD\n\nDIRN=$(dirname \"$0\");\n\ncommands=(\n \"{ echo \"foo\" && exit 4; }\"\n \"{ echo \"bar\" && exit 3; }\"\n \"{ echo \"baz\" && exit 5; }\"\n)\n\nclen=`expr \"${#commands[@]}\" - 1` # get length of commands - 1\n\nfor i in `seq 0 \"$clen\"`; do\n (echo \"${commands[$i]}\" | bash) & # run the command via bash in subshell\n echo \"$i ith command has been issued as a background job\"\ndone\n\n# wait for all to finish\nwait;\n\necho \"EXIT_CODE => $EXIT_CODE\"\nexit \"$EXIT_CODE\"\n\n# end\n"
},
{
"answer_id": 51760074,
"author": "Anju Prasannan",
"author_id": 4261208,
"author_profile": "https://Stackoverflow.com/users/4261208",
"pm_score": 2,
"selected": false,
"text": "isProcessComplete(){\nPID=$1\nwhile [ -e /proc/$PID ]\ndo\n echo \"Process: $PID is still running\"\n sleep 5\ndone\necho \"Process $PID has finished\"\n}\n"
},
{
"answer_id": 51869066,
"author": "Mark",
"author_id": 2203038,
"author_profile": "https://Stackoverflow.com/users/2203038",
"pm_score": 0,
"selected": false,
"text": "#!/bin/bash\nrm -f fail\nfor i in `seq 0 9`; do\n doCalculations $i || touch fail &\ndone\nwait \n! [ -f fail ]\n #!/bin/bash\ntrap 'rm -f fail.$$' EXIT\nfor i in `seq 0 9`; do\n doCalculations $i || touch fail.$$ &\ndone\nwait \n! [ -f fail.$$ ] \n #!/bin/bash\ntrap 'rm -fr $WORK' EXIT\n\nWORK=/tmp/$$.work\nmkdir -p $WORK\ncd $WORK\n\nfor i in `seq 0 9`; do\n doCalculations $i >$i.result &\ndone\nwait \ngrep $ * # display the results with filenames and contents\n"
},
{
"answer_id": 52608642,
"author": "vishnuitta",
"author_id": 3898515,
"author_profile": "https://Stackoverflow.com/users/3898515",
"pm_score": 1,
"selected": false,
"text": "#!/bin/bash\nwait_for_pids()\n{\n for (( i = 1; i <= $#; i++ )) do\n wait -n $@\n status=$?\n echo \"received status: \"$status\n if [ $status -ne 0 ] && [ $status -ne 127 ]; then\n exit 1\n fi\n done\n}\n\nsleep_for_10()\n{\n sleep 10\n exit 10\n}\n\nsleep_for_20()\n{\n sleep 20\n}\n\nsleep_for_10 &\npid1=$!\n\nsleep_for_20 &\npid2=$!\n\nwait_for_pids $pid2 $pid1\n"
},
{
"answer_id": 55972098,
"author": "jplozier",
"author_id": 9732482,
"author_profile": "https://Stackoverflow.com/users/9732482",
"pm_score": 4,
"selected": false,
"text": "#wait for jobs\nfor job in `jobs -p`; do wait ${job}; done\n"
},
{
"answer_id": 57753054,
"author": "Ente",
"author_id": 3215929,
"author_profile": "https://Stackoverflow.com/users/3215929",
"pm_score": 2,
"selected": false,
"text": "bash :for :for #!/usr/bin/env bash\n\n# Wait for pids to terminate. If one pid exits with\n# a non zero exit code, send the TERM signal to all\n# processes and retain that exit code\n#\n# usage:\n# :wait 123 32\nfunction :wait(){\n local pids=(\"$@\")\n [ ${#pids} -eq 0 ] && return $?\n\n trap 'kill -INT \"${pids[@]}\" &>/dev/null || true; trap - INT' INT\n trap 'kill -TERM \"${pids[@]}\" &>/dev/null || true; trap - RETURN TERM' RETURN TERM\n\n for pid in \"${pids[@]}\"; do\n wait \"${pid}\" || return $?\n done\n\n trap - INT RETURN TERM\n}\n\n# Run a function in parallel for each argument.\n# Stop all instances if one exits with a non zero\n# exit code\n#\n# usage:\n# :for func 1 2 3\n#\n# env:\n# FOR_PARALLEL: Max functions running in parallel\nfunction :for(){\n local f=\"${1}\" && shift\n\n local i=0\n local pids=()\n for arg in \"$@\"; do\n ( ${f} \"${arg}\" ) &\n pids+=(\"$!\")\n if [ ! -z ${FOR_PARALLEL+x} ]; then\n (( i=(i+1)%${FOR_PARALLEL} ))\n if (( i==0 )) ;then\n :wait \"${pids[@]}\" || return $?\n pids=()\n fi\n fi\n done && [ ${#pids} -eq 0 ] || :wait \"${pids[@]}\" || return $?\n}\n for.sh #!/usr/bin/env bash\nset -e\n\n# import :for from gist: https://gist.github.com/Enteee/c8c11d46a95568be4d331ba58a702b62#file-for\n# if you don't like curl imports, source the actual file here.\nsource <(curl -Ls https://gist.githubusercontent.com/Enteee/c8c11d46a95568be4d331ba58a702b62/raw/)\n\nmsg=\"You should see this three times\"\n\n:(){\n i=\"${1}\" && shift\n\n echo \"${msg}\"\n\n sleep 1\n if [ \"$i\" == \"1\" ]; then sleep 1\n elif [ \"$i\" == \"2\" ]; then false\n elif [ \"$i\" == \"3\" ]; then\n sleep 3\n echo \"You should never see this\"\n fi\n} && :for : 1 2 3 || exit $?\n\necho \"You should never see this\"\n $ ./for.sh; echo $?\nYou should see this three times\nYou should see this three times\nYou should see this three times\n1\n"
},
{
"answer_id": 59723887,
"author": "Erik Aronesty",
"author_id": 627042,
"author_profile": "https://Stackoverflow.com/users/627042",
"pm_score": 3,
"selected": false,
"text": "function wait_ex {\n # this waits for all jobs and returns the exit code of the last failing job\n ecode=0\n while true; do\n [ -z \"$(jobs)\" ] && break\n wait -n\n err=\"$?\"\n [ \"$err\" != \"0\" ] && ecode=\"$err\"\n done\n return $ecode\n}\n"
},
{
"answer_id": 61372369,
"author": "Daniel C. Sobral",
"author_id": 53013,
"author_profile": "https://Stackoverflow.com/users/53013",
"pm_score": 1,
"selected": false,
"text": "jobs -p wait -n #!/usr/bin/env bash\n\nsleeper() {\n echo \"Sleeper $1\"\n sleep $2\n echo \"Exiting $1\"\n return $3\n}\n\nstart_sleepers() {\n sleeper 1 1 0 &\n sleeper 2 2 $1 &\n sleeper 3 5 0 &\n sleeper 4 6 0 &\n sleep 4\n}\n\necho \"Using jobs\"\nstart_sleepers 1\n\npids=( $(jobs -p) )\n\necho \"PIDS: ${pids[*]}\"\n\nfor pid in \"${pids[@]}\"; do\n wait \"$pid\"\n echo \"Exit code $?\"\ndone\n\necho \"Clearing other children\"\nwait -n; echo \"Exit code $?\"\nwait -n; echo \"Exit code $?\"\n\necho \"Waiting for N processes\"\nstart_sleepers 2\n\nfor ignored in $(seq 1 4); do\n wait -n\n echo \"Exit code $?\"\ndone\n Using jobs\nSleeper 1\nSleeper 2\nSleeper 3\nSleeper 4\nExiting 1\nExiting 2\nPIDS: 56496 56497\nExiting 3\nExit code 0\nExiting 4\nExit code 0\nClearing other children\nExit code 0\nExit code 1\nWaiting for N processes\nSleeper 1\nSleeper 2\nSleeper 3\nSleeper 4\nExiting 1\nExiting 2\nExit code 0\nExit code 2\nExiting 3\nExit code 0\nExiting 4\nExit code 0\n"
},
{
"answer_id": 67826557,
"author": "Mark",
"author_id": 2111124,
"author_profile": "https://Stackoverflow.com/users/2111124",
"pm_score": 0,
"selected": false,
"text": "#!/bin/bash\necho > tmpscript.sh\nfor i in `seq 0 9`; do\n echo \"doCalculations $i &\" >> tmpscript.sh\ndone\necho \"wait\" >> tmpscript.sh\nchmod u+x tmpscript.sh\n./tmpscript.sh\n"
},
{
"answer_id": 69786242,
"author": "Fonic",
"author_id": 1976617,
"author_profile": "https://Stackoverflow.com/users/1976617",
"pm_score": 2,
"selected": false,
"text": "wait -p #!/usr/bin/env bash\n\n# Spawn background jobs\nfor ((i=0; i < 10; i++)); do\n secs=$((RANDOM % 10)); code=$((RANDOM % 256))\n (sleep ${secs}; exit ${code}) &\n echo \"Started background job (pid: $!, sleep: ${secs}, code: ${code})\"\ndone\n\n# Wait for background jobs, print individual results, determine overall result\nresult=0\nwhile true; do\n wait -n -p pid; code=$?\n [[ -z \"${pid}\" ]] && break\n echo \"Background job ${pid} finished with code ${code}\"\n (( ${code} != 0 )) && result=1\ndone\n\n# Return overall result\nexit ${result}\n"
},
{
"answer_id": 70670852,
"author": "Gabriel Staples",
"author_id": 4561887,
"author_profile": "https://Stackoverflow.com/users/4561887",
"pm_score": 3,
"selected": false,
"text": "n_procs procs $! & cmd & myarray=() wait help wait wait jobs #!/usr/bin/env bash\n\n\n# This is a special sleep function which returns the number of seconds slept as\n# the \"error code\" or return code\" so that we can easily see that we are in\n# fact actually obtaining the return code of each process as it finishes.\nmy_sleep() {\n seconds_to_sleep=\"$1\"\n sleep \"$seconds_to_sleep\"\n return \"$seconds_to_sleep\"\n}\n\n# Create an array of whatever commands you want to run as subprocesses\nprocs=() # bash array\nprocs+=(\"my_sleep 5\")\nprocs+=(\"my_sleep 2\")\nprocs+=(\"my_sleep 3\")\nprocs+=(\"my_sleep 4\")\n\nnum_procs=${#procs[@]} # number of processes\necho \"num_procs = $num_procs\"\n\n# run commands as subprocesses and store pids in an array\npids=() # bash array\nfor (( i=0; i<\"$num_procs\"; i++ )); do\n echo \"cmd = ${procs[$i]}\"\n ${procs[$i]} & # run the cmd as a subprocess\n # store pid of last subprocess started; see:\n # https://unix.stackexchange.com/a/30371/114401\n pids+=(\"$!\")\n echo \" pid = ${pids[$i]}\"\ndone\n\n# OPTION 1 (comment this option out if using Option 2 below): wait for all pids\nfor pid in \"${pids[@]}\"; do\n wait \"$pid\"\n return_code=\"$?\"\n echo \"PID = $pid; return_code = $return_code\"\ndone\necho \"All $num_procs processes have ended.\"\n chmod +x multi_process_program.sh time ./multi_process_program.sh \n time eRCaGuy_hello_world/bash$ time ./multi_process_program.sh \nnum_procs = 4\ncmd = my_sleep 5\n pid = 21694\ncmd = my_sleep 2\n pid = 21695\ncmd = my_sleep 3\n pid = 21697\ncmd = my_sleep 4\n pid = 21699\nPID = 21694; return_code = 5\nPID = 21695; return_code = 2\nPID = 21697; return_code = 3\nPID = 21699; return_code = 4\nAll 4 processes have ended.\nPID 21694 is done; return_code = 5; 3 PIDs remaining.\nPID 21695 is done; return_code = 2; 2 PIDs remaining.\nPID 21697 is done; return_code = 3; 1 PIDs remaining.\nPID 21699 is done; return_code = 4; 0 PIDs remaining.\n\nreal 0m5.084s\nuser 0m0.025s\nsys 0m0.061s\n while # OR OPTION 2 (comment out Option 1 above if using Option 2): poll to detect\n# when each process terminates, and print out when each process finishes!\nwhile true; do\n for i in \"${!pids[@]}\"; do\n pid=\"${pids[$i]}\"\n # echo \"pid = $pid\" # debugging\n\n # See if PID is still running; see my answer here:\n # https://stackoverflow.com/a/71134379/4561887\n ps --pid \"$pid\" > /dev/null\n if [ \"$?\" -ne 0 ]; then\n # PID doesn't exist anymore, meaning it terminated\n\n # 1st, read its return code\n wait \"$pid\"\n return_code=\"$?\"\n\n # 2nd, remove this PID from the `pids` array by `unset`ting the\n # element at this index; NB: due to how bash arrays work, this does\n # NOT actually remove this element from the array. Rather, it\n # removes its index from the `\"${!pids[@]}\"` list of indices,\n # adjusts the array count(`\"${#pids[@]}\"`) accordingly, and it sets\n # the value at this index to either a null value of some sort, or\n # an empty string (I'm not exactly sure).\n unset \"pids[$i]\"\n\n num_pids=\"${#pids[@]}\"\n echo \"PID $pid is done; return_code = $return_code;\" \\\n \"$num_pids PIDs remaining.\"\n fi\n done\n\n # exit the while loop if the `pids` array is empty\n if [ \"${#pids[@]}\" -eq 0 ]; then\n break\n fi\n\n # Do some small sleep here to keep your polling loop from sucking up\n # 100% of one of your CPUs unnecessarily. Sleeping allows other processes\n # to run during this time.\n sleep 0.1\ndone\n eRCaGuy_hello_world/bash$ ./multi_process_program.sh \nnum_procs = 4\ncmd = my_sleep 5\n pid = 22275\ncmd = my_sleep 2\n pid = 22276\ncmd = my_sleep 3\n pid = 22277\ncmd = my_sleep 4\n pid = 22280\nPID 22276 is done; return_code = 2; 3 PIDs remaining.\nPID 22277 is done; return_code = 3; 2 PIDs remaining.\nPID 22280 is done; return_code = 4; 1 PIDs remaining.\nPID 22275 is done; return_code = 5; 0 PIDs remaining.\n PID XXXXX is done sleep 5 22275 wait <n> wait true"
}
] | 2008/12/10 | [
"https://Stackoverflow.com/questions/356100",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/42201/"
] |
356,121 | <p>I want to refactor this mumbo jumbo of a method to make it more readible, it has way to many nested IF's for my liking.</p>
<p>How would you refactor this?</p>
<pre><code>public static void HandleUploadedFile(string filename)
{
try
{
if(IsValidFileFormat(filename)
{
int folderID = GetFolderIDFromFilename(filename);
if(folderID > 0)
{
if(HasNoViruses(filename)
{
if(VerifyFileSize(filename)
{
// file is OK
MoveToSafeFolder(filename);
}
else
{
DeleteFile(filename);
LogError("file size invalid");
}
}
else
{
DeleteFile(filename);
LogError("failed virus test");
}
}
else
{
DeleteFile(filename);
LogError("invalid folder ID");
}
}
else
{
DeleteFile(filename);
LogError("invalid file format");
}
}
catch (Exception ex)
{
LogError("unknown error", ex.Message);
}
finally
{
// do some things
}
}
</code></pre>
| [
{
"answer_id": 356148,
"author": "David Waters",
"author_id": 12148,
"author_profile": "https://Stackoverflow.com/users/12148",
"pm_score": 6,
"selected": true,
"text": "try{\n if(IsValidFileFormat(filename) == false){\n DeleteFile(filename);\n LogError(\"invalid file format\");\n return;\n }\n\n int folderID = GetFolderIDFromFilename(filename);\n if(folderID <= 0){\n DeleteFile(filename);\n LogError(\"invalid folder ID\");\n return;\n }\n ...\n\n}...\n"
},
{
"answer_id": 356159,
"author": "jamesh",
"author_id": 4737,
"author_profile": "https://Stackoverflow.com/users/4737",
"pm_score": 3,
"selected": false,
"text": "if(IsValidFileFormat(filename)\n{\n // then\n}\nelse\n{\n // else\n}\n if(!IsValidFileFormat(filename)\n{\n // else \n return; \n}\n// then\n"
},
{
"answer_id": 356209,
"author": "Tomalak",
"author_id": 18771,
"author_profile": "https://Stackoverflow.com/users/18771",
"pm_score": 2,
"selected": false,
"text": "public static void HandleUploadedFile(string filename)\n{\n try\n {\n int folderID = GetFolderIDFromFilename(filename);\n\n if (folderID == 0)\n throw new InvalidFolderException(\"invalid folder ID\");\n\n if (!IsValidFileFormat(filename))\n throw new InvalidFileException(\"invalid file format!\");\n\n if (!HasNoViruses(filename))\n throw new VirusFoundException(\"failed virus test!\");\n\n if (!VerifyFileSize(filename))\n throw new InvalidFileSizeException(\"file size invalid\");\n\n // file is OK\n MoveToSafeFolder(filename);\n }\n catch (Exception ex)\n {\n DeleteFile(filename);\n LogError(ex.message);\n }\n finally\n {\n // do some things\n }\n}\n"
},
{
"answer_id": 356222,
"author": "Binary Worrier",
"author_id": 18797,
"author_profile": "https://Stackoverflow.com/users/18797",
"pm_score": 0,
"selected": false,
"text": " string errorMessage = \"invalid file format\";\n if (IsValidFileFormat(filename))\n {\n errorMessage = \"invalid folder ID\";\n int folderID = GetFolderIDFromFilename(filename);\n if (folderID > 0)\n {\n errorMessage = \"failed virus test\";\n if (HasNoViruses(filename))\n {\n errorMessage = \"file size invalid\";\n if (VerifyFileSize(filename))\n {\n // file is OK \n MoveToSafeFolder(filename);\n errorMessage = \"\";\n }\n }\n }\n }\n if (!string.IsNullOrEmpty(errorMessage))\n {\n DeleteFile(filename);\n LogError(errorMessage);\n }\n"
},
{
"answer_id": 356338,
"author": "Stefan",
"author_id": 19307,
"author_profile": "https://Stackoverflow.com/users/19307",
"pm_score": 0,
"selected": false,
"text": "public enum FileStates {\n\nMoveToSafeFolder = 1,\n\nInvalidFileSize = 2,\n\nFailedVirusTest = 3,\n\nInvalidFolderID = 4,\n\nInvalidFileFormat = 5,\n}\n\n\npublic static void HandleUploadedFile(string filename) {\n try {\n switch (Handledoc(filename)) {\n case FileStates.FailedVirusTest:\n deletefile(filename);\n logerror(\"Virus\");\n break;\n case FileStates.InvalidFileFormat:\n deletefile(filename);\n logerror(\"Invalid File format\");\n break;\n case FileStates.InvalidFileSize:\n deletefile(filename);\n logerror(\"Invalid File Size\");\n break;\n case FileStates.InvalidFolderID:\n deletefile(filename);\n logerror(\"Invalid Folder ID\");\n break;\n case FileStates.MoveToSafeFolder:\n MoveToSafeFolder(filename);\n break;\n }\n }\n catch (Exception ex) {\n logerror(\"unknown error\", ex.Message);\n }\n}\n\nprivate static FileStates Handledoc(string filename) {\n if (isvalidfileformat(filename)) {\n return FileStates.InvalidFileFormat;\n }\n if ((getfolderidfromfilename(filename) <= 0)) {\n return FileStates.InvalidFolderID;\n }\n if ((HasNoViruses(filename) == false)) {\n return FileStates.FailedVirusTest;\n }\n if ((VerifyFileSize(filename) == false)) {\n return FileStates.InvalidFileSize;\n }\n return FileStates.MoveToSafeFolder;\n}\n"
},
{
"answer_id": 356341,
"author": "plinth",
"author_id": 20481,
"author_profile": "https://Stackoverflow.com/users/20481",
"pm_score": 1,
"selected": false,
"text": "public static void HandleUploadedFile(string filename)\n{\n try\n {\n string errorMessage = TestForInvalidFile(filename);\n if (errorMessage != null)\n {\n LogError(errorMessage);\n DeleteFile(filename);\n }\n else\n {\n MoveToSafeFolder(filename);\n }\n }\n catch (Exception err)\n {\n LogError(err.Message);\n DeleteFile(filename);\n }\n finally { /* */ }\n}\n\nprivate static string TestForInvalidFile(filename)\n{\n if (!IsValidFormat(filename))\n return \"invalid file format.\";\n if (!IsValidFolder(filename))\n return \"invalid folder.\";\n if (!IsVirusFree(filename))\n return \"has viruses\";\n if (!IsValidSize(filename))\n return \"invalid size.\";\n // ... etc ...\n return null;\n }\n"
},
{
"answer_id": 356508,
"author": "Charles Bretana",
"author_id": 32632,
"author_profile": "https://Stackoverflow.com/users/32632",
"pm_score": 0,
"selected": false,
"text": "public static void HandleUploadedFile(string filename)\n{ \n try \n { \n if(!IsValidFileFormat(filename)) \n { DeleteAndLog(filename, \"invalid file format\"); return; }\n if(GetFolderIDFromFilename(filename)==0) \n { DeleteAndLog(filename, \"invalid folder ID\"); return; }\n if(!HasNoViruses(filename)) \n { DeleteAndLog(filename, \"failed virus test\"); return; }\n if(!!VerifyFileSize(filename)) \n { DeleteAndLog(filename, \"file size invalid\"); return; }\n // --------------------------------------------------------\n MoveToSafeFolder(filename); \n }\n catch (Exception ex) { LogError(\"unknown error\", ex.Message); throw; }\n finally { // do some things }\n} \nprivate void DeleteAndLog(string fileName, string logMessage)\n{\n DeleteFile(fileName);\n LogError(logMessage));\n}\n public static void HandleUploadedFile(string filename)\n{ \n try \n { \n if(ValidateUploadedFile(filename)) \n MoveToSafeFolder(filename); \n }\n catch (Exception ex) { LogError(\"unknown error\", ex.Message); throw; }\n finally { // do some things }\n} \nprivate bool ValidateUploadedFile(string fileName)\n{\n if(!IsValidFileFormat(filename)) \n { DeleteAndLog(filename, \"invalid file format\"); return false; }\n if(GetFolderIDFromFilename(filename)==0) \n { DeleteAndLog(filename, \"invalid folder ID\"); return false; }\n if(!HasNoViruses(filename)) \n { DeleteAndLog(filename, \"failed virus test\"); return false; }\n if(!!VerifyFileSize(filename)) \n { DeleteAndLog(filename, \"file size invalid\"); return false; }\n // ---------------------------------------------------------------\n return true;\n\n} \nprivate void DeleteAndLog(string fileName, string logMessage)\n{\n DeleteFile(fileName);\n LogError(logMessage));\n}\n"
}
] | 2008/12/10 | [
"https://Stackoverflow.com/questions/356121",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/39677/"
] |
356,122 | <p>I am writing a .NET library that for various reasons cannot be registered in the GAC.
This dll (let's call it SDK.dll) depends on other DLLs in order to be loaded.</p>
<p>When writing a program that uses this SDK.dll, I noticed that my program failed loading the dll with a FileNotFoundException thrown. This happens because although I was able to find the referenced SDK.dll, the CLR failed to load its dependencies.</p>
<p>The only way I found to solve the problem is to "Copy Local" the SDK.dll and all its dependencies (something I can't do because of deployment problems), or compiling my program into the same directory as SDK.dll</p>
<p>Is there a way to tell SDK.dll where to look for it's dependencies regardless of its location? Maybe a SDK.dll.config file can help?</p>
| [
{
"answer_id": 356466,
"author": "Snooganz",
"author_id": 28224,
"author_profile": "https://Stackoverflow.com/users/28224",
"pm_score": 4,
"selected": true,
"text": "AppDomain.CurrentDomain.AssemblyResolve\n public SDKClass()\n{\n AppDomain.CurrentDomain.AssemblyResolve += new ResolveEventHandler(FindAssembly);\n}\n\nprivate Assembly FindAssembly(object sender, ResolveEventArgs args)\n{\n string assemblyPath = \"c:\\PathToAssembly\";\n string assemblyName = args.Name.Substring(0, args.Name.IndexOf(\",\")) + \".dll\";\n string assemblyFullName = Path.Combine(assemblyPath, assemblyName);\n\n Assembly theAssembly = Assembly.Load(assemblyFullName);\n\n return theAssembly;\n}\n"
},
{
"answer_id": 1492843,
"author": "MauriceL",
"author_id": 167733,
"author_profile": "https://Stackoverflow.com/users/167733",
"pm_score": 0,
"selected": false,
"text": "Assembly theAssembly = Assembly.LoadFile(assemblyFullName);\n Assembly.Load"
}
] | 2008/12/10 | [
"https://Stackoverflow.com/questions/356122",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12818/"
] |
356,126 | <p>I am getting 'trailing whitespace' errors trying to commit some files in Git.</p>
<p>I want to remove these trailing whitespace characters automatically right before I save Python files.</p>
<p>Can you configure Vim to do this? If so, how?</p>
| [
{
"answer_id": 356130,
"author": "Paul D. Eden",
"author_id": 3045,
"author_profile": "https://Stackoverflow.com/users/3045",
"pm_score": 9,
"selected": true,
"text": "autocmd BufWritePre *.py :%s/\\s\\+$//e\n e :h :s_flags"
},
{
"answer_id": 356214,
"author": "mat",
"author_id": 42083,
"author_profile": "https://Stackoverflow.com/users/42083",
"pm_score": 6,
"selected": false,
"text": "match Todo /\\s\\+$/\n .vimrc TODO FIXME XXX"
},
{
"answer_id": 361406,
"author": "gregf",
"author_id": 18933,
"author_profile": "https://Stackoverflow.com/users/18933",
"pm_score": 3,
"selected": false,
"text": "autocmd BufWritePre * :call <SID>StripWhite()\nfun! <SID>StripWhite()\n %s/[ \\t]\\+$//ge\n %s!^\\( \\+\\)\\t!\\=StrRepeat(\"\\t\", 1 + strlen(submatch(1)) / 8)!ge\nendfun\n"
},
{
"answer_id": 1618401,
"author": "stepancheg",
"author_id": 15018,
"author_profile": "https://Stackoverflow.com/users/15018",
"pm_score": 7,
"selected": false,
"text": "function! <SID>StripTrailingWhitespaces()\n if !&binary && &filetype != 'diff'\n let l:save = winsaveview()\n keeppatterns %s/\\s\\+$//e\n call winrestview(l:save)\n endif\nendfun\n\nautocmd FileType c,cpp,java,php,ruby,python autocmd BufWritePre <buffer> :call <SID>StripTrailingWhitespaces()\n autocmd * autocmd BufWritePre,FileWritePre,FileAppendPre,FilterWritePre *\n \\ :call <SID>StripTrailingWhitespaces()\n"
},
{
"answer_id": 7255709,
"author": "lazysoundsystem",
"author_id": 103577,
"author_profile": "https://Stackoverflow.com/users/103577",
"pm_score": 3,
"selected": false,
"text": "highlight ExtraWhitespace ctermbg=red guibg=red\nau ColorScheme * highlight ExtraWhitespace guibg=red\nau BufEnter * match ExtraWhitespace /\\s\\+$/\nau InsertEnter * match ExtraWhitespace /\\s\\+\\%#\\@<!$/\nau InsertLeave * match ExtraWhiteSpace /\\s\\+$/\n"
},
{
"answer_id": 8857415,
"author": "syvex",
"author_id": 766172,
"author_profile": "https://Stackoverflow.com/users/766172",
"pm_score": 4,
"selected": false,
"text": "autocmd FileType c,cpp,python,ruby,java autocmd BufWritePre <buffer> :%s/\\s\\+$//e\n"
},
{
"answer_id": 13795287,
"author": "Michael Durrant",
"author_id": 631619,
"author_profile": "https://Stackoverflow.com/users/631619",
"pm_score": 6,
"selected": false,
"text": "highlight ExtraWhitespace ctermbg=red guibg=red\nmatch ExtraWhitespace /\\s\\+$/\nautocmd BufWinEnter * match ExtraWhitespace /\\s\\+$/\nautocmd InsertEnter * match ExtraWhitespace /\\s\\+\\%#\\@<!$/\nautocmd InsertLeave * match ExtraWhitespace /\\s\\+$/\nautocmd BufWinLeave * call clearmatches()\n function! TrimWhiteSpace()\n %s/\\s\\+$//e\nendfunction\nautocmd BufWritePre *.rb :call TrimWhiteSpace()\n"
},
{
"answer_id": 22440291,
"author": "Kaz",
"author_id": 1250772,
"author_profile": "https://Stackoverflow.com/users/1250772",
"pm_score": 2,
"selected": false,
"text": "#!/bin/sh\n\nset -e # bail on errors\n\ngit stash save commit-cleanup\ngit stash show -p | sed '/^\\+/s/ *$//' | git apply\ngit stash drop\n +"
},
{
"answer_id": 26299952,
"author": "mb21",
"author_id": 214446,
"author_profile": "https://Stackoverflow.com/users/214446",
"pm_score": 1,
"selected": false,
"text": ".vimrc set encoding=utf-8\nset listchars=trail:·\nset list\n"
},
{
"answer_id": 30578724,
"author": "aemonge",
"author_id": 1360897,
"author_profile": "https://Stackoverflow.com/users/1360897",
"pm_score": 0,
"selected": false,
"text": "autocmd BufWritePre * :%s/\\s\\+$//<CR>:let @/=''<CR>"
},
{
"answer_id": 38903793,
"author": "Mr_Pouet",
"author_id": 901417,
"author_profile": "https://Stackoverflow.com/users/901417",
"pm_score": 1,
"selected": false,
"text": "autocmd BufWritePre *.c,*.cpp,*.cc,*.h,*.hpp,*.py,*.m,*.mm :%s/\\s\\+$//e\n autocmd BufWritePre *.{c,cpp,cc,h,hpp,py,m,mm} :%s/\\s\\+$//e\n"
},
{
"answer_id": 39779783,
"author": "KP99",
"author_id": 4381764,
"author_profile": "https://Stackoverflow.com/users/4381764",
"pm_score": 1,
"selected": false,
"text": "autocmd BufNewFile,BufRead *.test call KarlDetectWhitespace()\n\nfun! KarlDetectWhitespace()\npython << endpython\nimport vim\nnr_unclean = 0\nfor line in vim.current.buffer:\n if line.rstrip() != line:\n nr_unclean += 1\n\nprint \"Unclean Lines: %d\" % nr_unclean\nprint \"Name: %s\" % vim.current.buffer.name\ncmd = \"autocmd BufWritePre <buffer> call KarlStripTrailingWhitespace()\"\nif nr_unclean == 0:\n print \"Enabling Whitespace Trimming on Save\"\n vim.command(cmd)\nelse:\n print \"Whitespace Trimming Disabled\"\nendpython\nendfun\n\nfun! KarlStripTrailingWhitespace()\n let l = line(\".\")\n let c = col(\".\")\n %s/\\s\\+$//e\n call cursor(l, c)\nendfun\n"
},
{
"answer_id": 42757712,
"author": "Diego Juliao",
"author_id": 4237205,
"author_profile": "https://Stackoverflow.com/users/4237205",
"pm_score": 3,
"selected": false,
"text": ". .vimrc \" Removes trailing spaces\nfunction TrimWhiteSpace()\n %s/\\s*$//\n ''\nendfunction\n\nset list listchars=trail:.,extends:>\nautocmd FileWritePre * call TrimWhiteSpace()\nautocmd FileAppendPre * call TrimWhiteSpace()\nautocmd FilterWritePre * call TrimWhiteSpace()\nautocmd BufWritePre * call TrimWhiteSpace()\n"
},
{
"answer_id": 69100164,
"author": "frippe",
"author_id": 7868781,
"author_profile": "https://Stackoverflow.com/users/7868781",
"pm_score": 1,
"selected": false,
"text": "autocmd BufWritePre *.py execute 'norm m`' | %s/\\s\\+$//e | norm g``\n"
}
] | 2008/12/10 | [
"https://Stackoverflow.com/questions/356126",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3045/"
] |
356,128 | <p>If I have several classes with functions that I need but want to store separately for organisation, can I extend a class to have both?</p>
<p>i.e. <code>class a extends b extends c</code></p>
<p>edit: I know how to extend classes one at a time, but I'm looking for a method to instantly extend a class using multiple base classes - AFAIK you can't do this in PHP but there should be ways around it without resorting to <code>class c extends b</code>, <code>class b extends a</code></p>
| [
{
"answer_id": 356172,
"author": "adam",
"author_id": 33604,
"author_profile": "https://Stackoverflow.com/users/33604",
"pm_score": 7,
"selected": false,
"text": "// this is NOT allowed (for all you google speeders)\nMatron extends Nurse, HumanEntity\n Matron extends Nurse \nConsultant extends Doctor\n\nNurse extends HumanEntity\nDoctor extends HumanEntity\n\nHumanEntity extends DatabaseTable\nDatabaseTable extends AbstractTable\n"
},
{
"answer_id": 356431,
"author": "Franck",
"author_id": 38072,
"author_profile": "https://Stackoverflow.com/users/38072",
"pm_score": 9,
"selected": true,
"text": "class B {\n public function method_from_b($s) {\n echo $s;\n }\n}\n\nclass C {\n public function method_from_c($s) {\n echo $s;\n }\n}\n\nclass A extends B\n{\n private $c;\n \n public function __construct()\n {\n $this->c = new C;\n }\n \n // fake \"extends C\" using magic function\n public function __call($method, $args)\n {\n $this->c->$method($args[0]);\n }\n}\n\n\n$a = new A;\n$a->method_from_b(\"abc\");\n$a->method_from_c(\"def\");\n"
},
{
"answer_id": 356772,
"author": "PhiLho",
"author_id": 15459,
"author_profile": "https://Stackoverflow.com/users/15459",
"pm_score": 3,
"selected": false,
"text": "class C\n{\n private $a, $b;\n\n public function __construct($x, $y)\n {\n $this->a = new A(42, $x);\n $this->b = new B($y);\n }\n\n protected function DoSomething()\n {\n $this->a->Act();\n $this->b->Do();\n }\n}\n"
},
{
"answer_id": 358562,
"author": "Sam",
"author_id": 43005,
"author_profile": "https://Stackoverflow.com/users/43005",
"pm_score": 4,
"selected": false,
"text": "class Extendable{\n private $extender=array();\n\n public function addExtender(Extender $obj){\n $this->extenders[] = $obj;\n $obj->setExtendee($this);\n }\n\n public function __call($name, $params){\n foreach($this->extenders as $extender){\n //do reflection to see if extender has this method with this argument count\n if (method_exists($extender, $name)){\n return call_user_func_array(array($extender, $name), $params);\n }\n }\n }\n}\n\n\n$foo = new Extendable();\n$foo->addExtender(new OtherClass());\n$foo->other_class_method();\n"
},
{
"answer_id": 9094209,
"author": "blomman9",
"author_id": 566867,
"author_profile": "https://Stackoverflow.com/users/566867",
"pm_score": 1,
"selected": false,
"text": "class Session {\n public $username;\n}\n\nclass MyServiceResponsetype {\n protected $only_avaliable_in_response;\n}\n\nclass SessionResponse extends MyServiceResponsetype {\n /** has shared $only_avaliable_in_response */\n\n public $session;\n\n public function __construct(Session $session) {\n $this->session = $session;\n }\n\n}\n"
},
{
"answer_id": 20741203,
"author": "user2226755",
"author_id": 2226755,
"author_profile": "https://Stackoverflow.com/users/2226755",
"pm_score": 1,
"selected": false,
"text": "class B {\n public function method_from_b($s) {\n echo $s;\n }\n}\n\nclass C {\n public function method_from_c($l, $l1, $l2) {\n echo $l.$l1.$l2;\n }\n}\n\nclass A extends B {\n private $c;\n\n public function __construct() {\n $this->c = new C;\n }\n\n public function __call($method, $args) {\n if (method_exists($this->c, $method)) {\n $reflection = new ReflectionMethod($this->c, $method);\n if (!$reflection->isPublic()) {\n throw new RuntimeException(\"Call to not public method \".get_class($this).\"::$method()\");\n }\n\n return call_user_func_array(array($this->c, $method), $args);\n } else {\n throw new RuntimeException(\"Call to undefined method \".get_class($this).\"::$method()\");\n }\n }\n}\n\n\n$a = new A;\n$a->method_from_b(\"abc\");\n$a->method_from_c(\"d\", \"e\", \"f\");\n"
},
{
"answer_id": 26226748,
"author": "Mehdi Homeyli",
"author_id": 3512939,
"author_profile": "https://Stackoverflow.com/users/3512939",
"pm_score": 3,
"selected": false,
"text": "<?php\n// what if we want to extend more than one class?\n\nabstract class ExtensionBridge\n{\n // array containing all the extended classes\n private $_exts = array();\n public $_this;\n\n function __construct() {$_this = $this;}\n\n public function addExt($object)\n {\n $this->_exts[]=$object;\n }\n\n public function __get($varname)\n {\n foreach($this->_exts as $ext)\n {\n if(property_exists($ext,$varname))\n return $ext->$varname;\n }\n }\n\n public function __call($method,$args)\n {\n foreach($this->_exts as $ext)\n {\n if(method_exists($ext,$method))\n return call_user_method_array($method,$ext,$args);\n }\n throw new Exception(\"This Method {$method} doesn't exists\");\n }\n\n\n}\n\nclass Ext1\n{\n private $name=\"\";\n private $id=\"\";\n public function setID($id){$this->id = $id;}\n public function setName($name){$this->name = $name;}\n public function getID(){return $this->id;}\n public function getName(){return $this->name;}\n}\n\nclass Ext2\n{\n private $address=\"\";\n private $country=\"\";\n public function setAddress($address){$this->address = $address;}\n public function setCountry($country){$this->country = $country;}\n public function getAddress(){return $this->address;}\n public function getCountry(){return $this->country;}\n}\n\nclass Extender extends ExtensionBridge\n{\n function __construct()\n {\n parent::addExt(new Ext1());\n parent::addExt(new Ext2());\n }\n\n public function __toString()\n {\n return $this->getName().', from: '.$this->getCountry();\n }\n}\n\n$o = new Extender();\n$o->setName(\"Mahdi\");\n$o->setCountry(\"Al-Ahwaz\");\necho $o;\n?>\n"
},
{
"answer_id": 32625540,
"author": "jave.web",
"author_id": 1835470,
"author_profile": "https://Stackoverflow.com/users/1835470",
"pm_score": 4,
"selected": false,
"text": "use extends class firstInheritance{}\nclass secondInheritance extends firstInheritance{}\nclass someFinalClass extends secondInheritance{}\n//...and so on...\n class A{\n function a_hi(){\n echo \"I am a of A\".PHP_EOL.\"<br>\".PHP_EOL; \n }\n}\n\nclass B extends A{\n function b_hi(){\n echo \"I am b of B\".PHP_EOL.\"<br>\".PHP_EOL; \n }\n}\n\nclass C extends B{\n function c_hi(){\n echo \"I am c of C\".PHP_EOL.\"<br>\".PHP_EOL; \n }\n}\n\n$myTestInstance = new C();\n\n$myTestInstance->a_hi();\n$myTestInstance->b_hi();\n$myTestInstance->c_hi();\n I am a of A \nI am b of B \nI am c of C \n"
},
{
"answer_id": 42065824,
"author": "ling",
"author_id": 405042,
"author_profile": "https://Stackoverflow.com/users/405042",
"pm_score": 2,
"selected": false,
"text": "<?php\n\n\ninterface Animal\n{\n public function sayHello();\n}\n\n\ninterface HairyThing\n{\n public function plush();\n}\n\ninterface Dog extends Animal, HairyThing\n{\n public function bark();\n}\n\n\nclass Puppy implements Dog\n{\n public function bark()\n {\n echo \"ouaf\";\n }\n\n public function sayHello()\n {\n echo \"hello\";\n }\n\n public function plush()\n {\n echo \"plush\";\n }\n\n\n}\n\n\necho PHP_VERSION; // 5.6.1\n$o = new Puppy();\n$o->bark();\n$o->plush();\n$o->sayHello(); // displays: 5.6.16ouafplushhello\n interface Swift_Transport_IoBuffer extends Swift_InputByteStream, Swift_OutputByteStream\n"
},
{
"answer_id": 46240045,
"author": "Alice",
"author_id": 7760530,
"author_profile": "https://Stackoverflow.com/users/7760530",
"pm_score": 4,
"selected": false,
"text": "trait business{\n function sell(){\n\n }\n\n function buy(){\n\n }\n\n function collectMoney(){\n }\n\n}\n\ntrait human{\n\n function think(){\n\n }\n\n function speak(){\n\n }\n\n}\n\nclass BusinessPerson{\n use business;\n use human;\n // If you have more traits bring more\n}\n\n\nclass BusinessWoman extends BusinessPerson{\n\n function getPregnant(){\n\n }\n\n}\n\n\n$bw = new BusinessWoman();\n$bw ->speak();\n$bw->getPregnant();\n"
}
] | 2008/12/10 | [
"https://Stackoverflow.com/questions/356128",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/24416/"
] |
356,144 | <p>I want to use the GridView mode of a ListView to display a set of data that my program will be receiving from an external source. The data will consist of two arrays, one of column names and one of strings values to populate the control.</p>
<p>I don't see how to create a suitable class that I can use as the Item in a ListView. The only way I know to populate the Items is to set it to a class with properties that represent the columns, but I have no knowledge of the columns before run-time.</p>
<p>I could create an ItemTemplate dynamically as described in: <a href="https://stackoverflow.com/questions/125638/create-wpf-itemtemplate-dynamically-at-runtime">Create WPF ItemTemplate DYNAMICALLY at runtime</a> but it still leaves me at a loss as to how to describe the actual data.</p>
<p>Any help gratefully received.</p>
| [
{
"answer_id": 357306,
"author": "Robert Macnee",
"author_id": 19273,
"author_profile": "https://Stackoverflow.com/users/19273",
"pm_score": 5,
"selected": true,
"text": "private void AddColumns(GridView gv, string[] columnNames)\n{\n for (int i = 0; i < columnNames.Length; i++)\n {\n gv.Columns.Add(new GridViewColumn\n {\n Header = columnNames[i],\n DisplayMemberBinding = new Binding(String.Format(\"[{0}]\", i))\n });\n }\n}\n <Grid>\n <Grid.Resources>\n <x:Array x:Key=\"data\" Type=\"{x:Type sys:String[]}\">\n <x:Array Type=\"{x:Type sys:String}\">\n <sys:String>a</sys:String>\n <sys:String>b</sys:String>\n <sys:String>c</sys:String>\n </x:Array>\n <x:Array Type=\"{x:Type sys:String}\">\n <sys:String>do</sys:String>\n <sys:String>re</sys:String>\n <sys:String>mi</sys:String>\n </x:Array>\n </x:Array>\n </Grid.Resources>\n <ListView ItemsSource=\"{StaticResource data}\">\n <ListView.View>\n <GridView>\n <GridViewColumn DisplayMemberBinding=\"{Binding Path=[0]}\" Header=\"column1\"/>\n <GridViewColumn DisplayMemberBinding=\"{Binding Path=[1]}\" Header=\"column2\"/>\n <GridViewColumn DisplayMemberBinding=\"{Binding Path=[2]}\" Header=\"column3\"/>\n </GridView>\n </ListView.View>\n </ListView>\n</Grid>\n"
},
{
"answer_id": 379024,
"author": "TomDestry",
"author_id": 7989,
"author_profile": "https://Stackoverflow.com/users/7989",
"pm_score": 3,
"selected": false,
"text": "private void AddColumns(List<String> myColumns)\n{\n GridView viewLayout = new GridView();\n for (int i = 0; i < myColumns.Count; i++)\n {\n viewLayout.Columns.Add(new GridViewColumn\n {\n Header = myColumns[i],\n DisplayMemberBinding = new Binding(String.Format(\"[{0}]\", i))\n });\n }\n myListview.View = viewLayout;\n}\n <ListView Name=\"myListview\" DockPanel.Dock=\"Left\"/>\n public class MyCollection : ObservableCollection<List<String>>\n{\n public MyCollection()\n : base()\n {\n }\n}\n results = new MyCollection();\n\nBinding binding = new Binding();\nbinding.Source = results;\nmyListview.SetBinding(ListView.ItemsSourceProperty, binding);\n results.Clear();\nList<String> details = new List<string>();\nfor (int ii=0; ii < externalDataCollection.Length; ii++)\n{\n details.Add(externalDataCollection[ii]);\n}\nresults.Add(details);\n"
},
{
"answer_id": 3154200,
"author": "ChrisWue",
"author_id": 220986,
"author_profile": "https://Stackoverflow.com/users/220986",
"pm_score": 2,
"selected": false,
"text": " public class DataMatrixCellTemplateSelectorWrapper : DataTemplateSelector\n {\n private readonly DataTemplateSelector _ActualSelector;\n private readonly string _ColumnName;\n private Dictionary<string, object> _OriginalRow;\n\n public DataMatrixCellTemplateSelectorWrapper(DataTemplateSelector actualSelector, string columnName)\n {\n _ActualSelector = actualSelector;\n _ColumnName = columnName;\n }\n\n public override DataTemplate SelectTemplate(object item, DependencyObject container)\n {\n // The item is basically the Content of the ContentPresenter.\n // In the DataMatrix binding case that is the dictionary containing the cell objects.\n // In order to be able to select a template based on the actual cell object and also\n // be able to bind to that object within the template we need to set the DataContext\n // of the template to the actual cell object. However after the template is selected\n // the ContentPresenter will set the DataContext of the template to the presenters\n // content. \n // So in order to achieve what we want, we remember the original DataContext and then\n // change the ContentPresenter content to the actual cell object.\n // Therefor we need to remember the orginal DataContext otherwise in subsequent calls\n // we would get the first cell object.\n\n // remember old data context\n if (item is Dictionary<string, object>)\n {\n _OriginalRow = item as Dictionary<string, object>;\n }\n\n if (_OriginalRow == null)\n return null;\n\n // get the actual cell object\n var obj = _OriginalRow[_ColumnName];\n\n // select the template based on the cell object\n var template = _ActualSelector.SelectTemplate(obj, container);\n\n // find the presenter and change the content to the cell object so that it will become\n // the data context of the template\n var presenter = WpfUtils.GetFirstParentForChild<ContentPresenter>(container);\n if (presenter != null)\n {\n presenter.Content = obj;\n }\n\n return template;\n }\n }\n var column = new GridViewColumn\n {\n Header = col.Name,\n HeaderTemplate = gridView.ColumnHeaderTemplate\n };\n if (listView.CellTemplateSelector != null)\n {\n column.CellTemplateSelector = new DataMatrixCellTemplateSelectorWrapper(listView.CellTemplateSelector, col.Name);\n }\n else\n {\n column.DisplayMemberBinding = new Binding(string.Format(\"[{0}]\", col.Name));\n }\n gridView.Columns.Add(column);\n"
},
{
"answer_id": 6940220,
"author": "Kayomani",
"author_id": 878427,
"author_profile": "https://Stackoverflow.com/users/878427",
"pm_score": 1,
"selected": false,
"text": " var view = grid.View as GridView;\n view.Columns.Clear();\n int count=0;\n foreach (var column in ViewModel.GridData.Columns)\n {\n //Create Column\n var nc = new GridViewColumn();\n nc.Header = column.Field;\n nc.Width = column.Width;\n //Create template\n nc.CellTemplate = new DataTemplate();\n var factory = new FrameworkElementFactory(typeof(System.Windows.Controls.Border));\n var tbf = new FrameworkElementFactory(typeof(System.Windows.Controls.TextBlock));\n\n factory.AppendChild(tbf);\n factory.SetValue(System.Windows.Controls.Border.BorderThicknessProperty, new Thickness(0,0,1,1));\n factory.SetValue(System.Windows.Controls.Border.MarginProperty, new Thickness(-7,0,-7,0));\n factory.SetValue(System.Windows.Controls.Border.BorderBrushProperty, Brushes.LightGray);\n tbf.SetValue(System.Windows.Controls.TextBlock.MarginProperty, new Thickness(6,2,6,2));\n tbf.SetValue(System.Windows.Controls.TextBlock.HorizontalAlignmentProperty, column.Alignment);\n\n //Bind field\n tbf.SetBinding(System.Windows.Controls.TextBlock.TextProperty, new Binding(){Converter = new GridCellConverter(), ConverterParameter=column.BindingField});\n nc.CellTemplate.VisualTree = factory;\n\n view.Columns.Add(nc);\n count++;\n }\n"
}
] | 2008/12/10 | [
"https://Stackoverflow.com/questions/356144",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7989/"
] |
356,161 | <p>In python do you generally use <a href="http://www.python.org/dev/peps/pep-0008/" rel="noreferrer">PEP 8 -- Style Guide for Python Code</a> as your coding standards/guidelines? Are there any other formalized standards that you prefer?</p>
| [
{
"answer_id": 356426,
"author": "Ryan Cox",
"author_id": 620,
"author_profile": "https://Stackoverflow.com/users/620",
"pm_score": 3,
"selected": false,
"text": "# dict's setdefault method turns this:\nif key in dictobj:\n dictobj[key].append(val)\nelse:\n dictobj[key] = [val]\n# into this:\ndictobj.setdefault(key,[]).append(val)\n"
},
{
"answer_id": 684233,
"author": "S.Lott",
"author_id": 10661,
"author_profile": "https://Stackoverflow.com/users/10661",
"pm_score": 3,
"selected": false,
"text": "spam(ham[1], {eggs: 2}) spam( ham[ 1 ], { eggs: 2 } ) x = x * 2 - 1 x= x * 2 - 1"
}
] | 2008/12/10 | [
"https://Stackoverflow.com/questions/356161",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/52490/"
] |
356,164 | <p>Image i have a view that is cached with the OutputCache attribute but i still need to increment a counter that records that the page has been viewed, how could i do it?</p>
<p>I thought about creating my own Custom ActionFilterAttribute, and using Action Filter Order of Execution to record this .. but i'm not sure it will work.</p>
<p>eg.</p>
<pre><code>[IncrementViewCountFilter(Order=1)]
[OutputCache(Duration=60,Order=2)]
public ActionResult Index(int questionId)
{ ... }
</code></pre>
<p>Firstly, my assumption here is that if the OutputCache is called, and the page is cached, then the controller code will not be ran.</p>
<p>Next problem i'm guessing is that the IncrementViewCountFilter wouldn't know about the questionId, so how would it know what to increment (because it is executed before the main Index code is executed).</p>
<p>Secondly, if the IncrementViewCountFilter did know the questionId .. and it's getting lots of hits, you wouldn't want it to write all the time to the DB.. but only when it gets to a certain number .. and then u 'flush' the output.</p>
<p>Anyone have any thoughts?</p>
| [
{
"answer_id": 356363,
"author": "Dan Esparza",
"author_id": 19020,
"author_profile": "https://Stackoverflow.com/users/19020",
"pm_score": 4,
"selected": true,
"text": "<img src=\"/controller/action\"> \n http://www.domain.com/home/action\n http://www.domain.com/tracking/action\n"
}
] | 2008/12/10 | [
"https://Stackoverflow.com/questions/356164",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/30674/"
] |
356,167 | <p>I could do this myself given time but does anyone have a nice asp.net implementation of an a-z list coming from a sql query. I would like it to come in the form:</p>
<p>A<br />
aardvark<br />
anagram<br />
apple</p>
<p>B<br />
barry<br />
brown....</p>
<p>That is with each entry being a link.</p>
| [
{
"answer_id": 356176,
"author": "Joel Coehoorn",
"author_id": 3043,
"author_profile": "https://Stackoverflow.com/users/3043",
"pm_score": 2,
"selected": true,
"text": "Upper(Substring([myfield],1,1)) AS Letter"
},
{
"answer_id": 356195,
"author": "Shawn",
"author_id": 26,
"author_profile": "https://Stackoverflow.com/users/26",
"pm_score": 0,
"selected": false,
"text": "select word from \n (select word from table \n union all \n select Upper(Substring([word],1,1)) as letter from table\n ) t order by word\n"
}
] | 2008/12/10 | [
"https://Stackoverflow.com/questions/356167",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16989/"
] |
356,174 | <p><strong>Dup of <a href="https://stackoverflow.com/questions/330709/some-basic-php-questions#330829">Some Basic PHP Questions</a></strong></p>
<p>Hello,</p>
<p>I have a heap of tinyint fields in a mysql database I need to show with PHP. At the moment I am doing something like this:</p>
<pre><code>if ($row['PAYPAL_ACCEPT'] == "1"){
$paypal = "Yes";
else
$paypal = "No";
}
</code></pre>
<p>For each field, which is tedious and seems like there should be a better way, than using an if clause for each field. If there is, what is it?</p>
| [
{
"answer_id": 356182,
"author": "lpfavreau",
"author_id": 35935,
"author_profile": "https://Stackoverflow.com/users/35935",
"pm_score": 2,
"selected": false,
"text": "$paypal = $row['PAYPAL_ACCEPT'] ? 'YES' : 'NO';\n"
},
{
"answer_id": 356184,
"author": "adam",
"author_id": 33604,
"author_profile": "https://Stackoverflow.com/users/33604",
"pm_score": 2,
"selected": false,
"text": "$paypal = ($row['PAYPAL_ACCEPT'] ? \"Yes\" : \"No\");\n"
},
{
"answer_id": 356189,
"author": "Tader",
"author_id": 30700,
"author_profile": "https://Stackoverflow.com/users/30700",
"pm_score": 0,
"selected": false,
"text": "$paypal = ($row['PAYPAL_ACCEPT']?'Yes':'No');\n"
},
{
"answer_id": 356193,
"author": "Irmantas",
"author_id": 43182,
"author_profile": "https://Stackoverflow.com/users/43182",
"pm_score": 0,
"selected": false,
"text": "$paypal = $row['PAYPAL_ACCEPT'];\n"
},
{
"answer_id": 356250,
"author": "chriscena",
"author_id": 32671,
"author_profile": "https://Stackoverflow.com/users/32671",
"pm_score": 2,
"selected": true,
"text": "// $columns = string array of column names\n// $columns = array('PAYPAL_ACCEPT' ... );\nforeach($columns as $column) {\n $$column = $row[$column] ? 'YES' : 'NO';\n}\n print $PAYPAL_ACCEPT;\n"
}
] | 2008/12/10 | [
"https://Stackoverflow.com/questions/356174",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1246613/"
] |
356,180 | <p>Suppose to feed the filter standard input with these line:</p>
<pre><code>line 1
line 2
line 3
line 4
line 5
line 6
line 7
line 8
line 9
line 10
</code></pre>
<p>It would be nicer if someone tell me how to write a script that prints only every 4 lines, in the case of the example input above:</p>
<pre><code>line 1
line 5
line 9
</code></pre>
| [
{
"answer_id": 356198,
"author": "mat",
"author_id": 42083,
"author_profile": "https://Stackoverflow.com/users/42083",
"pm_score": 5,
"selected": true,
"text": "$ yes | cat -n | head -10 | awk 'NR % 4 == 1'\n 1 y\n 5 y\n 9 y\n awk 'NR % 4 == 1'"
},
{
"answer_id": 356203,
"author": "Stephen Darlington",
"author_id": 2998,
"author_profile": "https://Stackoverflow.com/users/2998",
"pm_score": 2,
"selected": false,
"text": "awk '{ if ((NR-1) %4 ==0) print}'\n"
},
{
"answer_id": 356210,
"author": "Keltia",
"author_id": 16143,
"author_profile": "https://Stackoverflow.com/users/16143",
"pm_score": 1,
"selected": false,
"text": "awk 'NR%4 == 1 {print}'</etc/hosts\n"
},
{
"answer_id": 38886166,
"author": "plhn",
"author_id": 766330,
"author_profile": "https://Stackoverflow.com/users/766330",
"pm_score": 0,
"selected": false,
"text": "sed -ne '1~4p’\n sed"
}
] | 2008/12/10 | [
"https://Stackoverflow.com/questions/356180",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/36131/"
] |
356,194 | <p>I know that I can make a setter that checks to see if a value is NULL and do something. Example:</p>
<pre><code><TextBlock>
<TextBlock.Style>
<Style>
<Style.Triggers>
<DataTrigger Binding="{Binding SomeField}" Value="{x:Null}">
<Setter Property="TextBlock.Text" Value="It's NULL Baby!" />
</DataTrigger>
</Style.Triggers>
</Style>
</TextBlock.Style>
</TextBlock>
</code></pre>
<p>But how can I check for a "not" value... as in "NOT NULL", or "NOT = 3"? Is that possible in XAML?</p>
<p><strong>Results:</strong> Thanks for your answers... I knew I could do a value converter (which means I would have to go in code, and that would not be pure XAML as I hoped for). However, that does answer the question that effectively "no" you can't do it in pure XAML. The answer selected, however, shows probably the best way to <em>create</em> that kind of functionality. Good find.</p>
| [
{
"answer_id": 356690,
"author": "Robert Macnee",
"author_id": 19273,
"author_profile": "https://Stackoverflow.com/users/19273",
"pm_score": 7,
"selected": false,
"text": "<TextBlock>\n <TextBlock.Resources>\n <conv:IsNullConverter x:Key=\"isNullConverter\"/>\n </TextBlock.Resources>\n <TextBlock.Style>\n <Style>\n <Style.Triggers>\n <DataTrigger Binding=\"{Binding SomeField, Converter={StaticResource isNullConverter}}\" Value=\"False\">\n <Setter Property=\"TextBlock.Text\" Value=\"It's NOT NULL Baby!\"/>\n </DataTrigger>\n </Style.Triggers>\n </Style>\n </TextBlock.Style>\n</TextBlock>\n public class IsNullConverter : IValueConverter\n{\n public object Convert(object value, Type targetType, object parameter, CultureInfo culture)\n {\n return (value == null);\n }\n\n public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)\n {\n throw new InvalidOperationException(\"IsNullConverter can only be used OneWay.\");\n }\n}\n"
},
{
"answer_id": 593288,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 8,
"selected": false,
"text": " <Style> \n <!-- Highlight for Reviewed (Default) -->\n <Setter Property=\"Control.Background\" Value=\"PaleGreen\" /> \n <Style.Triggers>\n <!-- Highlight for Not Reviewed -->\n <DataTrigger Binding=\"{Binding Path=REVIEWEDBY}\" Value=\"{x:Null}\">\n <Setter Property=\"Control.Background\" Value=\"LightIndianRed\" />\n </DataTrigger>\n </Style.Triggers>\n </Style>\n"
},
{
"answer_id": 7278298,
"author": "SteveCav",
"author_id": 167611,
"author_profile": "https://Stackoverflow.com/users/167611",
"pm_score": 4,
"selected": false,
"text": "<Style TargetType=\"{x:Type Button}\">\n <Setter Property=\"IsEnabled\" Value=\"True\"/>\n <Style.Triggers>\n <DataTrigger Binding=\"{Binding ElementName=lvMyList, Path=SelectedItem}\" Value=\"{x:Null}\">\n <Setter Property=\"IsEnabled\" Value=\"False\"/>\n </DataTrigger>\n </Style.Triggers>\n</Style>\n"
},
{
"answer_id": 9645182,
"author": "APaglia",
"author_id": 1078693,
"author_profile": "https://Stackoverflow.com/users/1078693",
"pm_score": 3,
"selected": false,
"text": " Public ReadOnly Property IsSomeFieldNull() As Boolean\n Get\n Return If(SomeField is Null, True, False)\n End Get\n End Property\n <DataTrigger Binding=\"{Binding IsSomeFieldNull}\" Value=\"False\">\n <Setter Property=\"TextBlock.Text\" Value=\"It's NOT NULL Baby!\" />\n </DataTrigger>\n"
},
{
"answer_id": 10518047,
"author": "JoanComasFdz",
"author_id": 383129,
"author_profile": "https://Stackoverflow.com/users/383129",
"pm_score": 5,
"selected": false,
"text": "<Style>\n <Style.Triggers>\n <DataTrigger Binding=\"{Binding SomeProperty}\" Value=\"{x:Null}\">\n <Setter Property=\"Visibility\" Value=\"Collapsed\" />\n </DataTrigger>\n </Style.Triggers>\n</Style>\n <Style>\n <Setter Property=\"Visibility\" Value=\"Collapsed\" />\n <Style.Triggers>\n <DataTrigger Binding=\"{Binding SomeProperty}\" Value=\"{x:Null}\">\n <Setter Property=\"Visibility\" Value=\"Visible\" />\n </DataTrigger>\n </Style.Triggers>\n</Style>\n"
},
{
"answer_id": 10534129,
"author": "abatishchev",
"author_id": 41956,
"author_profile": "https://Stackoverflow.com/users/41956",
"pm_score": 2,
"selected": false,
"text": "public class NullableToVisibilityConverter: IValueConverter\n{\n public object Convert(object value, Type targetType, object parameter, CultureInfo culture)\n {\n return value == null ? Visibility.Collapsed : Visibility.Visible;\n }\n}\n Visibility=\"{Binding PropertyToBind, Converter={StaticResource nullableToVisibilityConverter}}\"\n"
},
{
"answer_id": 16167501,
"author": "yossharel",
"author_id": 184175,
"author_profile": "https://Stackoverflow.com/users/184175",
"pm_score": 4,
"selected": false,
"text": "DataTrigger <i:Interaction.Triggers>\n <i:DataTrigger Binding=\"{Binding YourProperty}\" Value=\"{x:Null}\" Comparison=\"NotEqual\">\n <ie:ChangePropertyAction PropertyName=\"YourTargetPropertyName\" Value=\"{Binding YourValue}\"/>\n </i:DataTrigger\n</i:Interaction.Triggers>\n GreaterThan LessThan"
},
{
"answer_id": 18541244,
"author": "aromore",
"author_id": 1035156,
"author_profile": "https://Stackoverflow.com/users/1035156",
"pm_score": 3,
"selected": false,
"text": "<StackPanel.Style>\n <Style>\n <Setter Property=\"StackPanel.Visibility\" Value=\"Visible\"></Setter>\n <Style.Triggers>\n <DataTrigger Binding=\"{Binding ElementName=ProfileSelectorComboBox, Path=SelectedItem.Tag}\" Value=\"{x:Null}\">\n <Setter Property=\"StackPanel.Visibility\" Value=\"Collapsed\"></Setter>\n </DataTrigger>\n </Style.Triggers>\n </Style>\n</StackPanel.Style>\n"
},
{
"answer_id": 34180619,
"author": "Simon",
"author_id": 2214067,
"author_profile": "https://Stackoverflow.com/users/2214067",
"pm_score": 3,
"selected": false,
"text": "<Windows....\n xmlns:conv=\"clr-namespace:CalcBinding;assembly=CalcBinding\"\n>\n <TextBlock>\n <TextBlock.Style>\n <Style.Triggers>\n <DataTrigger Binding=\"{conv:Binding 'MyValue==null'}\" Value=\"false\">\n <Setter Property=\"Background\" Value=\"#FF80C983\"></Setter>\n </DataTrigger>\n </Style.Triggers>\n </TextBlock.Style>\n </TextBlock>\n"
},
{
"answer_id": 35649716,
"author": "Butsaty",
"author_id": 1041827,
"author_profile": "https://Stackoverflow.com/users/1041827",
"pm_score": 2,
"selected": false,
"text": "public bool CanDoIt\n{\n get\n {\n return !string.IsNullOrEmpty(SomeField);\n }\n}\n <DataTrigger Binding=\"{Binding SomeField}\" Value=\"{Binding CanDoIt}\">\n"
},
{
"answer_id": 37746025,
"author": "Chaitanya Kadamati",
"author_id": 4402011,
"author_profile": "https://Stackoverflow.com/users/4402011",
"pm_score": 2,
"selected": false,
"text": " <StackPanel>\n <TextBlock Text=\"Border = Red when null value\" />\n <Border x:Name=\"border_objectForNullValueTrigger\" HorizontalAlignment=\"Stretch\" Height=\"20\"> \n <Border.Style>\n <Style TargetType=\"Border\">\n <Setter Property=\"Background\" Value=\"Black\" />\n <Style.Triggers>\n <DataTrigger Binding=\"{Binding ObjectForNullValueTrigger}\" Value=\"{x:Null}\">\n <Setter Property=\"Background\" Value=\"Red\" />\n </DataTrigger>\n </Style.Triggers>\n </Style>\n </Border.Style>\n </Border>\n <TextBlock Text=\"Border = Green when not null value\" />\n <Border HorizontalAlignment=\"Stretch\" Height=\"20\">\n <Border.Style>\n <Style TargetType=\"Border\">\n <Setter Property=\"Background\" Value=\"Green\" />\n <Style.Triggers>\n <DataTrigger Binding=\"{Binding Background, ElementName=border_objectForNullValueTrigger}\" Value=\"Red\">\n <Setter Property=\"Background\" Value=\"Black\" />\n </DataTrigger>\n </Style.Triggers>\n </Style>\n </Border.Style>\n </Border>\n <Button Content=\"Invert Object state\" Click=\"Button_Click_1\"/>\n </StackPanel>\n"
}
] | 2008/12/10 | [
"https://Stackoverflow.com/questions/356194",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11917/"
] |
356,217 | <p>I keep seeing code that does checks like this</p>
<pre><code>if (IsGood == false)
{
DoSomething();
}
</code></pre>
<p>or this</p>
<pre><code>if (IsGood == true)
{
DoSomething();
}
</code></pre>
<p>I hate this syntax, and always use the following syntax.</p>
<pre><code>if (IsGood)
{
DoSomething();
}
</code></pre>
<p>or</p>
<pre><code>if (!IsGood)
{
DoSomething();
}
</code></pre>
<p>Is there any reason to use '<code>== true</code>' or '<code>== false</code>'?</p>
<p>Is it a readability thing? Do people just not understand Boolean variables?</p>
<p>Also, is there any performance difference between the two?</p>
| [
{
"answer_id": 356223,
"author": "Bob",
"author_id": 45,
"author_profile": "https://Stackoverflow.com/users/45",
"pm_score": 2,
"selected": false,
"text": "!IsGood boolean == true IsGood == false"
},
{
"answer_id": 356224,
"author": "Patrick Desjardins",
"author_id": 13913,
"author_profile": "https://Stackoverflow.com/users/13913",
"pm_score": 8,
"selected": true,
"text": "== true"
},
{
"answer_id": 356226,
"author": "Michael Haren",
"author_id": 29,
"author_profile": "https://Stackoverflow.com/users/29",
"pm_score": 4,
"selected": false,
"text": "IsGood == true bool IsGood SomeStringObject.ToString()"
},
{
"answer_id": 356232,
"author": "xan",
"author_id": 15667,
"author_profile": "https://Stackoverflow.com/users/15667",
"pm_score": 2,
"selected": false,
"text": "if(strcmp(string1, string2)==0) { /*do something*/ }\n if(!isCached)\n{\n Cache(thing);\n}\n"
},
{
"answer_id": 356234,
"author": "ctacke",
"author_id": 13154,
"author_profile": "https://Stackoverflow.com/users/13154",
"pm_score": 3,
"selected": false,
"text": "if(IsGood) DoSomething();\n if(IsBad == false) DoSomething();\n if(!IsBad) DoSomething();\n"
},
{
"answer_id": 356241,
"author": "mookid8000",
"author_id": 6560,
"author_profile": "https://Stackoverflow.com/users/6560",
"pm_score": 1,
"selected": false,
"text": "(...)\n if (ShouldDoSomething())\n {\n DoSomething();\n }\n(...)\n\nbool ShouldDoSomething()\n{\n return IsGood;\n}\n"
},
{
"answer_id": 356244,
"author": "IgorK",
"author_id": 44647,
"author_profile": "https://Stackoverflow.com/users/44647",
"pm_score": 5,
"selected": false,
"text": "== false bool? bool? (!IsGood) IsGood bool? (IsGood.HasValue && IsGood.Value) (IsGood == true) bool? value = true; // try false and null too\n\nif (value == true)\n{\n Console.WriteLine(\"value is true\");\n}\nelse if (value == false)\n{\n Console.WriteLine(\"value is false\");\n}\nelse\n{\n Console.WriteLine(\"value is null\");\n}\n if (!IsGood) { ... } if (IsGood == false) { ... } using System;\n\nnamespace BoolHack\n{\n class Program\n {\n public struct CrazyBool\n {\n private readonly bool value;\n\n public CrazyBool(bool value)\n {\n this.value = value;\n }\n\n // Just to make nice init possible ;)\n public static implicit operator CrazyBool(bool value)\n {\n return new CrazyBool(value);\n }\n\n public static bool operator==(CrazyBool crazyBool, bool value)\n {\n return crazyBool.value == value;\n }\n\n public static bool operator!=(CrazyBool crazyBool, bool value)\n {\n return crazyBool.value != value;\n }\n\n #region Twisted logic!\n\n public static bool operator true(CrazyBool crazyBool)\n {\n return !crazyBool.value;\n }\n\n public static bool operator false(CrazyBool crazyBool)\n {\n return crazyBool.value;\n }\n\n #endregion Twisted logic!\n }\n\n static void Main()\n {\n CrazyBool IsGood = false;\n\n if (IsGood)\n {\n if (IsGood == false)\n {\n Console.WriteLine(\"Now you should understand why those type is called CrazyBool!\");\n }\n }\n }\n }\n}\n"
},
{
"answer_id": 356261,
"author": "Nick Berardi",
"author_id": 17,
"author_profile": "https://Stackoverflow.com/users/17",
"pm_score": 4,
"selected": false,
"text": "if (IsGood)\nif (!IsGood)\n"
},
{
"answer_id": 356300,
"author": "John Kraft",
"author_id": 7495,
"author_profile": "https://Stackoverflow.com/users/7495",
"pm_score": 0,
"selected": false,
"text": "if(IsGood)\n if(IsGood == false)\n if not IsNotGuam then\n"
},
{
"answer_id": 356366,
"author": "Brian Genisio",
"author_id": 36687,
"author_profile": "https://Stackoverflow.com/users/36687",
"pm_score": 2,
"selected": false,
"text": "public bool IsBad => !IsGood;\n if (IsBad)\n{\n ...\n}\n"
},
{
"answer_id": 356530,
"author": "user30364",
"author_id": 30364,
"author_profile": "https://Stackoverflow.com/users/30364",
"pm_score": 0,
"selected": false,
"text": "if (!(IsGood ^ true))\n true / 2\n"
},
{
"answer_id": 356565,
"author": "Rob Gilliam",
"author_id": 23408,
"author_profile": "https://Stackoverflow.com/users/23408",
"pm_score": 5,
"selected": false,
"text": "if (someBoolean == true) { /* ... */ }\n if ((someBoolean == true) == true) { /* ... */ }\n if (((someBoolean == true) == true) == true) { /* ... */ }\n"
},
{
"answer_id": 356608,
"author": "Chris",
"author_id": 7529,
"author_profile": "https://Stackoverflow.com/users/7529",
"pm_score": 0,
"selected": false,
"text": "if (IsGood == false) if(!IsGood)"
},
{
"answer_id": 356614,
"author": "Herms",
"author_id": 1409,
"author_profile": "https://Stackoverflow.com/users/1409",
"pm_score": 0,
"selected": false,
"text": "function myFunc(b:Boolean):Void {\n if(b == true) {\n // causes b to default to false, as null/undefined != true\n }\n}\n function myFunc(b:Boolean):Void {\n if(b != false) {\n // causes b to default to true, as null/undefined != false\n }\n}\n function myFunc(b:Boolean):Void {\n b = (b == true); // default to false\n}\n function myFunc(b:Boolean):Void {\n b = (b != false); // default to true\n}\n"
},
{
"answer_id": 356668,
"author": "PhiLho",
"author_id": 15459,
"author_profile": "https://Stackoverflow.com/users/15459",
"pm_score": 1,
"selected": false,
"text": "if (isSuccessful) if (returnCode) if (PropertyProvider.getBooleanProperty(SOME_SETTING, true) == true)"
},
{
"answer_id": 356709,
"author": "Michael Burr",
"author_id": 12711,
"author_profile": "https://Stackoverflow.com/users/12711",
"pm_score": 4,
"selected": false,
"text": "true // needs C++ to get true/false keywords\n// or needs macros (or something) defining true/false appropriately\nint main( int argc, char* argv[])\n{\n int isGood = -1;\n\n if (isGood == true) {\n printf( \"isGood == true\\n\");\n }\n else {\n printf( \"isGood != true\\n\");\n }\n\n if (isGood) {\n printf( \"isGood is true\\n\");\n }\n else {\n printf( \"isGood is not true\\n\");\n }\n\n return 0;\n}\n isGood != true\nisGood is true\n 0 0 if (isGood != false) ... // instead of using if (isGood == true)\n"
},
{
"answer_id": 356753,
"author": "Jonas Elfström",
"author_id": 44620,
"author_profile": "https://Stackoverflow.com/users/44620",
"pm_score": 1,
"selected": false,
"text": "if (IsGood)\n if (!IsBad)\n unless (IsBad)\n raise InvalidColor unless AllowedColors.include?(color)\n"
},
{
"answer_id": 356849,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 3,
"selected": false,
"text": "if (IsGood)\n{\n DoSomething();\n}\n if (IsGood == false)\n{\n DoSomething();\n}\n"
},
{
"answer_id": 356924,
"author": "Sydius",
"author_id": 43496,
"author_profile": "https://Stackoverflow.com/users/43496",
"pm_score": 2,
"selected": false,
"text": "if (something) ...\n if (something == true) ...\n"
},
{
"answer_id": 357052,
"author": "Wavel",
"author_id": 13413,
"author_profile": "https://Stackoverflow.com/users/13413",
"pm_score": 2,
"selected": false,
"text": "if (true == IsGood) {....\n"
},
{
"answer_id": 357129,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 3,
"selected": false,
"text": "if ( true == FunctionCall()) {\n // stuff\n}\n"
},
{
"answer_id": 357210,
"author": "Cybis",
"author_id": 32998,
"author_profile": "https://Stackoverflow.com/users/32998",
"pm_score": -1,
"selected": false,
"text": "\nif (something == true)\nif (something == false)\n \nif (something)\nif (!something)\n if (something) if (something == false) \nif something:\nif not something:\n"
},
{
"answer_id": 357238,
"author": "yogman",
"author_id": 24349,
"author_profile": "https://Stackoverflow.com/users/24349",
"pm_score": 2,
"selected": false,
"text": "!IsGood IsGood == false /\\b!IsGood\\b/\n /\\bIsGood\\s*==\\s*false\\b/\n/\\bIsGood\\s*!=\\s*true\\b/\n/\\bIsGood\\s*(?:==\\s*false|!=\\s*true)\\b/\n"
},
{
"answer_id": 357647,
"author": "Marc",
"author_id": 27947,
"author_profile": "https://Stackoverflow.com/users/27947",
"pm_score": 1,
"selected": false,
"text": "if (not foo ())\n bar ();\n"
},
{
"answer_id": 357784,
"author": "Calyth",
"author_id": 45144,
"author_profile": "https://Stackoverflow.com/users/45144",
"pm_score": 0,
"selected": false,
"text": "if(foo(bar)) { ... }\n"
},
{
"answer_id": 358674,
"author": "Murthy",
"author_id": 17187,
"author_profile": "https://Stackoverflow.com/users/17187",
"pm_score": 0,
"selected": false,
"text": "if (isGood) if (!isGood) if (!getGreatGrandFateher.getGrandFather().getFather().getFirstChild().isMale())\n{\n doSomething();\n}\n doSomething if(getGreatGrandFateher.getGrandFather().getFather().getFirstChild().isMale() == false)\n{\n doSomething();\n}\n"
},
{
"answer_id": 359532,
"author": "Pokus",
"author_id": 21386,
"author_profile": "https://Stackoverflow.com/users/21386",
"pm_score": 1,
"selected": false,
"text": "== != != == hasXYZ() isABC()"
},
{
"answer_id": 364326,
"author": "hhafez",
"author_id": 42303,
"author_profile": "https://Stackoverflow.com/users/42303",
"pm_score": 0,
"selected": false,
"text": "if (is_good == True)\n{\n}\n true false is_good"
},
{
"answer_id": 365426,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "if(IsSomething)\n if(Something == true)\n if(Something) and if(Something == true)\n"
},
{
"answer_id": 1575864,
"author": "Kyle",
"author_id": 33886,
"author_profile": "https://Stackoverflow.com/users/33886",
"pm_score": 0,
"selected": false,
"text": "if (isValidDate == true) {\n if (isValidQuantity == true) {\n if (isOtherThingValid == true) {\n bool result = doThing();\n if (result == true) {\n thatWorked();\n } // long block of code that tries to compensate for OtherThing's invalidness\n } // obtuse function call to a third party library to send an email regarding the invalid quantity\n} // is this the function close brace or the if...\n if (isValidDate == false) {\n logThisProblem(\"Invalid date provided.\");\n return somethingUseful;\n}\n\nif (isValidQuantity == false) {\n logThisProblem(\"Invalid quantity provided.\");\n return somethingUseful;\n}\n\nif (isOtherThingValid == false) {\n logThisProble(\"Other thing not valid.\");\n return somethingUseful;\n}\n\n// OK ... we've made it this far...\nbool result = doThing(date, quantity, otherThing);\n"
},
{
"answer_id": 1575894,
"author": "OscarRyz",
"author_id": 20654,
"author_profile": "https://Stackoverflow.com/users/20654",
"pm_score": -1,
"selected": false,
"text": "if (isGood) {\n doSomething();\n}\n if (isNotGood) {\n doSomethngElse();\n}\n"
},
{
"answer_id": 1651254,
"author": "jon-hanson",
"author_id": 84538,
"author_profile": "https://Stackoverflow.com/users/84538",
"pm_score": 1,
"selected": false,
"text": "if (Flag == true)\n if ((Flag == true) == true)\n"
},
{
"answer_id": 1651349,
"author": "Tim",
"author_id": 190106,
"author_profile": "https://Stackoverflow.com/users/190106",
"pm_score": 1,
"selected": false,
"text": "unless($isGood)\n"
}
] | 2008/12/10 | [
"https://Stackoverflow.com/questions/356217",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23855/"
] |
356,219 | <p>Suppose you need to run a program on the world’s fastest supercomputer which will take 10 years to complete. You could:</p>
<ul>
<li>Spend $250M now</li>
<li>Program for 9 years, <a href="http://en.wikipedia.org/wiki/Moore%27s_Law" rel="nofollow noreferrer">Moore’s law</a> speedup (4,000x faster), spend $1M in 10years, complete in 2 weeks.</li>
</ul>
<p><strong>What is the optimum strategy?</strong></p>
<p><sub>Question from "<a href="https://research.microsoft.com/~Gray/talks/IO_talk_2006.ppt" rel="nofollow noreferrer">Long Term Storage Trends and You</a>"</sub></p>
| [
{
"answer_id": 356926,
"author": "Michael Myers",
"author_id": 13531,
"author_profile": "https://Stackoverflow.com/users/13531",
"pm_score": 4,
"selected": true,
"text": "endtime(startyear) = startyear + (calculations / speed(startyear)) speed(year) = speed(year-1.5) endtime(0) = 0 + (calculations/speed(0)) = 10 years speed(0) = calculations/(10 years) speed(year) = speed(0)*4 = (calculations/10)*4 calculations() {\n return 10000000; // random constant (gets cancelled out anyway)\n}\nspeed(year) {\n speed0 = calculations()/10; // constant factor\n return speed0*Math.pow(4.0, year/1.5);\n}\nendtime(startyear) {\n return startyear + calculations()/speed(startyear);\n}\nfindmin() {\n start = 0.0;\n finish = 10.0;\n result = 0.0;\n // home in on the best solution (there should only be one minimum)\n for (inc = 1; inc > 0.00000001; inc /= 2.0) {\n result = findmin(start,finish,inc);\n start = result-2*inc;\n finish = result+inc;\n }\n print(\"Minimum value is \" + result + \", taking a total of \" +\n endtime(result) + \" years\");\n}\nfindmin(start,finish,inc) {\n lastNum = 0;\n lastVal = Double.MAX_VALUE;\n for (i = start; i < finish; i += inc) {\n result = endtime(i);\n if (result > lastVal) {\n print(\"Minimum value between \" + start + \" and \" + finish +\n \" is \" + lastVal + \", occurring at \" + lastNum);\n return i;\n }\n lastNum = i;\n lastVal = result;\n }\n return lastNum;\n}\n bsh % source(\"moore.bsh\");\nbsh % findmin();\nMinimum value between 0.0 and 10.0 is 3.5749013123685915, occurring at 2.0\nMinimum value between 1.0 and 4.0 is 3.4921256574801243, occurring at 2.5\nMinimum value between 2.0 and 3.5 is 3.4921256574801243, occurring at 2.5\nMinimum value between 2.25 and 3.0 is 3.4886233976754246, occurring at 2.375\nMinimum value between 2.25 and 2.625 is 3.488620519067143, occurring at 2.4375\nMinimum value between 2.375 and 2.5625 is 3.488170701257679, occurring at 2.40625\nMinimum value between 2.375 and 2.46875 is 3.488170701257679, occurring at 2.40625\nMinimum value between 2.390625 and 2.4375 is 3.488170701257679, occurring at 2.40625\n(snip)\nMinimum value between 2.406149387359619 and 2.4061494767665863 is 3.4881706965827037,\noccurring at 2.4061494171619415\nMinimum value is 2.4061494320631027, taking a total of 3.488170696582704 years\n endtime(x) = x + c/speed(x) (where c = calculations)\nspeed(x) = speed(0) * 4^(x/1.5) = (c/10)*4^(2x/3)\n=> endtime(x) = x + c/((c/10)*4^(2x/3))\n = x + 10*(4^(-2x/3))\nd/dx endtime(x) = 1 + 10*ln(4)*(-2/3)*(4^(-2x/3))\n 1 + 10*ln(4)*(-2/3)*(4^(-2x/3)) = 0\n=> 4^(-2x/3) = 1/(10*ln(4)*(2/3))\n -2x/3 = ln(1/(10*ln(4)*(2/3))) / ln(4)\n = -ln(10*ln(4)*2/3) / ln(4)\n=> x = (-3/2) * -ln(1/(10*ln(4)*2/3)) / ln(4)\n = 3*ln(10*ln(4)*(2/3)) / 2*ln(4)\n -(some constant)*4"
}
] | 2008/12/10 | [
"https://Stackoverflow.com/questions/356219",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/383/"
] |
356,243 | <p>What I want to do is basically this: on <strong>ONE</strong> page, my customers can click a <strong>VIEW CART</strong> link and the contents of their cart shows below on that same page. Here is my basic link form:</p>
<pre><code> <FORM METHOD=post ACTION="http://www.123websiteservices.com/cgi-bin/cybercart.pl">
<INPUT TYPE=hidden NAME=merchant VALUE="jessicas"/>
<INPUT TYPE=hidden NAME=action VALUE=order/>
<INPUT TYPE=hidden NAME=page_name VALUE="homepage.html"/>
<INPUT TYPE=image src="http://www.123websiteservices.com/~jessicas/images/viewcart.gif" border=0/></FORM>
</code></pre>
<p>I can't figure out how to wrap JavaScript around it to make it work. Any help is greatly appreciated!</p>
| [
{
"answer_id": 356272,
"author": "Stephen Wrighton",
"author_id": 7516,
"author_profile": "https://Stackoverflow.com/users/7516",
"pm_score": 1,
"selected": false,
"text": "< script>\nfunction ShowScript() {\n // Do Your Show cart stuff here \n return false\n}\n< /script>\n\n...\n\n< input type=\"image\" src=\"viewcart.gif\" onClick=\"return ShowScript();\" />\n"
},
{
"answer_id": 356429,
"author": "Jess",
"author_id": 45002,
"author_profile": "https://Stackoverflow.com/users/45002",
"pm_score": 0,
"selected": false,
"text": "< FORM METHOD=post ACTION=\"http://www.123websiteservices.com/cgi-bin/cybercart.pl\">\n< INPUT TYPE=hidden NAME=merchant VALUE=\"jessicas\">\n< INPUT TYPE=hidden NAME=action VALUE=order>\n< INPUT TYPE=hidden NAME=page_name VALUE=\"viewcart.html\">\n< script>function ShowScript() { \n // !!! Don't know what \"show cart stuff needs to go here!!!\n return false}< /script>...<input type=\"image\" src=\"viewcart.gif\" onClick=\"return ShowScript();\" /></FORM >\n"
}
] | 2008/12/10 | [
"https://Stackoverflow.com/questions/356243",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/45002/"
] |
356,248 | <p>I have a deceptively simple scenario, and I want a simple solution, but it's not obvious which is "most correct" or "most Java".</p>
<p>Let's say I have a small authenticate(Client client) method in some class. The authentication could fail for a number of reasons, and I want to return a simple boolean for control flow, but also return a String message for the user. These are the possibilities I can think of:</p>
<ul>
<li>Return a boolean, and pass in a StringBuilder to collect the message. This is the closest to a C-style way of doing it.</li>
<li>Throw an exception instead of returning false, and include the message. I don't like this since failure is not exceptional.</li>
<li>Create a new class called AuthenticationStatus with the boolean and the String. This seems like overkill for one small method.</li>
<li>Store the message in a member variable. This would introduce a potential race condition, and I don't like that it implies some state that isn't really there.</li>
</ul>
<p>Any other suggestions?</p>
<p><strong>Edit</strong> Missed this option off</p>
<ul>
<li>Return null for success - Is this unsafe?</li>
</ul>
<p><strong>Edit</strong> Solution:</p>
<p>I went for the most OO solution and created a small AuthenticationResult class. I wouldn't do this in any other language, but I like it in Java. I also liked the suggestion
of returning an String[] since it's like the null return but safer. One advantage of the Result class is that you can have a success message with further details if required.</p>
| [
{
"answer_id": 356287,
"author": "adam",
"author_id": 33604,
"author_profile": "https://Stackoverflow.com/users/33604",
"pm_score": 4,
"selected": false,
"text": "try {\n AuthenticateMethod();\n} catch (AuthenticateError ae) { \n // Display ae.getMessage() to user..\n System.out.println(ae.getMessage());\n //ae.printStackTrace(); \n}\n"
},
{
"answer_id": 356293,
"author": "Bas Leijdekkers",
"author_id": 4510,
"author_profile": "https://Stackoverflow.com/users/4510",
"pm_score": 2,
"selected": false,
"text": "class Tuple<L, R> {\n\n public final L left;\n public final R right;\n\n public Tuple( L left, R right) {\n this.left = left;\n this.right = right;\n }\n}\n"
},
{
"answer_id": 356320,
"author": "bruno conde",
"author_id": 31136,
"author_profile": "https://Stackoverflow.com/users/31136",
"pm_score": -1,
"selected": false,
"text": "public boolean authenticate(Client client, final StringBuilder sb) {\n if (sb == null)\n throw new IllegalArgumentException();\n if (isOK()) {\n sb.append(\"info message\");\n return true;\n } else {\n sb.append(\"error message\");\n return false;\n }\n}\n"
},
{
"answer_id": 356326,
"author": "Ma99uS",
"author_id": 20390,
"author_profile": "https://Stackoverflow.com/users/20390",
"pm_score": -1,
"selected": false,
"text": "public static void main(String[] args)\n{\n Object[] result = methodReturningStatus();\n if(!(Boolean)result[0])\n System.out.println(\"Method return: \"+ result[1]);\n}\n\nstatic Object[] methodReturningStatus()\n{\n Object[] result = new Object[2];\n\n result[0] = false;\n result[1] = \"Error happened\";\n\n return result;\n}\n"
},
{
"answer_id": 356335,
"author": "Olivier",
"author_id": 43585,
"author_profile": "https://Stackoverflow.com/users/43585",
"pm_score": 0,
"selected": false,
"text": "\nclass SomeClass {\npublic int authenticate (Client client) {\n//returns 0 if success otherwise one value per possible failure\n}\npublic String getAuthenticationResultMessage (int authenticateResult) {}\n//returns message associated to authenticateResult\n}\n"
},
{
"answer_id": 356415,
"author": "Apocalisp",
"author_id": 3434,
"author_profile": "https://Stackoverflow.com/users/3434",
"pm_score": 3,
"selected": false,
"text": "P2<A, B> Option<T> Some<T> None<T> Option Iterable<T> public Option<String> authenticate(String arg) {\n if (success(arg))\n return Option.some(\"Just an example\");\n else\n return Option.none();\n}\n\n...\n\nfor(String s : authenticate(secret)) {\n privilegedMethod();\n}\n Either<L, R> L R Iterable<T> L R public Either<Fail, String> authenticate(String arg) {\n if (success(arg))\n return Either.right(\"Just an example\");\n else\n return Either.left(Fail.authenticationFailure());\n}\n\n...\n\nEither<Fail, String> auth = authenticate(secret);\nfor(String s : auth.rightProjection()) {\n privilegedMethod();\n}\nfor(Fail f : auth.leftProjection()) {\n System.out.println(\"FAIL\");\n}\n P2 Option Either"
},
{
"answer_id": 356875,
"author": "Markus",
"author_id": 45064,
"author_profile": "https://Stackoverflow.com/users/45064",
"pm_score": 0,
"selected": false,
"text": "if (authenticate()) {\n // normal behaviour...\n}\nelse {\n // error case...\n}\n authenticate();\n// normal behaviour...\n if (isAuthenticated()) {\n//...\n}\n"
}
] | 2008/12/10 | [
"https://Stackoverflow.com/questions/356248",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/26334/"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.