qid int64 4 19.1M | question stringlengths 18 48.3k | answers list | date stringlengths 10 10 | metadata list |
|---|---|---|---|---|
324,245 | <p>I have a asp.net web application which has a number of versions deployed on different customer servers inside their networks. One practice that we have is to have clients email screenshots when they have issues.</p>
<p>In the old asp.net 1.1 days, we could grab details of the build DLL, using reflection, and show info about the build date and numbering on the screen in a subtle location.</p>
<p>With .NET 2.0 and higher, the build model changed, and this mechanism no longer works. I have heard of different build systems out there, but I'm really looking for the simplest way, on the 3.5 framework, to do what this functionality did on framework 1.1.</p>
<ol>
<li>Every time a build is performed, update the build date/time, and somehow update the build number</li>
<li>Be able to see the build timestamp and number, to display on the screen</li>
<li>be as simple to implement as possible </li>
</ol>
| [
{
"answer_id": 324279,
"author": "g .",
"author_id": 6944,
"author_profile": "https://Stackoverflow.com/users/6944",
"pm_score": 5,
"selected": true,
"text": "Assembly assembly = Assembly.GetExecutingAssembly();\nstring version = assembly.GetName().Version.ToString();\nstring buildDate = ((AssemblyDescriptionAttribute)Attribute.GetCustomAttribute(\n assembly, typeof(AssemblyDescriptionAttribute))).Description;\n <asminfo output=\"Properties\\AssemblyInfo.cs\" language=\"CSharp\">\n <imports>\n <import namespace=\"System\" />\n <import namespace=\"System.Reflection\" />\n <import namespace=\"System.Runtime.CompilerServices\" />\n <import namespace=\"System.Runtime.InteropServices\" />\n </imports>\n <attributes>\n <attribute type=\"AssemblyVersionAttribute\" value=\"${assembly.version}\" />\n <attribute type=\"AssemblyInformationalVersionAttribute\" value=\"${assembly.version}\" />\n <attribute type=\"AssemblyDescriptionAttribute\" value=\"${datetime::now()}\" />\n ...\n </attributes>\n </asminfo>\n"
},
{
"answer_id": 381792,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 4,
"selected": false,
"text": "private System.DateTime BuildDate()\n{\n\n//This ONLY works if the assembly was built using VS.NET and the assembly version attribute is set to something like the below. The asterisk (*) is the important part, as if present, VS.NET generates both the build and revision numbers automatically.\n//<Assembly: AssemblyVersion(\"1.0.*\")> \n//Note for app the version is set by opening the 'My Project' file and clicking on the 'assembly information' button. \n//An alternative method is to simply read the last time the file was written, using something similar to:\n//Return System.IO.File.GetLastWriteTime(System.Reflection.Assembly.GetExecutingAssembly.Location)\n\n//Build dates start from 01/01/2000\n\nSystem.DateTime result = DateTime.Parse(\"1/1/2000\");\n\n//Retrieve the version information from the assembly from which this code is being executed\n\nSystem.Version version = System.Reflection.Assembly.GetExecutingAssembly().GetName().Version;\n\n//Add the number of days (build)\n\nresult = result.AddDays(version.Build);\n\n//Add the number of seconds since midnight (revision) multiplied by 2\n\nresult = result.AddSeconds(version.Revision * 2);\n\n//If we're currently in daylight saving time add an extra hour\n\nif (TimeZone.IsDaylightSavingTime(System.DateTime.Now, TimeZone.CurrentTimeZone.GetDaylightChanges(System.DateTime.Now.Year)))\n{\n result = result.AddHours(1);\n}\n\nreturn result;\n\n}\n"
},
{
"answer_id": 677402,
"author": "Jørn Jensen",
"author_id": 34585,
"author_profile": "https://Stackoverflow.com/users/34585",
"pm_score": 5,
"selected": false,
"text": "lblVersion.Text = String.Format(\"Version: {0}<br>Dated: {1}\",\n System.Reflection.Assembly.GetExecutingAssembly().GetName().Version.ToString(),\n System.IO.File.GetLastWriteTime(System.Reflection.Assembly.GetExecutingAssembly().Location).ToShortDateString());\n"
}
] | 2008/11/27 | [
"https://Stackoverflow.com/questions/324245",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/24126/"
] |
324,258 | <p>I find the .Net FileSystemWatcher class really handy for writing utilities that automatically come to life when files show up in their watched folders. Is there any equivalent to this functionality in the *nix world that would allow me to watch a folder (and possibly all of its subdirectories)?</p>
<p><strong>Edit:</strong> Preferably this will be something that doesn't require kernel patches.</p>
| [
{
"answer_id": 4501060,
"author": "J Mills",
"author_id": 1121437,
"author_profile": "https://Stackoverflow.com/users/1121437",
"pm_score": 4,
"selected": false,
"text": "using System;\nusing System.Collections.Generic;\nusing System.Collections;\nusing System.Text;\nusing System.IO;\nusing System.Reflection;\n\nnamespace FileSystemWatcherSandbox\n{\n public class Program\n {\n static void Main(string[] args)\n {\n foreach(DictionaryEntry de in Environment.GetEnvironmentVariables())\n {\n Console.WriteLine(\"{0} = {1}\",de.Key,de.Value);\n }\n string basePath = AppDomain.CurrentDomain.BaseDirectory;\n Console.WriteLine(\"watching: {0}\", basePath);\n FileSystemWatcher fsw = new FileSystemWatcher(basePath);\n fsw.Changed += new FileSystemEventHandler(fsw_Changed);\n fsw.Created += new FileSystemEventHandler(fsw_Created);\n fsw.Deleted += new FileSystemEventHandler(fsw_Deleted);\n fsw.Error += new ErrorEventHandler(fsw_Error);\n fsw.Renamed += new RenamedEventHandler(fsw_Renamed);\n fsw.EnableRaisingEvents = true;\n fsw.IncludeSubdirectories = true;\n while (true)\n {\n WaitForChangedResult result = fsw.WaitForChanged(WatcherChangeTypes.All,10000);\n Console.WriteLine(result.TimedOut ? \"Time out\" : \"hmmm\");\n }\n }\n\n static void fsw_Renamed(object sender, RenamedEventArgs e)\n {\n Console.WriteLine(\"({0}): {1} | {2}\", MethodInfo.GetCurrentMethod().Name, e.ChangeType, e.FullPath);\n }\n\n static void fsw_Error(object sender, ErrorEventArgs e)\n {\n Console.WriteLine(\"({0}): {1}\", MethodInfo.GetCurrentMethod().Name, e.GetException().Message);\n }\n\n static void fsw_Deleted(object sender, FileSystemEventArgs e)\n {\n Console.WriteLine(\"({0}): {1} | {2}\", MethodInfo.GetCurrentMethod().Name, e.ChangeType, e.FullPath);\n }\n\n static void fsw_Created(object sender, FileSystemEventArgs e)\n {\n Console.WriteLine(\"({0}): {1} | {2}\", MethodInfo.GetCurrentMethod().Name, e.ChangeType, e.FullPath);\n }\n\n static void fsw_Changed(object sender, FileSystemEventArgs e)\n {\n Console.WriteLine(\"({0}): {1} | {2}\", MethodInfo.GetCurrentMethod().Name, e.ChangeType, e.FullPath);\n }\n }\n}\n"
}
] | 2008/11/27 | [
"https://Stackoverflow.com/questions/324258",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/327/"
] |
324,261 | <p>I'm compiling a vc8 C++ project in a WinXp VmWare session. It's a hell of a lot slower than gcc3.2 in a RedHat VmWare session, so I'm looking at Task Manager. It's saying a very large percentage of my compile process is spent in the kernel. That doesn't sounds right to me.</p>
<p>Is there an equivalent of strace for Win32? At least something which will give me an overview of which kernel functions are being called. There might be something that stands out as being the culprit.</p>
| [
{
"answer_id": 324298,
"author": "Barry Kelly",
"author_id": 3712,
"author_profile": "https://Stackoverflow.com/users/3712",
"pm_score": 2,
"selected": false,
"text": "SRV*C:\\symbolcache*http://msdl.microsoft.com/download/symbols\n"
},
{
"answer_id": 324452,
"author": "atzz",
"author_id": 23252,
"author_profile": "https://Stackoverflow.com/users/23252",
"pm_score": 2,
"selected": false,
"text": "kernrate"
}
] | 2008/11/27 | [
"https://Stackoverflow.com/questions/324261",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23434/"
] |
324,267 | <p>How do I create a batch file to delete files older than a specified date?</p>
<p>This does not seem to work;</p>
<pre><code>:: --------DELOLD.BAT----------
@echo off
SET OLDERTHAN=%1
IF NOT DEFINED OLDERTHAN GOTO SYNTAX
for /f "tokens=2" %%i in ('date /t') do set thedate=%%i
type %1
pause
set mm=%thedate:~0,2%
set dd=%thedate:~3,2%
set yyyy=%thedate:~6,4%
set /A dd=%dd% - %OLDERTHAN%
set /A mm=%mm% + 0
if /I %dd% GTR 0 goto DONE
set /A mm=%mm% - 1
if /I %mm% GTR 0 goto ADJUSTDAY
set /A mm=12
set /A yyyy=%yyyy% - 1
:ADJUSTDAY
if %mm%==1 goto SET31
if %mm%==2 goto LEAPCHK
if %mm%==3 goto SET31
if %mm%==4 goto SET30
if %mm%==5 goto SET31
if %mm%==6 goto SET30
if %mm%==7 goto SET31
if %mm%==8 goto SET31
if %mm%==9 goto SET30
if %mm%==10 goto SET31
if %mm%==11 goto SET30
if %mm%==12 goto SET31
goto ERROR
:SET31
set /A dd=31 + %dd%
goto DONE
:SET30
set /A dd=30 + %dd%
goto DONE
:LEAPCHK
set /A tt=%yyyy% %% 4
if not %tt%==0 goto SET28
set /A tt=%yyyy% %% 100
if not %tt%==0 goto SET29
set /A tt=%yyyy% %% 400
if %tt%==0 goto SET29
:SET28
set /A dd=28 + %dd%
goto DONE
:SET29
set /A dd=29 + %dd%
:DONE
if /i %dd% LSS 10 set dd=0%dd%
if /I %mm% LSS 10 set mm=0%mm%
for %%i in (*.*) do (
set FileName=%%i
call :PROCESSFILE %%~ti
)
set mm=
set yyyy=
set dd=
set thedate=
goto EXIT
:SYNTAX
ECHO.
ECHO USAGE:
ECHO DELOLD X
ECHO Where X is the number of days previous to Today.
ECHO.
ECHO EX: "DELOLD 5" Deletes files older than 5 days.
GOTO EXIT
:PROCESSFILE
set temp=%1
set fyyyy=20%temp:~6%
set fmm=%temp:~0,2%
set fdd=%temp:~3,2%
if /I %fyyyy% GTR 2069 set fyyyy=19%temp:~6%
:: ***************************************
:: * This is where the files are deleted *
:: * Change the ECHO command to DEL to *
:: * delete. ECHO is used for test. *
:: ***************************************
if /I %yyyy%/%mm%/%dd% GEQ %fyyyy%/%fmm%/%fdd% (
ECHO %FileName%
)
set temp=
set fyyyy=
set fmm=
set fdd=
:EXIT
:: ----------END-DELOLD.BAT-------------
</code></pre>
| [
{
"answer_id": 324349,
"author": "e.James",
"author_id": 33686,
"author_profile": "https://Stackoverflow.com/users/33686",
"pm_score": 3,
"selected": false,
"text": "REM del_old.bat\nREM usage: del_old MM-DD-YYY\nfor /f \"tokens=*\" %%a IN ('xcopy *.* /d:%1 /L /I null') do if exist %%~nxa echo %%~nxa >> FILES_TO_KEEP.TXT\nfor /f \"tokens=*\" %%a IN ('xcopy *.* /L /I /EXCLUDE:FILES_TO_KEEP.TXT null') do if exist \"%%~nxa\" del \"%%~nxa\" REM del_new.bat\nREM usage: del_new MM-DD-YYYY\nfor /f \"tokens=*\" %%a IN ('xcopy *.* /d:%1 /L /I null') do if exist \"%%~nxa\" del \"%%~nxa\""
},
{
"answer_id": 324412,
"author": "Vincent Robert",
"author_id": 268,
"author_profile": "https://Stackoverflow.com/users/268",
"pm_score": 3,
"selected": false,
"text": "////////////////////////////////////////////////////////\n// Deletes file older than a number of days \n// in the current directory\n////////////////////////////////////////////////////////\n// Usage: wscript DeleteOlderThan.js [#Days]\n// By default, remove files older than 30 days\n////////////////////////////////////////////////////////\n\nfunction removeDays(date, nDays)\n{\n var dateRet = date\n return dateRet.setDate(date.getDate() - nDays);\n}\n\nfunction addSlash(strPath)\n{\n var c = strPath.substr(-1, 1);\n if( c !== '\\\\' && c !== '/' )\n {\n strPath += '\\\\';\n }\n return strPath;\n}\n\n// Read arguments\nvar nDays = WScript.Arguments(0) || 30;\n\n// Create system objects\nvar fs = WScript.CreateObject(\"Scripting.FileSystemObject\");\nvar shell = WScript.CreateObject(\"WScript.Shell\");\n\n// Retrieve current directory\nvar strDirectoryPath = addSlash(shell.CurrentDirectory);\n\n// Compute date\nvar dateNow = new Date();\nvar dateTest = removeDays(dateNow, nDays);\n\n// Iterate on files\nvar folder = fs.GetFolder(strDirectoryPath);\nvar files = folder.Files;\n\nfor( var it = new Enumerator(files); !it.atEnd(); it.moveNext() )\n{\n var file = it.item();\n\n if( file.DateLastModified < dateTest)\n {\n file.Delete(true);\n }\n}\n wscript \"C:\\Program Files\\Utils\\DeletesOlderThan.js\" 30\n"
},
{
"answer_id": 324480,
"author": "atzz",
"author_id": 23252,
"author_profile": "https://Stackoverflow.com/users/23252",
"pm_score": 1,
"selected": false,
"text": "touch date touch date /T date <param> for /f %%I in ('dir /od')"
},
{
"answer_id": 1180746,
"author": "HerbCSO",
"author_id": 120818,
"author_profile": "https://Stackoverflow.com/users/120818",
"pm_score": 3,
"selected": false,
"text": "@echo off\nSET OLDERTHAN=%1\nIF NOT DEFINED OLDERTHAN GOTO SYNTAX\n\necho >> ~~~FILES_TO_KEEP.TXT~\nfor /f \"tokens=*\" %%a IN ('xcopy *.pdf /d:%1 /L /I null') do if exist %%~nxa echo %%~nxa >> ~~~FILES_TO_KEEP.TXT~\nfor /f \"tokens=*\" %%a IN ('xcopy *.pdf /L /I /EXCLUDE:~~~FILES_TO_KEEP.TXT~ null') do if exist \"%%~nxa\" del \"%%~nxa\"\ndel ~~~FILES_TO_KEEP.TXT~\n\nGOTO END\n\n:SYNTAX\nECHO.\nECHO USAGE:\nECHO DELOLD mm-dd-yyyy\nECHO Where mm-dd-yyyy is the date prior to which you want to delete files.\nECHO.\nECHO EX: \"DELOLD 10-17-2008\" Deletes files older than October 17, 2008.\nECHO.\nECHO This should work on any language version of Windows, but has only been \nECHO tested in English-US versions.\nGOTO END\n\n:END\n"
},
{
"answer_id": 2017729,
"author": "ℳ .",
"author_id": 10660,
"author_profile": "https://Stackoverflow.com/users/10660",
"pm_score": 3,
"selected": false,
"text": "forfiles /S /D -180 /C \"cmd /C Echo @Path\" >olderthan180days.txt\n forfiles /S /M *.pdf /D -365 /C \"cmd /C Del @Path\"\n"
}
] | 2008/11/27 | [
"https://Stackoverflow.com/questions/324267",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
324,284 | <p>What's the best way to throw an exception in objective-c/cocoa?</p>
| [
{
"answer_id": 324301,
"author": "e.James",
"author_id": 33686,
"author_profile": "https://Stackoverflow.com/users/33686",
"pm_score": 10,
"selected": true,
"text": "[NSException raise:format:] [NSException raise:@\"Invalid foo value\" format:@\"foo of %d is invalid\", foo];"
},
{
"answer_id": 324451,
"author": "Peter Hosey",
"author_id": 30461,
"author_profile": "https://Stackoverflow.com/users/30461",
"pm_score": 6,
"selected": false,
"text": "@throw([NSException exceptionWith…])\n @throw return @throw [NSException raise:…] @throw"
},
{
"answer_id": 324745,
"author": "rustyshelf",
"author_id": 6044,
"author_profile": "https://Stackoverflow.com/users/6044",
"pm_score": 4,
"selected": false,
"text": "@try {\n.....\n}\n@catch{\n...\n}\n@finally{\n...\n}\n"
},
{
"answer_id": 1098438,
"author": "Daniel Yankowsky",
"author_id": 120278,
"author_profile": "https://Stackoverflow.com/users/120278",
"pm_score": 5,
"selected": false,
"text": "[NSException raise:format:]"
},
{
"answer_id": 14478146,
"author": "Subbu",
"author_id": 1726647,
"author_profile": "https://Stackoverflow.com/users/1726647",
"pm_score": 3,
"selected": false,
"text": "@throw[NSException exceptionWithName];\n NSException e;\n[e raise];\n"
},
{
"answer_id": 23603375,
"author": "Johannes",
"author_id": 89862,
"author_profile": "https://Stackoverflow.com/users/89862",
"pm_score": 3,
"selected": false,
"text": "@throw [NSException exceptionWithName:@\"Something is not right exception\"\n reason:@\"Can't perform this operation because of this or that\"\n userInfo:nil];\n"
},
{
"answer_id": 47200770,
"author": "Aleksandr B.",
"author_id": 7599955,
"author_profile": "https://Stackoverflow.com/users/7599955",
"pm_score": 0,
"selected": false,
"text": "- (void)parseError:(NSError *)error\n completionBlock:(void (^)(NSString *error))completionBlock {\n\n\n NSString *resultString = [NSString new];\n\n @try {\n\n NSData *errorData = [NSData dataWithData:error.userInfo[@\"SomeKeyForData\"]];\n\n if(!errorData.bytes) {\n\n @throw([NSException exceptionWithName:@\"<Set Yours exc. name: > Test Exc\" reason:@\"<Describe reason: > Doesn't contain data\" userInfo:nil]);\n }\n\n\n NSDictionary *dictFromData = [NSJSONSerialization JSONObjectWithData:errorData\n options:NSJSONReadingAllowFragments\n error:&error];\n\n resultString = dictFromData[@\"someKey\"];\n ...\n\n\n} @catch (NSException *exception) {\n\n NSLog( @\"Caught Exception Name: %@\", exception.name);\n NSLog( @\"Caught Exception Reason: %@\", exception.reason );\n\n resultString = exception.reason;\n\n} @finally {\n\n completionBlock(resultString);\n}\n [self parseError:error completionBlock:^(NSString *error) {\n NSLog(@\"%@\", error);\n }];\n - (void)parseError:(NSError *)error completionBlock:(void (^)(NSString *error))completionBlock {\n\nNSString *resultString = [NSString new];\n\nNSException* customNilException = [NSException exceptionWithName:@\"NilException\"\n reason:@\"object is nil\"\n userInfo:nil];\n\nNSException* customNotNumberException = [NSException exceptionWithName:@\"NotNumberException\"\n reason:@\"object is not a NSNumber\"\n userInfo:nil];\n\n@try {\n\n NSData *errorData = [NSData dataWithData:error.userInfo[@\"SomeKeyForData\"]];\n\n if(!errorData.bytes) {\n\n @throw([NSException exceptionWithName:@\"<Set Yours exc. name: > Test Exc\" reason:@\"<Describe reason: > Doesn't contain data\" userInfo:nil]);\n }\n\n\n NSDictionary *dictFromData = [NSJSONSerialization JSONObjectWithData:errorData\n options:NSJSONReadingAllowFragments\n error:&error];\n\n NSArray * array = dictFromData[@\"someArrayKey\"];\n\n for (NSInteger i=0; i < array.count; i++) {\n\n id resultString = array[i];\n\n if (![resultString isKindOfClass:NSNumber.class]) {\n\n [customNotNumberException raise]; // <====== HERE is just the same as: @throw customNotNumberException;\n\n break;\n\n } else if (!resultString){\n\n @throw customNilException; // <======\n\n break;\n }\n\n }\n\n} @catch (SomeCustomException * sce) {\n // most specific type\n // handle exception ce\n //...\n} @catch (CustomException * ce) {\n // most specific type\n // handle exception ce\n //...\n} @catch (NSException *exception) {\n // less specific type\n\n // do whatever recovery is necessary at his level\n //...\n // rethrow the exception so it's handled at a higher level\n\n @throw (SomeCustomException * customException);\n\n} @finally {\n // perform tasks necessary whether exception occurred or not\n\n}\n"
}
] | 2008/11/27 | [
"https://Stackoverflow.com/questions/324284",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/36182/"
] |
324,289 | <p>If I have several <code>Section</code> elements in an XML document, what XQuery do I use to get a list of all the <code>name</code> values?</p>
<pre><code><Section name="New Clients" filePath="XNEWCUST.TXT" skipSection="False">
</code></pre>
| [
{
"answer_id": 324299,
"author": "James Curran",
"author_id": 12725,
"author_profile": "https://Stackoverflow.com/users/12725",
"pm_score": 0,
"selected": false,
"text": " /Section/@name\n"
},
{
"answer_id": 324339,
"author": "Dimitre Novatchev",
"author_id": 36305,
"author_profile": "https://Stackoverflow.com/users/36305",
"pm_score": 4,
"selected": true,
"text": "for $attr in //Section/@name\n return string($attr)\n"
},
{
"answer_id": 324415,
"author": "Oliver Hallam",
"author_id": 19995,
"author_profile": "https://Stackoverflow.com/users/19995",
"pm_score": 1,
"selected": false,
"text": "//Section/@name\n //Section/@name/string(.)\n"
}
] | 2008/11/27 | [
"https://Stackoverflow.com/questions/324289",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8741/"
] |
324,303 | <p>I have html code that looks roughly like this:</p>
<pre><code><div id="id1">
<div id="id2">
<p>some html</p>
<span>maybe some more</span>
</div>
<div id="id3">
<p>different text here</p>
<input type="text">
<span>maybe even a form item</span>
</div>
</div>
</code></pre>
<p>Obviously there's more to it than that, but that's the basic idea. What I need to do is switch the location of #id2 and #id3, so the result is:</p>
<pre><code><div id="id1">
<div id="id3">...</div>
<div id="id2">...</div>
</div>
</code></pre>
<p>Does anyone know of a function (I'm sure I'm not the first person to require this functionality) that can read and write the two nodes (and all their children) so as to swap their location in the DOM?</p>
| [
{
"answer_id": 324308,
"author": "Greg",
"author_id": 24181,
"author_profile": "https://Stackoverflow.com/users/24181",
"pm_score": 7,
"selected": true,
"text": "document.getElementById('id1').appendChild(document.getElementById('id2')); insertBefore()"
},
{
"answer_id": 46595686,
"author": "zfrisch",
"author_id": 3700849,
"author_profile": "https://Stackoverflow.com/users/3700849",
"pm_score": 2,
"selected": false,
"text": "function wrap(node, tag) {\n node.parentNode.insertBefore(document.createElement(tag), node);\n node.previousElementSibling.appendChild(node);\n}\n function wrap(node, tag) {\n node.parentNode.insertBefore(document.createElement(tag), node);\n node.previousElementSibling.appendChild(node);\n}\nlet toWrap = document.querySelector(\"#hi\");\nwrap(toWrap, \"section\");\nconsole.log(document.querySelector(\"section > #hi\"), \" section wrapped element\"); <span id=\"hi\">hello there!</span>"
},
{
"answer_id": 68638127,
"author": "S.Serpooshan",
"author_id": 2803565,
"author_profile": "https://Stackoverflow.com/users/2803565",
"pm_score": 1,
"selected": false,
"text": "appendChild targetElement.insertAdjacentElement(position, element) //beforebegin\n<p>\n //afterbegin\n foo\n //beforeend\n</p>\n//afterend\n document.getElementById('id2').insertAdjacentElement('beforebegin', document.getElementById('id3'));\n function changePosition() {\n document.getElementById('id2').insertAdjacentElement('afterend', document.getElementById('id5'));\n} <div id='container'>\n <div id='id1'>id1</div>\n <div id='id2'><u>id2</u></div> \n <div id='id3'>id3</div> \n <div id='id4'>id4</div> \n <div id='id5'><b>id5</b></div> \n <div id='id6'>id6</div> \n</div>\n\n<p><input type='button' onclick=\"changePosition()\" value=\"change position\"></p>"
},
{
"answer_id": 72151857,
"author": "GBra 4.669",
"author_id": 12184371,
"author_profile": "https://Stackoverflow.com/users/12184371",
"pm_score": 1,
"selected": false,
"text": "document.addEventListener(\"DOMContentLoaded\", function () {\n\n const btnEl = document.getElementById('btn-swap');\n const elToSwap = document.getElementById('id2');\n \n \n btnEl.addEventListener('click', e => {\n elToSwap.classList.toggle(\"first\");\n });\n\n}); .container {\n display: flex;\n flex-direction: column;\n}\n\n.first {\n order: -1;\n} <div class=\"container\">\n <div id=\"id1\">first DIV</div>\n <div id=\"id2\">second DIV</div>\n</div>\n\n<button id=\"btn-swap\">swap divs</button>"
}
] | 2008/11/27 | [
"https://Stackoverflow.com/questions/324303",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/41435/"
] |
324,311 | <p>How can I give a general rule that includes all the expressions below?
E.g one expression, another one for sub and one for mult.
I need to use recursion but i got confused...</p>
<pre><code>simplify :: Expr->Expr
simplify (Mult (Const 0)(Var"x"))
= Const 0
simplify (Mult (Var "x") (Const 0))
= Const 0
simplify (Plus (Const 0) (Var "x"))
= Var "x"
simplify (Plus (Var "x") (Const 0))
= Var "x"
simplify (Mult (Const 1) (Var"x"))
= Var "x"
simplify (Mult(Var"x") (Const 1))
= Var "x"
simplify (Minus (Var"x") (Const 0))
= Var "x"
simplify (Plus (Const x) (Const y))
= Const (x + y)
simplify (Minus (Const x) (Const y))
= Const (x - y)
simplify (Mult (Const x) (Const y))
= Const (x * y)
simplify x = x
</code></pre>
| [
{
"answer_id": 324354,
"author": "Andru Luvisi",
"author_id": 5922,
"author_profile": "https://Stackoverflow.com/users/5922",
"pm_score": 0,
"selected": false,
"text": "simplify (Plus x y) = simplify_one_level (Plus (simplify x) (simplify y))\n"
},
{
"answer_id": 324567,
"author": "Barry Kelly",
"author_id": 3712,
"author_profile": "https://Stackoverflow.com/users/3712",
"pm_score": 3,
"selected": false,
"text": "data Expr = Const Int | Mult Expr Expr | Plus Expr Expr | Var String\n instance Show Expr where\n show (Const n) = show n\n show (Var n) = show n\n show (Plus a b) = (show a) ++ \"+\" ++ (show b)\n show (Mult a b) = \"(\" ++ (show a) ++ \") * (\" ++ (show b) ++ \")\"\n -- Tries to evaluate any constant expressions.\neval :: Expr -> Expr\neval (Mult (Const a) (Const b)) = Const (a * b)\neval (Mult (Const a) b)\n | a == 0 = Const 0\n | a == 1 = b\n | otherwise = (Mult (Const a) b)\neval (Mult a (Const b))\n | b == 0 = Const 0\n | b == 1 = a\n | otherwise = (Mult a (Const b))\neval (Plus (Const a) (Const b)) = Const (a + b)\neval (Plus (Const a) b)\n | a == 0 = b\n | otherwise = (Plus (Const a) b)\neval (Plus a (Const b))\n | b == 0 = a\n | otherwise = (Plus a (Const b))\neval e = e\n -- Tries to match evaluation rules after simplifying subtrees.\nsimplify :: Expr -> Expr\nsimplify (Plus a b) = eval (Plus (simplify a) (simplify b))\nsimplify (Mult a b) = eval (Mult (simplify a) (simplify b))\nsimplify e = e\n"
}
] | 2008/11/27 | [
"https://Stackoverflow.com/questions/324311",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/41000/"
] |
324,315 | <p>I have a degrafa surface into a canvas container.
I want to link both width and height.
When i use binding like it works as expected:</p>
<pre><code>// binding
BindingUtils.bindProperty(rect,"height",this,"height");
BindingUtils.bindProperty(rect,"width",this,"width");
</code></pre>
<p>Now, someone told me that i should do it on validateSize() or updateDisplayList(),
with my current knowledge of flex i dont realy know why but i tried the following</p>
<pre><code>override protected function updateDisplayList(unscaledWidth:Number, unscaledHeight:Number):void {
trace(unscaledWidth, unscaledHeight);
this.width = unscaledWidth;
rect.width =unscaledWidth;
this.height = unscaledHeight;
rect.height = unscaledHeight;
}
</code></pre>
<p>The degrafa rectangle get resized well but not the 'this' canvas container.
They seem to be not binded, did i miss something ?</p>
<p>Also i would like to modify a little bit the relation in rect.width = this.width with some factor in it which i cant do using the bindproperty method.</p>
<p>Thanks a lot for any clue.</p>
| [
{
"answer_id": 324551,
"author": "coulix",
"author_id": 32032,
"author_profile": "https://Stackoverflow.com/users/32032",
"pm_score": 0,
"selected": false,
"text": "public class RectangleShape extends BaseShape \n{\npublic function RectangleShape(fillColor:int) {\n super.name = shapeName;\n solidFill.color = fillColor;\n\n\n // shape\n solidFill.alpha = 0.3;\n rect.fill = solidFill;\n rect.stroke = solidStroke; \n geoGroup.geometryCollection.addItem(rect); \n geoGroup.target = surface;\n\n surface.graphicsCollection.addItem(geoGroup); \n this.addChild(surface);\n\n // binding\n // BindingUtils.bindProperty(rect,\"height\",this,\"height\"); \n // BindingUtils.bindProperty(rect,\"width\",this,\"width\"); \n}\n\n\n\n\n override protected function updateDisplayList(unscaledWidth:Number, unscaledHeight:Number):void {\n\n trace(unscaledWidth, unscaledHeight);\n this.width = unscaledWidth;\n rect.width =unscaledWidth;\n this.height = unscaledHeight;\n rect.height = unscaledHeight;\n\n}\n"
},
{
"answer_id": 10106388,
"author": "Janroel",
"author_id": 1326633,
"author_profile": "https://Stackoverflow.com/users/1326633",
"pm_score": 1,
"selected": false,
"text": "super.updateDisplayList(unscaledWidth, unscaledHeight); \n"
},
{
"answer_id": 10109421,
"author": "Sunil D.",
"author_id": 398606,
"author_profile": "https://Stackoverflow.com/users/398606",
"pm_score": 0,
"selected": false,
"text": "updateDisplayList() this.width=100 updateDisplayList() updateDisplayList() unscaledWidth unscaledHeight updateDisplayList() setActualSize() move() setLayoutBoundsSize() setLayoutBoundsPosition() updateDisplayList() override protected function updateDisplayList(unscaledWidth:Number, unscaledHeight:Number):void {\n\n trace(unscaledWidth, unscaledHeight);\n\n // like Janroel said above, you should call the super class method\n // the only time you don't need to is when your component extends UIComponent\n // (because UIComponent's updateDisplayList doesn't do anything)\n super.updateDisplayList(unscaledWidth, unscaledHeight);\n\n // don't do this (your component will get sized by its parent)\n //this.width = unscaledWidth;\n // if 'rect' inherits from UIComponent you should use the setActualSize() method:\n rect.setActualSize(unscaledWidth, unscaledHeight);\n // if it doesn't inherit from UIComponent, do it the regular way...\n rect.width =unscaledWidth;\n //this.height = unscaledHeight;\n rect.height = unscaledHeight;\n}\n"
}
] | 2008/11/27 | [
"https://Stackoverflow.com/questions/324315",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/32032/"
] |
324,341 | <p>I may be going about this backwards...
I have a class which is like a document and another class which is like a template. They both inherit from the same base class and I have a method to create a new document from a template (or from another document, the method it is in the base class).
So, if I want to create a new document from a template, I just instantiate the template and call GetNewDoc() on it;</p>
<pre><code>Document doc = mytemplate.GetNewDoc();
</code></pre>
<p>In the Document class I have a blank constructor creating a new, blank document as well as another constructor that takes a document ID so I can load the document from the database. However, I would also like a constructor that takes a Template ID. This way I can do</p>
<pre><code>Document doc = New Document(TemplateID)
</code></pre>
<p>Because the template class already has the ability to return a document, I'd like the constructor to do something like</p>
<pre><code>Template temp = new Template(TemplateID);
this = temp.GetNewDoc();
</code></pre>
<p>Of course, I can't do this as "this" is read-only - and it feels odd anyway. I have a feeling I am being very stupid here so feel free to shout :)</p>
<p>The thing is that the object in question is pretty complex with several collections of child objects and database persistence over multiple tables so i don't want to duplicate too much code. Though, I guess I could just get the new document from the template and then copy the fields/properties across as the collections should follow easily enough - it just seems like duplication.</p>
<p>A more elaborate code example:</p>
<p><code></p>
<pre><code>using System;
using System.Collections.Generic;
using System.Text;
namespace Test
{
class Program
{
static void Main(string[] args)
{
// This just creates the object and assigns a value
Instance inst = new Instance();
inst.name = "Manually created";
Console.WriteLine("Direct: {0}", inst.name);
//This creates a new instance directly from a template
MyTemplate def = new MyTemplate();
Instance inst2 = def.GetInstance(100);
Console.WriteLine("Direct from template: {0}", inst2.name);
Instance inst3 = new Instance(101);
Console.WriteLine("Constructor called the template: {0}", inst3.name);
Console.ReadKey();
}
}
public class Instance
{
public string name;
public Instance(int TemplateID)
{
MyTemplate def = new MyTemplate();
//If I uncomment this line the build will fail
//this = def.GetInstance(TemplateID);
}
public Instance()
{
}
}
class MyTemplate
{
public Instance GetInstance(int TemplateID)
{
Instance inst = new Instance();
//Find the template in the DB and get some values
inst.name = String.Format("From template: {0}", TemplateID.ToString());
return inst;
}
}
}
</code></pre>
<p></code></p>
| [
{
"answer_id": 324356,
"author": "Jon Skeet",
"author_id": 22656,
"author_profile": "https://Stackoverflow.com/users/22656",
"pm_score": 4,
"selected": true,
"text": "public static Instance CreateInstance(int id)\n{\n MyTemplate def = new MyTemplate();\n return def.GetInstance(id);\n}\n"
},
{
"answer_id": 324365,
"author": "David Rodríguez - dribeas",
"author_id": 36565,
"author_profile": "https://Stackoverflow.com/users/36565",
"pm_score": 2,
"selected": false,
"text": "public class Factory {\n public static Document createBlankDocument();\n public static Document createDocument( DocumentId id );\n public static Document createDocumentFromTemplate( TemplateId id );\n}\n"
}
] | 2008/11/27 | [
"https://Stackoverflow.com/questions/324341",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11534/"
] |
324,344 | <p>I'm a bit flabbergasted at this, so I'm wondering if any SOers have encountered it before.</p>
<p>I have an essentially flat page with a number of input=text seeded in the markup with default values of say A,B,C,D,E in order. The markup looks like this in view source:</p>
<pre><code><td class="action invoice">
<a href="#foo">Toggle Invoice</a>
<div class="data">
<input type="text" class="formatted" value="A" />
<a href="#" class="notes" title="Add Note">Add Note</a>
</div>
</td>
</code></pre>
<p>Iterated for a number of rows A->E.</p>
<p>The page is created by an ASP.NET 2.0 app. Version 1 is merely "user.aspx?id=1" Version 2 is path mapped by a RESTlike HTTPModule from "users/1" to "user.aspx?id=1" internally.</p>
<p>Version 1 is fine. Version 2 <em>after rendering</em> leaves me with inputs with values in the order E, A, B, D, E repeatably, but I can see no reason for that order especially.</p>
<p>I can view source and the value="X" is correct, and on DOM inspection in firebug the <em>defaultValue</em> is correct, but the <em>value</em> is not.</p>
<ul>
<li>This is not a CSS issue - CSS is removed from the page.</li>
<li>This is not a JS issue - JS is off.</li>
<li>This is not an HTML issue - the markup is literally identical in all cases.</li>
</ul>
<p>The only difference is how the markup is requested. It's like Firefox is quantumly entangled with the server somehow. </p>
<p>Has anyone ever <em>heard</em> of such a thing? I'm stunned.</p>
<p><strong>Edit</strong>: this is also definitely a FF issue. IE, Opera and Chrome are all fine with the page.</p>
<p><strong>Edit 2</strong>: I literally mean the path of the request. One version is a request to <em><a href="http://localhost/user.aspx?id=1" rel="nofollow noreferrer">http://localhost/user.aspx?id=1</a></em>, the other (failing) version is to <em><a href="http://localhost/users/1" rel="nofollow noreferrer">http://localhost/users/1</a></em> and this version is mapped by an HTTPModule to the first path. name= won't help because the default values are not human entered, they're in the source as served.</p>
| [
{
"answer_id": 379211,
"author": "Kenan Banks",
"author_id": 43089,
"author_profile": "https://Stackoverflow.com/users/43089",
"pm_score": 0,
"selected": false,
"text": "autocomplete=\"off\""
}
] | 2008/11/27 | [
"https://Stackoverflow.com/questions/324344",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13018/"
] |
324,353 | <p>Why are the split lists always empty in this program? (It is derived from the code on the <a href="http://en.wikipedia.org/wiki/Linked_List#Language_support" rel="nofollow noreferrer">Wikipedia</a> page on Linked Lists.)</p>
<pre><code>/*
Example program from wikipedia linked list article
Modified to find nth node and to split the list
*/
#include <stdio.h>
#include <stdlib.h>
typedef struct ns
{
int data;
struct ns *next; /* pointer to next element in list */
} node;
node *list_add(node **p, int i)
{
node *n = (node *)malloc(sizeof(node));
if (n == NULL)
return NULL;
n->next = *p; //* the previous element (*p) now becomes the "next" element */
*p = n; //* add new empty element to the front (head) of the list */
n->data = i;
return *p;
}
void list_print(node *n)
{
int i=0;
if (n == NULL)
{
printf("list is empty\n");
}
while (n != NULL)
{
printf("Value at node #%d = %d\n", i, n->data);
n = n->next;
i++;
}
}
node *list_nth(node *head, int index) {
node *current = head;
node *temp=NULL;
int count = 0; // the index of the node we're currently looking at
while (current != NULL) {
if (count == index)
temp = current;
count++;
current = current->next;
}
return temp;
}
/*
This function is to split a linked list:
Return a list with nodes starting from index 'int ind' and
step the index by 'int step' until the end of list.
*/
node *list_split(node *head, int ind, int step) {
node *current = head;
node *temp=NULL;
int count = ind; // the index of the node we're currently looking at
temp = list_nth(current, ind);
while (current != NULL) {
count = count+step;
temp->next = list_nth(head, count);
current = current->next;
}
return temp; /* return the final stepped list */
}
int main(void)
{
node *n = NULL, *list1=NULL, *list2=NULL, *list3=NULL, *list4=NULL;
int i;
/* List with 30 nodes */
for(i=0;i<=30;i++){
list_add(&n, i);
}
list_print(n);
/* Get 1th, 5th, 9th, 13th, 18th ... nodes of n etc */
list1 = list_split(n, 1, 4);
list_print(list1);
list2 = list_split(n, 2, 4); /* 2, 6, 10, 14 etc */
list_print(list2);
list3 = list_split(n, 3, 4); /* 3, 7, 11, 15 etc */
list_print(list3);
list3 = list_split(n, 4, 4); /* 4, 8, 12, 16 etc */
list_print(list4);
getch();
return 0;
}
</code></pre>
| [
{
"answer_id": 324380,
"author": "Rob Walker",
"author_id": 3631,
"author_profile": "https://Stackoverflow.com/users/3631",
"pm_score": 3,
"selected": false,
"text": " temp = list_nth(current, ind);\n\n while (current != NULL) {\n count = count+step;\n temp->next = list_nth(head, count);\n current = current->next;\n }\n"
},
{
"answer_id": 324419,
"author": "atzz",
"author_id": 23252,
"author_profile": "https://Stackoverflow.com/users/23252",
"pm_score": 0,
"selected": false,
"text": "O(n) O(1) list_nth temp->next list_split list_split temp list_nth list_split O(n**2) list_nth current = list_nth(current, step) list_nth(head, count)"
},
{
"answer_id": 324422,
"author": "ysth",
"author_id": 17389,
"author_profile": "https://Stackoverflow.com/users/17389",
"pm_score": 0,
"selected": false,
"text": "node *list_split(node *head, int ind, int step) {\n node *current = head;\n node *newlist=NULL;\n node **end = &newlist;\n node *temp = list_nth(current, ind);\n\n while (temp != NULL) {\n *end = (node *)malloc(sizeof(node));\n if (*end == NULL) return NULL;\n (*end)->data = temp->data;\n end = &((*end)->next);\n temp = list_nth(temp, step);\n }\n\n return newlist; /* return the final stepped list */\n}\n"
},
{
"answer_id": 324521,
"author": "BIBD",
"author_id": 685,
"author_profile": "https://Stackoverflow.com/users/685",
"pm_score": 0,
"selected": false,
"text": "[0]->[1]->[2]->[3]->[4]->[5]->[6]->[7]->[8]->[9]->...->[10]->[NULL]\n"
}
] | 2008/11/27 | [
"https://Stackoverflow.com/questions/324353",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
324,358 | <p>I need to cast single figures (1 to 9) to (01 to 09). I can think of a way but its big and ugly and cumbersome. I'm sure there must be some concise way. Any Suggestions</p>
| [
{
"answer_id": 324368,
"author": "Konrad Rudolph",
"author_id": 1968,
"author_profile": "https://Stackoverflow.com/users/1968",
"pm_score": 8,
"selected": false,
"text": "Double $s = sprintf('%02d', $digit);\n sprintf"
},
{
"answer_id": 324402,
"author": "LeppyR64",
"author_id": 16592,
"author_profile": "https://Stackoverflow.com/users/16592",
"pm_score": 7,
"selected": false,
"text": "<?php\n$input = \"Alien\";\necho str_pad($input, 10); // produces \"Alien \"\necho str_pad($input, 10, \"-=\", STR_PAD_LEFT); // produces \"-=-=-Alien\"\necho str_pad($input, 10, \"_\", STR_PAD_BOTH); // produces \"__Alien___\"\necho str_pad($input, 6 , \"___\"); // produces \"Alien_\"\n?>\n"
},
{
"answer_id": 6357780,
"author": "Alex",
"author_id": 331308,
"author_profile": "https://Stackoverflow.com/users/331308",
"pm_score": 6,
"selected": false,
"text": "str_pad($digit,2,'0',STR_PAD_LEFT);\n $start = microtime(true);\nfor ($i=0;$i<100000;$i++) {\n str_pad(9,2,'0',STR_PAD_LEFT);\n str_pad(15,2,'0',STR_PAD_LEFT);\n str_pad(100,2,'0',STR_PAD_LEFT);\n}\n$end = microtime(true);\necho \"Result str_pad : \",($end-$start),\"\\n\";\n\n$start = microtime(true);\nfor ($i=0;$i<100000;$i++) {\n sprintf(\"%02d\", 9);\n sprintf(\"%02d\", 15);\n sprintf(\"%02d\", 100);\n}\n$end = microtime(true);\necho \"Result sprintf : \",($end-$start),\"\\n\";\n"
},
{
"answer_id": 62890110,
"author": "Cray",
"author_id": 11271432,
"author_profile": "https://Stackoverflow.com/users/11271432",
"pm_score": 2,
"selected": false,
"text": "str_pad $padded_string = str_repeat(\"0\", $length-strlen($number)) . $number;\n $number = strval(123);\n str_repeat: 0.086055040359497 (number: 123, padding: 1)\nstr_repeat: 0.085798978805542 (number: 123, padding: 3)\nstr_repeat: 0.085641145706177 (number: 123, padding: 10)\nstr_repeat: 0.091305017471313 (number: 123, padding: 100)\n\nstr_pad: 0.086184978485107 (number: 123, padding: 1)\nstr_pad: 0.096981048583984 (number: 123, padding: 3)\nstr_pad: 0.14874792098999 (number: 123, padding: 10)\nstr_pad: 0.85979700088501 (number: 123, padding: 100)\n"
},
{
"answer_id": 71018641,
"author": "user889030",
"author_id": 889030,
"author_profile": "https://Stackoverflow.com/users/889030",
"pm_score": 0,
"selected": false,
"text": "<?php\n\n// add zeros to a number at left or right side.\nfunction add_zeros_to_number( $number, $number_of_zeros, $zeros_position=\"left\"){\n // check if number is negative\n $is_negative = FALSE;\n if ( strpos($number , '-') !== FALSE ){\n $is_negative = TRUE;\n $number = substr($number, 1);\n }\n if($zeros_position == \"right\"){\n $r = str_pad($number, $number_of_zeros, \"0\", STR_PAD_RIGHT);\n }else{\n $r = str_pad($number, $number_of_zeros, \"0\", STR_PAD_LEFT);\n }\n if( $is_negative ){\n return \"-\".$r;\n }else{\n return $r;\n }\n}\n\n// how to use\n$number = -333; // Desire number \n$number_of_zeros = 4; // number of zeros [ your number length + zeros ]\n$position = \"right\"; // left or right . default left\necho $result = add_zeros_to_number($number, $number_of_zeros, $position);\n\n// output\n// -333 => -3330 left\n// -333 => -0333 right\n\n"
}
] | 2008/11/27 | [
"https://Stackoverflow.com/questions/324358",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
324,373 | <p>I have written an ASP.NET composite control which includes some Javascript which communicates with a web service.</p>
<p>I have packaged the classes for the control and the service into a DLL to make it nice and easy for people to use it in other projects.</p>
<p>The problem I'm having is that as well as referencing the DLL in their project, the consumer of my control must also include a .ASMX file for the web service. Whilst it isn't a complicated file (just a one-liner which refers to the class in the DLL), I would like to avoid having it if I can.</p>
<p>Is there any way to avoid having to have the .ASMX file?</p>
<ul>
<li>Can I register the service with the web server in Application_Start?</li>
<li>Can I make a web.config change to reference it somehow?</li>
</ul>
<p>All suggestions gratefully received!</p>
<p><strong>UPDATE:</strong> The article linked to in John Sheehan's response (below) does work - but not if you want to call the web service using AJAX. Does anybody know of an AJAX friendly version?</p>
| [
{
"answer_id": 324462,
"author": "John Sheehan",
"author_id": 1786,
"author_profile": "https://Stackoverflow.com/users/1786",
"pm_score": 3,
"selected": false,
"text": "<configuration>\n <system.web>\n <httpHandlers>\n <add verb=\"*\" path=\"*WebService.asmx\" type=\"MyHandler.WebServiceHandler, MyHandler\" />\n </httpHandlers>\n </system.web>\n</configuration>\n"
},
{
"answer_id": 2004906,
"author": "lubos hasko",
"author_id": 275,
"author_profile": "https://Stackoverflow.com/users/275",
"pm_score": 2,
"selected": false,
"text": "System.Web.Services.Protocols.WebServiceHandlerFactory CoreGetHandler public IHttpHandler GetHttpHandlerForWebService(WebService webService, HttpContext context)\n{\n var webServiceType = webService.GetType();\n var wshf = new System.Web.Services.Protocols.WebServiceHandlerFactory();\n var coreGetHandler = wshf.GetType().GetMethod(\"CoreGetHandler\");\n var httpHandler = (IHttpHandler)coreGetHandler.Invoke(wshf, new object[] { webServiceType, context, context.Request, context.Response });\n return httpHandler;\n}\n"
}
] | 2008/11/27 | [
"https://Stackoverflow.com/questions/324373",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/475/"
] |
324,381 | <p>This is a multi-site problem. I have a lot of sites with .htaccess files with multiple line similar to:</p>
<pre><code>rewriterule ^(page-one|page-two|page-three)/?$ /index.php?page=$1 [L]
</code></pre>
<p>This means that both www.domain.com/page-one and www.domain.com/page-one/ will both load www.domain.com/index.php?page=page-one</p>
<p>However I'm always told that it is good SEO practice to make sure you use only one URL per page so what I'd like to do make www.domain.com/page-one to redirect to www.domain.com/page-one/ via the .htaccess file. </p>
<p>Please note the answer I'm <strong>NOT</strong> looking for is to remove the ?$ from the end of the line as that will just cause www.domain.com/page-one to become a 404 link.</p>
| [
{
"answer_id": 324390,
"author": "Konrad Rudolph",
"author_id": 1968,
"author_profile": "https://Stackoverflow.com/users/1968",
"pm_score": 1,
"selected": false,
"text": "RewriteRule ^(.*[^/])$ $1/\nRewriteRule ^(page-one|page-two|page-three)?$ /index.php?page=$1 [L]\n"
},
{
"answer_id": 324448,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": " RewriteRule ^(.+[^/])$ $1/ [R]\n"
},
{
"answer_id": 1747056,
"author": "Andrew G. Johnson",
"author_id": 428190,
"author_profile": "https://Stackoverflow.com/users/428190",
"pm_score": 3,
"selected": true,
"text": "rewritecond %{REQUEST_FILENAME} !-f\nrewritecond %{REQUEST_URI} !(.*)/$\nrewriterule ^(.*)$ http://%{HTTP_HOST}/$1/ [L,R=301]\n"
}
] | 2008/11/27 | [
"https://Stackoverflow.com/questions/324381",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/428190/"
] |
324,386 | <p>We have cases wherein we write a lot of log files to the host increasing the i/o on a host. Are there any good open source logging over the wire solutions.</p>
<p>The application language is C++ on Red Hat Linux 3.</p>
| [
{
"answer_id": 324806,
"author": "Andrew Edgecombe",
"author_id": 11694,
"author_profile": "https://Stackoverflow.com/users/11694",
"pm_score": 2,
"selected": false,
"text": "openlog() syslog() closelog() syslog.conf"
}
] | 2008/11/27 | [
"https://Stackoverflow.com/questions/324386",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
324,400 | <p>I have an existing htaccess that works fine:</p>
<pre><code>RewriteEngine On
RewriteCond %{SCRIPT_FILENAME} !-f
RewriteCond %{SCRIPT_FILENAME} !-d
RewriteRule (.*) /default.php
DirectoryIndex index.php /default.php
</code></pre>
<p>I wish to modify this so that all urls that start with /test/ go to /test/default.php.</p>
<p>Example: <a href="http://www.x.com/hello.php" rel="nofollow noreferrer">http://www.x.com/hello.php</a> -- > <a href="http://www.x.com/default.php" rel="nofollow noreferrer">http://www.x.com/default.php</a>
Example: <a href="http://www.x.com/test/hello.php" rel="nofollow noreferrer">http://www.x.com/test/hello.php</a> -- > <a href="http://www.x.com/test/default.php" rel="nofollow noreferrer">http://www.x.com/test/default.php</a></p>
| [
{
"answer_id": 324410,
"author": "Konrad Rudolph",
"author_id": 1968,
"author_profile": "https://Stackoverflow.com/users/1968",
"pm_score": 2,
"selected": false,
"text": "/test/ RewriteRule ^/test/ /test/default.php\n"
},
{
"answer_id": 324427,
"author": "Ken",
"author_id": 20074,
"author_profile": "https://Stackoverflow.com/users/20074",
"pm_score": 0,
"selected": false,
"text": "RewriteRule ^/test/(.*)$ /test/default.php/$1\n"
},
{
"answer_id": 446862,
"author": "Gumbo",
"author_id": 53114,
"author_profile": "https://Stackoverflow.com/users/53114",
"pm_score": 0,
"selected": false,
"text": "RewriteCond %{REQUEST_URI} ^/([^/]*/)*\nRewriteRule !/default\\.php$ %0default.php [L]\n"
},
{
"answer_id": 655384,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "RewriteRule ^/test(/.*)?$ /test/default.php [L]\n RewriteEngine On\nRewriteCond %{SCRIPT_FILENAME} !-f\nRewriteCond %{SCRIPT_FILENAME} !-d\nRewriteRule ^/test(/.*)?$ /test/default.php [L]\nRewriteCond %{SCRIPT_FILENAME} !-f\nRewriteCond %{SCRIPT_FILENAME} !-d\nRewriteRule ^(.*)$ /default.php\n"
}
] | 2008/11/27 | [
"https://Stackoverflow.com/questions/324400",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
324,428 | <blockquote>
<p><strong>Possible Duplicate:</strong><br>
<a href="https://stackoverflow.com/questions/324311/symbolic-simplification-in-haskell-using-recursion">Symbolic simplification in Haskell (using recursion?)</a> </p>
</blockquote>
<p>The simplifications I have in mind are</p>
<pre><code>0*e = e*0 = 0
1*e = e*1 = 0+e = e+0 = e-0 = e
</code></pre>
<p>and simplifying constant subexpressions, e.g. <code>Plus (Const 1) (Const 2)</code> would become <code>Const 3</code>. I would not expect variables (or variables and constants) to be concatenated: <code>Var "st"</code> is a distinct variable from <code>Var "s"</code>. </p>
<p>For example <code>simplify(Plus (Var "x") (Const 0))= Var "x"</code></p>
| [
{
"answer_id": 324440,
"author": "Konrad Rudolph",
"author_id": 1968,
"author_profile": "https://Stackoverflow.com/users/1968",
"pm_score": 2,
"selected": false,
"text": "simplify (Plus (Const 0) (Expr x)) = simplify (Expr x)\nsimplify (Plus (Expr x) (Const 0)) = simplify (Expr x)\nsimplify (Mult (Const 0) _) = Const 0\nsimplify (Mult _ (Const 0)) = Const 0\n– … and so on\n"
},
{
"answer_id": 324547,
"author": "luke",
"author_id": 25920,
"author_profile": "https://Stackoverflow.com/users/25920",
"pm_score": 0,
"selected": false,
"text": "simplify(Exp e)\nif (e is const) return e\nelse if (e is var) return e\nelse\n{//encode simplification rules\n Exp left = simplify(e.left)\n Exp right = simplify(e.right)\n if(operator is PLUS)\n {\n if(left == 0) return right;\n if(right == 0) return left;\n }\n else if(operator is MULT)\n {\n if(left == 1) return right;\n if(right == 1) return left;\n if(left == 0) return 0;\n if(right == 0) return 0;\n }\n//and so on for other operators\n} \n"
}
] | 2008/11/27 | [
"https://Stackoverflow.com/questions/324428",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/41000/"
] |
324,436 | <p>There's this program, pdftotext, that can convert a pdf file to a text file. To use it directly on the linux console:</p>
<pre><code>pdftotext file.pdf
</code></pre>
<p>That will generate a file.txt on the same directory as the pdf file. I was looking for a way to do it from inside a php program, and after some googling I ended with two commands that should work for me: <em>system()</em> and <em>exec()</em>. So I made a php file with this:</p>
<pre><code><?php
system('pdftotext file.pdf');
?>
</code></pre>
<p>But when I run this code, it doesn't work. No txt file is created.
So I tried to create a test file with another command:</p>
<pre><code><?php
system('touch test.txt');
?>
</code></pre>
<p>This worked fine. I've also used exec() and the results were the same. Why doesn't it work?</p>
<p><strong>EDIT:</strong> following RoBorg advice, i added the 2>&1 argument to the command, so:</p>
<pre><code><?php
system('pdftotext file.pdf 2>&1');
?>
</code></pre>
<p>it printed a error message:</p>
<blockquote>
<p>pdftotext: error while loading shared
libraries: libfontconfig.so.1: cannot
open shared object file: No such file
or directory</p>
</blockquote>
<p>Seems like something is missing on the server.</p>
| [
{
"answer_id": 324472,
"author": "Greg",
"author_id": 24181,
"author_profile": "https://Stackoverflow.com/users/24181",
"pm_score": 4,
"selected": true,
"text": "<?php\n system('pdftotext file.pdf 2>&1');\n?>\n 2>&1"
}
] | 2008/11/27 | [
"https://Stackoverflow.com/questions/324436",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/27090/"
] |
324,457 | <p>I've been looking into adopting Carbon Emacs for use on my Mac, and the only stumbling block I've run into is the annoying scroll beep when you try to scroll past the end of the document. I've looked online but I can't seem to find what I should add to my .emacs that will stop it from beeping when scrolling. I don't want to silence it completely, just when scrolling. Any ideas?</p>
| [
{
"answer_id": 324501,
"author": "Svante",
"author_id": 31615,
"author_profile": "https://Stackoverflow.com/users/31615",
"pm_score": 2,
"selected": false,
"text": "ring-bell-function"
},
{
"answer_id": 331590,
"author": "wunki",
"author_id": 34020,
"author_profile": "https://Stackoverflow.com/users/34020",
"pm_score": 3,
"selected": false,
"text": "(setq visible-bell t)\n"
},
{
"answer_id": 731660,
"author": "nominolo",
"author_id": 73706,
"author_profile": "https://Stackoverflow.com/users/73706",
"pm_score": 3,
"selected": false,
"text": "(defun my-bell-function ()\n (unless (memq this-command\n '(isearch-abort abort-recursive-edit exit-minibuffer\n keyboard-quit mwheel-scroll down up next-line previous-line\n backward-char forward-char))\n (ding)))\n(setq ring-bell-function 'my-bell-function)\n C-h k"
},
{
"answer_id": 14295903,
"author": "Stephen Hassard",
"author_id": 1972779,
"author_profile": "https://Stackoverflow.com/users/1972779",
"pm_score": 0,
"selected": false,
"text": "(setq ring-bell-function nil)\n"
},
{
"answer_id": 27513202,
"author": "Karim Nassar",
"author_id": 948217,
"author_profile": "https://Stackoverflow.com/users/948217",
"pm_score": 2,
"selected": false,
"text": "(setq ring-bell-function 'ignore)\n"
}
] | 2008/11/27 | [
"https://Stackoverflow.com/questions/324457",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/658/"
] |
324,463 | <p>How can I display something over all other application. I want to to display something over all form of my program and all other programs open on my desktop (not mine).</p>
<p><strong>*Top Most doesn't work I have tested and my browser can go OVER my application :S</strong></p>
<p>Here is an image of when I use TopMost to TRUE. You can see my browser is over it...</p>
<p><a href="http://www.freeimagehosting.net/uploads/5a98165605.png" rel="noreferrer">http://www.freeimagehosting.net/uploads/5a98165605.png</a></p>
| [
{
"answer_id": 324464,
"author": "Patrick Desjardins",
"author_id": 13913,
"author_profile": "https://Stackoverflow.com/users/13913",
"pm_score": 5,
"selected": true,
"text": "[System.Runtime.InteropServices.DllImport(\"user32.dll\")]\npublic static extern bool SetForegroundWindow(IntPtr hWnd);\n SetForegroundWindow(this.Handle);\n"
},
{
"answer_id": 324487,
"author": "Yona",
"author_id": 40007,
"author_profile": "https://Stackoverflow.com/users/40007",
"pm_score": 3,
"selected": false,
"text": "myForm.TopMost = true; // This will do the job\n"
}
] | 2008/11/27 | [
"https://Stackoverflow.com/questions/324463",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21386/"
] |
324,466 | <p>I have installed Delphi Prism and XNA Game Studio 3.0. I have managed to translate to Delphi Prism XNA Tutorial 1 "Displaying a 3D Model on the Screen" (<a href="http://msdn.microsoft.com/en-us/library/bb197293.aspx" rel="nofollow noreferrer">http://msdn.microsoft.com/en-us/library/bb197293.aspx</a>).
Project compiles fine, but I cannot load a model. It looks like there is a new "contentproj" type in XNA that is not in Delphi Prism...
Any idea how to get it to work?</p>
| [
{
"answer_id": 17538490,
"author": "sav",
"author_id": 2040876,
"author_profile": "https://Stackoverflow.com/users/2040876",
"pm_score": 0,
"selected": false,
"text": "method Game1.LoadContent;\nvar\n importer : TextureImporter;\n texContent : Texture2DContent;\n cc : ContentCompiler;\n fullPath : String;\n fs : FileStream;\n args : array[1..7] of System.Object;\n begin\n spriteBatch := new SpriteBatch(GraphicsDevice);\n importer := new TextureImporter;\n texContent := importer.Import(’asset.png’, nil) as Texture2DContent;\n\n var compilerType := typeOf(ContentCompiler);\n\n cc := compilerType.GetConstructors(BindingFlags.NonPublic or BindingFlags.Instance)[0].Invoke(nil) as ContentCompiler;\n\n var compileMethod := compilerType.GetMethod(\"Compile\", BindingFlags.NonPublic or BindingFlags.Instance);\n\n fullPath := ‘assestName.xnb’;\n\n fs := File.Create(fullPath);\n\n args[1] := fs;\n args[2] := texContent;\n args[3] := TargetPlatform.Windows;\n args[4] := GraphicsProfile.Reach;\n args[5] := true;\n args[6] := fullPath;\n args[7] := fullPath;\n\n compileMethod.Invoke\n (\n cc,\n args\n );\n\n //SpriteTexture := Content.Load(’assetName’);\nend;\n"
}
] | 2008/11/27 | [
"https://Stackoverflow.com/questions/324466",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15733/"
] |
324,470 | <p>A custom HTTP header is being passed to a Servlet application for authentication purposes. The header value must be able to contain accents and other non-ASCII characters, so must be in a certain encoding (ideally UTF-8).</p>
<p>I am provided with this piece of Java code by the developers who control the authentication environment:</p>
<pre><code>String firstName = request.getHeader("my-custom-header");
String decodedFirstName = new String(firstName.getBytes(),"UTF-8");
</code></pre>
<p>But this code doesn't look right to me: it presupposes the encoding of the header value, when it seemed to me that there was a proper way of specifying an encoding for header values (from MIME I believe).</p>
<p>Here is my question: what is the right way (tm) of dealing with custom header values that need to support a UTF-8 encoding:</p>
<ul>
<li>on the wire (how the header looks like over the wire)</li>
<li>from the decoding point of view (how to decode it using the Java Servlet API, and can we assume that request.getHeader() already properly does the decoding)</li>
</ul>
<p>Here is an environment independent code sample to treat headers as UTF-8 in case you can't change your service:</p>
<pre><code>String valueAsISO = request.getHeader("my-custom-header");
String valueAsUTF8 = new String(firstName.getBytes("ISO8859-1"),"UTF-8");
</code></pre>
| [
{
"answer_id": 331187,
"author": "ebruchez",
"author_id": 5144,
"author_profile": "https://Stackoverflow.com/users/5144",
"pm_score": 2,
"selected": false,
"text": "=?UTF-8?Q?...?=\n"
}
] | 2008/11/27 | [
"https://Stackoverflow.com/questions/324470",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5144/"
] |
324,477 | <p>In a Django form, how do I make a field read-only (or disabled)?</p>
<p>When the form is being used to create a new entry, all fields should be enabled - but when the record is in update mode some fields need to be read-only.</p>
<p>For example, when creating a new <code>Item</code> model, all fields must be editable, but while updating the record, is there a way to disable the <code>sku</code> field so that it is visible, but cannot be edited?</p>
<pre><code>class Item(models.Model):
sku = models.CharField(max_length=50)
description = models.CharField(max_length=200)
added_by = models.ForeignKey(User)
class ItemForm(ModelForm):
class Meta:
model = Item
exclude = ('added_by')
def new_item_view(request):
if request.method == 'POST':
form = ItemForm(request.POST)
# Validate and save
else:
form = ItemForm()
# Render the view
</code></pre>
<p>Can class <code>ItemForm</code> be reused? What changes would be required in the <code>ItemForm</code> or <code>Item</code> model class? Would I need to write another class, "<code>ItemUpdateForm</code>", for updating the item?</p>
<pre><code>def update_item_view(request):
if request.method == 'POST':
form = ItemUpdateForm(request.POST)
# Validate and save
else:
form = ItemUpdateForm()
</code></pre>
| [
{
"answer_id": 325038,
"author": "Daniel Naab",
"author_id": 32638,
"author_profile": "https://Stackoverflow.com/users/32638",
"pm_score": 10,
"selected": true,
"text": "readonly class ItemForm(ModelForm):\n def __init__(self, *args, **kwargs):\n super(ItemForm, self).__init__(*args, **kwargs)\n instance = getattr(self, 'instance', None)\n if instance and instance.pk:\n self.fields['sku'].widget.attrs['readonly'] = True\n\n def clean_sku(self):\n instance = getattr(self, 'instance', None)\n if instance and instance.pk:\n return instance.sku\n else:\n return self.cleaned_data['sku']\n if instance and instance.pk disabled readonly clean_sku readonly POST ModelForm"
},
{
"answer_id": 331550,
"author": "muhuk",
"author_id": 42188,
"author_profile": "https://Stackoverflow.com/users/42188",
"pm_score": 7,
"selected": false,
"text": "readonly clean_sku instance.sku def clean_sku(self):\n if self.instance: \n return self.instance.sku\n else: \n return self.fields['sku']\n"
},
{
"answer_id": 1424453,
"author": "Humphrey",
"author_id": 142556,
"author_profile": "https://Stackoverflow.com/users/142556",
"pm_score": 6,
"selected": false,
"text": "ForeignKey SELECT HTML disabled=\"disabled\" class ItemForm(ModelForm):\n\n def __init__(self, *args, **kwargs):\n super(ItemForm, self).__init__(*args, **kwargs)\n instance = getattr(self, 'instance', None)\n if instance and instance.id:\n self.fields['sku'].required = False\n self.fields['sku'].widget.attrs['disabled'] = 'disabled'\n\n def clean_sku(self):\n # As shown in the above answer.\n instance = getattr(self, 'instance', None)\n if instance:\n return instance.sku\n else:\n return self.cleaned_data.get('sku', None)\n POST clean"
},
{
"answer_id": 4647579,
"author": "StefanNch",
"author_id": 430590,
"author_profile": "https://Stackoverflow.com/users/430590",
"pm_score": 5,
"selected": false,
"text": "sku = forms.CharField(widget = forms.TextInput(attrs={'readonly':'readonly'}))\n"
},
{
"answer_id": 5238191,
"author": "awalker",
"author_id": 536791,
"author_profile": "https://Stackoverflow.com/users/536791",
"pm_score": 4,
"selected": false,
"text": "get_readonly_fields ModelAdmin # In the admin.py file\n\nclass ItemAdmin(admin.ModelAdmin):\n\n def get_readonly_display(self, request, obj=None):\n if obj:\n return ['sku']\n else:\n return []\n obj get_readonly_display"
},
{
"answer_id": 5255112,
"author": "Evan Brumley",
"author_id": 652816,
"author_profile": "https://Stackoverflow.com/users/652816",
"pm_score": 3,
"selected": false,
"text": "class ItemForm(ModelForm):\n\n def __init__(self, *args, **kwargs):\n super(ItemForm, self).__init__(*args, **kwargs)\n instance = getattr(self, 'instance', None)\n if instance and instance.id:\n self.fields['sku'].required = False\n self.fields['sku'].widget.attrs['disabled'] = 'disabled'\n\n def clean_sku(self):\n # As shown in the above answer.\n instance = getattr(self, 'instance', None)\n if instance:\n try:\n self.changed_data.remove('sku')\n except ValueError, e:\n pass\n return instance.sku\n else:\n return self.cleaned_data.get('sku', None)\n"
},
{
"answer_id": 5322503,
"author": "alzclarke",
"author_id": 662049,
"author_profile": "https://Stackoverflow.com/users/662049",
"pm_score": 3,
"selected": false,
"text": "form.instance.fieldName form.fieldName"
},
{
"answer_id": 5994681,
"author": "Madis",
"author_id": 752697,
"author_profile": "https://Stackoverflow.com/users/752697",
"pm_score": 3,
"selected": false,
"text": "def clean_sku(self):\n if self.instance and self.instance.pk:\n return self.instance.sku\n else:\n return self.cleaned_data['sku']\n"
},
{
"answer_id": 6789609,
"author": "christophe31",
"author_id": 267364,
"author_profile": "https://Stackoverflow.com/users/267364",
"pm_score": 4,
"selected": false,
"text": "from django import forms\nfrom django.db.models.manager import Manager\n\n# I used this instead of lambda expression after scope problems\ndef _get_cleaner(form, field):\n def clean_field():\n value = getattr(form.instance, field, None)\n if issubclass(type(value), Manager):\n value = value.all()\n return value\n return clean_field\n\nclass ROFormMixin(forms.BaseForm):\n def __init__(self, *args, **kwargs):\n super(ROFormMixin, self).__init__(*args, **kwargs)\n if hasattr(self, \"read_only\"):\n if self.instance and self.instance.pk:\n for field in self.read_only:\n self.fields[field].widget.attrs['readonly'] = \"readonly\"\n setattr(self, \"clean_\" + field, _get_cleaner(self, field))\n\n# Basic usage\nclass TestForm(AModelForm, ROFormMixin):\n read_only = ('sku', 'an_other_field')\n"
},
{
"answer_id": 7049879,
"author": "chirale",
"author_id": 892951,
"author_profile": "https://Stackoverflow.com/users/892951",
"pm_score": 6,
"selected": false,
"text": "app/admin.py class ItemAdmin(admin.ModelAdmin):\n ...\n readonly_fields = ('url',)\n # In the admin.py file\nclass ItemAdmin(admin.ModelAdmin):\n ...\n def get_readonly_fields(self, request, obj=None):\n if obj:\n return ['url']\n else:\n return []\n url"
},
{
"answer_id": 9944067,
"author": "JamesD",
"author_id": 115694,
"author_profile": "https://Stackoverflow.com/users/115694",
"pm_score": 3,
"selected": false,
"text": "ModelChoiceField SELECTED --------- HiddenInputField() class ItemForm(ModelForm):\n\n def __init__(self, *args, **kwargs):\n super(ItemForm, self).__init__(*args, **kwargs)\n instance = getattr(self, 'instance', None)\n if instance and instance.id:\n self.fields['sku'].widget=HiddenInput()\n <div>\n {{ form.instance.sku }} <!-- This prints the value -->\n {{ form }} <!-- Prints form normally, and makes the hidden input -->\n</div>\n"
},
{
"answer_id": 11058596,
"author": "Hassek",
"author_id": 836144,
"author_profile": "https://Stackoverflow.com/users/836144",
"pm_score": 2,
"selected": false,
"text": "def get_readonly_fields(self, request, obj=None):\n skips = ('sku', 'other_field')\n fields = super(ItemAdmin, self).get_readonly_fields(request, obj)\n\n if not obj:\n return [field for field in fields if not field in skips]\n return fields\n"
},
{
"answer_id": 12261941,
"author": "Rune Kaagaard",
"author_id": 164449,
"author_profile": "https://Stackoverflow.com/users/164449",
"pm_score": 2,
"selected": false,
"text": "<span class=\"hidden\"></span> render_readonly() import django.forms.widgets as f\nimport xml.etree.ElementTree as etree\nfrom django.utils.safestring import mark_safe\n\ndef make_readonly(form):\n \"\"\"\n Makes all fields on the form readonly and prevents it from POST hacks.\n \"\"\"\n\n def _get_cleaner(_form, field):\n def clean_field():\n return getattr(_form.instance, field, None)\n return clean_field\n\n for field_name in form.fields.keys():\n form.fields[field_name].widget = ReadOnlyWidget(\n initial_widget=form.fields[field_name].widget)\n setattr(form, \"clean_\" + field_name, \n _get_cleaner(form, field_name))\n\n form.is_readonly = True\n\nclass ReadOnlyWidget(f.Select):\n \"\"\"\n Renders the content of the initial widget in a hidden <span>. If the\n initial widget has a ``render_readonly()`` method it uses that as display\n text, otherwise it tries to guess by parsing the html of the initial widget.\n \"\"\"\n\n def __init__(self, initial_widget, *args, **kwargs):\n self.initial_widget = initial_widget\n super(ReadOnlyWidget, self).__init__(*args, **kwargs)\n\n def render(self, *args, **kwargs):\n def guess_readonly_text(original_content):\n root = etree.fromstring(\"<span>%s</span>\" % original_content)\n\n for element in root:\n if element.tag == 'input':\n return element.get('value')\n\n if element.tag == 'select':\n for option in element:\n if option.get('selected'):\n return option.text\n\n if element.tag == 'textarea':\n return element.text\n\n return \"N/A\"\n\n original_content = self.initial_widget.render(*args, **kwargs)\n try:\n readonly_text = self.initial_widget.render_readonly(*args, **kwargs)\n except AttributeError:\n readonly_text = guess_readonly_text(original_content)\n\n return mark_safe(\"\"\"<span class=\"hidden\">%s</span>%s\"\"\" % (\n original_content, readonly_text))\n\n# Usage example 1.\nself.fields['my_field'].widget = ReadOnlyWidget(self.fields['my_field'].widget)\n\n# Usage example 2.\nform = MyForm()\nmake_readonly(form)\n"
},
{
"answer_id": 15134622,
"author": "Danny Staple",
"author_id": 490188,
"author_profile": "https://Stackoverflow.com/users/490188",
"pm_score": 4,
"selected": false,
"text": "class ReadOnlyWidget(widgets.Widget):\n \"\"\"Some of these values are read only - just a bit of text...\"\"\"\n def render(self, _, value, attrs=None):\n return value\n my_read_only = CharField(widget=ReadOnlyWidget())\n"
},
{
"answer_id": 20246739,
"author": "Robert Lujo",
"author_id": 565525,
"author_profile": "https://Stackoverflow.com/users/565525",
"pm_score": 2,
"selected": false,
"text": "def save(self, *args, **kwargs):\n for fname in self.readonly_fields:\n if fname in self.cleaned_data:\n del self.cleaned_data[fname]\n return super(<form-name>, self).save(*args,**kwargs)\n def clean_<fieldname>(self):\n return self.initial[<fieldname>] # or getattr(self.instance, fieldname)\n from functools import partial\n\nclass <Form-name>(...):\n\n def __init__(self, ...):\n ...\n super(<Form-name>, self).__init__(*args, **kwargs)\n ...\n for i, (fname, field) in enumerate(self.fields.iteritems()):\n if fname in self.readonly_fields:\n field.widget.attrs['readonly'] = \"readonly\"\n field.required = False\n # set clean method to reset value back\n clean_method_name = \"clean_%s\" % fname\n assert clean_method_name not in dir(self)\n setattr(self, clean_method_name, partial(self._clean_for_readonly_field, fname=fname))\n\n def _clean_for_readonly_field(self, fname):\n \"\"\" will reset value to initial - nothing will be changed \n needs to be added dynamically - partial, see init_fields\n \"\"\"\n return self.initial[fname] # or getattr(self.instance, fieldname)\n"
},
{
"answer_id": 21512530,
"author": "fly_frog",
"author_id": 3263118,
"author_profile": "https://Stackoverflow.com/users/3263118",
"pm_score": 1,
"selected": false,
"text": "def resume_edit(request, r_id):\n ..... \n r = Resume.get.object(pk=r_id)\n resume = ResumeModelForm(instance=r)\n .....\n resume.fields['email'].widget.attrs['readonly'] = True \n .....\n return render(request, 'resumes/resume.html', context)\n"
},
{
"answer_id": 21654713,
"author": "Michael",
"author_id": 1232891,
"author_profile": "https://Stackoverflow.com/users/1232891",
"pm_score": 3,
"selected": false,
"text": "class ReadOnlyFieldsMixin(object):\n readonly_fields =()\n\n def __init__(self, *args, **kwargs):\n super(ReadOnlyFieldsMixin, self).__init__(*args, **kwargs)\n for field in (field for name, field in self.fields.iteritems() if name in self.readonly_fields):\n field.widget.attrs['disabled'] = 'true'\n field.required = False\n\n def clean(self):\n cleaned_data = super(ReadOnlyFieldsMixin,self).clean()\n for field in self.readonly_fields:\n cleaned_data[field] = getattr(self.instance, field)\n\n return cleaned_data\n class MyFormWithReadOnlyFields(ReadOnlyFieldsMixin, MyForm):\n readonly_fields = ('field1', 'field2', 'fieldx')\n"
},
{
"answer_id": 29226377,
"author": "utapyngo",
"author_id": 517316,
"author_profile": "https://Stackoverflow.com/users/517316",
"pm_score": 0,
"selected": false,
"text": "class ReadonlyFieldsMixin(object):\n def get_readonly_fields(self, request, obj=None):\n if obj:\n return super(ReadonlyFieldsMixin, self).get_readonly_fields(request, obj)\n else:\n return tuple()\n\nclass MyAdmin(ReadonlyFieldsMixin, ModelAdmin):\n readonly_fields = ('sku',)\n"
},
{
"answer_id": 29974906,
"author": "austinheiman",
"author_id": 3343740,
"author_profile": "https://Stackoverflow.com/users/3343740",
"pm_score": 0,
"selected": false,
"text": "<span> <p> readonly"
},
{
"answer_id": 36745852,
"author": "darklow",
"author_id": 641263,
"author_profile": "https://Stackoverflow.com/users/641263",
"pm_score": 2,
"selected": false,
"text": "ModelMultipleChoiceField form.cleaned_data class ReadOnlyFieldsMixin(object):\n readonly_fields = ()\n\n def __init__(self, *args, **kwargs):\n super(ReadOnlyFieldsMixin, self).__init__(*args, **kwargs)\n for field in (field for name, field in self.fields.iteritems() if\n name in self.readonly_fields):\n field.widget.attrs['disabled'] = 'true'\n field.required = False\n\n def clean(self):\n for f in self.readonly_fields:\n self.cleaned_data.pop(f, None)\n return super(ReadOnlyFieldsMixin, self).clean()\n class MyFormWithReadOnlyFields(ReadOnlyFieldsMixin, MyForm):\n readonly_fields = ('field1', 'field2', 'fieldx')\n"
},
{
"answer_id": 39036431,
"author": "Sarath Ak",
"author_id": 4783719,
"author_profile": "https://Stackoverflow.com/users/4783719",
"pm_score": 2,
"selected": false,
"text": "class ItemForm(ModelForm):\n readonly = ('sku',)\n\n def __init__(self, *arg, **kwrg):\n super(ItemForm, self).__init__(*arg, **kwrg)\n for x in self.readonly:\n self.fields[x].widget.attrs['disabled'] = 'disabled'\n\n def clean(self):\n data = super(ItemForm, self).clean()\n for x in self.readonly:\n data[x] = getattr(self.instance, x)\n return data\n class AdvancedModelForm(ModelForm):\n\n\n def __init__(self, *arg, **kwrg):\n super(AdvancedModelForm, self).__init__(*arg, **kwrg)\n if hasattr(self, 'readonly'):\n for x in self.readonly:\n self.fields[x].widget.attrs['disabled'] = 'disabled'\n\n def clean(self):\n data = super(AdvancedModelForm, self).clean()\n if hasattr(self, 'readonly'):\n for x in self.readonly:\n data[x] = getattr(self.instance, x)\n return data\n\n\nclass ItemForm(AdvancedModelForm):\n readonly = ('sku',)\n"
},
{
"answer_id": 45284664,
"author": "Lucas B",
"author_id": 4458246,
"author_profile": "https://Stackoverflow.com/users/4458246",
"pm_score": 3,
"selected": false,
"text": "class ItemForm(ModelForm):\n disabled_fields = ('added_by',)\n\n class Meta:\n model = Item\n fields = '__all__'\n\n def __init__(self, *args, **kwargs):\n super(ItemForm, self).__init__(*args, **kwargs)\n for field in self.disabled_fields:\n self.fields[field].disabled = True\n"
},
{
"answer_id": 49486845,
"author": "Ajinkya Bhosale",
"author_id": 1305158,
"author_profile": "https://Stackoverflow.com/users/1305158",
"pm_score": 4,
"selected": false,
"text": "class EmployeeForm(forms.ModelForm):\n employee_code = forms.CharField(disabled=True)\n class Meta:\n model = Employee\n fields = ('employee_code', 'designation', 'salary')\n"
},
{
"answer_id": 52149259,
"author": "Yaroslav Varkhol",
"author_id": 9176275,
"author_profile": "https://Stackoverflow.com/users/9176275",
"pm_score": 1,
"selected": false,
"text": "Django ver < 1.9 1.9 Field.disabled __init__ def bound_data_readonly(_, initial):\n return initial\n\n\ndef to_python_readonly(field):\n native_to_python = field.to_python\n\n def to_python_filed(_):\n return native_to_python(field.initial)\n\n return to_python_filed\n\n\ndef disable_read_only_fields(init_method):\n\n def init_wrapper(*args, **kwargs):\n self = args[0]\n init_method(*args, **kwargs)\n for field in self.fields.values():\n if field.widget.attrs.get('readonly', None):\n field.widget.attrs['disabled'] = True\n setattr(field, 'bound_data', bound_data_readonly)\n setattr(field, 'to_python', to_python_readonly(field))\n\n return init_wrapper\n\n\nclass YourForm(forms.ModelForm):\n\n @disable_read_only_fields\n def __init__(self, *args, **kwargs):\n ...\n readonly initial yuor_form_field.widget.attrs['readonly'] = True"
},
{
"answer_id": 63216910,
"author": "nofoobar",
"author_id": 11652661,
"author_profile": "https://Stackoverflow.com/users/11652661",
"pm_score": 2,
"selected": false,
"text": "class SurveyModaForm(forms.ModelForm):\n class Meta:\n model = Survey\n fields = ['question_no']\n widgets = {\n 'question_no':forms.NumberInput(attrs={'class':'form-control','readonly':True}),\n }\n"
},
{
"answer_id": 69902303,
"author": "Richard Scholtens",
"author_id": 8955282,
"author_profile": "https://Stackoverflow.com/users/8955282",
"pm_score": 2,
"selected": false,
"text": "\n# form class in forms.py\n\n# Alter import User if you have created your own User class with Django default as abstract class.\nfrom .models import User \n# from django.contrib.auth.models import User\n\n# Same goes for these forms.\nfrom django.contrib.auth.forms import UserCreationForm, UserChangeForm\n\n\nclass ProfileChangeForm(UserChangeForm):\n\n class Meta(UserCreationForm)\n model = User\n fields = ['first_name', 'last_name', 'email',]\n\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n self.fields['email'].disabled = True\n\n \n# view class in views.py\n\nfrom django.contrib import messages\nfrom django.contrib.messages.views import SuccessMessageMixin\nfrom django.contrib.auth.mixins import LoginRequiredMixin\nfrom django.views.generic import TemplateView, UpdateView\nfrom django.utils.translation import gettext_lazy as _\n\n\nclass ProfileView(LoginRequiredMixin, TemplateView):\n template_name = 'app_name/profile.html'\n model = User\n\n\n def get_context_data(self, **kwargs):\n context = super().get_context_data(**kwargs)\n context.update({'user': self.request.user, })\n return context\n\n\nclass UserUpdateView(LoginRequiredMixin, SuccesMessageMixin, UpdateView):\n template_name = 'app_name/update_profile.html'\n model = User\n form_class = ProfileChangeForm\n success_message = _(\"Successfully updated your personal information\")\n\n\n def get_success_url(self):\n # Please note, one has to specify a get_absolute_url() in the User class\n # In my case I return: reverse(\"app_name:profile\")\n return self.request.user.get_absolute_url()\n\n\n def get_object(self, **kwargs):\n return self.request.user\n\n\n def form_valid(self, form):\n messages.add_message(self.request, messages.INFO, _(\"Successfully updated your profile\"))\n return super().form_valid(form)\n\n\n \n# HTML template in 'templates/app_name/update_profile.html' \n\n{% extends \"base.html\" %}\n{% load static %}\n{% load crispy_form_tags %}\n\n\n{% block content %}\n\n\n<h1>\n Update your personal information\n<h1/>\n<div>\n <form class=\"form-horizontal\" method=\"post\" action=\"{% url 'app_name:update' %}\">\n {% csrf_token %} \n {{ form|crispy }}\n <div class=\"btn-group\">\n <button type=\"submit\" class=\"btn btn-primary\">\n Update\n </button>\n </div>\n</div>\n\n\n{% endblock %}\n\n # URL routing for views in urls.py\n\nfrom django.urls import path\nfrom . import views\n\napp_name = 'app_name'\n\nurlpatterns = [\n path('profile/', view=views.ProfileView.as_view(), name='profile'),\n path('update/', view=views.UserUpdateView.as_view(), name='update'),\n ]\n\n"
},
{
"answer_id": 70417690,
"author": "Dhiaa Shalabi",
"author_id": 11795918,
"author_profile": "https://Stackoverflow.com/users/11795918",
"pm_score": 2,
"selected": false,
"text": "sku sku class Item(models.Model):\n sku = models.CharField(max_length=50)\n description = models.CharField(max_length=200)\n added_by = models.ForeignKey(User)\n\n\nclass ItemForm(ModelForm):\n def disable_sku_field(self):\n elf.fields['sku'].widget.attrs['readonly'] = True\n\n class Meta:\n model = Item\n exclude = ('added_by')\n\ndef new_item_view(request):\n if request.method == 'POST':\n form = ItemForm(request.POST)\n # Just create an object or instance of the form.\n # Validate and save\n else:\n form = ItemForm()\n # Render the view\n\n def update_item_view(request):\n if request.method == 'POST':\n form = ItemForm(request.POST)\n # Just create an object or instance of the form.\n # Validate and save\n else:\n form = ItemForm()\n form.disable_sku_field() # call the method that will disable field.\n\n # Render the view with the form that will have the `sku` field disabled on it.\n\n"
},
{
"answer_id": 73153765,
"author": "paeduardo",
"author_id": 11976901,
"author_profile": "https://Stackoverflow.com/users/11976901",
"pm_score": 1,
"selected": false,
"text": "class ModelAllDisabledFormMixin(forms.ModelForm):\n def __init__(self, *args, **kwargs):\n '''\n This mixin to ModelForm disables all fields. Useful to have detail view based on model\n '''\n super().__init__(*args, **kwargs)\n form_fields = self.fields\n for key in form_fields.keys():\n form_fields[key].disabled = True\n class MyModelAllDisabledForm(ModelAllDisabledFormMixin, forms.ModelForm):\n class Meta:\n model = MyModel\n fields = '__all__'\n class MyModelDetailView(LoginRequiredMixin, UpdateView):\n model = MyModel\n template_name = 'my_model_detail.html'\n form_class = MyModelAllDisabledForm\n <div class=\"form\">\n <form method=\"POST\" enctype=\"multipart/form-data\">\n {% csrf_token %}\n {{ form | crispy }}\n </form>\n </div>\n"
},
{
"answer_id": 73446901,
"author": "Conor",
"author_id": 1843452,
"author_profile": "https://Stackoverflow.com/users/1843452",
"pm_score": 1,
"selected": false,
"text": "class RecordForm(ModelForm):\n\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n var = self.fields['the_field']\n var.disabled = True\n"
}
] | 2008/11/27 | [
"https://Stackoverflow.com/questions/324477",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11452/"
] |
324,482 | <p>I'm working on a tool to simplify an application's deployment. Hence I'm aiming to automate the build of the setup project.</p>
<p>The Situation:
When I use Visual Studio to build the setup project this, creates the msi and exe files and concludes successfully. The problem occurs when I run a command in the command prompt, I keep getting this error <em>"ERROR: Cannot find outputs of project output group '(unable to determine name)'"</em></p>
<p>The command for the command prompt is:</p>
<blockquote>
<p>C:\Program Files\Microsoft Visual Studio 9.0\Common7\IDE>devenv "C:\Project's Directory\Project.Setup.vdproj" /Build</p>
</blockquote>
<p>Can anyone help me with it.
I'm really stuck.</p>
<hr>
<p>EDIT: The solution to my problem was to create a solution which contains the setup project and the project which is actually the output project of the setup project.</p>
<blockquote>
<p>C:\Program Files\Microsoft Visual Studio 9.0\Common7\IDE>devenv "C:\Project's Directory\Project.Setup.sln" /Build</p>
</blockquote>
<p>Thanks to everyone.</p>
| [
{
"answer_id": 324846,
"author": "jageall",
"author_id": 27036,
"author_profile": "https://Stackoverflow.com/users/27036",
"pm_score": 2,
"selected": false,
"text": "devenv [solutionname] /build\n"
}
] | 2008/11/27 | [
"https://Stackoverflow.com/questions/324482",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/30339/"
] |
324,486 | <p>I would like to return a string with all of the contents of a CSS rule, like the format you'd see in an inline style. I'd like to be able to do this without knowing what is contained in a particular rule, so I can't just pull them out by style name (like <code>.style.width</code> etc.) </p>
<p>The CSS:</p>
<pre><code>.test {
width:80px;
height:50px;
background-color:#808080;
}
</code></pre>
<p>The code so far:</p>
<pre><code>function getStyle(className) {
var classes = document.styleSheets[0].rules || document.styleSheets[0].cssRules
for(var x=0;x<classes.length;x++) {
if(classes[x].selectorText==className) {
//this is where I can collect the style information, but how?
}
}
}
getStyle('.test')
</code></pre>
| [
{
"answer_id": 324527,
"author": "scunliffe",
"author_id": 6144,
"author_profile": "https://Stackoverflow.com/users/6144",
"pm_score": 0,
"selected": false,
"text": "alert(classes[x].style.cssText);\n"
},
{
"answer_id": 324533,
"author": "nsdel",
"author_id": 40807,
"author_profile": "https://Stackoverflow.com/users/40807",
"pm_score": 8,
"selected": true,
"text": "function getStyle(className) {\n var cssText = \"\";\n var classes = document.styleSheets[0].rules || document.styleSheets[0].cssRules;\n for (var x = 0; x < classes.length; x++) { \n if (classes[x].selectorText == className) {\n cssText += classes[x].cssText || classes[x].style.cssText;\n } \n }\n return cssText;\n}\n\nalert(getStyle('.test'));\n"
},
{
"answer_id": 350573,
"author": "Larsenal",
"author_id": 337,
"author_profile": "https://Stackoverflow.com/users/337",
"pm_score": 3,
"selected": false,
"text": "div#a { ... }\ndiv#b, div#c { ... }\n <!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\"\n \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">\n<html xmlns=\"http://www.w3.org/1999/xhtml\" xml:lang=\"en\" lang=\"en\">\n<head>\n <style>\n div#a { }\n div#b, div#c { }\n </style>\n <script>\n function PrintRules() {\n var rules = document.styleSheets[0].rules || document.styleSheets[0].cssRules\n for(var x=0;x<rules.length;x++) {\n document.getElementById(\"rules\").innerHTML += rules[x].selectorText + \"<br />\";\n }\n }\n </script>\n</head>\n<body>\n <input onclick=\"PrintRules()\" type=\"button\" value=\"Print Rules\" /><br />\n RULES:\n <div id=\"rules\"></div>\n</body>\n</html>\n"
},
{
"answer_id": 3345851,
"author": "adardesign",
"author_id": 56449,
"author_profile": "https://Stackoverflow.com/users/56449",
"pm_score": 1,
"selected": false,
"text": "<div> (function getStyles(){var CSSrules,allRules,CSSSheets, unNeeded, currentRule;\nCSSSheets=document.styleSheets;\n\nfor(j=0;j<CSSSheets.length;j++){\nfor(i=0;i<CSSSheets[j].cssRules.length;i++){\n currentRule = CSSSheets[j].cssRules[i].selectorText;\n\n if(!document.querySelectorAll(currentRule).length){ \n unNeeded+=CSSSheets[j].cssRules[i].cssText+\"<br>\"; \n } \n }\n}\n\ndocBody=document.getElementsByTagName(\"body\")[0];\nallRulesContainer=document.createElement(\"div\");\ndocBody.appendChild(allRulesContainer);\nallRulesContainer.innerHTML=unNeeded+isHover;\nreturn false\n})()\n"
},
{
"answer_id": 5960538,
"author": "sivaprakasht ",
"author_id": 748162,
"author_profile": "https://Stackoverflow.com/users/748162",
"pm_score": 2,
"selected": false,
"text": "function getStyle(className) {\n document.styleSheets.item(\"menu\").cssRules.item(className).cssText;\n}\ngetStyle('.test')\n"
},
{
"answer_id": 15823002,
"author": "grigb",
"author_id": 627013,
"author_profile": "https://Stackoverflow.com/users/627013",
"pm_score": 0,
"selected": false,
"text": " var getStyle = function(className){\n var x, sheets,classes;\n for( sheets=document.styleSheets.length-1; sheets>=0; sheets-- ){\n classes = document.styleSheets[sheets].rules || document.styleSheets[sheets].cssRules;\n for(x=0;x<classes.length;x++) {\n if(classes[x].selectorText===className) {\n return (classes[x].cssText ? classes[x].cssText : classes[x].style.cssText);\n }\n }\n }\n return false;\n };\n"
},
{
"answer_id": 18987296,
"author": "sledmouth",
"author_id": 2812012,
"author_profile": "https://Stackoverflow.com/users/2812012",
"pm_score": 0,
"selected": false,
"text": "var getClassStyle = function(className){\n var x, sheets,classes;\n for( sheets=document.styleSheets.length-1; sheets>=0; sheets-- ){\n classes = document.styleSheets[sheets].rules || document.styleSheets[sheets].cssRules;\n for(x=0;x<classes.length;x++) {\n if(classes[x].selectorText===className){\n classStyleTxt = (classes[x].cssText ? classes[x].cssText : classes[x].style.cssText).match(/\\{\\s*([^{}]+)\\s*\\}/)[1];\n var classStyles = {};\n var styleSets = classStyleTxt.match(/([^;:]+:\\s*[^;:]+\\s*)/g);\n for(y=0;y<styleSets.length;y++){\n var style = styleSets[y].match(/\\s*([^:;]+):\\s*([^;:]+)/);\n if(style.length > 2)\n classStyles[style[1]]=style[2];\n }\n return classStyles;\n }\n }\n }\n return false;\n};\n"
},
{
"answer_id": 27527462,
"author": "dude",
"author_id": 3894981,
"author_profile": "https://Stackoverflow.com/users/3894981",
"pm_score": 5,
"selected": false,
"text": " /**\n * Gets styles by a classname\n * \n * @notice The className must be 1:1 the same as in the CSS\n * @param string className_\n */\n function getStyle(className_) {\n\n var styleSheets = window.document.styleSheets;\n var styleSheetsLength = styleSheets.length;\n for(var i = 0; i < styleSheetsLength; i++){\n var classes = styleSheets[i].rules || styleSheets[i].cssRules;\n if (!classes)\n continue;\n var classesLength = classes.length;\n for (var x = 0; x < classesLength; x++) {\n if (classes[x].selectorText == className_) {\n var ret;\n if(classes[x].cssText){\n ret = classes[x].cssText;\n } else {\n ret = classes[x].style.cssText;\n }\n if(ret.indexOf(classes[x].selectorText) == -1){\n ret = classes[x].selectorText + \"{\" + ret + \"}\";\n }\n return ret;\n }\n }\n }\n\n }\n"
},
{
"answer_id": 29130215,
"author": "T.Todua",
"author_id": 2377343,
"author_profile": "https://Stackoverflow.com/users/2377343",
"pm_score": 4,
"selected": false,
"text": "function GetProperty(classOrId,property)\n{ \n var FirstChar = classOrId.charAt(0); var Remaining= classOrId.substring(1);\n var elem = (FirstChar =='#') ? document.getElementById(Remaining) : document.getElementsByClassName(Remaining)[0];\n return window.getComputedStyle(elem,null).getPropertyValue(property);\n}\n\nalert( GetProperty(\".my_site_title\",\"position\") ) ;\n function GetStyle(CLASSname) \n{\n var styleSheets = document.styleSheets;\n var styleSheetsLength = styleSheets.length;\n for(var i = 0; i < styleSheetsLength; i++){\n if (styleSheets[i].rules ) { var classes = styleSheets[i].rules; }\n else { \n try { if(!styleSheets[i].cssRules) {continue;} } \n //Note that SecurityError exception is specific to Firefox.\n catch(e) { if(e.name == 'SecurityError') { console.log(\"SecurityError. Cant readd: \"+ styleSheets[i].href); continue; }}\n var classes = styleSheets[i].cssRules ;\n }\n for (var x = 0; x < classes.length; x++) {\n if (classes[x].selectorText == CLASSname) {\n var ret = (classes[x].cssText) ? classes[x].cssText : classes[x].style.cssText ;\n if(ret.indexOf(classes[x].selectorText) == -1){ret = classes[x].selectorText + \"{\" + ret + \"}\";}\n return ret;\n }\n }\n }\n}\n\nalert( GetStyle('.my_site_title') );\n"
},
{
"answer_id": 30917685,
"author": "dparnas",
"author_id": 250787,
"author_profile": "https://Stackoverflow.com/users/250787",
"pm_score": 2,
"selected": false,
"text": "//Get all styles where the provided class is involved\n//Input parameters should be css selector such as .myClass or #m\n//returned as an array of tuples {selectorText:\"\", styleDefinition:\"\"}\nfunction getStyleWithCSSSelector(cssSelector) {\n var styleSheets = window.document.styleSheets;\n var styleSheetsLength = styleSheets.length;\n var arStylesWithCSSSelector = [];\n\n //in order to not find class which has the current name as prefix\n var arValidCharsAfterCssSelector = [\" \", \".\", \",\", \"#\",\">\",\"+\",\":\",\"[\"];\n\n //loop through all the stylessheets in the bor\n for(var i = 0; i < styleSheetsLength; i++){\n var classes = styleSheets[i].rules || styleSheets[i].cssRules;\n var classesLength = classes.length;\n for (var x = 0; x < classesLength; x++) {\n //check for any reference to the class in the selector string\n if(typeof classes[x].selectorText != \"undefined\"){\n var matchClass = false;\n\n if(classes[x].selectorText === cssSelector){//exact match\n matchClass=true;\n }else {//check for it as part of the selector string\n //TODO: Optimize with regexp\n for (var j=0;j<arValidCharsAfterCssSelector.length; j++){\n var cssSelectorWithNextChar = cssSelector+ arValidCharsAfterCssSelector[j];\n\n if(classes[x].selectorText.indexOf(cssSelectorWithNextChar)!=-1){\n matchClass=true;\n //break out of for-loop\n break;\n }\n }\n }\n\n if(matchClass === true){\n //console.log(\"Found \"+ cssSelectorWithNextChar + \" in css class definition \" + classes[x].selectorText);\n var styleDefinition;\n if(classes[x].cssText){\n styleDefinition = classes[x].cssText;\n } else {\n styleDefinition = classes[x].style.cssText;\n }\n if(styleDefinition.indexOf(classes[x].selectorText) == -1){\n styleDefinition = classes[x].selectorText + \"{\" + styleDefinition + \"}\";\n }\n arStylesWithCSSSelector.push({\"selectorText\":classes[x].selectorText, \"styleDefinition\":styleDefinition});\n }\n }\n }\n }\n if(arStylesWithCSSSelector.length==0) {\n return null;\n }else {\n return arStylesWithCSSSelector; \n }\n}\n function getAllCSSClassDefinitionsForSubtree(selectorOfRootElement){\n //stack in which elements are pushed and poped from\n var arStackElements = [];\n //dictionary for checking already added css class definitions\n var existingClassDefinitions = {}\n\n //use jquery for selecting root element\n var rootElement = $(selectorOfRootElement)[0];\n //string with the complete CSS output\n var cssString = \"\";\n\n console.log(\"Fetching all classes used in sub tree of \" +selectorOfRootElement);\n arStackElements.push(rootElement);\n var currentElement;\n\n while(currentElement = arStackElements.pop()){\n currentElement = $(currentElement);\n console.log(\"Processing element \" + currentElement.attr(\"id\"));\n\n //Look at class attribute of element \n var classesString = currentElement.attr(\"class\");\n if(typeof classesString != 'undefined'){\n var arClasses = classesString.split(\" \");\n\n //for each class in the current element\n for(var i=0; i< arClasses.length; i++){\n\n //fetch the CSS Styles for a single class. Need to append the . char to indicate its a class\n var arStylesWithCSSSelector = getStyleWithCSSSelector(\".\"+arClasses[i]);\n console.log(\"Processing class \"+ arClasses[i]);\n\n if(arStylesWithCSSSelector != null){\n //console.log(\"Found \"+ arStylesWithCSSSelector.length + \" CSS style definitions for class \" +arClasses[i]);\n //append all found styles to the cssString\n for(var j=0; j< arStylesWithCSSSelector.length; j++){\n var tupleStyleWithCSSSelector = arStylesWithCSSSelector[j];\n\n //check if it has already been added\n if(typeof existingClassDefinitions[tupleStyleWithCSSSelector.selectorText] === \"undefined\"){\n //console.log(\"Adding \" + tupleStyleWithCSSSelector.styleDefinition);\n cssString+= tupleStyleWithCSSSelector.styleDefinition;\n existingClassDefinitions[tupleStyleWithCSSSelector.selectorText] = true;\n }else {\n //console.log(\"Already added \" + tupleStyleWithCSSSelector.styleDefinition);\n }\n }\n }\n }\n }\n //push all child elments to stack\n if(currentElement.children().length>0){\n arStackElements= arStackElements.concat(currentElement.children().toArray());\n }\n }\n\n console.log(\"Found \" + Object.keys(existingClassDefinitions).length + \" CSS class definitions\");\n return cssString;\n}\n"
},
{
"answer_id": 40298390,
"author": "Derek Ziemba",
"author_id": 2651894,
"author_profile": "https://Stackoverflow.com/users/2651894",
"pm_score": 3,
"selected": false,
"text": "//Inside closure so that the inner functions don't need regeneration on every call.\nconst getCssClasses = (function () {\n function normalize(str) {\n if (!str) return '';\n str = String(str).replace(/\\s*([>~+])\\s*/g, ' $1 '); //Normalize symbol spacing.\n return str.replace(/(\\s+)/g, ' ').trim(); //Normalize whitespace\n }\n function split(str, on) { //Split, Trim, and remove empty elements\n return str.split(on).map(x => x.trim()).filter(x => x);\n }\n function containsAny(selText, ors) {\n return selText ? ors.some(x => selText.indexOf(x) >= 0) : false;\n }\n return function (selector) {\n const logicalORs = split(normalize(selector), ',');\n const sheets = Array.from(window.document.styleSheets);\n const ruleArrays = sheets.map((x) => Array.from(x.rules || x.cssRules || []));\n const allRules = ruleArrays.reduce((all, x) => all.concat(x), []);\n return allRules.filter((x) => containsAny(normalize(x.selectorText), logicalORs));\n };\n})();\n"
},
{
"answer_id": 40526517,
"author": "brauliobo",
"author_id": 670229,
"author_profile": "https://Stackoverflow.com/users/670229",
"pm_score": -1,
"selected": false,
"text": ".recurly-input { \n display: block; \n border-radius: 2px; \n -webkit-border-radius: 2px; \n outline: 0; \n box-shadow: none; \n border: 1px solid #beb7b3; \n padding: 0.6em; \n background-color: #f7f7f7; \n width:100%; \n}\n backgroundColor:\n\"rgb(247, 247, 247)\"\nborder\n:\n\"1px solid rgb(190, 183, 179)\"\nborderBottom\n:\n\"1px solid rgb(190, 183, 179)\"\nborderBottomColor\n:\n\"rgb(190, 183, 179)\"\nborderBottomLeftRadius\n:\n\"2px\"\nborderBottomRightRadius\n:\n\"2px\"\nborderBottomStyle\n:\n\"solid\"\nborderBottomWidth\n:\n\"1px\"\nborderColor\n:\n\"rgb(190, 183, 179)\"\nborderLeft\n:\n\"1px solid rgb(190, 183, 179)\"\nborderLeftColor\n:\n\"rgb(190, 183, 179)\"\nborderLeftStyle\n:\n\"solid\"\nborderLeftWidth\n:\n\"1px\"\nborderRadius\n:\n\"2px\"\nborderRight\n:\n\"1px solid rgb(190, 183, 179)\"\nborderRightColor\n:\n\"rgb(190, 183, 179)\"\nborderRightStyle\n:\n\"solid\"\nborderRightWidth\n:\n\"1px\"\nborderStyle\n:\n\"solid\"\nborderTop\n:\n\"1px solid rgb(190, 183, 179)\"\nborderTopColor\n:\n\"rgb(190, 183, 179)\"\nborderTopLeftRadius\n:\n\"2px\"\nborderTopRightRadius\n:\n\"2px\"\nborderTopStyle\n:\n\"solid\"\nborderTopWidth\n:\n\"1px\"\nborderWidth\n:\n\"1px\"\nboxShadow\n:\n\"none\"\ndisplay\n:\n\"block\"\noutline\n:\n\"0px\"\noutlineWidth\n:\n\"0px\"\npadding\n:\n\"0.6em\"\npaddingBottom\n:\n\"0.6em\"\npaddingLeft\n:\n\"0.6em\"\npaddingRight\n:\n\"0.6em\"\npaddingTop\n:\n\"0.6em\"\nwidth\n:\n\"100%\"\n function getStyle(className_) {\n\n var styleSheets = window.document.styleSheets;\n var styleSheetsLength = styleSheets.length;\n for(var i = 0; i < styleSheetsLength; i++){\n var classes = styleSheets[i].rules || styleSheets[i].cssRules;\n if (!classes)\n continue;\n var classesLength = classes.length;\n for (var x = 0; x < classesLength; x++) {\n if (classes[x].selectorText == className_) {\n return _.pickBy(classes[x].style, (v, k) => isNaN(parseInt(k)) && typeof(v) == 'string' && v && v != 'initial' && k != 'cssText' )\n }\n }\n }\n\n}\n"
},
{
"answer_id": 45486783,
"author": "John Doherty",
"author_id": 443431,
"author_profile": "https://Stackoverflow.com/users/443431",
"pm_score": 0,
"selected": false,
"text": "getStylesBySelector('.pure-form-html', true);\n {\n \".pure-form-html body\": \"padding: 0; margin: 0; font-size: 14px; font-family: tahoma;\",\n \".pure-form-html h1\": \"margin: 0; font-size: 18px; font-family: tahoma;\"\n}\n .pure-form-html body {\n padding: 0;\n margin: 0;\n font-size: 14px;\n font-family: tahoma;\n}\n\n.pure-form-html h1 {\n margin: 0;\n font-size: 18px;\n font-family: tahoma;\n}\n /**\n * Get all CSS style blocks matching a CSS selector from stylesheets\n * @param {string} className - class name to match\n * @param {boolean} startingWith - if true matches all items starting with selector, default = false (exact match only)\n * @example getStylesBySelector('pure-form .pure-form-html ')\n * @returns {object} key/value object containing matching styles otherwise null\n */\nfunction getStylesBySelector(className, startingWith) {\n\n if (!className || className === '') throw new Error('Please provide a css class name');\n\n var styleSheets = window.document.styleSheets;\n var result = {};\n\n // go through all stylesheets in the DOM\n for (var i = 0, l = styleSheets.length; i < l; i++) {\n\n var classes = styleSheets[i].rules || styleSheets[i].cssRules || [];\n\n // go through all classes in each document\n for (var x = 0, ll = classes.length; x < ll; x++) {\n\n var selector = classes[x].selectorText || '';\n var content = classes[x].cssText || classes[x].style.cssText || '';\n\n // if the selector matches\n if ((startingWith && selector.indexOf(className) === 0) || selector === className) {\n\n // create an object entry with selector as key and value as content\n result[selector] = content.split(/(?:{|})/)[1].trim();\n }\n }\n }\n\n // only return object if we have values, otherwise null\n return Object.keys(result).length > 0 ? result : null;\n}\n"
},
{
"answer_id": 45517927,
"author": "kofifus",
"author_id": 460084,
"author_profile": "https://Stackoverflow.com/users/460084",
"pm_score": 2,
"selected": false,
"text": "function iterateCSS(f) {\n for (const styleSheet of window.document.styleSheets) {\n const classes = styleSheet.rules || styleSheet.cssRules;\n if (!classes) continue;\n\n for (const cssRule of classes) {\n if (cssRule.type !== 1 || !cssRule.style) continue;\n const selector = cssRule.selectorText, style=cssRule.style;\n if (!selector || !style.cssText) continue;\n for (let i=0; i<style.length; i++) {\n const propertyName=style.item(i);\n if (f(selector, propertyName, style.getPropertyValue(propertyName), style.getPropertyPriority(propertyName), cssRule)===false) return;\n }\n }\n }\n}\n\niterateCSS( (selector, propertyName, propertyValue, propertyPriority, cssRule) => {\n console.log(selector+' { '+propertyName+': '+propertyValue+(propertyPriority==='important' ? ' !important' : '')+' }');\n});"
},
{
"answer_id": 58744482,
"author": "pery mimon",
"author_id": 1919821,
"author_profile": "https://Stackoverflow.com/users/1919821",
"pm_score": 0,
"selected": false,
"text": " function AllImagesUrl (domain){\n return performance.getEntries()\n .filter( e=> \n e.initiatorType == \"img\" &&\n new RegExp(domain).test(e.name) \n )\n .map( e=> e.name.replace('some cleaning work here','') ) ```\n"
},
{
"answer_id": 62482074,
"author": "x86",
"author_id": 13779546,
"author_profile": "https://Stackoverflow.com/users/13779546",
"pm_score": 2,
"selected": false,
"text": "const getStyle = query => [...document.querySelector(query).computedStyleMap().entries()].map(e=>(e[1]+=[],e)).map(e=>e.join`:`+';').join`\\n`\n"
}
] | 2008/11/27 | [
"https://Stackoverflow.com/questions/324486",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12579/"
] |
324,498 | <p>Given:</p>
<pre><code>my @mylist1;
push(@mylist1,"A");
push(@mylist1,"B");
push(@mylist1,"C");
my @mylist2;
push(@mylist2,"A");
push(@mylist2,"D");
push(@mylist2,"E");
</code></pre>
<p>What's the quickest way in Perl to insert in mylist2 all elements that are in mylist1 and not already in mylist2 (ABCDE). </p>
| [
{
"answer_id": 324522,
"author": "Alnitak",
"author_id": 6782,
"author_profile": "https://Stackoverflow.com/users/6782",
"pm_score": 5,
"selected": true,
"text": "my %k;\nmap { $k{$_} = 1 } @mylist1;\nmap { $k{$_} = 1 } @mylist2;\n@mylist2 = keys %k;\n my %k;\nmap { $k{$_} = 1 } @mylist2;\npush(@mylist2, grep { !exists $k{$_} } @mylist1);\n @mylist2 = @mylist1 U @mylist2"
},
{
"answer_id": 324534,
"author": "Jonathan Leffler",
"author_id": 15168,
"author_profile": "https://Stackoverflow.com/users/15168",
"pm_score": 2,
"selected": false,
"text": "#!/bin/perl -w\nuse strict;\n\nmy @mylist1;\npush(@mylist1,\"A\");\npush(@mylist1,\"B\");\npush(@mylist1,\"C\");\n\nmy @mylist2;\npush(@mylist2,\"A\");\npush(@mylist2,\"D\");\npush(@mylist2,\"E\");\n\nsub value_in\n{\n my($value, @array) = @_;\n foreach my $element (@array)\n {\n return 1 if $value eq $element;\n }\n return 0;\n}\n\n@mylist2 = (@mylist2, grep { ! value_in($_, @mylist2) } @mylist1);\n\nprint sort @mylist2, \"\\n\";\n value_in #!/bin/perl -w\nuse strict;\nuse List::MoreUtils qw(uniq);\nuse Benchmark::Timer;\n\nmy @mylist1;\npush(@mylist1,\"A\");\npush(@mylist1,\"B\");\npush(@mylist1,\"C\");\n\nmy @mylist2;\npush(@mylist2,\"A\");\npush(@mylist2,\"D\");\npush(@mylist2,\"E\");\n\nsub value_in\n{\n my($value) = shift @_;\n return grep { $value eq $_ } @_;\n}\n\nmy @mylist3;\nmy @mylist4;\nmy @mylist5;\nmy @mylist6;\n\nmy $t = Benchmark::Timer->new(skip=>1);\nmy $iterations = 10000;\n\nfor my $i (1..$iterations)\n{\n $t->start('JLv2');\n @mylist3 = (@mylist2, grep { ! value_in($_, @mylist2) } @mylist1);\n $t->stop('JLv2');\n}\nprint $t->report('JLv2');\n\nfor my $i (1..$iterations)\n{\n $t->start('LMU');\n @mylist4 = uniq( @mylist1, @mylist2 );\n $t->stop('LMU');\n}\nprint $t->report('LMU');\n\nfor my $i (1..$iterations)\n{\n @mylist5 = @mylist2;\n $t->start('HV1');\n my %k;\n map { $k{$_} = 1 } @mylist5;\n push(@mylist5, grep { !exists $k{$_} } @mylist1);\n $t->stop('HV1');\n}\nprint $t->report('HV1');\n\nfor my $i (1..$iterations)\n{\n $t->start('HV2');\n my %k;\n map { $k{$_} = 1 } @mylist1;\n map { $k{$_} = 1 } @mylist2;\n @mylist6 = keys %k;\n $t->stop('HV2');\n}\nprint $t->report('HV2');\n\n\nprint sort(@mylist3), \"\\n\";\nprint sort(@mylist4), \"\\n\";\nprint sort(@mylist5), \"\\n\";\nprint sort(@mylist6), \"\\n\";\n\nBlack JL: perl xxx.pl\n9999 trials of JLv2 (1.298s total), 129us/trial\n9999 trials of LMU (968.176ms total), 96us/trial\n9999 trials of HV1 (516.799ms total), 51us/trial\n9999 trials of HV2 (768.073ms total), 76us/trial\nABCDE\nABCDE\nABCDE\nABCDE\nBlack JL:\n Black JL: perl xxx.pl\n9999 trials of JLv2 (1.293s total), 129us/trial\n9999 trials of LMU (938.504ms total), 93us/trial\n9999 trials of HV1 (505.998ms total), 50us/trial\n9999 trials of HV2 (756.722ms total), 75us/trial\nABCDE\nABCDE\nABCDE\nABCDE\n9999 trials of HV1A (655.582ms total), 65us/trial\nBlack JL:\n"
},
{
"answer_id": 324544,
"author": "ysth",
"author_id": 17389,
"author_profile": "https://Stackoverflow.com/users/17389",
"pm_score": 1,
"selected": false,
"text": "my %in_mylist1;\n@in_mylist1{@mylist1} = ();\npush @mylist1, grep ! exists $in_mylist1{$_}, @mylist2;\n"
},
{
"answer_id": 324561,
"author": "oeuftete",
"author_id": 7674,
"author_profile": "https://Stackoverflow.com/users/7674",
"pm_score": 5,
"selected": false,
"text": "List::MoreUtils uniq use List::MoreUtils qw(uniq);\n\nmy @mylist1;\npush( @mylist1, \"A\" );\npush( @mylist1, \"B\" );\npush( @mylist1, \"C\" );\n\nmy @mylist2;\npush( @mylist2, \"A\" );\npush( @mylist2, \"D\" );\npush( @mylist2, \"E\" );\n\n@mylist2 = uniq( @mylist1, @mylist2 );\n\nprintf \"%s\\n\", ( join ',', @mylist2 ); # A,B,C,D,E\n"
},
{
"answer_id": 328266,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "my(%work);\n@work{@mylist1, @mylist2} = undef;\n@mylist2 = sort keys %work;\n"
}
] | 2008/11/27 | [
"https://Stackoverflow.com/questions/324498",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5195/"
] |
324,499 | <p>I am running JVM 1.5.0 (Mac OS X Default), and I am monitoring my Java program in the Activity Monitor. I have the following:</p>
<pre><code>import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Date;
public class MemoryTest {
public static void memoryUsage() {
System.out.println(
Runtime.getRuntime().totalMemory() -
Runtime.getRuntime().freeMemory()
);
}
public static void main( String[] args ) throws IOException {
/* create a list */
ArrayList<Date> list = new ArrayList<Date>();
/* fill it with lots of data */
for ( int i = 0; i < 5000000; i++ ) {
list.add( new Date() );
} // systems shows ~164 MB of physical being used
/* clear it */
memoryUsage(); // about 154 MB
list.clear();
list = null;
System.gc();
memoryUsage(); // about 151 KB, garbage collector worked
// system still shows 164 MB of physical being used.
System.out.println("Press enter to end...");
BufferedReader br = new BufferedReader(
new InputStreamReader( System.in )
);
br.readLine();
}
</code></pre>
<p>}</p>
<p>So why doesn't the physical memory get freed even though the garbage collector seems to work just fine?</p>
| [
{
"answer_id": 324505,
"author": "erickson",
"author_id": 3474,
"author_profile": "https://Stackoverflow.com/users/3474",
"pm_score": 5,
"selected": true,
"text": "-XX:MinHeapFreeRatio -XX:MaxHeapFreeRatio"
}
] | 2008/11/27 | [
"https://Stackoverflow.com/questions/324499",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10675/"
] |
324,506 | <p>I have the following problem:</p>
<pre><code> # line is a line from a file that contains ["baa","beee","0"]
line = TcsLine.split(",")
NumPFCs = eval(line[2])
if NumPFCs==0:
print line
</code></pre>
<p>I want to print all the lines from the file if the second position of the list has a value == 0.</p>
<p>I print the lines but after that the following happens:
Traceback (most recent call last):</p>
<p>['baaa', 'beee', '0', '\n']</p>
<p><strong><em>BUT after I have the next ERROR</em></strong></p>
<pre><code>ilation.py", line 141, in ?
getZeroPFcs()
ilation.py", line 110, in getZeroPFcs
NumPFCs = eval(line[2])
File "<string>", line 0
</code></pre>
<p>Can you please help me?
thanks</p>
<p>What0s</p>
| [
{
"answer_id": 324524,
"author": "Dustin",
"author_id": 39975,
"author_profile": "https://Stackoverflow.com/users/39975",
"pm_score": 0,
"selected": false,
"text": "line=TcsLine.split(\",\")\nif line[2] == \"0\":\n print line\n line=TcsLine.split(\",\")\nif int(line[2]) == 0:\n print line\n"
},
{
"answer_id": 324525,
"author": "Kozyarchuk",
"author_id": 52490,
"author_profile": "https://Stackoverflow.com/users/52490",
"pm_score": 0,
"selected": false,
"text": "line=TcsLine.split(\",\")\nif len(line) >=3 and line[2].rfind(\"0\") != -1:\n print line\n"
},
{
"answer_id": 324686,
"author": "tzot",
"author_id": 6899,
"author_profile": "https://Stackoverflow.com/users/6899",
"pm_score": 1,
"selected": false,
"text": "NumPFCs = eval(line[2])\n NumPFCs = eval(line)[2]\n NumPFCs = eval(eval(line)[2])\n if NumPFCs == \"0\":\n eval"
},
{
"answer_id": 325193,
"author": "Henrik Gustafsson",
"author_id": 2010,
"author_profile": "https://Stackoverflow.com/users/2010",
"pm_score": 0,
"selected": false,
"text": "TcsLine = '[\"baa\",\"beee\",\"0\"]'\n\nline = TcsLine.strip('[]').split(\",\")\nif line[2] == '\"0\"':\n print line\n TcsLine = '[\"baa\",\"beee\",\"0\"]'\n\nline = [e.strip('\"') for e in TcsLine.strip('[]').split(\",\")]\nNumPFCs = int(line[2])\nif NumPFCs==0:\n print line\n TcsLine = '[\"baa\",\"beee\",\"0\"]'\n\n#import json # for >= Python2.6\nimport simplejson as json # for <Python2.6\n\nline = json.loads(TcsLine)\nNumPFCs = int(line[2])\nif NumPFCs==0:\n print line\n"
}
] | 2008/11/27 | [
"https://Stackoverflow.com/questions/324506",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
324,518 | <p>How do you look up a user in Active Directory?</p>
<p>Some example usernames are:</p>
<ul>
<li>avatopia\ian</li>
<li>avatar\ian</li>
<li>ian@avatopia.com</li>
<li>ian@avatopia.local</li>
<li>avatopia.com\ian</li>
</ul>
<p>It's important to note that i don't know the name of the domain, <a href="https://stackoverflow.com/questions/192366/how-to-grab-ad-credentials-from-client-machine-in-a-web-application#192414">and i shouldn't be hard-coding it</a>.</p>
<p>There is some <a href="https://stackoverflow.com/questions/192366/how-to-grab-ad-credentials-from-client-machine-in-a-web-application">sample code on stack-overflow</a> that fails. </p>
<pre><code>using System.DirectoryServices;
/// <summary>
/// Gets the email address, if defined, of a user from Active Directory.
/// </summary>
/// <param name="userid">The userid of the user in question. Make
/// sure the domain has been stripped first!</param>
/// <returns>A string containing the user's email address, or null
/// if one was not defined or found.</returns>
public static string GetEmail(string userid)
{
DirectorySearcher searcher;
SearchResult result;
string email;
// Check first if there is a slash in the userid
// If there is, domain has not been stripped
if (!userid.Contains("\\"))
{
searcher = new DirectorySearcher();
searcher.Filter = String.Format("(SAMAccountName={0})", userid);
searcher.PropertiesToLoad.Add("mail");
result = searcher.FindOne();
if (result != null)
{
email = result.Properties["mail"][0].ToString();
}
}
return email;
}
</code></pre>
<p>It specifically ensures that you didn't pass a full username. e.g. </p>
<pre><code>Bad: avatopia\ian
Bad: avatar\ian
Good: ian
Good: ian
</code></pre>
<p>Because you are not allowed to pass the domain, it can't differentiate between the two users</p>
<pre><code>ian
ian
</code></pre>
<p>Another guy has <a href="https://stackoverflow.com/questions/161398/finding-a-user-in-active-directory-with-the-login-name">the same question</a> on sackoverflow, but the accepted answer says that you must </p>
<blockquote>
<p>first locate the naming context for
the required domain</p>
</blockquote>
<p>i <a href="https://stackoverflow.com/search?q=naming+context+active+directory">don't know</a> what a "naming context" is, and i don't know what the "required domain" is. i'd really rather not write a regular expression to try to parse usernames into domain names and account names, e.g. </p>
<pre><code>domain.something\user-name
</code></pre>
<p>into</p>
<pre><code>domain.something
user-name
</code></pre>
<p>because i know there will be some edge case that i'll get wrong. i want the proper, intended, method of looking up a user in active directory.</p>
<p>There's a nice page on CodeProject <a href="http://www.codeproject.com/KB/system/everythingInAD.aspx" rel="nofollow noreferrer">How to do almost everything in Active Directory</a>, but you can't lookup a user's information by username</p>
<p>i would hope that i can give my domain controller (<a href="http://weblogs.asp.net/steveschofield/archive/2004/04/28/121857.aspx" rel="nofollow noreferrer">whoever it is, where ever it is, whatever it's called</a>) a username, and it will figure out which domain that user belongs to, talk to that domain controller, and get the work done.</p>
| [
{
"answer_id": 324585,
"author": "Ian G",
"author_id": 31765,
"author_profile": "https://Stackoverflow.com/users/31765",
"pm_score": 4,
"selected": true,
"text": " /// This is some imaginary code to show you how to use it\n\n Session[\"USER\"] = User.Identity.Name.ToString();\n Session[\"LOGIN\"] = RemoveDomainPrefix(User.Identity.Name.ToString()); // not a real function :D\n string ldappath = \"LDAP://your_ldap_path\";\n // \"LDAP://CN=<group name>, CN =<Users>, DC=<domain component>, DC=<domain component>,...\"\n\n\n Session[\"cn\"] = GetAttribute(ldappath, (string)Session[\"LOGIN\"], \"cn\");\n Session[\"displayName\"] = GetAttribute(ldappath, (string)Session[\"LOGIN\"], \"displayName\");\n Session[\"mail\"] = GetAttribute(ldappath, (string)Session[\"LOGIN\"], \"mail\");\n Session[\"givenName\"] = GetAttribute(ldappath, (string)Session[\"LOGIN\"], \"givenName\");\n Session[\"sn\"] = GetAttribute(ldappath, (string)Session[\"LOGIN\"], \"sn\");\n\n\n/// working code\n\npublic static string GetAttribute(string ldappath, string sAMAccountName, string attribute)\n {\n string OUT = string.Empty;\n\n try\n {\n DirectoryEntry de = new DirectoryEntry(ldappath);\n DirectorySearcher ds = new DirectorySearcher(de);\n ds.Filter = \"(&(objectClass=user)(objectCategory=person)(sAMAccountName=\" + sAMAccountName + \"))\";\n \n SearchResultCollection results = ds.FindAll();\n\n foreach (SearchResult result in ds.FindAll())\n {\n OUT = GetProperty(result, attribute);\n }\n }\n catch (Exception t)\n {\n // System.Diagnostics.Debug.WriteLine(t.Message);\n }\n\n return (OUT != null) ? OUT : string.Empty;\n }\n\npublic static string GetProperty(SearchResult searchResult, string PropertyName)\n {\n if (searchResult.Properties.Contains(PropertyName))\n {\n return searchResult.Properties[PropertyName][0].ToString();\n }\n else\n {\n return string.Empty;\n }\n }\n public static string GetDomain(string s)\n {\n int stop = s.IndexOf(\"\\\\\");\n return (stop > -1) ? s.Substring(0, stop + 1) : null;\n }\n\n public static string GetLogin(string s)\n {\n int stop = s.IndexOf(\"\\\\\");\n return (stop > -1) ? s.Substring(stop + 1, s.Length - stop - 1) : null;\n }\n public static string GetDomain(string s) //untested\n {\n int stop = s.IndexOf(\"@\");\n return (stop > -1) ? s.Substring(stop + 1, s.Length - stop - 1) : null;\n }\n\n\n public static string GetLogin(string s) //untested\n {\n int stop = s.IndexOf(\"@\");\n return (stop > -1) ? s.Substring(0, stop) : null;\n }\n"
}
] | 2008/11/27 | [
"https://Stackoverflow.com/questions/324518",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12597/"
] |
324,539 | <p>For the moment my batch file look like this:</p>
<pre><code>myprogram.exe param1
</code></pre>
<p>The program starts but the DOS Window remains open. How can I close it?</p>
| [
{
"answer_id": 324540,
"author": "Patrick Desjardins",
"author_id": 13913,
"author_profile": "https://Stackoverflow.com/users/13913",
"pm_score": 8,
"selected": true,
"text": "start myProgram.exe param1\nexit\n"
},
{
"answer_id": 324545,
"author": "Lasse V. Karlsen",
"author_id": 267,
"author_profile": "https://Stackoverflow.com/users/267",
"pm_score": 6,
"selected": false,
"text": "START rest-of-your-program-name\n @echo off\nnotepad c:\\test.txt\n @echo off\nstart notepad c:\\test.txt\n"
},
{
"answer_id": 324546,
"author": "Chris Dail",
"author_id": 5077,
"author_profile": "https://Stackoverflow.com/users/5077",
"pm_score": 4,
"selected": false,
"text": "start \"name\" /B myprogram.exe param1\n"
},
{
"answer_id": 324549,
"author": "VonC",
"author_id": 6309,
"author_profile": "https://Stackoverflow.com/users/6309",
"pm_score": 5,
"selected": false,
"text": "start /b myProgram.exe params...\n wscript.exe invis.vbs myProgram.exe %*\n set args = WScript.Arguments\nnum = args.Count\n\nif num = 0 then\n WScript.Echo \"Usage: [CScript | WScript] invis.vbs aScript.bat <some script arguments>\"\n WScript.Quit 1\nend if\n\nsargs = \"\"\nif num > 1 then\n sargs = \" \"\n for k = 1 to num - 1\n anArg = args.Item(k)\n sargs = sargs & anArg & \" \"\n next\nend if\n\nSet WshShell = WScript.CreateObject(\"WScript.Shell\")\n\nWshShell.Run \"\"\"\" & WScript.Arguments(0) & \"\"\"\" & sargs, 0, False\n"
},
{
"answer_id": 11160353,
"author": "Midas",
"author_id": 1475409,
"author_profile": "https://Stackoverflow.com/users/1475409",
"pm_score": 1,
"selected": false,
"text": "TARGET %COMSPEC% /C \"START \"\" \"PROGRAMNAME\"\" RUN PROGRAMNAME PROGRAMNAME %CD% START IN"
},
{
"answer_id": 12694405,
"author": "Zosimas",
"author_id": 816468,
"author_profile": "https://Stackoverflow.com/users/816468",
"pm_score": 5,
"selected": false,
"text": "start \"cmdWindowTitle\" /B \"javaw\" -cp . testprojectpak.MainForm start Syntax\n START \"title\" [/Dpath] [options] \"command\" [parameters]\n\nKey:\n title : Text for the CMD window title bar (required)\n path : Starting directory\n command : The command, batch file or executable program to run\n parameters : The parameters passed to the command\n\nOptions:\n /MIN : Minimized\n /MAX : Maximized\n /WAIT : Start application and wait for it to terminate\n /LOW : Use IDLE priority class\n /NORMAL : Use NORMAL priority class\n /HIGH : Use HIGH priority class\n /REALTIME : Use REALTIME priority class\n\n /B : Start application without creating a new window. In this case\n ^C will be ignored - leaving ^Break as the only way to \n interrupt the application\n /I : Ignore any changes to the current environment.\n\n Options for 16-bit WINDOWS programs only\n\n /SEPARATE Start in separate memory space (more robust)\n /SHARED Start in shared memory space (default)\n"
},
{
"answer_id": 15549987,
"author": "Marshall",
"author_id": 2195480,
"author_profile": "https://Stackoverflow.com/users/2195480",
"pm_score": 8,
"selected": false,
"text": "Start \"\" \"C:\\Program Files (x86)\\Microsoft Visual Studio 11.0\\Common7\\IDE\\devenv.exe\"\n"
},
{
"answer_id": 29855046,
"author": "Leustad",
"author_id": 4585349,
"author_profile": "https://Stackoverflow.com/users/4585349",
"pm_score": 0,
"selected": false,
"text": "Task Scheduler 'cmd' taskschd.msc Create Basic Task"
},
{
"answer_id": 31487152,
"author": "Gilco",
"author_id": 3213705,
"author_profile": "https://Stackoverflow.com/users/3213705",
"pm_score": 4,
"selected": false,
"text": "@echo off\ncd \"C:\\Program Files\\HeidiSQL\"\nstart heidisql.exe\n\ncd \"C:\\Program Files (x86)\\Google\\Chrome\\Application\"\nstart chrome.exe\n\nexit\n"
},
{
"answer_id": 40959147,
"author": "Ilyich",
"author_id": 2796593,
"author_profile": "https://Stackoverflow.com/users/2796593",
"pm_score": 0,
"selected": false,
"text": "Set WshShell = CreateObject(\"WScript.Shell\")\nWshShell.Run chr(34) & \"C:\\path\\to\\your\\batchfile.bat\" & Chr(34), 0\nSet WshShell = Nothing\n"
},
{
"answer_id": 58880241,
"author": "Gerhard",
"author_id": 7818749,
"author_profile": "https://Stackoverflow.com/users/7818749",
"pm_score": 3,
"selected": false,
"text": "Start \"C:\\Program Files\\someprog.exe\"\n Start Start \"\" \"C:\\Program Files\\someprog.exe\"\n Start \"Window Title\" \"C:\\Program Files\\someprog.exe\"\n"
}
] | 2008/11/27 | [
"https://Stackoverflow.com/questions/324539",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14441/"
] |
324,572 | <p>I am trying to set one bindable variable to be bound to another. Essentially I want to create an alias. I would give up, but this seems like something that would be good to know.</p>
<p>essentially, I want changes in model.configView to be reflected in view, so that things bound to view.... behave the same as things bound to model.configView... in this example <pre>[Bindable]
var view = model.configView;</p>
<p>...
<mx:Label text="{view.lblThisLabel.name}" />
</pre></p>
<p>at the moment it does not, and I am getting errors that say "unable to bind to property 'lblThisLabel' on class 'Object' (class is not an IEventDispatcher)"</p>
| [
{
"answer_id": 324577,
"author": "Simon",
"author_id": 24039,
"author_profile": "https://Stackoverflow.com/users/24039",
"pm_score": 1,
"selected": false,
"text": "view view view lblThisLabel"
},
{
"answer_id": 340916,
"author": "Jérémy Reynaud",
"author_id": 43051,
"author_profile": "https://Stackoverflow.com/users/43051",
"pm_score": 0,
"selected": false,
"text": "view view model.configView"
}
] | 2008/11/27 | [
"https://Stackoverflow.com/questions/324572",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/40397/"
] |
324,604 | <p>Greetings!</p>
<p>If I have XML such as this:</p>
<pre><code><Root>
<AlphaSection>
.
.
.
</AlphaSection>
<BetaSection>
<Choices>
<SetA>
<Choice id="choice1">Choice One</Choice>
<Choice id="choice2">Choice Two</Choice>
</SetA>
<SetB>
<Choice id="choice3">Choice Three</Choice>
<Choice id="choice4">Choice Four</Choice>
</SetB>
</Choices>
</BetaSection>
<GammaSection>
.
.
.
</GammaSection>
</Root>
</code></pre>
<p>I'd like to get all of the Choice items in the "BetaSection", regardless of the "Set" that they belong to. I've tried the following:</p>
<pre><code>var choiceList = from choices in myXDoc.Root.Element("BetaSection").Elements("Choices")
where (choices.Name == "Choice")
select new
{
Name = choices.Attribute("id").Value,
Data = choice.Value
};
</code></pre>
<p>But to no avail. How would I go about this?</p>
<p>Thanks.</p>
| [
{
"answer_id": 324616,
"author": "Jon Skeet",
"author_id": 22656,
"author_profile": "https://Stackoverflow.com/users/22656",
"pm_score": 4,
"selected": true,
"text": "var choiceList = myXDoc.Root\n .Element(\"BetaSection\")\n .Descendants(\"Choice\")\n .Select(element => new\n {\n Name = element.Attribute(\"id\").Value,\n Data = element.Value;\n });\n"
},
{
"answer_id": 324877,
"author": "Eugenio Miró",
"author_id": 41236,
"author_profile": "https://Stackoverflow.com/users/41236",
"pm_score": 0,
"selected": false,
"text": "class Program\n{\n static void Main(string[] args)\n {\n String xml = @\"<Root>\n <AlphaSection></AlphaSection>\n <BetaSection>\n <Choices>\n <SetA>\n <Choice id='choice1'>Choice One</Choice>\n <Choice id='choice2'>Choice Two</Choice>\n </SetA>\n <SetB>\n <Choice id='choice3'>Choice Three</Choice>\n <Choice id='choice4'>Choice Four</Choice>\n </SetB>\n </Choices>\n </BetaSection>\n <GammaSection></GammaSection>\n </Root>\";\n XElement xmlElement = XElement.Parse(xml);\n var choiceList = from c in xmlElement.Descendants().Elements(\"Choice\")\n select new {\n Name = c.Attribute(\"id\").Value,\n Data = c.Value\n };\n foreach (var choice in choiceList) {\n Console.WriteLine(\"Name: {0} Data: {1}\", choice.Name, choice.Data );\n }\n }\n}\n"
}
] | 2008/11/27 | [
"https://Stackoverflow.com/questions/324604",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/27870/"
] |
324,605 | <p>I have a trigger in which I want to have a variable that holds an INT I get from a <code>SELECT</code>, so I can use it in two IF statements instead of calling the <code>SELECT</code> twice. How do you declare/use variables in MySQL triggers?</p>
| [
{
"answer_id": 324715,
"author": "IgorS",
"author_id": 1476181,
"author_profile": "https://Stackoverflow.com/users/1476181",
"pm_score": 3,
"selected": false,
"text": "`CREATE TRIGGER `category_before_ins_tr` BEFORE INSERT ON `category`\n FOR EACH ROW\nBEGIN\n **SET @tableId= (SELECT id FROM dummy LIMIT 1);**\n\nEND;`;\n"
},
{
"answer_id": 328186,
"author": "Bill Karwin",
"author_id": 20860,
"author_profile": "https://Stackoverflow.com/users/20860",
"pm_score": 6,
"selected": false,
"text": "DECLARE DROP TABLE IF EXISTS foo;\nCREATE TABLE FOO (\n i SERIAL PRIMARY KEY\n);\n\nDELIMITER //\nDROP TRIGGER IF EXISTS bar //\n\nCREATE TRIGGER bar AFTER INSERT ON foo\nFOR EACH ROW BEGIN\n DECLARE x INT;\n SET x = NEW.i;\n SET @a = x; -- set user variable outside trigger\nEND//\n\nDELIMITER ;\n\nSET @a = 0;\n\nSELECT @a; -- returns 0\n\nINSERT INTO foo () VALUES ();\n\nSELECT @a; -- returns 1, the value it got during the trigger\n ERROR 1242: Subquery returns more than 1 row LIMIT MAX() CREATE TRIGGER bar AFTER INSERT ON foo\nFOR EACH ROW BEGIN\n DECLARE x INT;\n SET x = (SELECT age FROM users WHERE name = 'Bill'); \n -- ERROR 1242 if more than one row with 'Bill'\nEND//\n\nCREATE TRIGGER bar AFTER INSERT ON foo\nFOR EACH ROW BEGIN\n DECLARE x INT;\n SET x = (SELECT MAX(age) FROM users WHERE name = 'Bill');\n -- OK even when more than one row with 'Bill'\nEND//\n"
},
{
"answer_id": 868469,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 3,
"selected": false,
"text": "CREATE TRIGGER clearcamcdr AFTER INSERT ON `asteriskcdrdb`.`cdr` \nFOR EACH ROW\nBEGIN\n SET @INC = (SELECT sip_inc FROM trunks LIMIT 1);\n IF NEW.billsec >1 AND NEW.channel LIKE @INC \n AND NEW.dstchannel NOT LIKE \"\" \n THEN\n insert into `asteriskcdrdb`.`filtre` (id_appel,date_appel,source,destinataire,duree,sens,commentaire,suivi) \n values (NEW.id,NEW.calldate,NEW.src,NEW.dstchannel,NEW.billsec,\"entrant\",\"\",\"\"); \n END IF;\nEND$$\n"
},
{
"answer_id": 41246122,
"author": "WEBjuju",
"author_id": 2788896,
"author_profile": "https://Stackoverflow.com/users/2788896",
"pm_score": 2,
"selected": false,
"text": "rridprefix rrid on duplicate key BEGIN\n -- prevent duplicate composite keys when merging in archive to main\n SET @EXIST_COMPOSITE_KEY = (SELECT count(*) FROM patientrecords where rridprefix = NEW.rridprefix and rrid = NEW.rrid);\n\n -- if the composite key to be introduced during merge exists, rearrange the data for insert\n IF @EXIST_COMPOSITE_KEY > 0\n THEN\n\n -- set the incoming column data this way (if composite key exists)\n\n -- the legacy duplicate rrid field will help us keep the bad data\n SET NEW.legacyduperrid = NEW.rrid;\n\n -- allow the following block to set the new rrid appropriately\n SET NEW.rrid = null;\n\n END IF;\n\n -- legacy code tried set the rrid (race condition), now the db does it\n SET NEW.rrid = (\n SELECT if(NEW.rrid is null and NEW.legacyduperrid is null, IFNULL(MAX(rrid), 0) + 1, NEW.rrid)\n FROM patientrecords\n WHERE rridprefix = NEW.rridprefix\n );\nEND\n"
},
{
"answer_id": 62671827,
"author": "Reda lehmadi",
"author_id": 13824812,
"author_profile": "https://Stackoverflow.com/users/13824812",
"pm_score": 1,
"selected": false,
"text": "DECLARE\nYourVar varchar(50);\nbegin \nselect ID into YourVar from table\nwhere ...\n"
}
] | 2008/11/27 | [
"https://Stackoverflow.com/questions/324605",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
324,612 | <p>The comments on <a href="http://steve-yegge.blogspot.com/" rel="nofollow noreferrer">Steve Yegge</a>'s <a href="http://steve-yegge.blogspot.com/2008/06/rhinos-and-tigers.html" rel="nofollow noreferrer">post</a> about <a href="http://www.mozilla.org/rhino/" rel="nofollow noreferrer">server-side Javascript</a> started discussing the merits of type systems in languages and this <a href="http://steve-yegge.blogspot.com/2008/06/rhinos-and-tigers.html?showComment=1213654200000#c869153593831177660" rel="nofollow noreferrer">comment</a> describes:</p>
<blockquote>
<p>... examples from <a href="http://en.wikipedia.org/wiki/Hindley-Milner" rel="nofollow noreferrer">H-M</a> style systems where you can get things like: </p>
<pre><code>expected signature Int*Int->Int but got Int*Int->Int
</code></pre>
</blockquote>
<p>Can you give an example of a function definition (or two?) and a function call that would produce that error? That looks like it might be quite hard to debug in a large-ish program.</p>
<p>Also, might I have seen a similar error in <a href="http://miranda.org.uk/" rel="nofollow noreferrer">Miranda</a>? (I have not used it in 15 years and so my memory of it is vague) </p>
| [
{
"answer_id": 324635,
"author": "Barry Kelly",
"author_id": 3712,
"author_profile": "https://Stackoverflow.com/users/3712",
"pm_score": 4,
"selected": true,
"text": "let f x y = x + y;;\n val f : int -> int -> int\n f(1, 2)\n"
},
{
"answer_id": 324663,
"author": "Daniel Spiewak",
"author_id": 9815,
"author_profile": "https://Stackoverflow.com/users/9815",
"pm_score": 2,
"selected": false,
"text": "int int int int int fun f g = g (1, 2);\n\nf (42, fn x => x * 2)\n int * int -> int int * (int -> int)"
},
{
"answer_id": 962074,
"author": "Chris Conway",
"author_id": 1412,
"author_profile": "https://Stackoverflow.com/users/1412",
"pm_score": 2,
"selected": false,
"text": "t # let f x = x + 1;;\nval f : int -> int = <fun>\n# type int = Foo of string;;\ntype int = Foo of string\n# f (Foo \"hello\");;\nThis expression has type int but is here used with type int\n int int # let f g x y = g(x,y) + x + y;;\nval f : (int * int -> int) -> int -> int -> int = <fun>\n# type int = Foo of int;;\ntype int = Foo of int\n# let h (Foo a, Foo b) = (Foo a);;\nval h : int * int -> int = <fun>\n# f h;;\nThis expression has type int * int -> int but is here used with type\n int * int -> int\n"
}
] | 2008/11/27 | [
"https://Stackoverflow.com/questions/324612",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3366/"
] |
324,624 | <p>I have a MFC application in which I want to add internationalization support. The project is configured to use the "multi-byte character set" (the "unicode character set" is not an option in my situation).</p>
<p>Now, I would expect the CWnd::OnChar() function to send me multi-byte characters if I set my keyboard to some foreign language, but it doesn't seem to work that way. The OnChar() function always sends me a 1-byte character in its nChar variable.</p>
<p>I thought that the _getmbcp() function would give me the current code page for the application, but this function always return 0.</p>
<p>Any advice would be appreciated.</p>
| [
{
"answer_id": 325025,
"author": "Michael Burr",
"author_id": 12711,
"author_profile": "https://Stackoverflow.com/users/12711",
"pm_score": 2,
"selected": false,
"text": "SetThreadLocale() setlocale() SetThreadLocale setlocale"
},
{
"answer_id": 338634,
"author": "Martin Cote",
"author_id": 9936,
"author_profile": "https://Stackoverflow.com/users/9936",
"pm_score": 0,
"selected": false,
"text": "SetWindowLongW( m_hWnd, GWL_WNDPROC, GetWindowLong( m_hWnd, GWL_WNDPROC ) );\n"
}
] | 2008/11/27 | [
"https://Stackoverflow.com/questions/324624",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9936/"
] |
324,627 | <p>What is the best way to include data in an HTML page? The data is not human-readable and will be processed by a script once the page has loaded. The options I can think of are:</p>
<ul>
<li><p>Using class and title attributes on hidden/empty <code><div></code> or <code><span></code> elements within the page</p></li>
<li><p>JSON in a <code><script></code> element at the bottom of the page</p></li>
<li><p>Load the data via an XMLHttpRequest after the page has loaded</p></li>
<li><p>XML Data Islands</p></li>
</ul>
<p>All of these methods seem to come with drawbacks so I would like to know what your thoughts are.</p>
| [
{
"answer_id": 325025,
"author": "Michael Burr",
"author_id": 12711,
"author_profile": "https://Stackoverflow.com/users/12711",
"pm_score": 2,
"selected": false,
"text": "SetThreadLocale() setlocale() SetThreadLocale setlocale"
},
{
"answer_id": 338634,
"author": "Martin Cote",
"author_id": 9936,
"author_profile": "https://Stackoverflow.com/users/9936",
"pm_score": 0,
"selected": false,
"text": "SetWindowLongW( m_hWnd, GWL_WNDPROC, GetWindowLong( m_hWnd, GWL_WNDPROC ) );\n"
}
] | 2008/11/27 | [
"https://Stackoverflow.com/questions/324627",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/30119/"
] |
324,633 | <p>I really love WeakReference's. But I wish there was a way to tell the CLR how much (say, on a scale of 1 to 5) how weak you consider the reference to be. That would be brilliant.</p>
<p>Java has SoftReference, WeakReference and I believe also a third type called a "phantom reference". That's 3 levels right there which the GC has a different behaviour algorithm for when deciding if that object gets the chop.</p>
<p>I am thinking of subclassing .NET's WeakReference (luckily and slightly bizzarely it isn't sealed) to make a pseudo-SoftReference that is based on a expiration timer or something.</p>
| [
{
"answer_id": 7102321,
"author": "Adam Gawne-Cain",
"author_id": 899870,
"author_profile": "https://Stackoverflow.com/users/899870",
"pm_score": 4,
"selected": false,
"text": "-Xmx128M -Xmx -Xmx"
}
] | 2008/11/27 | [
"https://Stackoverflow.com/questions/324633",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
324,641 | <p>I have a border element with rounded corners containing a 3x3 grid. The corners of the grid are sticking out of the border. How can I fix that? I tried using ClipToBounds but didn't get anywhere.
Thanks for your help</p>
| [
{
"answer_id": 325003,
"author": "Micah",
"author_id": 17744,
"author_profile": "https://Stackoverflow.com/users/17744",
"pm_score": 7,
"selected": true,
"text": " /// <Remarks>\n /// As a side effect ClippingBorder will surpress any databinding or animation of \n /// its childs UIElement.Clip property until the child is removed from ClippingBorder\n /// </Remarks>\n public class ClippingBorder : Border {\n protected override void OnRender(DrawingContext dc) {\n OnApplyChildClip(); \n base.OnRender(dc);\n }\n\n public override UIElement Child \n {\n get\n {\n return base.Child;\n }\n set\n {\n if (this.Child != value)\n {\n if(this.Child != null)\n {\n // Restore original clipping\n this.Child.SetValue(UIElement.ClipProperty, _oldClip);\n }\n\n if(value != null)\n {\n _oldClip = value.ReadLocalValue(UIElement.ClipProperty);\n }\n else \n {\n // If we dont set it to null we could leak a Geometry object\n _oldClip = null;\n }\n\n base.Child = value;\n }\n }\n }\n\n protected virtual void OnApplyChildClip()\n {\n UIElement child = this.Child;\n if(child != null)\n {\n _clipRect.RadiusX = _clipRect.RadiusY = Math.Max(0.0, this.CornerRadius.TopLeft - (this.BorderThickness.Left * 0.5));\n _clipRect.Rect = new Rect(Child.RenderSize);\n child.Clip = _clipRect;\n }\n }\n\n private RectangleGeometry _clipRect = new RectangleGeometry();\n private object _oldClip;\n }\n"
},
{
"answer_id": 8614051,
"author": "DXM",
"author_id": 459146,
"author_profile": "https://Stackoverflow.com/users/459146",
"pm_score": 3,
"selected": false,
"text": "<Border CornerRadius=\"10\">\n <Grid>\n ... your UI ...\n </Grid>\n</Border>\n <Grid> <Border>"
},
{
"answer_id": 18628179,
"author": "Artur A",
"author_id": 304371,
"author_profile": "https://Stackoverflow.com/users/304371",
"pm_score": 4,
"selected": false,
"text": "ClipToBounds Border.ConerRadius Border <Border Background=\"Blue\" CornerRadius=\"3\" Height=\"100\" Width=\"100\">\n <Border.Clip>\n <RectangleGeometry RadiusX=\"3\" RadiusY=\"3\" Rect=\"0,0,100,100\"/>\n </Border.Clip>\n <Grid Background=\"Green\"/>\n</Border>\n Converter Border.Clip"
},
{
"answer_id": 28344788,
"author": "Andrew Mikhailov",
"author_id": 963384,
"author_profile": "https://Stackoverflow.com/users/963384",
"pm_score": 6,
"selected": false,
"text": "<Border CornerRadius=\"30\" Background=\"Green\">\n <Border.OpacityMask>\n <VisualBrush>\n <VisualBrush.Visual>\n <Border \n Background=\"Black\"\n SnapsToDevicePixels=\"True\"\n CornerRadius=\"{Binding CornerRadius, RelativeSource={RelativeSource AncestorType=Border}}\"\n Width=\"{Binding ActualWidth, RelativeSource={RelativeSource AncestorType=Border}}\"\n Height=\"{Binding ActualHeight, RelativeSource={RelativeSource AncestorType=Border}}\"\n />\n </VisualBrush.Visual>\n </VisualBrush>\n </Border.OpacityMask>\n <TextBlock Text=\"asdas das d asd a sd a sda\" />\n</Border>\n <Grid>\n <Grid.OpacityMask>\n <VisualBrush Visual=\"{Binding ElementName=Border1}\" />\n </Grid.OpacityMask>\n <Border x:Name=\"Border1\" CornerRadius=\"30\" Background=\"Green\" />\n <TextBlock Text=\"asdas das d asd a sd a sda\" />\n</Grid>\n"
},
{
"answer_id": 42009469,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "VisualBrush public class ClippedBorder : Border\n{\n public ClippedBorder() : base()\n {\n var e = new Border()\n {\n Background = Brushes.Black,\n SnapsToDevicePixels = true,\n };\n e.SetBinding(Border.CornerRadiusProperty, new Binding()\n {\n Mode = BindingMode.OneWay,\n Path = new PropertyPath(\"CornerRadius\"),\n Source = this\n });\n e.SetBinding(Border.HeightProperty, new Binding()\n {\n Mode = BindingMode.OneWay,\n Path = new PropertyPath(\"ActualHeight\"),\n Source = this\n });\n e.SetBinding(Border.WidthProperty, new Binding()\n {\n Mode = BindingMode.OneWay,\n Path = new PropertyPath(\"ActualWidth\"),\n Source = this\n });\n\n OpacityMask = new VisualBrush(e);\n }\n}\n <!-- You should see a blue rectangle with rounded corners/no red! -->\n<Controls:ClippedBorder\n Background=\"Red\"\n CornerRadius=\"10\"\n Height=\"425\"\n HorizontalAlignment=\"Center\"\n VerticalAlignment=\"Center\"\n Width=\"425\">\n <Border Background=\"Blue\">\n </Border>\n</Controls:ClippedBorder>\n\n<!-- You should see a blue rectangle with NO rounded corners/still no red! -->\n<Border\n Background=\"Red\"\n CornerRadius=\"10\"\n Height=\"425\"\n HorizontalAlignment=\"Center\"\n VerticalAlignment=\"Center\"\n Width=\"425\">\n <Border Background=\"Blue\">\n </Border>\n</Border>\n"
},
{
"answer_id": 52420494,
"author": "Der_Meister",
"author_id": 991267,
"author_profile": "https://Stackoverflow.com/users/991267",
"pm_score": 0,
"selected": false,
"text": "using System.Linq;\nusing System.Windows;\nusing System.Windows.Interactivity;\n\n/// <summary>\n/// Base class for behaviors that could be used in style.\n/// </summary>\n/// <typeparam name=\"TComponent\">Component type.</typeparam>\n/// <typeparam name=\"TBehavior\">Behavior type.</typeparam>\npublic class AttachableForStyleBehavior<TComponent, TBehavior> : Behavior<TComponent>\n where TComponent : System.Windows.DependencyObject\n where TBehavior : AttachableForStyleBehavior<TComponent, TBehavior>, new()\n{\n#pragma warning disable SA1401 // Field must be private.\n\n /// <summary>\n /// IsEnabledForStyle attached property.\n /// </summary>\n public static DependencyProperty IsEnabledForStyleProperty =\n DependencyProperty.RegisterAttached(\"IsEnabledForStyle\", typeof(bool),\n typeof(AttachableForStyleBehavior<TComponent, TBehavior>), new FrameworkPropertyMetadata(false, OnIsEnabledForStyleChanged));\n\n#pragma warning restore SA1401\n\n /// <summary>\n /// Sets IsEnabledForStyle value for element.\n /// </summary>\n public static void SetIsEnabledForStyle(UIElement element, bool value)\n {\n element.SetValue(IsEnabledForStyleProperty, value);\n }\n\n /// <summary>\n /// Gets IsEnabledForStyle value for element.\n /// </summary>\n public static bool GetIsEnabledForStyle(UIElement element)\n {\n return (bool)element.GetValue(IsEnabledForStyleProperty);\n }\n\n private static void OnIsEnabledForStyleChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)\n {\n UIElement uie = d as UIElement;\n\n if (uie != null)\n {\n var behColl = Interaction.GetBehaviors(uie);\n var existingBehavior = behColl.FirstOrDefault(b => b.GetType() ==\n typeof(TBehavior)) as TBehavior;\n\n if ((bool)e.NewValue == false && existingBehavior != null)\n {\n behColl.Remove(existingBehavior);\n }\n else if ((bool)e.NewValue == true && existingBehavior == null)\n {\n behColl.Add(new TBehavior());\n }\n }\n }\n}\n using System.Windows;\nusing System.Windows.Controls;\nusing System.Windows.Data;\nusing System.Windows.Media;\n\n/// <summary>\n/// Behavior that creates opacity mask brush.\n/// </summary>\ninternal class OpacityMaskBehavior : AttachableForStyleBehavior<Border, OpacityMaskBehavior>\n{\n protected override void OnAttached()\n {\n base.OnAttached();\n\n var border = new Border()\n {\n Background = Brushes.Black,\n SnapsToDevicePixels = true,\n };\n\n border.SetBinding(Border.CornerRadiusProperty, new Binding()\n {\n Mode = BindingMode.OneWay,\n Path = new PropertyPath(\"CornerRadius\"),\n Source = AssociatedObject\n });\n\n border.SetBinding(FrameworkElement.HeightProperty, new Binding()\n {\n Mode = BindingMode.OneWay,\n Path = new PropertyPath(\"ActualHeight\"),\n Source = AssociatedObject\n });\n\n border.SetBinding(FrameworkElement.WidthProperty, new Binding()\n {\n Mode = BindingMode.OneWay,\n Path = new PropertyPath(\"ActualWidth\"),\n Source = AssociatedObject\n });\n\n AssociatedObject.OpacityMask = new VisualBrush(border);\n }\n\n protected override void OnDetaching()\n {\n base.OnDetaching();\n\n AssociatedObject.OpacityMask = null;\n }\n}\n <Style x:Key=\"BorderWithRoundCornersStyle\" TargetType=\"{x:Type Border}\">\n <Setter Property=\"CornerRadius\" Value=\"50\" />\n <Setter Property=\"behaviors:OpacityMaskBehavior.IsEnabledForStyle\" Value=\"True\" />\n</Style>\n"
}
] | 2008/11/27 | [
"https://Stackoverflow.com/questions/324641",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/28029/"
] |
324,643 | <p>In C++ often do something like this:</p>
<pre><code>typedef map<int, vector<int> > MyIndexType;
</code></pre>
<p>Where I then use it like this:</p>
<pre><code>MyIndexType myIndex;
for( ... some loop ...)
{
myIndex[someId].push_back(someVal);
}
</code></pre>
<p>If there was no entry in the map the code will insert a new empty vector and then append to it.</p>
<p>In Python it would look like this:</p>
<pre><code>myIndex = {}
for (someId,someVal) in collection:
try:
myIndex[someId].append(someVal)
except KeyError:
myIndex[someId] = [someVal]
</code></pre>
<p>The try except is a bit ugly here. Is there a way to tell the dictionary an object type to insert when a KeyError is encountered at dictionary declaration time?</p>
| [
{
"answer_id": 324648,
"author": "Alastair",
"author_id": 31038,
"author_profile": "https://Stackoverflow.com/users/31038",
"pm_score": 3,
"selected": false,
"text": "myIndex = {}\nfor (someId,someVal) in collection:\n myIndex.setdefault(someId, []).append(someVal)\n"
},
{
"answer_id": 324653,
"author": "ddaa",
"author_id": 11549,
"author_profile": "https://Stackoverflow.com/users/11549",
"pm_score": 5,
"selected": true,
"text": "from collections import defaultdict\nmyIndex = defaultdict(list)\nmyIndex[someId].append(someVal)\n defaultdict >>> s = [('yellow', 1), ('blue', 2), ('yellow', 3), ('blue', 4), ('red', 1)]\n>>> d = defaultdict(list)\n>>> for k, v in s:\n d[k].append(v)\n\n>>> d.items()\n[('blue', [2, 4]), ('red', [1]), ('yellow', [1, 3])]\n"
},
{
"answer_id": 324660,
"author": "Matt Campbell",
"author_id": 41110,
"author_profile": "https://Stackoverflow.com/users/41110",
"pm_score": 0,
"selected": false,
"text": "myIndex = {}\n\nfor (someId,someVal) in collection:\n if someId not in myIndex:\n myIndex[someId] = []\n myIndex[someId].append(someVal)\n"
},
{
"answer_id": 324721,
"author": "Boris Gorelik",
"author_id": 17523,
"author_profile": "https://Stackoverflow.com/users/17523",
"pm_score": 2,
"selected": false,
"text": "myIndex = {}\nsomeId = None\nmyList = myIndex.get(someId, []) # myList is [] now\n"
},
{
"answer_id": 324723,
"author": "Henrik Gustafsson",
"author_id": 2010,
"author_profile": "https://Stackoverflow.com/users/2010",
"pm_score": 1,
"selected": false,
"text": "__missing__(k)\n"
}
] | 2008/11/27 | [
"https://Stackoverflow.com/questions/324643",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7743/"
] |
324,649 | <p>Some examples I found that apparently worked with older versions of mvc suggest that there was a length parameter of sorts:</p>
<pre><code><%=Html.TextBox("test", 50)%>
</code></pre>
<p>But that may have been mistakenly setting the value.</p>
<p>How do this work in the current release? Passing in the style doesn't appear to have any effect.</p>
| [
{
"answer_id": 324751,
"author": "Tim Scott",
"author_id": 29493,
"author_profile": "https://Stackoverflow.com/users/29493",
"pm_score": 3,
"selected": false,
"text": "<%=Html.TextBox(\"test\", new { style=\"width:50px\" })%>\n <%=Html.TextBox(\"test\")%>\n\n<style type=\"text/css\">\n input[type=\"text\"] { width:50px; } \n</style>\n"
},
{
"answer_id": 324774,
"author": "Drejc",
"author_id": 6482,
"author_profile": "https://Stackoverflow.com/users/6482",
"pm_score": 1,
"selected": false,
"text": "<input style=\"width:100px\" />\n"
},
{
"answer_id": 325077,
"author": "Nikita Ignatov",
"author_id": 40185,
"author_profile": "https://Stackoverflow.com/users/40185",
"pm_score": 5,
"selected": false,
"text": "new { Attrubute=\"Value\", AttributeTwo = IntegerValue, @class=\"className\" };\n new { style=\"width:50px\" };\nnew { style=\"width:50px\", maxsize = 50 };\nnew {size=30, @class=\"required\"}\n <%= Html.TextBox(\"test\", new { style=\"width:50px\" }) %> \n <%= Html.TextBox(\"test\", null, new { style=\"width:50px\" }) %> \n @Html.TextBox(\"test\", null, new { style=\"width:50px\" })\n"
},
{
"answer_id": 2123862,
"author": "Bob Palmer",
"author_id": 198770,
"author_profile": "https://Stackoverflow.com/users/198770",
"pm_score": 7,
"selected": true,
"text": "<%=Html.TextBox(\"test\", new { style=\"width:50px\" })%> \n <%=Html.TextBox(\"test\", \"\", new { style=\"width:50px\" })%> \n"
},
{
"answer_id": 5642856,
"author": "NoWar",
"author_id": 196919,
"author_profile": "https://Stackoverflow.com/users/196919",
"pm_score": 1,
"selected": false,
"text": "<% using (Html.BeginForm()) { %>\n\n<p>\n\nStart Date: <%: Html.TextBox(\"datepicker1\", DateTime.Now.ToString(\"MM/dd/yyyy\"), new { style = \"width:80px;\", maxlength = 10 })%> \n\nEnd Date: <%: Html.TextBox(\"datepicker2\", DateTime.Now.ToString(\"MM/dd/yyyy\"), new { style = \"width:80px;\", maxlength = 10 })%> \n\n<input type=\"submit\" name=\"btnSubmit\" value=\"Search\" /> \n\n</p>\n\n<% } %>\n"
},
{
"answer_id": 14191124,
"author": "Manoj",
"author_id": 1954228,
"author_profile": "https://Stackoverflow.com/users/1954228",
"pm_score": 0,
"selected": false,
"text": "@Html.TextBoxFor(model => model.SearchUrl, new { style = \"width:650px;\",maxlength = 250 }) \n"
}
] | 2008/11/27 | [
"https://Stackoverflow.com/questions/324649",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9913/"
] |
324,665 | <p>Is it faster to do the following:</p>
<pre><code> if ($var != 'test1' && $var != 'test2' && $var != 'test3' && $var != 'test4') { ... }
</code></pre>
<p>Or:</p>
<pre><code> if (!in_array($var, array('test1', 'test2', 'test3', 'test4') { ... }
</code></pre>
<p>Is there a number of values at which point it's faster to do one or the other?</p>
<p>(In this case, the array used in the second option doesn't alreay exist.)</p>
| [
{
"answer_id": 324669,
"author": "Owen",
"author_id": 4853,
"author_profile": "https://Stackoverflow.com/users/4853",
"pm_score": 5,
"selected": true,
"text": "in_array() $array = array('test1', 'test2', 'test3', 'test4');\n$var = 'test';\n$iterations = 1000000;\n\n$start = microtime(true);\nfor($i = 0; $i < $iterations; ++$i) {\n if ($var != 'test1' && $var != 'test2' && $var != 'test3' && $var != 'test4') {}\n}\n$end = microtime(true);\n\nprint \"Time1: \". ($end - $start).\"<br />\";\n\n$start2 = microtime(true);\nfor($i = 0; $i < $iterations; ++$i) {\n if (!in_array($var, $array) ) {}\n}\n$end2 = microtime(true);\n\nprint \"Time2: \".($end2 - $start2).\"<br />\";\n\n// Time1: 1.12536692619\n// Time2: 1.57462596893\n $var test3 Time1: 0.20484399795532\nTime2: 0.29854393005371\n Time1: 0.064045906066895\nTime2: 0.056781053543091\n Time1: 0.048759937286377\nTime2: 0.049691915512085\n Time1: 0.045055150985718\nTime2: 0.049431085586548\n"
},
{
"answer_id": 324671,
"author": "Greg",
"author_id": 24181,
"author_profile": "https://Stackoverflow.com/users/24181",
"pm_score": 3,
"selected": false,
"text": "Time1: 1.33601498604\nTime2: 4.9349629879\n Time1: 1.34736609459\nTime2: 6.29464697838\n"
},
{
"answer_id": 324676,
"author": "Sparr",
"author_id": 13675,
"author_profile": "https://Stackoverflow.com/users/13675",
"pm_score": 2,
"selected": false,
"text": "$array2 = array_flip($array);\n$iterations = 10000000;\n\n$start = microtime(true);\nfor($i = 0; $i < $iterations; ++$i) {\n if (!isset($array2[$var])) {}\n}\n$end = microtime(true);\nprint \"Time3: \".($end - $start).\"<br />\";\n\nTime1: 12.875\nTime2: 13.7037701607\nTime3: 3.70514011383\n"
},
{
"answer_id": 324934,
"author": "Rob",
"author_id": 3542,
"author_profile": "https://Stackoverflow.com/users/3542",
"pm_score": 3,
"selected": false,
"text": "!== in_array true !="
},
{
"answer_id": 552231,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "$array = array('test1', 'test2', 'test3', 'test4');\n$var = 'test';\n$iterations = 1000000;\n\n$start = microtime(true);\nfor($i = 0; $i < $iterations; ++$i) {\n if ($var != 'test1' && $var != 'test2' && $var != 'test3' && $var != 'test4') {}\n}\nprint \"Time1: \". (microtime(true) - $start);\n\n$start = microtime(true);\nfor($i = 0; $i < $iterations; ++$i) {\n if (!in_array($var, $array) ) {}\n}\nprint \"Time2: \".(microtime(true) - $start);\n\n$start = microtime(true);\nfor($i = 0; $i < $iterations; ++$i) {\n if (!in_array($var, array('test1', 'test2', 'test3', 'test4')) ) {}\n}\nprint \"Time2a: \".(microtime(true) - $start);\n\n$array2 = array_flip($array);\n$start = microtime(true);\nfor($i = 0; $i < $iterations; ++$i) {\n if (!isset($array2[$var])) {}\n}\nprint \"Time3: \".(microtime(true) - $start);\n\n$start = microtime(true);\nfor($i = 0; $i < $iterations; ++$i) {\n $array2 = array_flip($array);\n if (!isset($array2[$var])) {}\n}\nprint \"Time3a: \".(microtime(true) - $start);\n Time1 : 0.59490108493 // straight comparison\nTime2 : 0.83790588378 // array() outside loop - not accurate\nTime2a: 2.16737604141 // array() inside loop\nTime3 : 0.16908097267 // array_flip outside loop - not accurate\nTime3a: 1.57209014893 // array_flip inside loop\n array_flip"
},
{
"answer_id": 27418758,
"author": "user2729768",
"author_id": 2729768,
"author_profile": "https://Stackoverflow.com/users/2729768",
"pm_score": 2,
"selected": false,
"text": "$var = 'test';\n$num_values = 1000;\n$iterations = 1000000;\nprint \"\\nComparison performance test with \".$num_values.\" values and \".$iterations.\" loop iterations\";\nprint \"\\n\";\n\n$start = microtime(true);\nfor($i = 0; $i < $iterations; ++$i) {\n if ($var != 'test0' &&\n $var != 'test1' &&\n // ...\n // yes I really have 1000 lines in my file\n // ...\n $var != 'test999') {}\n}\nprint \"\\nCase 1: plain comparison\";\nprint \"\\nTime 1: \". (microtime(true) - $start);\nprint \"\\n\";\n\n$start = microtime(true);\n$array = array();\nfor($i=0; $i<$num_values; $i++) {\n $array1[] = 'test'.$i;\n}\nfor($i = 0; $i < $iterations; ++$i) {\n if (!in_array($var, $array1) ) {}\n}\nprint \"\\nCase 2: in_array comparison\";\nprint \"\\nTime 2: \".(microtime(true) - $start);\nprint \"\\n\";\n\n$start = microtime(true);\n$array = array();\nfor($i=0; $i<$num_values; $i++) {\n $array2['test'.$i] = 1;\n}\nfor($i = 0; $i < $iterations; ++$i) {\n if (!isset($array2[$var])) {}\n}\nprint \"\\nCase 3: values as keys, isset comparison\";\nprint \"\\nTime 3: \".(microtime(true) - $start);\nprint \"\\n\";\n\n$start = microtime(true);\n$array = array();\nfor($i=0; $i<$num_values; $i++) {\n $array3['test'.$i] = 1;\n}\nfor($i = 0; $i < $iterations; ++$i) {\n if (!array_key_exists($var, $array3)) {}\n}\nprint \"\\nCase 4: values as keys, array_key_exists comparison\";\nprint \"\\nTime 4: \".(microtime(true) - $start);\nprint \"\\n\";\n Case 1: plain comparison\nTime 1: 31.616894006729\n\nCase 2: in_array comparison\nTime 2: 23.226133823395\n\nCase 3: values as keys, isset comparison\nTime 3: 0.050863981246948\n\nCase 4: values as keys, array_key_exists comparison\nTime 4: 0.13700890541077\n"
},
{
"answer_id": 30968868,
"author": "Mark Goldfain",
"author_id": 2013894,
"author_profile": "https://Stackoverflow.com/users/2013894",
"pm_score": 1,
"selected": false,
"text": "switch ($var)\n{ case 'test1': case 'test2': case 'test3': case 'test4':\n echo \"We have a good value\"; break;\n default:\n echo \"We do not have a good value\";\n}\n"
},
{
"answer_id": 45902815,
"author": "vr_driver",
"author_id": 1190051,
"author_profile": "https://Stackoverflow.com/users/1190051",
"pm_score": 0,
"selected": false,
"text": "foreach(array_values($haystack) as $v)\n $new_haystack[$v] = 1; \n}\n\n// So haystack becomes:\n$arr[“String1”] = 1;\n$arr[“String2”] = 1;\n$arr[“String3”] = 1;\n\n\n// Then check for the key:\nif (isset($haystack[$needle])) {\n echo(\"needle \".$needle.\" found in haystack\");\n}\n"
},
{
"answer_id": 54601641,
"author": "Eliu Florez",
"author_id": 11036068,
"author_profile": "https://Stackoverflow.com/users/11036068",
"pm_score": 0,
"selected": false,
"text": "$array = array('test1', 'test2', 'test3', 'test4');\n$var = 'test';\n$iterations = 1000000;\n\n$start = microtime(true);\nfor($i = 0; $i < $iterations; ++$i) {\n if ($var != 'test1' && $var != 'test2' && $var != 'test3' && $var != 'test4') {}\n}\n$end = microtime(true);\n\nprint \"Time1: \". ($end - $start).\"<br />\";\n\n$start2 = microtime(true);\nfor($i = 0; $i < $iterations; ++$i) {\n if (!in_array($var, $array) ) {}\n}\n$end2 = microtime(true);\n\nprint \"Time2: \".($end2 - $start2).\"<br />\";\n\n$array_flip = array_flip($array);\n\n$start = microtime(true);\nfor($i = 0; $i < $iterations; ++$i) {\n if (!isset($array_flip[$var])) {}\n}\n$end = microtime(true);\nprint \"Time3: \".($end - $start).\"<br />\";\n\n$start = microtime(true);\nfor($i = 0; $i < $iterations; ++$i) {\n if (!isset($array[$var])) {}\n}\n$end = microtime(true);\n\nprint \"Time4: \". ($end - $start).\"<br />\";\n"
}
] | 2008/11/27 | [
"https://Stackoverflow.com/questions/324665",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5441/"
] |
324,666 | <p>When implementing an +initialize or +load method in one of your Objective-C classes, should you <em>always</em> start with this kind of guard?:</p>
<pre><code>@implementation MyClass
+ (void)initialize {
if (self == [MyClass class]) {
...
}
}
...
@end
</code></pre>
<p>Seems like code in +load and +initialize usually only wants to be executed once. So this would help avoid dupe execution when subclasses load/initialize.</p>
<p>I guess I'm just wanting some reinforcement from some ObjC wizards that this is necessary/common practice...</p>
<p>What's the common wisdom on this? would you recommend always doing this?</p>
<p>Is your advice the same for both +load and +initialize, or is there a difference in they way they should be handled?</p>
<p>thanks.</p>
| [
{
"answer_id": 324719,
"author": "Matt Gallagher",
"author_id": 36103,
"author_profile": "https://Stackoverflow.com/users/36103",
"pm_score": 3,
"selected": true,
"text": "id myGlobalObject = nil;\n\n+(void)initialize\n{\n if (myGlobalObject == nil)\n {\n myGlobalObject = [[MyGlobalClass alloc] init];\n }\n}\n"
},
{
"answer_id": 324734,
"author": "e.James",
"author_id": 33686,
"author_profile": "https://Stackoverflow.com/users/33686",
"pm_score": 3,
"selected": false,
"text": "+initialize +initialize"
},
{
"answer_id": 18143488,
"author": "Lings",
"author_id": 2118477,
"author_profile": "https://Stackoverflow.com/users/2118477",
"pm_score": 1,
"selected": false,
"text": "@implementation BaseClass\n\n+ (void)initialize\n{\n NSLog(@\"BaseClass initialize self=%@, class=%@\", self, [BaseClass class]);\n}\n\n@end\n\n@interface SubClass : BaseClass\n@end\n\n@implementation SubClass\n\n// don't implement the initialize method\n\n@end\n [SNSBaseSubLogic alloc]\n BaseClass initialize self=BaseClass, class=BaseClass\nBaseClass initialize self=SubClass, class=BaseClass\n + (void)initialize\n{\n if (self == [BaseClass class]) {\n NSLog(@\"BaseClass initialize self=%@, class=%@\", self, [BaseClass class]);\n }\n}\n"
}
] | 2008/11/27 | [
"https://Stackoverflow.com/questions/324666",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/34934/"
] |
324,670 | <p>We perform updates of large text files by writing new records to a temp file, then replacing the old file with the temp file. A heavily abbreviated version:</p>
<pre><code>var tpath = Path.GetTempFileName();
try
{
using (var sf = new StreamReader(sourcepath))
using (var tf = new StreamWriter(tpath))
{
string line;
while ((line = sf.ReadLine()) != null)
tf.WriteLine(UpdateLine(line));
}
File.Delete(sourcepath);
File.Move(tpath, sourcepath);
}
catch
{
File.Delete(tpath);
throw;
}
</code></pre>
<p>If anything throws an exception (file not found, no permission), the original file is left untouched, which is what we want.</p>
<p>However, the code has the following problems:</p>
<ol>
<li><p>Is there a real-world situation where the <code>Delete</code> works but the <code>Move</code> fails? This would delete the original and updated data. This would be bad.</p></li>
<li><p>The most common failure is the source file being open from another application, and the <code>Delete</code> fails. This means all the Update work is discarded. Is there a way to see if the source file is deletable at the start, and abandon the update if not?</p></li>
<li><p>We have users putting Windows Explorer Summary properties, like Title or Comments, on files. These are discarded when we delete the file. Is there a way to copy the old file's Summary properties to a new file? Should we do this?</p></li>
</ol>
| [
{
"answer_id": 324760,
"author": "jyoung",
"author_id": 14841,
"author_profile": "https://Stackoverflow.com/users/14841",
"pm_score": 0,
"selected": false,
"text": "class Program {\n static void Main( string[] args ) {\n using( var ft = new FileTransaction( @\"C:\\MyDir\\MyFile.txt\" ) )\n using( var sw = new StreamWriter( ft.TempPath ) ) {\n sw.WriteLine( \"Hello\" );\n ft.Commit();\n }\n }\n}\n\npublic class FileTransaction :IDisposable {\n public string TempPath { get; private set; }\n private readonly string filePath;\n\n public FileTransaction( string filePath ) {\n this.filePath = filePath;\n this.TempPath = Path.GetTempFileName();\n }\n\n public void Dispose() {\n if( TempPath != null ) {\n try {\n File.Delete( TempPath );\n }\n catch { }\n }\n }\n\n public void Commit() {\n try {\n var oldPath = filePath + \".old\";\n File.Move( filePath, oldPath );\n }\n catch {}\n\n File.Move( TempPath, filePath );\n\n TempPath = null;\n }\n}\n"
},
{
"answer_id": 324791,
"author": "D3vtr0n",
"author_id": 40899,
"author_profile": "https://Stackoverflow.com/users/40899",
"pm_score": 2,
"selected": false,
"text": "//If File is readonly\nif ( (file.Attribute & System.FileAttributes.ReadOnly) == System.FileAttributes.ReadOnly ) \n //Don't delete. \n FileStream fs = File.OpenWrite(file);\n fs.Close();\n return false; \n protected virtual bool IsFileLocked(FileInfo file)\n{\n try\n {\n using (file.Open(FileMode.Open, FileAccess.ReadWrite, FileShare.None))\n {\n return false;\n }\n }\n\n catch (IOException)\n {\n return true;\n }\n fileIOPerm = New FileIOPermission(FileIOPermissionAccess.Write, FileSpec);\nfileIOPerm.Demand();\n"
},
{
"answer_id": 327033,
"author": "Dour High Arch",
"author_id": 22437,
"author_profile": "https://Stackoverflow.com/users/22437",
"pm_score": 2,
"selected": true,
"text": "var sInfo = new FileInfo(sourcePath);\nif (sInfo.IsReadOnly)\n throw new IOException(\"File '\" + sInfo.FullName + \"' is read-only.\");\n\nvar tPath = Path.GetTempFileName();\ntry\n{\n // This throws if sourcePath does not exist, is opened, or is not readable.\n using (var sf = sInfo.OpenText())\n using (var tf = new StreamWriter(tPath))\n {\n string line;\n while ((line = sf.ReadLine()) != null)\n tf.WriteLine(UpdateLine(line));\n }\n\n string backupPath = sInfo.FullName + \".bak\";\n if (File.Exists(backupPath))\n File.Delete(backupPath);\n\n File.Move(tPath, backupPath);\n tPath = backupPath;\n File.Replace(tPath, sInfo.FullName, null);\n}\ncatch (Exception ex)\n{\n File.Delete(tPath);\n throw new IOException(\"File '\" + sInfo.FullName + \"' could not be overwritten.\", ex);\n}\n OpenText Replace"
},
{
"answer_id": 327039,
"author": "Mitch Wheat",
"author_id": 16076,
"author_profile": "https://Stackoverflow.com/users/16076",
"pm_score": 0,
"selected": false,
"text": "// Try to open a file exclusively\nFileInfo fi = new FileInfo(fullFilePath);\n\nint attempts = maxAttempts;\ndo\n{\n try\n {\n // Try to open for reading with exclusive access...\n fs = fi.Open(FileMode.Open, FileAccess.Read, FileShare.None);\n }\n // Ignore any errors... \n catch { }\n\n if (fs != null)\n {\n break;\n }\n else\n {\n Thread.Sleep(100);\n }\n}\nwhile (--attempts > 0);\n\n// Did we manage to open file exclusively?\nif (fs != null)\n{\n // use open file....\n\n}\n"
}
] | 2008/11/27 | [
"https://Stackoverflow.com/questions/324670",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/22437/"
] |
324,677 | <p>I have clustered applications that requires one of the nodes to be designated as the master. The cluster nodes are tracked in a table with <strong>nodeID</strong>, <strong>isMaster</strong>, <strong>lastTimestamp</strong> columns.</p>
<p>Each node in the cluster will try to become a master every <strong>X</strong> seconds. Node can only become a master if either</p>
<ul>
<li>there is no other master nodes </li>
<li>the <strong>lastTimestamp</strong> on current master node is older by <strong>2*X</strong></li>
</ul>
<p>When one of the above conditions is satisfied</p>
<ul>
<li>the current master node's <strong>isMaster</strong> should be cleared</li>
<li>the new master node's <strong>isMaster</strong> should be set</li>
<li>the new master node's <strong>lastTimestamp</strong> should be set to 'now' timestamp.</li>
</ul>
<p>What is the <strong>single</strong> (portable) SQL statement to achieve the above without the possibility of two or more nodes becoming the master?</p>
| [
{
"answer_id": 324760,
"author": "jyoung",
"author_id": 14841,
"author_profile": "https://Stackoverflow.com/users/14841",
"pm_score": 0,
"selected": false,
"text": "class Program {\n static void Main( string[] args ) {\n using( var ft = new FileTransaction( @\"C:\\MyDir\\MyFile.txt\" ) )\n using( var sw = new StreamWriter( ft.TempPath ) ) {\n sw.WriteLine( \"Hello\" );\n ft.Commit();\n }\n }\n}\n\npublic class FileTransaction :IDisposable {\n public string TempPath { get; private set; }\n private readonly string filePath;\n\n public FileTransaction( string filePath ) {\n this.filePath = filePath;\n this.TempPath = Path.GetTempFileName();\n }\n\n public void Dispose() {\n if( TempPath != null ) {\n try {\n File.Delete( TempPath );\n }\n catch { }\n }\n }\n\n public void Commit() {\n try {\n var oldPath = filePath + \".old\";\n File.Move( filePath, oldPath );\n }\n catch {}\n\n File.Move( TempPath, filePath );\n\n TempPath = null;\n }\n}\n"
},
{
"answer_id": 324791,
"author": "D3vtr0n",
"author_id": 40899,
"author_profile": "https://Stackoverflow.com/users/40899",
"pm_score": 2,
"selected": false,
"text": "//If File is readonly\nif ( (file.Attribute & System.FileAttributes.ReadOnly) == System.FileAttributes.ReadOnly ) \n //Don't delete. \n FileStream fs = File.OpenWrite(file);\n fs.Close();\n return false; \n protected virtual bool IsFileLocked(FileInfo file)\n{\n try\n {\n using (file.Open(FileMode.Open, FileAccess.ReadWrite, FileShare.None))\n {\n return false;\n }\n }\n\n catch (IOException)\n {\n return true;\n }\n fileIOPerm = New FileIOPermission(FileIOPermissionAccess.Write, FileSpec);\nfileIOPerm.Demand();\n"
},
{
"answer_id": 327033,
"author": "Dour High Arch",
"author_id": 22437,
"author_profile": "https://Stackoverflow.com/users/22437",
"pm_score": 2,
"selected": true,
"text": "var sInfo = new FileInfo(sourcePath);\nif (sInfo.IsReadOnly)\n throw new IOException(\"File '\" + sInfo.FullName + \"' is read-only.\");\n\nvar tPath = Path.GetTempFileName();\ntry\n{\n // This throws if sourcePath does not exist, is opened, or is not readable.\n using (var sf = sInfo.OpenText())\n using (var tf = new StreamWriter(tPath))\n {\n string line;\n while ((line = sf.ReadLine()) != null)\n tf.WriteLine(UpdateLine(line));\n }\n\n string backupPath = sInfo.FullName + \".bak\";\n if (File.Exists(backupPath))\n File.Delete(backupPath);\n\n File.Move(tPath, backupPath);\n tPath = backupPath;\n File.Replace(tPath, sInfo.FullName, null);\n}\ncatch (Exception ex)\n{\n File.Delete(tPath);\n throw new IOException(\"File '\" + sInfo.FullName + \"' could not be overwritten.\", ex);\n}\n OpenText Replace"
},
{
"answer_id": 327039,
"author": "Mitch Wheat",
"author_id": 16076,
"author_profile": "https://Stackoverflow.com/users/16076",
"pm_score": 0,
"selected": false,
"text": "// Try to open a file exclusively\nFileInfo fi = new FileInfo(fullFilePath);\n\nint attempts = maxAttempts;\ndo\n{\n try\n {\n // Try to open for reading with exclusive access...\n fs = fi.Open(FileMode.Open, FileAccess.Read, FileShare.None);\n }\n // Ignore any errors... \n catch { }\n\n if (fs != null)\n {\n break;\n }\n else\n {\n Thread.Sleep(100);\n }\n}\nwhile (--attempts > 0);\n\n// Did we manage to open file exclusively?\nif (fs != null)\n{\n // use open file....\n\n}\n"
}
] | 2008/11/27 | [
"https://Stackoverflow.com/questions/324677",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/41465/"
] |
324,682 | <p>I'm trying to add HyperLinkColumns dynamically to my GridView. I have the following code:</p>
<pre><code>HyperLinkColumn objHC = new HyperLinkColumn();
objHC.DataNavigateUrlField = "title";
objHC.DataTextField = "Link text";
objHC.DataNavigateUrlFormatString = "id, title";
objHC.DataTextFormatString = "{2}";
GridView1.Columns.Add(objHC);
</code></pre>
<p>This doesn't work, so.. how can i add a HyperLinkColumn to my GridView?</p>
| [
{
"answer_id": 324717,
"author": "Patrick Desjardins",
"author_id": 13913,
"author_profile": "https://Stackoverflow.com/users/13913",
"pm_score": 3,
"selected": false,
"text": "protected void yourGrid_RowDataBound(object sender, GridViewRowEventArgs e)\n{\n HyperLink hlControl = new HyperLink();\n hlControl.Text = e.Row.Cells[2].Text; //Take back the text (let say you want it in cell of index 2)\n hlControl.NavigateUrl = \"http://www.stackoverflow.com\";\n e.Row.Cells[2].Controls.Add(hlControl);//index 2 for the example\n}\n"
}
] | 2008/11/27 | [
"https://Stackoverflow.com/questions/324682",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
324,695 | <p>When building an application with a CLI, it is useful to avoid using tokens that are commonly used for shell features.</p>
<p>For example, <code>|</code> is used for piping output of one application to input of the next.</p>
<p>Please supply a complete list of tokens that would need to be escaped to be used?</p>
<p>As a minimum/summary, for each token, please identify the applicable OS/shell(s), a simple explanation of what the token does, and any escape methods.</p>
<p>(Other useful information is welcome, once the above is clear.)</p>
| [
{
"answer_id": 324983,
"author": "Jonathan Leffler",
"author_id": 15168,
"author_profile": "https://Stackoverflow.com/users/15168",
"pm_score": 1,
"selected": false,
"text": "A-Z a-z 0-9 _ - . , / + @\n $@ $- $ @ -"
},
{
"answer_id": 324988,
"author": "Sparr",
"author_id": 13675,
"author_profile": "https://Stackoverflow.com/users/13675",
"pm_score": 1,
"selected": false,
"text": "CON, PRN, AUX, CLOCK$, NUL\nCOM0, COM1, COM2, COM3, COM4, COM5, COM6, COM7, COM8, COM9\nLPT0, LPT1, LPT2, LPT3, LPT4, LPT5, LPT6, LPT7, LPT8, LPT9\n"
}
] | 2008/11/27 | [
"https://Stackoverflow.com/questions/324695",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9360/"
] |
324,704 | <p>How do I access the user R13 and R14 which are saved when supervisor mode is entered? I am using an ARM7TDMI. </p>
<p>I.E. I do not want to access supervisor R14 which now contains the return address to user mode, instead want the value of user mode's link register. This is part of a debugger I am writing.</p>
<p>Are there special aliases for these registers?</p>
<p>Thanks</p>
| [
{
"answer_id": 326314,
"author": "Tarski",
"author_id": 27653,
"author_profile": "https://Stackoverflow.com/users/27653",
"pm_score": 2,
"selected": false,
"text": "stmfd r13, {r13-r14}^ ;store r13 and r14 usermode\nnop\nsub r13, r13, #8 ;update stack pointer\n"
}
] | 2008/11/27 | [
"https://Stackoverflow.com/questions/324704",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/27653/"
] |
324,711 | <p>I'm currently using <code>std::ofstream</code> as follows:</p>
<pre><code>std::ofstream outFile;
outFile.open(output_file);
</code></pre>
<p>Then I attempt to pass a <code>std::stringstream</code> object to <code>outFile</code> as follows:</p>
<pre><code>GetHolesResults(..., std::ofstream &outFile){
float x = 1234;
std::stringstream ss;
ss << x << std::endl;
outFile << ss;
}
</code></pre>
<p>Now my <code>outFile</code> contains nothing but garbage: "0012E708" repeated all over.</p>
<p>In <code>GetHolesResults</code> I can write </p>
<pre><code>outFile << "Foo" << std:endl;
</code></pre>
<p>and it will output correctly in <code>outFile</code>.</p>
<p>Any suggestion on what I'm doing wrong?</p>
| [
{
"answer_id": 324975,
"author": "Johannes Schaub - litb",
"author_id": 34509,
"author_profile": "https://Stackoverflow.com/users/34509",
"pm_score": 8,
"selected": true,
"text": "outFile << ss.rdbuf();\n"
},
{
"answer_id": 13760222,
"author": "2ndshot",
"author_id": 1884963,
"author_profile": "https://Stackoverflow.com/users/1884963",
"pm_score": 2,
"selected": false,
"text": "\\n"
},
{
"answer_id": 29070452,
"author": "Digital_Reality",
"author_id": 2648826,
"author_profile": "https://Stackoverflow.com/users/2648826",
"pm_score": 5,
"selected": false,
"text": "std::ostringstream ss.rdbuf() .str() outFile << oStream.str();\n"
},
{
"answer_id": 53772232,
"author": "chipsbarrier",
"author_id": 10124897,
"author_profile": "https://Stackoverflow.com/users/10124897",
"pm_score": 2,
"selected": false,
"text": "ss.str(); ss.rdbuf(); ss.rdbuf() outFile GetHolesResults(..., std::ofstream &outFile) outFile << std::setw(12) << GetHolesResults ...\n"
}
] | 2008/11/27 | [
"https://Stackoverflow.com/questions/324711",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6367/"
] |
324,726 | <p>I want to execute a php-script from php that will use different constants and different versions of classes that are already defined.</p>
<p>Is there a sandbox php_module where i could just:</p>
<pre><code>sandbox('script.php'); // run in a new php environment
</code></pre>
<p>instead of </p>
<pre><code>include('script.php'); // run in the same environment
</code></pre>
<p>Or is <a href="http://php.net/proc_open" rel="noreferrer">proc_open()</a> the only option?</p>
<p>PS: The script isn't accessible through the web, so fopen('<a href="http://host/script.php" rel="noreferrer">http://host/script.php</a>') is not an option.</p>
| [
{
"answer_id": 325500,
"author": "Vegard Larsen",
"author_id": 1606,
"author_profile": "https://Stackoverflow.com/users/1606",
"pm_score": 2,
"selected": false,
"text": "$sOutput = `php script_to_run.php`;\n"
},
{
"answer_id": 10189122,
"author": "hakre",
"author_id": 367456,
"author_profile": "https://Stackoverflow.com/users/367456",
"pm_score": 2,
"selected": false,
"text": "Runkit_Sandbox class SandboxState\n{\n private $members = array('_GET', '_POST');\n private $store = array();\n public function save() {\n foreach($members as $name) {\n $this->store[$name] = $$name;\n $$name = NULL;\n }\n }\n public function restore() {\n foreach($members as $name) {\n $$name = $this->store[$name];\n $this->store[$name] = NULL;\n }\n\n }\n}\n $state = new SanddboxState();\n$state->save();\n\n// compile your get/post request by setting the superglobals\n$_POST['submit'] = 'submit';\n...\n\n// execute your script:\n$exec = function() {\n include(func_get_arg(0)));\n};\n$exec('script.php');\n\n// check the outcome.\n...\n\n// restore your own global state:\n$state->restore();\n"
},
{
"answer_id": 14290267,
"author": "AgelessEssence",
"author_id": 209797,
"author_profile": "https://Stackoverflow.com/users/209797",
"pm_score": 0,
"selected": false,
"text": "function require_sandbox($__file,$__params=null,$__output=true) {\n\n /* original from http://stackoverflow.com/a/3850454/209797 */\n\n if($__params and is_array($__params))\n extract($__params);\n\n ob_start();\n $__returned=require $__file;\n $__contents=ob_get_contents();\n ob_end_clean();\n\n if($__output)\n echo $__contents;\n else\n return $__returned;\n\n};\n"
},
{
"answer_id": 32489135,
"author": "user3338098",
"author_id": 3338098,
"author_profile": "https://Stackoverflow.com/users/3338098",
"pm_score": 2,
"selected": false,
"text": "json_encode function proxyExternalFunction($fileName, $functionName, $args, $setupStatements = '') {\n $output = array();\n $command = $setupStatements.\";include('\".addslashes($fileName).\"');echo json_encode(\".$functionName.\"(\";\n foreach ($args as $arg) {\n $command .= \"json_decode('\".json_encode($arg).\"',true),\";\n }\n if (count($args) > 0) {\n $command[strlen($command)-1] = \")\";//end of $functionName\n }\n $command .= \");\";//end of json_encode\n $command = \"php -r \".escapeshellarg($command);\n\n exec($command, $output);\n $output = json_decode($output,true);\n}\n sudo -u restricedUser php -r ..."
}
] | 2008/11/27 | [
"https://Stackoverflow.com/questions/324726",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19165/"
] |
324,748 | <p>I'm developing class to represent special kind of matrix:</p>
<pre><code>type
DifRecord = record
Field: String;
Number: Byte;
Value: smallint;
end;
type
TData = array of array of MainModule.DataRecord;
type
TDifference = array of DifRecord;
type
TFogelMatrix = class
private
M: Byte;
N: Byte;
Data: ^TData;
DifVector: ^TDifference;
procedure init();
public
constructor Create(Rows, Cols: Byte);
destructor Destroy;
end;
</code></pre>
<p>Now in constructor I need to reserve memory for Data and DifVector class members. I use pointers to array of records, as you see. So, the main question is, how can I correctly reserve memory? I suppose I can not use something like that:<br>
<code>new(Data);<br>
new(DifVector);<br></code>
cause I`m loosing the main idea - to reserve memory space, as much as I want to, at run-time. Thanks for comments.</p>
| [
{
"answer_id": 324753,
"author": "Lasse V. Karlsen",
"author_id": 267,
"author_profile": "https://Stackoverflow.com/users/267",
"pm_score": 4,
"selected": true,
"text": "array of SetLength(Data, 100);\n Data: TData;\nDifVector: TDifference;\n"
},
{
"answer_id": 325251,
"author": "PatrickvL",
"author_id": 12170,
"author_profile": "https://Stackoverflow.com/users/12170",
"pm_score": 1,
"selected": false,
"text": "SetLength(Data, SizeOfFirstDimension);\nfor i = 0 to SizeOfFirstDimension - 1 do\n SetLength(Data[i], SizeOfSecondDimensionPerIndex(i));\n"
}
] | 2008/11/27 | [
"https://Stackoverflow.com/questions/324748",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/28298/"
] |
324,758 | <p>I'm interested in selectively parsing Mediawiki XML markup to generate a customized HTML page that's some subset of the HTML produced by the actual PHP Mediawiki render engine.</p>
<p>I want it for BzReader, an offline Mediawiki compressed dump reader written in C#. So a C# parser would be ideal, but any good code would help.</p>
<p>Of course, if no one has done it before, I guess it's time to start a project maintaining a free and separate Mediawiki parser, based on Mediawiki's own parser, but less tightly integrated with Mediawiki itself.</p>
<p>So, does anyone know of any base I could begin with, that would be better than hacking from the Mediawiki PHP code?</p>
| [
{
"answer_id": 532324,
"author": "Chris S",
"author_id": 21574,
"author_profile": "https://Stackoverflow.com/users/21574",
"pm_score": 3,
"selected": false,
"text": "public static class Formatter {\n\n}\n"
}
] | 2008/11/27 | [
"https://Stackoverflow.com/questions/324758",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7483/"
] |
324,776 | <p>I want to pass some parameters to a Crystal Report like this:</p>
<pre><code>ReportDocument.DataDefinition.FormulaFields[parameterName].Text = 'Text';
</code></pre>
<p>This workes fine unless I want to pass a multiline textbox from ASPX
(containing \n and \r chars.)</p>
<p>The reportviewer reports that "The matching ' for this string is missing.".</p>
<p>Is there any example/list/suggestion how to parse the (multiline) text and
make this work?</p>
<p>Thanks,</p>
<p><em>Stefan</em> </p>
| [
{
"answer_id": 351201,
"author": "user35193",
"author_id": 35193,
"author_profile": "https://Stackoverflow.com/users/35193",
"pm_score": 2,
"selected": false,
"text": "\"<html>\" + Replace({?ParameterField}, \"___\", \"<br>\") + \"<html/>\""
}
] | 2008/11/27 | [
"https://Stackoverflow.com/questions/324776",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
324,779 | <p>One of my API calls can result in updates to a large number of objects (Django models). I'm running into performance issues with this since I'm updating each item individually, saving, and moving on to the next:</p>
<pre><code>for item in Something.objects.filter(x='y'):
item.a="something"
item.save()
</code></pre>
<p>Sometimes my filter criterion looks like "where x in ('a','b','c',...)".</p>
<p>It seems the <a href="http://code.djangoproject.com/ticket/661" rel="nofollow noreferrer">official answer to this is "won't fix"</a>. I'm wondering what strategies people are using to improve performance in these scenarios.</p>
| [
{
"answer_id": 325066,
"author": "Jonny Buchanan",
"author_id": 6760,
"author_profile": "https://Stackoverflow.com/users/6760",
"pm_score": 5,
"selected": true,
"text": "save QuerySet update UPDATE Something.objects.filter(x__in=['a', 'b', 'c']).update(a='something')\n"
}
] | 2008/11/27 | [
"https://Stackoverflow.com/questions/324779",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13055/"
] |
324,786 | <p>I've read the several discussions about storing code snippets but I did't find the info that I'm looking for, so let's define it:</p>
<ul>
<li>At home, I have several side projects, most of them quite small, one large, and numerous little examples that demonstrate a specific language feature (for example, some template trick in C++).</li>
<li>Since I think that these examples will be useful to be available when I'm at work for a reference instead of trying to remember the exact details of this or that particular snippet that was tried and worked at home, I want to have it available for example on a USB flash drive.</li>
<li>The problem is that most of the snippets/small programs/examples are organized, written, compiled and tested in Visual Studio, it will be duplication if I have to put them in some code snippet organizer application. I can copy to the flash drive the source of the Visual Studio solution with all the examples, but it is not so convenient for searching compared with a dedicated snippet repository organizer. Or maybe I can change this if I write better comments and description of the examples, and that will do the job.</li>
</ul>
<p>Any ideas, best practices, solutions, and experience with similar stuff are appreciated.</p>
| [
{
"answer_id": 324811,
"author": "nickf",
"author_id": 9021,
"author_profile": "https://Stackoverflow.com/users/9021",
"pm_score": 1,
"selected": false,
"text": "svn:externals"
}
] | 2008/11/27 | [
"https://Stackoverflow.com/questions/324786",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/34752/"
] |
324,797 | <p>Say for example I have the following string:</p>
<p>var testString = "Hello, world";</p>
<p>And I want to call the following methods:</p>
<p>var newString = testString.Replace("Hello", "").Replace("world", "");</p>
<p>Is there some code construct that simplifies this, so that I only have to specify the Replace method once, and can specify a bunch of parameters to pass to it in one go?</p>
| [
{
"answer_id": 324809,
"author": "Vincent Van Den Berghe",
"author_id": 39259,
"author_profile": "https://Stackoverflow.com/users/39259",
"pm_score": 3,
"selected": true,
"text": "String Dictionary(String, String) InputString.Replace(DictionaryEntry.Key, DictionaryEntry.Value) .Replace.Replace"
},
{
"answer_id": 324813,
"author": "terjetyl",
"author_id": 29519,
"author_profile": "https://Stackoverflow.com/users/29519",
"pm_score": 1,
"selected": false,
"text": "public static string Replace(this string s, IEnumerable<string> strings, string replacementstring)\n{\n foreach (var s1 in strings)\n {\n s = s.Replace(s1, replacementstring);\n }\n\n return s;\n}\n"
},
{
"answer_id": 324821,
"author": "Erik van Brakel",
"author_id": 909,
"author_profile": "https://Stackoverflow.com/users/909",
"pm_score": 3,
"selected": false,
"text": "var newString = testString.Replace(\"Hello\", \"\")\n .Replace(\"world\", \"\")\n .Replace(\"and\", \"\")\n .Replace(\"something\", \"\")\n .Replace(\"else\",\"\");\n"
},
{
"answer_id": 324826,
"author": "Hallgrim",
"author_id": 15454,
"author_profile": "https://Stackoverflow.com/users/15454",
"pm_score": 0,
"selected": false,
"text": "string inputString = \"Hello, world\";\nstring newString = new[] { \"Hello\", \"world\" }.Aggregate(inputString, (result, replace) => result.Replace(replace, \"\"));\n List<Payment> payments = ...;\ndouble newDebt = payments.Aggregate(oldDebt, (debt, payment) => debt - payment.Amount);\n"
},
{
"answer_id": 324833,
"author": "Greg Beech",
"author_id": 13552,
"author_profile": "https://Stackoverflow.com/users/13552",
"pm_score": 1,
"selected": false,
"text": "var newString = Regex.Replace(testString, \"Hello|world\", \"\");\n var stringsToReplace = new[] { \"Hello\", \"world\" };\nvar regexParts = stringsToReplace.Select(Regex.Escape);\nvar regexText = string.Join(\"|\", regexParts.ToArray());\n"
}
] | 2008/11/27 | [
"https://Stackoverflow.com/questions/324797",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23341/"
] |
324,803 | <p>Is there a way to detect that a DirectShow filtergraph has reached the end of its file? By end of its file, I mean that a filtergraph with a SampleGrabber filter will never receive another SampleCB call.</p>
<p>Here are some things that don't work:</p>
<ul>
<li>Trust <code>IMediaDet::get_StreamLength</code> (it's often says there are more frames in a video than really exist)</li>
<li>Trust <code>IMediaSeeking::GetDuration</code> (it's consistent with IMediaDet, +/- one frame)</li>
<li>Use <code>IMediaControl::GetState</code> (the filtergraph remains running even if all frames have already been processed from a file)</li>
</ul>
<p><strong>Background:</strong></p>
<p>I am doing video processing and I have a class that creates a filtergraph with a SampleGrabber. Whenever <code>SampleGrabber::SampleCB</code> is called, I block it with a mutex so I can run the filtergraph in pull mode. When I'm ready for another frame, I unblock the mutex in my main thread and wait for <code>SampleGrabber::SampleCB</code> to send me a signal that it's done. For some videos, <code>IMediaDet::get_StreamLength</code> tells me that the video has more frames than really exist. Once I've extracted the final frame and request one more than actually exists, the main thread then blocks forever because <code>SampleGrabber::SampleCB</code> will never get called again. I'd like to be able to detect when <code>SampleGrabber::SampleCB</code> will never be called for file sources. Applications like Windows Media Player are able to somehow do this because the GUI reports that the video has ended after the last real frame, so apparently there's a way to do this.</p>
<p><strong>EDIT:</strong></p>
<p>I'm using <code>WaitForSingleObject</code> to implement the main thread blocking. The workaround that I've been using so far is to do what Greg suggested: have a finite timeout. Unfortunately, this gets a little tricky. The wait can fail for many reasons such as a true eof, slow network filesystem, lost network connection, slow decoder, etc.</p>
| [
{
"answer_id": 324810,
"author": "Greg Beech",
"author_id": 13552,
"author_profile": "https://Stackoverflow.com/users/13552",
"pm_score": 1,
"selected": false,
"text": "WaitForSingleObject"
}
] | 2008/11/27 | [
"https://Stackoverflow.com/questions/324803",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/25050/"
] |
324,822 | <p>I have something like this:</p>
<pre><code><node TEXT=" txt A "/>
<node TEXT="
txt X
"/>
<node>
<html>
<p>
txt Y
</p>
</html>
</node>
<node TEXT="txt B"/>
</code></pre>
<p>and i want to use XSLT to get this:</p>
<pre><code>txt A
txt X
txt Y
txt B
</code></pre>
<p>I want to strip all useless whitespaces and linebreaks of @TEXT's and CDATA's. The only XML-input that is giving structure to the output are the <code><node></code>-tags.</p>
| [
{
"answer_id": 324869,
"author": "Vincent Ramdhanie",
"author_id": 27439,
"author_profile": "https://Stackoverflow.com/users/27439",
"pm_score": 0,
"selected": false,
"text": " <xsl:strip-space elements=\"node\"/>\n"
},
{
"answer_id": 325245,
"author": "Dimitre Novatchev",
"author_id": 36305,
"author_profile": "https://Stackoverflow.com/users/36305",
"pm_score": 5,
"selected": true,
"text": "<xsl:stylesheet version=\"1.0\" xmlns:xsl=\"http://www.w3.org/1999/XSL/Transform\">\n<xsl:output method=\"text\"/>\n\n<xsl:template match=\"*\">\n <xsl:apply-templates select=\"@TEXT | node()\"/>\n</xsl:template>\n\n<xsl:template match=\"node/@TEXT | text()\">\n <xsl:if test=\"normalize-space(.)\">\n <xsl:value-of select=\n \"concat(normalize-space(.), '
')\"/>\n </xsl:if>\n\n <xsl:apply-templates />\n</xsl:template>\n\n</xsl:stylesheet>\n <t>\n<node TEXT=\" txt A \"/>\n<node TEXT=\" txt X\"/>\n<node>\n <html>\n <p> txt Y </p>\n </html>\n</node>\n<node TEXT=\"txt B\"/>\n</t>\n"
}
] | 2008/11/27 | [
"https://Stackoverflow.com/questions/324822",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8986/"
] |
324,831 | <p>If I have a for loop which is nested within another, how can I efficiently come out of both loops (inner and outer) in the quickest possible way?</p>
<p>I don't want to have to use a boolean and then have to say go to another method, but rather just to execute the first line of code after the outer loop.</p>
<p>What is a quick and nice way of going about this?</p>
<p>I was thinking that exceptions aren't cheap/should only be thrown in a truly exceptional condition etc. Hence I don't think this solution would be good from a performance perspective.</p>
<p>I don't feel it it is right to take advantage of the newer features in .NET (anon methods) to do something which is pretty fundamental.</p>
| [
{
"answer_id": 324837,
"author": "Marc Gravell",
"author_id": 23354,
"author_profile": "https://Stackoverflow.com/users/23354",
"pm_score": 9,
"selected": true,
"text": "goto return // goto\n for (int i = 0; i < 100; i++)\n {\n for (int j = 0; j < 100; j++)\n {\n goto Foo; // yeuck!\n }\n }\nFoo:\n Console.WriteLine(\"Hi\");\n // anon-method\nAction work = delegate\n{\n for (int x = 0; x < 100; x++)\n {\n for (int y = 0; y < 100; y++)\n {\n return; // exits anon-method\n }\n }\n};\nwork(); // execute anon-method\nConsole.WriteLine(\"Hi\");\n // local function (declared **inside** another method)\nvoid Work()\n{\n for (int x = 0; x < 100; x++)\n {\n for (int y = 0; y < 100; y++)\n {\n return; // exits local function\n }\n }\n};\nWork(); // execute local function\nConsole.WriteLine(\"Hi\");\n"
},
{
"answer_id": 324840,
"author": "David Rodríguez - dribeas",
"author_id": 36565,
"author_profile": "https://Stackoverflow.com/users/36565",
"pm_score": 5,
"selected": false,
"text": "for ( int i = 0; i < 10; ++i ) {\n for ( int j = 0; j < 10; ++j ) {\n // code\n if ( break_condition ) goto End;\n // more code\n }\n}\nEnd: ;\n bool exit = false;\nfor ( int i = 0; i < 10 && !exit; ++i ) {\n for ( int j = 0; j < 10 && !exit; ++j ) {\n // code\n if ( break_condition ) {\n exit = true;\n break; // or continue\n }\n // more code\n }\n}\n try {\n for ( int i = 0; i < 10 && !exit; ++i ) {\n for ( int j = 0; j < 10 && !exit; ++j ) {\n // code\n if ( break_condition ) {\n throw new Exception()\n }\n // more code\n }\n }\ncatch ( Exception e ) {}\n"
},
{
"answer_id": 324841,
"author": "tvanfosson",
"author_id": 12950,
"author_profile": "https://Stackoverflow.com/users/12950",
"pm_score": 5,
"selected": false,
"text": "bool exitedInner = false;\n\nfor (int i = 0; i < N && !exitedInner; ++i) {\n\n .... some outer loop stuff\n\n for (int j = 0; j < M; ++j) {\n\n if (sometest) {\n exitedInner = true;\n break;\n }\n }\n if (!exitedInner) {\n ... more outer loop stuff\n }\n}\n for (int i = 0; i < N; ++i) {\n\n .... some outer loop stuff\n\n if (!doInner(i, N, M)) {\n break;\n }\n\n ... more outer loop stuff\n}\n"
},
{
"answer_id": 324849,
"author": "Dustin Getz",
"author_id": 20003,
"author_profile": "https://Stackoverflow.com/users/20003",
"pm_score": 4,
"selected": false,
"text": "def do_until_equal():\n foreach a:\n foreach b:\n if a==b: return\n"
},
{
"answer_id": 324973,
"author": "Nils Pipenbrinck",
"author_id": 15955,
"author_profile": "https://Stackoverflow.com/users/15955",
"pm_score": 7,
"selected": false,
"text": "INT_MAX -1 for (int i = 0; i < 100; i++)\n{\n for (int j = 0; j < 100; j++)\n {\n if (exit_condition)\n {\n // cause the outer loop to break:\n // use i = INT_MAX - 1; otherwise i++ == INT_MIN < 100 and loop will continue \n i = int.MaxValue - 1;\n Console.WriteLine(\"Hi\");\n // break the inner loop\n break;\n }\n }\n // if you have code in outer loop it will execute after break from inner loop \n}\n break for while foreach foreach IEnumerator i = INT_MAX - 1 for foreach IntMax"
},
{
"answer_id": 325095,
"author": "Jesse C. Slicer",
"author_id": 3312,
"author_profile": "https://Stackoverflow.com/users/3312",
"pm_score": 2,
"selected": false,
"text": "break break; // our trusty friend, breaks out of current looping construct.\nbreak 2; // breaks out of the current and it's parent looping construct.\nbreak 3; // breaks out of 3 looping constructs.\nbreak all; // totally decimates any looping constructs in force.\n"
},
{
"answer_id": 383529,
"author": "dviljoen",
"author_id": 29021,
"author_profile": "https://Stackoverflow.com/users/29021",
"pm_score": 2,
"selected": false,
"text": "while( some_condition )\n{\n // outer loop stuff\n ...\n\n bool get_out = false;\n for(...)\n {\n // inner loop stuff\n ...\n\n get_out = true;\n break;\n }\n\n if( get_out )\n {\n some_condition=false;\n continue;\n }\n\n // more out loop stuff\n ...\n\n}\n"
},
{
"answer_id": 504983,
"author": "BCS",
"author_id": 1343,
"author_profile": "https://Stackoverflow.com/users/1343",
"pm_score": 6,
"selected": false,
"text": "outer: while(fn1())\n{\n while(fn2())\n {\n if(fn3()) continue outer;\n if(fn4()) break outer;\n }\n}\n"
},
{
"answer_id": 11901658,
"author": "mounesh hiremani",
"author_id": 1590220,
"author_profile": "https://Stackoverflow.com/users/1590220",
"pm_score": -1,
"selected": false,
"text": " bool breakInnerLoop=false\n for(int i=0;i<=10;i++)\n {\n for(int J=0;i<=10;i++)\n {\n if(i<=j)\n {\n breakInnerLoop=true;\n break;\n }\n }\n if(breakInnerLoop)\n {\n continue\n }\n }\n"
},
{
"answer_id": 17203745,
"author": "MG123",
"author_id": 1402196,
"author_profile": "https://Stackoverflow.com/users/1402196",
"pm_score": 0,
"selected": false,
"text": "var isDone = false;\nfor (var x in collectionX) {\n for (var y in collectionY) {\n for (var z in collectionZ) {\n if (conditionMet) {\n // some code\n isDone = true;\n }\n if (isDone)\n break;\n }\n if (isDone) \n break;\n }\n if (isDone)\n break;\n}\n"
},
{
"answer_id": 20578518,
"author": "Sky",
"author_id": 3101258,
"author_profile": "https://Stackoverflow.com/users/3101258",
"pm_score": 3,
"selected": false,
"text": "public void GetIndexOf(Transform transform, out int outX, out int outY)\n{\n outX = -1;\n outY = -1;\n\n for (int x = 0; x < Columns.Length; x++)\n {\n var column = Columns[x];\n\n for (int y = 0; y < column.Transforms.Length; y++)\n {\n if(column.Transforms[y] == transform)\n {\n outX = x;\n outY = y;\n\n return;\n }\n }\n }\n}\n"
},
{
"answer_id": 20578678,
"author": "Ingwie Phoenix",
"author_id": 2423150,
"author_profile": "https://Stackoverflow.com/users/2423150",
"pm_score": -1,
"selected": false,
"text": "break <?php\nfor(...) {\n while(...) {\n foreach(...) {\n break 3;\n }\n }\n}\n break break()"
},
{
"answer_id": 25767478,
"author": "Moesio",
"author_id": 1113510,
"author_profile": "https://Stackoverflow.com/users/1113510",
"pm_score": -1,
"selected": false,
"text": "for foreach while try catch exception try \n{\n foreach (object o in list)\n {\n foreach (object another in otherList)\n {\n // ... some stuff here\n if (condition)\n {\n throw new CustomExcpetion();\n }\n }\n }\n}\ncatch (CustomException)\n{\n // log \n}\n"
},
{
"answer_id": 29142887,
"author": "Steve",
"author_id": 2542618,
"author_profile": "https://Stackoverflow.com/users/2542618",
"pm_score": -1,
"selected": false,
"text": " for (; j < 10; j++)\n {\n //solution\n bool breakme = false;\n for (int k = 1; k < 10; k++)\n {\n //place the condition where you want to stop it\n if ()\n {\n breakme = true;\n break;\n }\n }\n\n if(breakme)\n break;\n }\n"
},
{
"answer_id": 35755622,
"author": "atlaste",
"author_id": 1031591,
"author_profile": "https://Stackoverflow.com/users/1031591",
"pm_score": 4,
"selected": false,
"text": "goto goto foreach (var item in array)\n{\n // ... \n break;\n // ...\n}\n foreach for for (int i=0; i<array.Length; ++i)\n{\n var item = array[i];\n // ...\n break;\n // ...\n}\n for break int i=0;\nwhile (i < array.Length)\n{\n var item = array[i];\n // ...\n break;\n // ...\n ++i;\n}\n break while int i=0; // for initialization\n\nstartLoop:\n if (i >= array.Length) // for condition\n {\n goto exitLoop;\n }\n var item = array[i];\n // ...\n goto exitLoop; // break\n // ...\n ++i; // for post-expression\n goto startLoop; \n foreach for while break goto int i=0; // for initialization\n\n if (i >= array.Length) // for condition\n {\n goto endOfLoop;\n }\n\nstartLoop:\n var item = array[i];\n // ...\n goto endOfLoop; // break\n // ...\n ++i; // for post-expression\n\n if (i >= array.Length) // for condition\n {\n goto startLoop;\n }\n\nendOfLoop:\n // ...\n break foreach goto break continue goto return // a is a variable.\n\nfor (int i=0; i<100; ++i) \n{\n for (int j=0; j<100; ++j)\n {\n // ...\n\n if (i*j > a) \n {\n // break everything\n }\n }\n}\n if int i, j;\nfor (i=0; i<100 && i*j <= a; ++i) \n{\n for (j=0; j<100 && i*j <= a; ++j)\n {\n // ...\n }\n}\n // Outer loop in method 1:\n\nfor (i=0; i<100 && processInner(i); ++i) \n{\n}\n\nprivate bool processInner(int i)\n{\n int j;\n for (j=0; j<100 && i*j <= a; ++j)\n {\n // ...\n }\n return i*j<=a;\n}\n bool more = true;\nfor (int i=0; i<100; ++i) \n{\n for (int j=0; j<100; ++j) \n {\n // ...\n if (i*j > a) { more = false; break; } // yuck.\n // ...\n }\n if (!more) { break; } // yuck.\n // ...\n}\n// ...\n more more more more for (int i=0; i<100; ++i) \n{\n for (int j=0; j<100; ++j)\n {\n // ...\n if (i*j > a) { goto exitLoop; } // perhaps add a comment\n // ...\n }\n // ...\n}\nexitLoop:\n\n// ...\n goto bool more"
},
{
"answer_id": 51264996,
"author": "Garvit Arora",
"author_id": 10059168,
"author_profile": "https://Stackoverflow.com/users/10059168",
"pm_score": 0,
"selected": false,
"text": "foreach (var substring in substrings) {\n //To be used to break from 1st loop.\n int breaker=1;\n foreach (char c in substring) {\n if (char.IsLetter(c)) {\n Console.WriteLine(line.IndexOf(c));\n \\\\setting condition to break from 1st loop.\n breaker=9;\n break;\n }\n }\n if (breaker==9) {\n break;\n }\n}"
},
{
"answer_id": 59980336,
"author": "Kyle",
"author_id": 12811621,
"author_profile": "https://Stackoverflow.com/users/12811621",
"pm_score": 1,
"selected": false,
"text": "string TestStr = \"The frog jumped over the hill\";\nchar[] KillChar = {'w', 'l'};\n\nfor(int i = 0; i < TestStr.Length; i++)\n{\n for(int E = 0; E < KillChar.Length; E++)\n {\n if(KillChar[E] == TestStr[i])\n {\n i = TestStr.Length; //Ends First Loop\n break; //Ends Second Loop\n }\n }\n}\n"
},
{
"answer_id": 59980956,
"author": "Daniel Fuentes",
"author_id": 12702547,
"author_profile": "https://Stackoverflow.com/users/12702547",
"pm_score": 1,
"selected": false,
"text": " static void Main(string[] args)\n {\n bool isBreak = false;\n for (int i = 0; ConditionLoop(isBreak, i, 500); i++)\n {\n Console.WriteLine($\"External loop iteration {i}\");\n for (int j = 0; ConditionLoop(isBreak, j, 500); j++)\n {\n Console.WriteLine($\"Inner loop iteration {j}\");\n\n // This code is only to produce the break.\n if (j > 3)\n {\n isBreak = true;\n } \n }\n\n Console.WriteLine(\"The code after the inner loop will be executed when breaks\");\n }\n\n Console.ReadKey();\n }\n\n private static bool ConditionLoop(bool isBreak, int i, int maxIterations) => i < maxIterations && !isBreak; \n"
},
{
"answer_id": 61175906,
"author": "Robert Einhorn",
"author_id": 3832151,
"author_profile": "https://Stackoverflow.com/users/3832151",
"pm_score": 3,
"selected": false,
"text": "new Action(() =>\n{\n for (int x = 0; x < 100; x++)\n {\n for (int y = 0; y < 100; y++)\n {\n return; // exits self invoked lambda expression\n }\n }\n})();\nConsole.WriteLine(\"Hi\");\n"
},
{
"answer_id": 66606398,
"author": "Jeroen",
"author_id": 4950874,
"author_profile": "https://Stackoverflow.com/users/4950874",
"pm_score": 0,
"selected": false,
"text": "int n; //set to max of first loop\nint m; //set to max of second loop\n\nfor (int k = 0; k < n * m; k++)\n{\n //calculate the values of i and j as if there was a double loop\n int i = k / m;\n int j = k % m;\n \n if(exitCondition)\n {\n break;\n }\n}\n"
},
{
"answer_id": 70698806,
"author": "fmigneault",
"author_id": 5936364,
"author_profile": "https://Stackoverflow.com/users/5936364",
"pm_score": 0,
"selected": false,
"text": "bool run = true;\nint finalx = 0;\nint finaly = 0;\nfor (int x = 0; x < 100 && run; x++)\n{\n finalx = x;\n for (int y = 0; y < 100 && run; y++)\n {\n finaly = y;\n if (x == 10 && y == 50) { run = false; }\n }\n}\nConsole.WriteLine(\"x: \" + finalx + \" y: \" + finaly); // outputs 'x: 10 y: 50'\n"
},
{
"answer_id": 71301688,
"author": "Jury CPA CMA",
"author_id": 10543667,
"author_profile": "https://Stackoverflow.com/users/10543667",
"pm_score": 0,
"selected": false,
"text": "return"
},
{
"answer_id": 73544899,
"author": "tdahman1325",
"author_id": 11580142,
"author_profile": "https://Stackoverflow.com/users/11580142",
"pm_score": 0,
"selected": false,
"text": "var breakOuterLoop = false;\nfor (int i = 0; i < 30; i++)\n{\n for (int j = 0; j < 30; j++)\n {\n if (condition)\n {\n breakOuterLoop = true;\n break;\n }\n }\n if (breakOuterLoop){\n break;\n }\n}\n"
}
] | 2008/11/27 | [
"https://Stackoverflow.com/questions/324831",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/32484/"
] |
324,860 | <p>I'm using a custom <code>tintColor</code> on my <code>UINavigationController</code>'s navigation bar, and because the color is so light I need to use dark colored text. It's relatively easy to swap out the title view, and the custom buttons I've added on the right hand side, but I can't seem to get a custom view to stick on the back button. This is what I'm trying right now:</p>
<pre><code>UILabel *backLabel = [[UILabel alloc] initWithFrame:CGRectZero];
[backLabel setFont:[UIFont fontWithName:[[UIFont fontNamesForFamilyName:@"Arial Rounded MT Bold"] objectAtIndex:0] size:24.0]];
[backLabel setTextColor:[UIColor blackColor]];
[backLabel setShadowColor:[UIColor clearColor]];
[backLabel setText:[aCategory displayName]];
[backLabel sizeToFit];
[backLabel setBackgroundColor:[UIColor clearColor]];
UIBarButtonItem *temporaryBarButtonItem=[[UIBarButtonItem alloc] initWithCustomView:backLabel];
temporaryBarButtonItem.customView = backLabel;
[backLabel release];
self.navigationItem.backBarButtonItem = temporaryBarButtonItem;
[temporaryBarButtonItem release];]
</code></pre>
<p>The custom view doesn't stick though, and I don't see any obviously easy way to get at the actual text inside the default button and start changing its style.</p>
| [
{
"answer_id": 2113404,
"author": "Skotch V",
"author_id": 256242,
"author_profile": "https://Stackoverflow.com/users/256242",
"pm_score": 2,
"selected": false,
"text": "UIBarButtonItem * backItem = [[UIBarButtonItem alloc] initWithImage:backImage style:UIBarButtonItemStylePlain target:nil action:nil];\nnavItem.backBarButtonItem = backItem;\n[backItem release];\n"
},
{
"answer_id": 8650810,
"author": "stephen",
"author_id": 963298,
"author_profile": "https://Stackoverflow.com/users/963298",
"pm_score": 0,
"selected": false,
"text": "UINavigationBar's UINavigationBar UIButtons UINavigationItems isKindOfClass: UIBarButtonItems setTitleTextAttributes UIBarButtonItems"
},
{
"answer_id": 10540618,
"author": "Adam",
"author_id": 153422,
"author_profile": "https://Stackoverflow.com/users/153422",
"pm_score": 5,
"selected": false,
"text": "[[UIBarButtonItem appearanceWhenContainedIn:[UINavigationBar class], nil] setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:[UIColor blackColor], UITextAttributeTextColor,nil]\n forState:UIControlStateNormal];\n"
}
] | 2008/11/28 | [
"https://Stackoverflow.com/questions/324860",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/41497/"
] |
324,867 | <p>Kind of a basic question but I'm having troubles thinking of a solution so I need a push in the right direction.</p>
<p>I have an input file that I'm pulling in, and I have to put it into one string variable. The problem is I need to split this string up into different things. There will be 3 strings and 1 int. They are separated by a ":".</p>
<p>I know I can find the position of the first ":" by find(), but I really don't know how to progress through the string, for each thing and put it into it's own string / int.</p>
<p>The actual input from the file looks something like this:</p>
<pre><code>A:PEP:909:Inventory Item
</code></pre>
<p>A is going to be command I have to execute... so that will be a string.
PEP is a key, needs to be a string.
909 is an int.</p>
<p>and the last is a string.</p>
<p>So what I think I want to do is have 3 string var's, and 1 int and get all those things put into their respective variables. </p>
<p>So I think I'll end up wanting to conver this C++ string to a C string so I can use atoi to convert the one section to an int.</p>
| [
{
"answer_id": 324883,
"author": "peterchen",
"author_id": 31317,
"author_profile": "https://Stackoverflow.com/users/31317",
"pm_score": 1,
"selected": false,
"text": "string SplitToken(string & body, char separator)\n CString SplitStringAt(CString & s, int idx)\n{\n CString ret;\n if (idx < 0)\n {\n ret = s;\n s.Empty();\n }\n else\n {\n ret = s.Left(idx);\n s = s.Mid(idx+1);\n }\n return ret;\n}\n\nCString SplitToken(CString & s,TCHAR separator)\n{\n return SplitStringAt(s, s.Find(separator));\n}\n"
},
{
"answer_id": 324938,
"author": "Johannes Schaub - litb",
"author_id": 34509,
"author_profile": "https://Stackoverflow.com/users/34509",
"pm_score": 2,
"selected": false,
"text": "std::getline std::istringstream std::string command;\nstd::string key;\nint id;\nstd::string item;\n\nstd::string line = \"A:PEP:909:Inventory Item\";\n\n// for each line: \nstd::istringstream stream(line);\n\nstd::getline(stream, command, ':');\nstd::getline(stream, key, ':');\nstream >> id;\nstd::getline(stream, item);\n\n// now, process them\n struct record {\n std::string command;\n std::string key;\n int id;\n std::string item;\n\n record(std::string const& line) {\n std::istringstream stream(line);\n stream >> *this;\n }\n\n friend std::istream& operator>>(std::istream& is, record & r){\n std::getline(is, r.command, ':');\n std::getline(is, r.key, ':');\n stream >> r.id;\n std::getline(is, r.item);\n return is;\n }\n};\n"
},
{
"answer_id": 324940,
"author": "Evan Teran",
"author_id": 13430,
"author_profile": "https://Stackoverflow.com/users/13430",
"pm_score": 3,
"selected": false,
"text": "void split(const std::string &s, char delim, std::vector<std::string> &elems) {\n std::stringstream ss(s);\n std::string item;\n while(std::getline(ss, item, delim)) {\n elems.push_back(item);\n }\n}\n std::vector<std::string> tokens;\nsplit(\"this:is:a:test\", ':', tokens);\n"
}
] | 2008/11/28 | [
"https://Stackoverflow.com/questions/324867",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/28392/"
] |
324,904 | <p>I added the following to my web.config to redirect the user to the login page if they aren't authenticated, but going to the URL does cause a redirect?</p>
<pre><code> <location path="user/add">
<system.web>
<authorization>
<deny users="?" />
</authorization>
</system.web>
</location>
</code></pre>
<p>I have setup forms authen. like this:</p>
<pre><code><authentication mode="Forms">
<forms loginUrl="/user/login"
protection="All"
timeout="30"
name="MyCookie"
requireSSL="false"
slidingExpiration="true"
defaultUrl="default.aspx"
/>
</authentication>
</code></pre>
<p>Using .net and mvc.</p>
| [
{
"answer_id": 324914,
"author": "Mark Glorie",
"author_id": 952,
"author_profile": "https://Stackoverflow.com/users/952",
"pm_score": 0,
"selected": false,
"text": "<authentication> <authorization>\n <deny users=\"?\"/>\n</authorization>\n"
},
{
"answer_id": 325231,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "(system.web)\n (authorization)\n (allow users=\"testuser\" /)\n (deny users=\"*\" /)\n (/authorization)\n(/system.web)\n"
}
] | 2008/11/28 | [
"https://Stackoverflow.com/questions/324904",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
324,905 | <p>Using Microsoft's AntiXssLibrary, how do you handle input that needs to be edited later?</p>
<p>For example:</p>
<p>User enters:
<code><i>title</i></code></p>
<p>Saved to the database as:
<code><i>title</i></code></p>
<p>On an edit page, in a text box it displays something like:
<code>&lt;i&gt;title&lt;/i&gt;</code> because I've encoded it before displaying in the text box.</p>
<p>User doesn't like that.</p>
<p>Is it ok not to encode when writing to an input control?</p>
<p>Update:</p>
<p>I'm still trying to figure this out. The answers below seem to say to decode the string before displaying, but wouldn't that allow for XSS attacks?</p>
<p>The one user who said that decoding the string in an input field value is ok was downvoted.</p>
| [
{
"answer_id": 869244,
"author": "Josef Pfleger",
"author_id": 98401,
"author_profile": "https://Stackoverflow.com/users/98401",
"pm_score": 3,
"selected": true,
"text": "<input type=\"text\" value=\"<%= AntiXss.HtmlAttributeEncode(\"<i>title</i>\") %>\" /> <input type=\"text\" value=\"<i>title</i>\" /> <i>title</i>"
}
] | 2008/11/28 | [
"https://Stackoverflow.com/questions/324905",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/32892/"
] |
324,923 | <p>I'm trying to gauge the possibility of a patch to WebKit which would allow all rendered graphics to be rendered onto a fully transparent background.</p>
<p>The desired effect is to render web content without any background at all, it should appear to float over the desktop (or whatever is displayed behind the browser window).</p>
<p>Has anyone seen an app do this? (I can think of some terminal emulators that can.) If anyone has worked inside of WebKit (or possibly Gecko?) do you think it would be possible to do this?</p>
<hr>
<p><strong>Update:</strong> I've come to realize that Mac OSX dashboard widgets use this exact technique. So, this must be possible.</p>
<hr>
<p><strong>Update 2:</strong> I've compiled WebKit on linux and noticed the configure options include:</p>
<pre><code>--enable-dashboard-support
enable Dashboard support default=yes
</code></pre>
<p>I'm getting closer. Can anyone help?</p>
<hr>
<p><strong>Update 3:</strong> I continue to find references to this in posts on various related mailing lists.</p>
<ul>
<li><a href="https://lists.webkit.org/pipermail/webkit-dev/2008-September/005019.html" rel="noreferrer">https://lists.webkit.org/pipermail/webkit-dev/2008-September/005019.html</a></li>
<li><a href="https://lists.webkit.org/pipermail/webkit-dev/2009-June/008182.html" rel="noreferrer">https://lists.webkit.org/pipermail/webkit-dev/2009-June/008182.html</a></li>
</ul>
| [
{
"answer_id": 843156,
"author": "Paul D. Waite",
"author_id": 20578,
"author_profile": "https://Stackoverflow.com/users/20578",
"pm_score": 2,
"selected": false,
"text": "defaults write com.apple.Safari IncludeDebugMenu 1"
},
{
"answer_id": 1133455,
"author": "Mark Renouf",
"author_id": 758,
"author_profile": "https://Stackoverflow.com/users/758",
"pm_score": 6,
"selected": true,
"text": "deb http://ppa.launchpad.net/webkit-team/ppa/ubuntu jaunty main\ndeb-src http://ppa.launchpad.net/webkit-team/ppa/ubuntu jaunty main\n webkit_web_view_set_transparent BODY { background-color: rgba(0,0,0,0); }\n #include <gtk/gtk.h>\n#include <webkit/webkit.h>\n\nstatic void destroy_cb(GtkWidget* widget, gpointer data) {\n gtk_main_quit();\n}\n\nint main(int argc, char* argv[]) {\n gtk_init(&argc, &argv);\n\n if(!g_thread_supported())\n g_thread_init(NULL);\n\n // Create a Window, set colormap to RGBA\n GtkWidget* window = gtk_window_new(GTK_WINDOW_TOPLEVEL);\n GdkScreen *screen = gtk_widget_get_screen(window);\n GdkColormap *rgba = gdk_screen_get_rgba_colormap (screen);\n\n if (rgba && gdk_screen_is_composited (screen)) {\n gtk_widget_set_default_colormap(rgba);\n gtk_widget_set_colormap(GTK_WIDGET(window), rgba);\n }\n\n gtk_window_set_default_size(GTK_WINDOW(window), 800, 800);\n g_signal_connect(window, \"destroy\", G_CALLBACK(destroy_cb), NULL);\n\n // Optional: for dashboard style borderless windows\n gtk_window_set_decorated(GTK_WINDOW(window), FALSE);\n\n\n // Create a WebView, set it transparent, add it to the window\n WebKitWebView* web_view = web_view = WEBKIT_WEB_VIEW(webkit_web_view_new());\n webkit_web_view_set_transparent(web_view, TRUE);\n gtk_container_add (GTK_CONTAINER(window), GTK_WIDGET(web_view));\n\n // Load a default page\n webkit_web_view_load_uri(web_view, \"http://stackoverflow.com/\");\n\n // Show it and continue running until the window closes\n gtk_widget_grab_focus(GTK_WIDGET(web_view));\n gtk_widget_show_all(window);\n gtk_main();\n return 0;\n}\n"
},
{
"answer_id": 36288625,
"author": "Eskel",
"author_id": 3163669,
"author_profile": "https://Stackoverflow.com/users/3163669",
"pm_score": 1,
"selected": false,
"text": "var page = require('webpage').create();\npage.viewportSize = { width: 1920, height: 1500 };\npage.open(\"http://www.theWebYouWantToRender\");\npage.onLoadFinished = function(status) {\n page.evaluate(function() {\n document.body.style.background = 'transparent';\n });\n\n page.render('render.png');\n phantom.exit();\n};\n"
}
] | 2008/11/28 | [
"https://Stackoverflow.com/questions/324923",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/758/"
] |
324,935 | <p>I'm trying to use MySQL to create a view with the "WITH" clause</p>
<pre><code>WITH authorRating(aname, rating) AS
SELECT aname, AVG(quantity)
FROM book
GROUP BY aname
</code></pre>
<p>But it doesn't seem like MySQL supports this.</p>
<p>I thought this was pretty standard and I'm sure Oracle supports this. Is there anyway to force MySQL to use the "WITH" clause? I've tried it with the MyISAM and innoDB engine. Both of these don't work.</p>
| [
{
"answer_id": 324964,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 4,
"selected": false,
"text": "WITH emps as (SELECT * FROM Employees)\nSELECT * FROM emps WHERE ID < 20\nUNION ALL\nSELECT * FROM emps where Sex = 'F'\n"
},
{
"answer_id": 325243,
"author": "Bill Karwin",
"author_id": 20860,
"author_profile": "https://Stackoverflow.com/users/20860",
"pm_score": 7,
"selected": false,
"text": "WITH"
},
{
"answer_id": 864553,
"author": "Ed Altorfer",
"author_id": 26552,
"author_profile": "https://Stackoverflow.com/users/26552",
"pm_score": 4,
"selected": false,
"text": "WITH AuthorRating(AuthorName, AuthorRating) AS\n SELECT aname AS AuthorName,\n AVG(quantity) AS AuthorRating\n FROM Book\n GROUP By Book.aname\n"
},
{
"answer_id": 9244074,
"author": "Mosty Mostacho",
"author_id": 268273,
"author_profile": "https://Stackoverflow.com/users/268273",
"pm_score": 5,
"selected": false,
"text": "select * from (\n select * from table\n) as Subquery\n"
},
{
"answer_id": 15084869,
"author": "Claus",
"author_id": 2110458,
"author_profile": "https://Stackoverflow.com/users/2110458",
"pm_score": 1,
"selected": false,
"text": "create temporary table abc (\ncolumn1 varchar(255)\ncolumn2 decimal\n);\ninsert into abc\nselect ...\nor otherwise\ninsert into abc\nvalues ('text', 5.5), ('text2', 0815.8);\n select * from abc inner join users on ...;\n"
},
{
"answer_id": 19718543,
"author": "Reuben",
"author_id": 343614,
"author_profile": "https://Stackoverflow.com/users/343614",
"pm_score": 3,
"selected": false,
"text": "select col1 from (\n select 'value1' as col1 union\n select 'value2' as col1 union\n select 'value3' as col1\n) as subquery\nleft join mytable as mytable.mycol = col1\nwhere mytable.mycol is null\norder by col1\n"
},
{
"answer_id": 56473999,
"author": "Mantas Dainys",
"author_id": 7967851,
"author_profile": "https://Stackoverflow.com/users/7967851",
"pm_score": 1,
"selected": false,
"text": " WITH authorRating as (select aname, rating from book)\n SELECT aname, AVG(quantity)\n FROM authorRating\n GROUP BY aname\n"
}
] | 2008/11/28 | [
"https://Stackoverflow.com/questions/324935",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
324,949 | <p>I'm working on a social networking system that will have comments coming from several different locations. One could be friends, one could be events, one could be groups--much like Facebook. What I'm wondering is, from a practical standpoint, what would be the simplest way to write a comments table? Should I do it all in one table and allow foreign keys to all sorts of different tables, or should each distinct table have its own comment table? Thanks for the help!</p>
| [
{
"answer_id": 324972,
"author": "Matt Campbell",
"author_id": 41110,
"author_profile": "https://Stackoverflow.com/users/41110",
"pm_score": 3,
"selected": true,
"text": "SELECT * FROM Comment c\nJOIN CommentedItem ci on c.CommentedItemId = ci.CommentedItemId\nJOIN Friend f on f.CommentedItemId = ci.CommentedItemId\nWHERE f.FriendId = @FriendId\n"
}
] | 2008/11/28 | [
"https://Stackoverflow.com/questions/324949",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
324,957 | <p>We have a legacy ASP.net powered site running on a IIS server, the site was developed by a central team and is used by multiple customers. Each customer however has their own copy of the site's aspx files plus a web.config file. This is causing problems as changes made by well meaning support engineers to the copies of the source aspx files are not being folded back into the central source, so our code base is diverging. Our current folder structure looks something like:
OurApp/Source aspx & default web.config<br/>
Customer1/Source aspx & web.config<br/>
Customer2/Source aspx & web.config<br/>
Customer3/Source aspx & web.config<br/>
Customer4/Source aspx & web.config<br/>
...<br/><br/></p>
<p>This is something I'd like to change to each customer having just a customised web.config file and all the customers sharing a common set of source files. So something like:
OurApp/Source aspx & default web.config<br/>
Customer1/web.config<br/>
Customer2/web.config<br/>
Customer3/web.config<br/>
Customer4/web.config<br/>
...<br/><br/>
So my question is, how do I set this up? I'm new to ASP.net and IIS as I usually use php and apache at home but we use ASP.net and ISS here at work.</p>
<hr>
<p>Source control is used and I intend to retrain the support engineers but is there any way to avoid having multiple copies of the source aspx files? I hate that sort of duplication!</p>
| [
{
"answer_id": 325030,
"author": "Corbin March",
"author_id": 7625,
"author_profile": "https://Stackoverflow.com/users/7625",
"pm_score": 4,
"selected": true,
"text": "<YourCustomConfigSection>\n <Customers>\n <Customer Name=\"Customer1\" SomeSetting=\"A\" Another=\"1\" />\n <Customer Name=\"Customer2\" SomeSetting=\"B\" Another=\"2\" />\n <Customer Name=\"Customer3\" SomeSetting=\"C\" Another=\"3\" />\n </Customers>\n</YourCustomConfigSection>\n"
}
] | 2008/11/28 | [
"https://Stackoverflow.com/questions/324957",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/39040/"
] |
324,959 | <p>Is it possible to pass a query string to Namescape's <a href="http://www.namescape.com/Products/rDirectory/Default.aspx" rel="nofollow noreferrer">rDirectory</a>? I'd like to build a web-app that can do a search and display the results in rDirectory, rather than first launching rDirectory and doing said search.</p>
| [
{
"answer_id": 325030,
"author": "Corbin March",
"author_id": 7625,
"author_profile": "https://Stackoverflow.com/users/7625",
"pm_score": 4,
"selected": true,
"text": "<YourCustomConfigSection>\n <Customers>\n <Customer Name=\"Customer1\" SomeSetting=\"A\" Another=\"1\" />\n <Customer Name=\"Customer2\" SomeSetting=\"B\" Another=\"2\" />\n <Customer Name=\"Customer3\" SomeSetting=\"C\" Another=\"3\" />\n </Customers>\n</YourCustomConfigSection>\n"
}
] | 2008/11/28 | [
"https://Stackoverflow.com/questions/324959",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5473/"
] |
324,961 | <p>I am looking for a regex pattern that would match several different combinations of
zeros such as 00-00-0000 or 0 or 0.0 or 00000 </p>
<p>Please help</p>
<p>Thanks!</p>
<p>EDIT:</p>
<p>Well, I have web service that returns me a result set, based on what it returns me I can decide if the result is worth displaying on the page. So if I get either 00-00-0000 or 0 or 00000 I would assume that data was not found, however if it brings back 001 or 000123 or 0356.00 - 1000 or 0.6700, this would be valid.</p>
<p>Hope this clarifies my question</p>
<p>Thanks</p>
| [
{
"answer_id": 324963,
"author": "SoapBox",
"author_id": 36384,
"author_profile": "https://Stackoverflow.com/users/36384",
"pm_score": 3,
"selected": false,
"text": "0([-.]?0+)* [1-9] .*[1-9].*"
},
{
"answer_id": 324994,
"author": "Timothy Khouri",
"author_id": 11917,
"author_profile": "https://Stackoverflow.com/users/11917",
"pm_score": 2,
"selected": false,
"text": "0+((\\.0+)|(-0+)*)\n"
},
{
"answer_id": 324996,
"author": "aib",
"author_id": 1088,
"author_profile": "https://Stackoverflow.com/users/1088",
"pm_score": 0,
"selected": false,
"text": "(00-00-0000|0|0\\\\.0|00000)\n"
},
{
"answer_id": 325002,
"author": "user39307",
"author_id": 39307,
"author_profile": "https://Stackoverflow.com/users/39307",
"pm_score": 3,
"selected": true,
"text": "[^123456789]+\n [^1-9]+\n"
},
{
"answer_id": 47753195,
"author": "Leandro S",
"author_id": 5606665,
"author_profile": "https://Stackoverflow.com/users/5606665",
"pm_score": 2,
"selected": false,
"text": "^[0]+$\n"
},
{
"answer_id": 70575839,
"author": "DINA TAKLIT",
"author_id": 9039646,
"author_profile": "https://Stackoverflow.com/users/9039646",
"pm_score": 0,
"selected": false,
"text": "^0([-.]?[0]*)$\n"
}
] | 2008/11/28 | [
"https://Stackoverflow.com/questions/324961",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/41508/"
] |
324,974 | <p>When I connect my digital camera with my computer, a dialog box containing all the registered programs can be used to get images from the camera will appear. Now I want to add my own program in the list, so that when I click the item of my program, I can use my own program to get images from the digital camera.</p>
<p>Thank you very much.</p>
| [
{
"answer_id": 1051861,
"author": "RBerteig",
"author_id": 68204,
"author_profile": "https://Stackoverflow.com/users/68204",
"pm_score": 3,
"selected": false,
"text": "IWiaDevMgr CoCreateInstance() IWiaDevMgr *pWiaDevMgr;\n HRESULT hr;\n hr = CoCreateInstance(CLSID_WiaDevMgr,\n NULL,\n CLSCTX_LOCAL_SERVER,\n IID_IWiaDevMgr,\n (void*)&pWiaDevMgr);\n pWiaDevMgr->RegisterEventCallbackProgram(\n WIA_REGISTER_EVENT_CALLBACK,\n NULL,\n &WIA_EVENT_DEVICE_CONNECTED,\n bstrCommandline,\n bstrName,\n bstrDescription,\n bstrIcon);\n BSTR SysAllocString() CoCreateInstance() pWiaDevMgr->Release();\n pWiaDevMgr->RegisterEventCallbackProgram(\n WIA_UNREGISTER_EVENT_CALLBACK,\n NULL,\n &WIA_EVENT_DEVICE_CONNECTED,\n bstrCommandline,\n bstrName,\n bstrDescription,\n bstrIcon);\n %1 %2 \"sti.dll,0\" HKLM\\SYSTEM\\CurrrentControlSet\\Control\\StillImage\\Events Connect HKLM\\SYSTEM\\CurrentControlSet\\Control\\Class\\{6BDD1FC6-810F-11D0-BEC7-08002BE2092F}"
}
] | 2008/11/28 | [
"https://Stackoverflow.com/questions/324974",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/26404/"
] |
324,980 | <p>I am having difficulty determining if the body of a text email message is base64 encoded.
if it is then use this line of code;
making use of jython 2.2.1</p>
<pre><code>dirty=base64.decodebytes(dirty)
</code></pre>
<p>else continue as normal.</p>
<p>This is the code I have atm. What line of code will allow me to extract this from the email: </p>
<p>"Content-Transfer-Encoding: base64" </p>
<pre><code>import email, email.Message
import base64
def _get_email_body(self):
try:
parts=self._email.get_payload()
check=parts[0].get_content_type()
if check=="text/plain":
part=parts[0].get_payload()
enc = part[0]['Content-Transfer-Encoding']
if enc == "base64":
dirty=base64.decodebytes(dirty)
elif check=="multipart/alternative":
part=parts[0].get_payload()
enc = part[0]['Content-Transfer-Encoding']
if part[0].get_content_type()=="text/plain":
dirty=part[0].get_payload()
if enc == "base64":
dirty=base64.decodebytes(dirty)
else:
return "cannot obtain the body of the email"
else:
return "cannot obtain the body of the email"
return dirty
except:
raise
</code></pre>
<p>OKAY this code works now! thanks all</p>
| [
{
"answer_id": 324989,
"author": "Harley Holcombe",
"author_id": 1057,
"author_profile": "https://Stackoverflow.com/users/1057",
"pm_score": 4,
"selected": true,
"text": "enc = msg['Content-Transfer-Encoding']\n"
},
{
"answer_id": 44186981,
"author": "Ricardo De Leon",
"author_id": 7902836,
"author_profile": "https://Stackoverflow.com/users/7902836",
"pm_score": 1,
"selected": false,
"text": "header = msg.get_payload()[0]\nheader['Content-Transfer-Encoding']\n"
}
] | 2008/11/28 | [
"https://Stackoverflow.com/questions/324980",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21537/"
] |
325,004 | <p>I have an onclick handler for an <a> element (actually, it's a jQuery-created handler, but that's not important). It looks like this:</p>
<pre><code>function handleOnClick() {
if(confirm("Are you sure?")) {
return handleOnClickConfirmed();
}
return false;
}
</code></pre>
<p>From this function, the <strong>this</strong> object is accessable as the <a> element clicked. However, handleOnClickConfirmed's <strong>this</strong> is a Window element! I want handleOnClickConfirmed to have the same <strong>this</strong> as handleOnClick does. How would I do this?</p>
<p>(I know I can pass <strong>this</strong> as an argument to handleOnClickConfirmed, but some of my code already uses handleOnClickConfirmed and I don't want to have to rewrite those calls. Besides, I think using <strong>this</strong> looks cleaner.)</p>
| [
{
"answer_id": 325013,
"author": "Rob",
"author_id": 3542,
"author_profile": "https://Stackoverflow.com/users/3542",
"pm_score": 6,
"selected": true,
"text": "function handleOnClick() {\n if( confirm( \"Sure?\" ) ) {\n return handleOnClickConfirmed.call( this );\n }\n return false;\n}\n call() Function"
},
{
"answer_id": 325184,
"author": "Benry",
"author_id": 28408,
"author_profile": "https://Stackoverflow.com/users/28408",
"pm_score": 4,
"selected": false,
"text": "function MyFunction(paramA, paraB) {\n // do nothing\n}\n MyFunction(1,2);\nMyFunction(1);\nMyFunction();\n function handleOnClickConfirmed(context) {\n context = context || this;\n // use context instead of 'this' through the rest of your code\n}\n"
}
] | 2008/11/28 | [
"https://Stackoverflow.com/questions/325004",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/39992/"
] |
325,007 | <p>can anyone show me how to get the users within a certain group using sharepoint?</p>
<p>so i have a list that contains users and or groups. i want to retrieve all users in that list. is there a way to differentiate between whether the list item is a group or user. if its a group, i need to get all the users within that group.</p>
<p>im using c#, and im trying to do thins by making it a console application.</p>
<p>im new to sharepoint and im really jumping into the deep end of the pool here, any help would be highly appreciated.</p>
<p>cheers..</p>
| [
{
"answer_id": 326218,
"author": "Pedrin",
"author_id": 36183,
"author_profile": "https://Stackoverflow.com/users/36183",
"pm_score": 5,
"selected": true,
"text": "SPSite site;\nSPWeb web;\nSPListItem item;\n SPFieldUserValue usersField = new SPFieldUserValue(mainWeb, item[\"Users\"].ToString());\nbool isUser = SPUtility.IsLoginValid(site, usersField.User.LoginName);\nList<SPUser> users = new List<SPUser>();\n\nif (isUser)\n{\n // add a single user to the list\n users.Add(usersField.User);\n}\nelse\n{\n SPGroup group = web.Groups.GetByID(usersField.LookupId);\n\n foreach (SPUser user in group.Users)\n {\n // add all the group users to the list\n users.Add(user.User);\n }\n}\n"
},
{
"answer_id": 5273938,
"author": "Sergey Turin",
"author_id": 655477,
"author_profile": "https://Stackoverflow.com/users/655477",
"pm_score": 0,
"selected": false,
"text": "web.SiteGroups web.Groups"
},
{
"answer_id": 6909197,
"author": "user874163",
"author_id": 874163,
"author_profile": "https://Stackoverflow.com/users/874163",
"pm_score": 0,
"selected": false,
"text": "private bool IsMember()\n {\n bool isMember;\n SPSite site = new SPSite(SiteURL);\n SPWeb web = site.OpenWeb();\n isMember = web.IsCurrentUserMemberOfGroup(web.Groups[\"GroupName\"].ID);\n web.Close();\n site.Close();\n return isMember;\n }\n"
}
] | 2008/11/28 | [
"https://Stackoverflow.com/questions/325007",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23491/"
] |
325,020 | <p>WinForms C#.. am getting some JSON in the format below (bottom of message) and trying to deserialise using:</p>
<p>using System.Web.Script.Serialization;</p>
<p>When I had simply this json returned:</p>
<pre><code>{
"objects": [
{
"categoryid": "1",
"name": "funny",
"serverimageid": "1",
"dateuploaded": "2008-11-17 16:16:41",
"enabled": "1"
},
{
"categoryid": "2",
"name": "happy",
"serverimageid": "2",
"dateuploaded": "2008-11-17 16:17:00",
"enabled": "1"
},
{
"categoryid": "3",
"name": "sad",
"serverimageid": "3",
"dateuploaded": "2008-11-16 16:17:13",
"enabled": "1"
}
]
}
</code></pre>
<p>Then is was easy to deserialize: (yikes.. a bit hacky)</p>
<pre><code>// s is the string
s = s.Remove(0, 11);
// last }
int stringLength = s.Length;
s = s.Remove(stringLength - 1, 1);
listOfCategories = serializer1.Deserialize<List<Category>>(s);
</code></pre>
<p>Where</p>
<pre><code>public class Category
{
public int categoryID;
public string name;
public int imageID;
public DateTime dateUpdated;
public int isActive;
public int displayOrder;
}
</code></pre>
<p>However now, I'm stuck! Have tried a list of lists... but can't get anywhere..</p>
<p>Much appreciated any help.</p>
<pre><code>{
"objects": {
"categories": [
{
"name": "Congratulations",
"imageID": "1",
"isActive": "1",
"displayOrder": "0",
"dateUpdated": "2008-11-27 00:00:00"
},
{
"name": "Animals",
"imageID": "2",
"isActive": "1",
"displayOrder": "0",
"dateUpdated": "2008-11-26 00:00:00"
},
{
"name": "Romance",
"imageID": "3",
"isActive": "1",
"displayOrder": "0",
"dateUpdated": "2008-11-24 00:00:00"
}
],
"present": [
{
"presentID": "1",
"name": "Tiger",
"categoryID": "2",
"imageID": "1",
"dateUpdated": "2008-11-27",
"isActive": "1",
"isAnimated": null,
"isInteractive": null,
"isAdaptive": null,
"webLinkURL": null
},
{
"giphtID": "2",
"name": "Donkey",
"categoryID": "2",
"imageID": "2",
"dateUpdated": "2008-11-27",
"isActive": "1",
"isAnimated": null,
"isInteractive": null,
"isAdaptive": null,
"webLinkURL": null
},
{
"giphtID": "3",
"name": "Elephant",
"categoryID": "2",
"imageID": "3",
"dateUpdated": "2008-11-27",
"isActive": "1",
"isAnimated": null,
"isInteractive": null,
"isAdaptive": null,
"webLinkURL": null
}
]
}
}
</code></pre>
| [
{
"answer_id": 325098,
"author": "Simon Buchan",
"author_id": 20135,
"author_profile": "https://Stackoverflow.com/users/20135",
"pm_score": 3,
"selected": true,
"text": "using System;\nusing System.Collections.Generic;\nusing System.Web.Script.Serialization;\n\nclass Program\n{\n static void Main( string[] args )\n {\n string json = System.IO.File.ReadAllText( \"../../input.json\" );\n\n var serializer = new JavaScriptSerializer();\n Structure jsonStructure = serializer.Deserialize<Structure>( json );\n System.Diagnostics.Debugger.Break();\n }\n}\n\nclass Structure\n{\n public StructureObjects objects;\n}\n\nclass StructureObjects\n{\n public List<StructureCategory> categories;\n public List<StructurePresent> present;\n}\n\nclass StructureCategory\n{\n public string name;\n public int imageID;\n public DateTime dateUpdated;\n public int isActive;\n public int displayOrder;\n}\n\nclass StructurePresent\n{\n public int presentID;\n public string name;\n public int categoryID;\n public int imageID;\n public DateTime dateUpdated;\n public int isActive;\n public int? isAnimated;\n public int? isInteractive;\n public int? isAdaptive;\n public Uri webLinkURL;\n}\n"
},
{
"answer_id": 325104,
"author": "Marc Gravell",
"author_id": 23354,
"author_profile": "https://Stackoverflow.com/users/23354",
"pm_score": 1,
"selected": false,
"text": "DataContractJsonSerializer [DataContract]\nclass Foo\n{\n [DataMember(Name = \"objects\")]\n public Bar Bar { get; set; }\n}\n\n[DataContract]\nclass Bar\n{\n public Bar() {\n Categories = new List<Category>();\n Present = new List<Present>();\n }\n [DataMember(Name = \"categories\")]\n public List<Category> Categories { get; private set; }\n [DataMember(Name = \"present\")]\n public List<Present> Present { get; private set; }\n}\n[DataContract]\nclass Category\n{\n [DataMember(Name = \"name\")]\n public string Name {get;set;}\n [DataMember(Name = \"imageID\")]\n public int ImageID {get;set;}\n [DataMember(Name = \"isActive\")]\n public int IsActive {get;set;}\n [DataMember(Name = \"displayOrder\")]\n public int DisplayOrder {get;set;}\n [DataMember(Name = \"dateUpdated\")]\n public string DateUpdated {get;set;}\n}\n[DataContract]\nclass Present\n{\n [DataMember(Name = \"presentID\")]\n public int PresentID {get;set;}\n [DataMember(Name = \"name\")]\n public string Name {get;set;}\n [DataMember(Name = \"categoryID\")]\n public int CategoryID {get;set;}\n [DataMember(Name = \"imageID\")]\n public int ImageID {get;set;} \n [DataMember(Name = \"dateUpdated\")]\n public string DateUpdated {get;set;}\n [DataMember(Name = \"isActive\")]\n public int IsActive {get;set;}\n [DataMember(Name = \"isAnimated\")]\n public int? IsAnimated {get;set;}\n [DataMember(Name = \"isInteractive\")]\n public int? IsInteractive {get;set;}\n [DataMember(Name = \"isAdaptive\")]\n public int? IsAdaptive {get;set;}\n [DataMember(Name = \"webLinkURL\")]\n public string WebLinkUrl {get;set;}\n}\n"
}
] | 2008/11/28 | [
"https://Stackoverflow.com/questions/325020",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/26086/"
] |
325,035 | <p>This is a program I'm writing (myself as opposed to copying someone else's and thus not learning) as part of the ObjectiveC and Cocoa learning curve. I want to draw simple shapes on a NSView (limiting it to ovals and rectangles for now). The idea is that I record each NSBezierPath to an NSMutableArray so I can also investigate/implement saving/loading, undo/redo. I have a canvas, can draw on it as well as 2 buttons that I use to select the tool. To handle the path I created another object that can hold a NSBezierPath, color values and size value for each object drawn. This is what I want to store in the array. I use mouseDown/Dragged/Up to get coordinates for the drawing path. However, this is where things go wonky. I can instantiate the object that is supposed to hold the path/color/etc. info but, when I try to change an instance variable, the app crashes with no useful message in the debugger. I'll try to keep my code snippets short but tell me if I need to include more. The code has also degenerated a little from me trying so many things to make it work.</p>
<p>Project: Cocoa document based app<br />
I have the following .m/.h files</p>
<ul>
<li><code>MyDocument:NSDocument</code> - generated by XCode</li>
<li><code>DrawnObject:NSObject</code> - deals with the drawn object i.e. path, color, type (oval/rect) and size</li>
<li><code>Canvas:NSView</code> - well, shows the drawing, deals with the mouse and buttons</li>
</ul>
<p>Canvas is also responsible for maintaining a <code>NSMutableArray</code> of <code>DrawnObject</code> objects.</p>
<p><code>DrawnObject.h</code> looks like this:
<code></p>
<pre>
#import <Foundation/Foundation.h>
//The drawn object must know what tool it was created with etc as this needs to be used for generating the drawing
@interface DrawnObject : NSObject {
NSBezierPath * aPath;
NSNumber * toolType;//0 for oval, 1 for rectangular etc....
float toolSize;
struct myCol{
float rd;
float grn;
float blu;
float alp;
} toolColor;
}
-(void)setAPath:(NSBezierPath *) path;
-(NSBezierPath *)aPath;
@property (readwrite,assign) NSNumber * toolType;
-(float)toolSize;
-(void)setToolSize:(float) size;
-(struct myCol *)toolColor;
-(void)setCurrentColor:(float)ref:(float)green:(float)blue:(float)alpha;
@end
</pre>
<p></code>
<code>Canvas.h</code> looks like this</p>
<pre>
#import
#import "drawnObject.h"
@interface Canvas : NSView {
NSMutableArray * myDrawing;
NSPoint downPoint;
NSPoint currentPoint;
NSBezierPath * viewPath;//to show the path as the user drags the mouse
NSNumber * currentToolType;
BOOL mouseUpFlag;//trying a diff way to make it work
BOOL mouseDrag;
}
-(IBAction)useOval:(id)sender;
-(IBAction)useRect:(id)sender;
-(IBAction)showTool:(id)sender;
-(NSRect)currentRect;
-(NSBezierPath *)createPath:(NSRect) aRect;
-(void)setCurrentToolType:(NSNumber *) t;
-(NSNumber *)currentToolType;
@end
</pre>
<p>In the <code>Canvas.m</code> file there are several functions to deal with the mouse and NSView/XCode also dropped in <code><br />-(id)initWithFrame:(NSRect)frame</code> and <code>-(void)drawRect:(NSRect)rect</code> Originally I use <code>mouseUp</code> to try to insert the new <code>DrawnObject</code> into the array but that caused a crash. So, now I use two <code>BOOL</code> flags to see when the mouse was released (clunky but I'm trying....)in <code>drawRect</code> to insert into the array. I've included the method below and indicated where it causes the app to fail:</p>
<pre>
- (void)drawRect:(NSRect)rect { //This is called automatically
// Drawing code here.
//NSLog(@"Within drawRect tool type is %d", [self currentTool]);
NSRect bounds = [self bounds];
NSRect aRect = [self currentRect];
viewPath = [self createPath:aRect];
//the createPath method uses the tool type to switch between oval and rect bezier curves
if(mouseUpFlag==YES && mouseDrag==YES){
mouseDrag=NO;
//Create a new drawnObject here
DrawnObject * anObject = [[DrawnObject alloc]init];//- WORKS FINE UP TO HERE
NSLog(@"CREATED NEW drawnObject");
[anObject setAPath:viewPath]; //- INSTANT APP DEATH!!!!
NSLog(@"Set a path in drawnObject");
[anObject setToolType:[[NSNumber alloc]initWithInt:5]];
NSLog(@"Set toolType in DrawnObject");
[anObject setToolType:currentToolType];
[myDrawing addObject:anObject];
NSLog(@"Added Object");
}
[[NSColor colorWithCalibratedRed:0.0 green:0.9 blue:0.0 alpha:0.5]set];
[NSBezierPath fillRect:bounds];
[[NSColor lightGrayColor]set];
[viewPath stroke]; //This is so the user can see where the drawing is being done
//Now, draw the paths in the array
[[NSColor blueColor]set];
for(DrawnObject * indexedObject in myDrawing){
[[indexedObject aPath] stroke];//This will do the actual drawing of ALL objects
}
}
</pre>
<p>I guess this has something to do with object scope or something but I just can not figure it out. As I said, as I've tried things the code has sort of undergone an metamorphosis, sadly not for the better. Like those BOOLS etc.</p>
<p><strong> HELP! Any clever people out there, point me in the right direction please!</strong></p>
<p>ADDED THIS ON:</p>
<pre><code>
-(NSBezierPath *)createPath:(NSRect) aRect
{
NSBezierPath * tempPath;
//I need to know what tool
switch(0){ //temporary - this would use the toolType as a selector
case 0:
tempPath = [NSBezierPath bezierPathWithOvalInRect:aRect];
break;
case 1:
tempPath = [NSBezierPath bezierPathWithRect:aRect];
break;
default:
tempPath = [NSBezierPath bezierPathWithOvalInRect:aRect];
break;
}
return tempPath;
}
</code></pre>
| [
{
"answer_id": 325227,
"author": "Adam Ernst",
"author_id": 79,
"author_profile": "https://Stackoverflow.com/users/79",
"pm_score": 2,
"selected": false,
"text": "-(void)init {\n[super init];\n//set default color = black\ntoolColor.rd=1.0;\ntoolColor.grn=1.0;\ntoolColor.blu=1.0;\ntoolColor.alp=1.0;\n//set default size\ntoolSize=0.8;\n//set default toolType\ntoolType=0;\n//oval\nNSLog(@\"Init %@\",self);\n}\n -(id)init {\nif (self = [super init]) {\n //set default color = black\n toolColor.rd=1.0;\n toolColor.grn=1.0;\n toolColor.blu=1.0;\n toolColor.alp=1.0;\n //set default size\n toolSize=0.8;\n //set default toolType\n toolType=0;\n //oval\n NSLog(@\"Init %@\",self);\n}\nreturn self;\n}\n"
}
] | 2008/11/28 | [
"https://Stackoverflow.com/questions/325035",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
325,041 | <p>I expect the column to be a VARCHAR2, in my Oracle Database.</p>
<p>US Zips are 9.</p>
<p>Canadian is 7.</p>
<p>I am thinking 32 characters would be reasonable upper limit</p>
<p>What am I missing?</p>
<p>[EDIT]
TIL: 12 is a reasonable answer to the question
Thanks to everyone who contributed.</p>
| [
{
"answer_id": 41374163,
"author": "PodTech.io",
"author_id": 1842743,
"author_profile": "https://Stackoverflow.com/users/1842743",
"pm_score": 2,
"selected": false,
"text": "Max 35 characters per line \n Minimum of 2 lines and maximum of 5 lines for the postal delivery point \ndetails, plus 1 line for country and 1 line for postcode/zip code \n Minimum 6 and Maximum 8 characters \n"
}
] | 2008/11/28 | [
"https://Stackoverflow.com/questions/325041",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7734/"
] |
325,057 | <p>I'm trying to display the contents of an ordered array in something like a JTextField.</p>
<pre><code>for (int i=0; i<array.length; i++) {
this.textField.setText(array[i]);
}
</code></pre>
<p>This won't work for two reasons. The first minor reason: if the array length is 4 then jtextfield is getting it's value reset 4 times rather than appending each element onto the last.
Second reason: The JTextField only takes strings. I can't find anything I can use in Swing that will let me display integers to the user. Any help?</p>
| [
{
"answer_id": 325062,
"author": "OscarRyz",
"author_id": 20654,
"author_profile": "https://Stackoverflow.com/users/20654",
"pm_score": 0,
"selected": false,
"text": "StringBuilder sb = new StringBuilder();\nfor( int i : array ) { // <-- alternative way to iterate the array\n sb.append( i );\n sb.append( \", \" );\n}\n\nsb.delete(sb.length()-2, sb.length()-1); // trim the extra \",\"\ntextField.setText( sb.toString() );\n"
},
{
"answer_id": 325063,
"author": "Johannes Schaub - litb",
"author_id": 34509,
"author_profile": "https://Stackoverflow.com/users/34509",
"pm_score": 3,
"selected": false,
"text": "for (int i=0; i<array.length; i++) {\n this.myJTextField.setText(this.myJTextField.getText() + \", \" + array[i]);\n}\n JTextField myTextField \"\" + number \", \" StringBuilder builder = new StringBuilder();\nfor (int i=0; i<array.length; i++) {\n builder.append(array[i]));\n if(i + 1 != array.length) \n builder.append(\", \");\n}\nthis.myJTextField.setText(builder.toString());\n this.myJTextField.setText(Arrays.toString(array));\n [1, 4, 5, 6]"
}
] | 2008/11/28 | [
"https://Stackoverflow.com/questions/325057",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
325,075 | <p>I am using a RichTextBox in WPF, and am trying to set the default paragraph spacing to 0 (so that there is no paragraph spacing). While I could do this in XAML, I would like to achieve it programmatically if possible. Any ideas?</p>
| [
{
"answer_id": 325080,
"author": "Ramesh Soni",
"author_id": 191,
"author_profile": "https://Stackoverflow.com/users/191",
"pm_score": 5,
"selected": false,
"text": "RichTextBox rtb = new RichTextBox(); \nParagraph p = rtb.Document.Blocks.FirstBlock as Paragraph; \np.LineHeight = 10;\n"
},
{
"answer_id": 325103,
"author": "Darren Oster",
"author_id": 691,
"author_profile": "https://Stackoverflow.com/users/691",
"pm_score": 4,
"selected": false,
"text": "p.Margin = new Thickness(0);\n"
},
{
"answer_id": 445897,
"author": "moogs",
"author_id": 26374,
"author_profile": "https://Stackoverflow.com/users/26374",
"pm_score": 9,
"selected": true,
"text": "<RichTextBox Margin=\"0,51,0,0\" Name=\"mainTextBox\" >\n <RichTextBox.Resources>\n <Style TargetType=\"{x:Type Paragraph}\">\n <Setter Property=\"Margin\" Value=\"0\"/>\n </Style>\n </RichTextBox.Resources>\n </RichTextBox>\n"
},
{
"answer_id": 2781442,
"author": "Haasan Sachdev",
"author_id": 334471,
"author_profile": "https://Stackoverflow.com/users/334471",
"pm_score": 1,
"selected": false,
"text": "<RichTextBox Height=\"250\" Width=\"500\" VerticalScrollBarVisibility=\"Auto\" TextWrapping=\"Wrap\" IsReadOnly=\"True\" >\n <Paragraph>\n XYZ\n <LineBreak />\n </Paragraph>\n</RichTextBox>\n"
},
{
"answer_id": 4042222,
"author": "Danny",
"author_id": 616081,
"author_profile": "https://Stackoverflow.com/users/616081",
"pm_score": 1,
"selected": false,
"text": "richtextbox1.SelectionCharOffset =\n -1 * ( Convert.ToInt32(R223.Txt_Space_Before.Text) * 100);\n richtextbox1.SelectionCharOffset =\n Convert.ToInt32(R223.Txt_Space_Before.Text) * 100;\n"
},
{
"answer_id": 40855334,
"author": "senquevila",
"author_id": 3092873,
"author_profile": "https://Stackoverflow.com/users/3092873",
"pm_score": 2,
"selected": false,
"text": "RichTextBox rtb = new RichTextBox();\nrtb.SetValue(Paragraph.LineHeightProperty, 1.0);\n"
},
{
"answer_id": 47513203,
"author": "m4rcel",
"author_id": 5685751,
"author_profile": "https://Stackoverflow.com/users/5685751",
"pm_score": 4,
"selected": false,
"text": " <RichTextBox HorizontalAlignment=\"Left\" Height=\"126\" Margin=\"10,280,0,0\" VerticalAlignment=\"Top\" Width=\"343\" FontSize=\"14\" Block.LineHeight=\"2\"/>\n"
},
{
"answer_id": 63138523,
"author": "RRM",
"author_id": 14010904,
"author_profile": "https://Stackoverflow.com/users/14010904",
"pm_score": 0,
"selected": false,
"text": "ShowSelectedMargin true"
}
] | 2008/11/28 | [
"https://Stackoverflow.com/questions/325075",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/691/"
] |
325,081 | <p>How do I create an ASP.NET web service that returns JSON formatted data?</p>
| [
{
"answer_id": 325176,
"author": "Jon DellOro",
"author_id": 36456,
"author_profile": "https://Stackoverflow.com/users/36456",
"pm_score": 1,
"selected": false,
"text": "// enclosing html page has loaded this:\n<script type=\"text/javascript\" src=\"res/js/json2.js\"></script> \n\n// Invoke like this:\n// var validObj = = callAnyWebservice(\"WebServiceName\", \"\");\n// if (!validObj || validObj.returnCode != 0) {\n// alert(\"Document number \" + DocId + \" is not in the vPage database. Cannot continue.\");\n// DocId = null;\n// }\n\n\nfunction callAnyWebservice(webserviceName, params) {\n var base = document.location.href;\n if (base.indexOf(globals.testingIPaddr) < 0) return;\n\n gDocPagesObject=null;\n\n var http = new XMLHttpRequest();\n var url = \"http://mywebserver/appdir/WebServices.asmx/\" + webserviceName;\n\n //alert(url + \" \" + params);\n\n http.open(\"POST\", url, false);\n http.setRequestHeader(\"Host\", globals.testingIPaddr);\n http.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');\n http.setRequestHeader(\"Content-Length\", params.length);\n // http.setRequestHeader(\"Connection\", \"close\");\n //Call a function when the state changes.\n http.onreadystatechange = function() { \n if (http.readyState == 4 ) {\n if (http.status == 200) {\n\n var JSON_text = http.responseText;\n\n var firstCurlyQuote = JSON_text.indexOf('{');\n JSON_text = JSON_text.substr(firstCurlyQuote);\n var lastCurlyQuote = JSON_text.lastIndexOf('}') + 1;\n JSON_text = JSON_text.substr(0, lastCurlyQuote); \n\n if (JSON_text!=\"\")\n {\n //if (DEBUG)\n // alert(url+\" \" +JSON_text);\n gDocPagesObject = eval(\"(\" + JSON_text + \")\");\n }\n }\n else if (http.readyState == 4)\n {alert(http.readyState + \" \" + http.status + \" \" + http.responseText)}\n }\n }\n\n http.send(params);\n\n if (gDocPagesObject != null) {\n //alert(gDocPagesObject.returnCode + \" \" + gDocPagesObject.returnString);\n return gDocPagesObject;\n }\n else\n return \"web service unavailable: data not ready\"; \n}\n"
},
{
"answer_id": 325207,
"author": "LeJeune",
"author_id": 37955,
"author_profile": "https://Stackoverflow.com/users/37955",
"pm_score": 0,
"selected": false,
"text": "[WebMethod]\n[ScriptMethod(ResponseFormat = ResponseFormat.Json)]\npublic String Foo(String p1, String p2)\n{\n return \"Result: p1= \" + p1 + \" p2= \" + p2;\n}\n var httpobj = getXmlHttpRequestObject();\n\n//Gets the browser specific XmlHttpRequest Object\nfunction getXmlHttpRequestObject() \n{\n if (window.XMLHttpRequest) \n return new XMLHttpRequest();\n else if(window.ActiveXObject) \n return new ActiveXObject(\"Microsoft.XMLHTTP\");\n} \n\n\nCallService()\n{\n //Set the JSON formatted input params\n var param = \"{'p1' : 'value1', 'p2' : 'value2'}\";\n\n //Send it to webservice\n if(httpobj.readyState == 4 || httpobj.readyState == 0)\n {\n httpobj.open(\"POST\", 'service.asmx/' + 'Foo', true);\n //Mark the request as JSON and UTF-8\n httpobj.setRequestHeader('Content-Type','application/json; charset=utf-8');\n httpobj.onreadystatechange = OnSuccess;\n httpobj.send(param);\n }\n\n}\n\nOnSuccess()\n{\n if (httpobj.readyState == 4) \n {\n //Retrieve the JSON return param\n var response = eval(\"(\" + httpobj.responseText + \")\");\n }\n}\n"
}
] | 2008/11/28 | [
"https://Stackoverflow.com/questions/325081",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/41524/"
] |
325,082 | <p>If there is more than one way, please list them. I only know of one, but I'm wondering if there is a cleaner, in-Ruby way.</p>
| [
{
"answer_id": 325088,
"author": "Dustin",
"author_id": 39975,
"author_profile": "https://Stackoverflow.com/users/39975",
"pm_score": 7,
"selected": true,
"text": ">> Process.kill 0, 370\n=> 1\n>> Process.kill 0, 2\nErrno::ESRCH: No such process\n from (irb):5:in `kill'\n from (irb):5\n>> \n"
},
{
"answer_id": 325092,
"author": "John T",
"author_id": 36457,
"author_profile": "https://Stackoverflow.com/users/36457",
"pm_score": 3,
"selected": false,
"text": "Process::kill 0, pid\n"
},
{
"answer_id": 325097,
"author": "Pistos",
"author_id": 28558,
"author_profile": "https://Stackoverflow.com/users/28558",
"pm_score": 6,
"selected": false,
"text": "Process.getpgid( pid )\n"
},
{
"answer_id": 3568291,
"author": "tonystubblebine",
"author_id": 272217,
"author_profile": "https://Stackoverflow.com/users/272217",
"pm_score": 6,
"selected": false,
"text": "Process.getpgid Process::kill Process.getpgid Process::kill (Errno::EPERM) Process.getpgid begin\n Process.getpgid( pid )\n true\nrescue Errno::ESRCH\n false\nend\n"
},
{
"answer_id": 14381862,
"author": "balu",
"author_id": 490153,
"author_profile": "https://Stackoverflow.com/users/490153",
"pm_score": 5,
"selected": false,
"text": "Process::WNOHANG nil pid = Process.spawn('sleep 5')\nProcess.waitpid(pid, Process::WNOHANG) # => nil\nsleep 5\nProcess.waitpid(pid, Process::WNOHANG) # => pid\n Errno::ECHILD: No child processes"
},
{
"answer_id": 18639290,
"author": "Daniel Doezema",
"author_id": 493702,
"author_profile": "https://Stackoverflow.com/users/493702",
"pm_score": 0,
"selected": false,
"text": "*nix ps \\n 1.9.3p448 :067 > `ps -p 56718` \n\" PID TTY TIME CMD\\n56718 ttys007 0:03.38 zeus slave: default_bundle \\n\"\n def process?(pid) \n !!`ps -p #{pid.to_i}`[\"\\n\"]\nend\n"
},
{
"answer_id": 20902743,
"author": "amenzhinsky",
"author_id": 1280277,
"author_profile": "https://Stackoverflow.com/users/1280277",
"pm_score": 2,
"selected": false,
"text": "File.read(\"/proc/#{pid}/cmdline\")\nFile.read(\"/proc/#{pid}/comm\")\n"
},
{
"answer_id": 25145588,
"author": "Wilson Silva",
"author_id": 3013522,
"author_profile": "https://Stackoverflow.com/users/3013522",
"pm_score": 0,
"selected": false,
"text": "require 'process_exists'\n\npid = 12\npid_exists = Process.exists?(pid)\n"
},
{
"answer_id": 32513298,
"author": "komatsu",
"author_id": 5323316,
"author_profile": "https://Stackoverflow.com/users/5323316",
"pm_score": 3,
"selected": false,
"text": "def alive?(pid)\n !!Process.kill(0, pid) rescue false\nend\n"
}
] | 2008/11/28 | [
"https://Stackoverflow.com/questions/325082",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/28558/"
] |
325,085 | <p>My requirement is just to display a set of values retrieved from database on a spread. I am using jquery.</p>
| [
{
"answer_id": 325141,
"author": "urig",
"author_id": 33404,
"author_profile": "https://Stackoverflow.com/users/33404",
"pm_score": 4,
"selected": false,
"text": "eval() JSON.parse()"
}
] | 2008/11/28 | [
"https://Stackoverflow.com/questions/325085",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16488/"
] |
325,086 | <p>Hi sometimes i encoutner this error after restarsting sun application server 8.2 domain anyone have any idea what could be the reason?</p>
<blockquote>
<p>javax.servlet.ServletException at
org.apache.jasper.servlet.JspServlet.service(JspServlet.java:255) at
javax.servlet.http.HttpServlet.service(HttpServlet.java:860) at
sun.reflect.GeneratedMethodAccessor156.invoke(Unknown
Source) at
sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) at
java.lang.reflect.Method.invoke(Method.java:585) at
org.apache.catalina.security.SecurityUtil$1.run(SecurityUtil.java:249) at
java.security.AccessController.doPrivileged(Native
Method) at
javax.security.auth.Subject.doAsPrivileged(Subject.java:517) at
org.apache.catalina.security.SecurityUtil.execute(SecurityUtil.java:282) at
org.apache.catalina.security.SecurityUtil.doAsPrivilege(SecurityUtil.java:165) at
org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:257) at
org.apache.catalina.core.ApplicationFilterChain.access$000(ApplicationFilterChain.java:55) at
org.apache.catalina.core.ApplicationFilterChain$1.run(ApplicationFilterChain.java:161) at
java.security.AccessController.doPrivileged(Native
Method) at
org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:157) at
org.apache.catalina.core.ApplicationDispatcher.invoke(ApplicationDispatcher.java:723) at
org.apache.catalina.core.ApplicationDispatcher.processRequest(ApplicationDispatcher.java:484) at
org.apache.catalina.core.ApplicationDispatcher.doForward(ApplicationDispatcher.java:417) at
org.apache.catalina.core.ApplicationDispatcher.access$000(ApplicationDispatcher.java:80) at
org.apache.catalina.core.ApplicationDispatcher$PrivilegedForward.run(ApplicationDispatcher.java:95) at
java.security.AccessController.doPrivileged(Native
Method) at
org.apache.catalina.core.ApplicationDispatcher.forward(ApplicationDispatcher.java:313) at
org.apache.catalina.core.StandardHostValve.custom(StandardHostValve.java:448) at
org.apache.catalina.core.StandardHostValve.status(StandardHostValve.java:339) at
org.apache.catalina.core.StandardHostValve.throwable(StandardHostValve.java:282) at
org.apache.catalina.core.StandardHostValve.postInvoke(StandardHostValve.java:184) at
org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:552) at
org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:132) at
org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:551) at
org.apache.catalina.core.ContainerBase.invoke(ContainerBase.java:933) at
org.apache.coyote.tomcat5.CoyoteAdapter.service(CoyoteAdapter.java:189) at
com.sun.enterprise.web.connector.grizzly.ProcessorTask.doProcess(ProcessorTask.java:604) at
com.sun.enterprise.web.connector.grizzly.ProcessorTask.process(ProcessorTask.java:475) at
com.sun.enterprise.web.connector.grizzly.ReadTask.executeProcessorTask(ReadTask.java:371) at
com.sun.enterprise.web.connector.grizzly.ReadTask.doTask(ReadTask.java:264) at
com.sun.enterprise.web.connector.grizzly.TaskBase.run(TaskBase.java:281) at
com.sun.enterprise.web.connector.grizzly.WorkerThread.run(WorkerThread.java:83)-----
Root Cause
-----java.lang.StackOverflowError at java.security.AccessController.doPrivileged(Native
Method) at
com.sun.security.auth.PolicyFile.getPermissions(PolicyFile.java:818) at
javax.security.auth.SubjectDomainCombiner$3.run(SubjectDomainCombiner.java:357) at
java.security.AccessController.doPrivileged(Native
Method) at
javax.security.auth.SubjectDomainCombiner.combineJavaxPolicy(SubjectDomainCombiner.java:353) at
javax.security.auth.SubjectDomainCombiner.combine(SubjectDomainCombiner.java:191) at
java.security.AccessControlContext.goCombiner(AccessControlContext.java:390) at
java.security.AccessControlContext.optimize(AccessControlContext.java:304) at
java.security.AccessController.checkPermission(AccessController.java:426) at
java.lang.SecurityManager.checkPermission(SecurityManager.java:532) at
java.security.Security.getProperty(Security.java:724) at
com.sun.security.auth.PolicyFile.initPolicyFile(PolicyFile.java:356) at
com.sun.security.auth.PolicyFile.init(PolicyFile.java:269) at
com.sun.security.auth.PolicyFile.getPermissions(PolicyFile.java:869) at
com.sun.security.auth.PolicyPermissions.init(PolicyFile.java:1416) at
com.sun.security.auth.PolicyPermissions.elements(PolicyFile.java:1429) at
javax.security.auth.SubjectDomainCombiner.combineJavaxPolicy(SubjectDomainCombiner.java:366) at
javax.security.auth.SubjectDomainCombiner.combine(SubjectDomainCombiner.java:191) </p>
</blockquote>
<p>… ad inifinitum</p>
| [
{
"answer_id": 366473,
"author": "Mark Renouf",
"author_id": 758,
"author_profile": "https://Stackoverflow.com/users/758",
"pm_score": 2,
"selected": false,
"text": "-Xss2M"
}
] | 2008/11/28 | [
"https://Stackoverflow.com/questions/325086",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
325,087 | <p>Given a jQuery result set, how do you convert that back into plain HTML?</p>
<pre><code><div class="abc">
foo <strong>FOO</strong>
</div>
<div class="def">
bar
</div>
</code></pre>
<p>--</p>
<pre><code>var $mySet = $('div');
</code></pre>
<p>Given <code>$mySet</code>, how would you go about returning to the plain HTML above?</p>
| [
{
"answer_id": 325089,
"author": "strager",
"author_id": 39992,
"author_profile": "https://Stackoverflow.com/users/39992",
"pm_score": 0,
"selected": false,
"text": "var $mySet = $('div');\nvar html = $mySet.html();\n var $mySet = $('div');\nvar html = $mySet.clone().wrap('<div></div>').html();\n"
},
{
"answer_id": 325152,
"author": "Owen",
"author_id": 4853,
"author_profile": "https://Stackoverflow.com/users/4853",
"pm_score": 4,
"selected": false,
"text": "html() var html = $('<div>').append( $('div').clone() ).html();\nalert(html);\n\n// alerts:\n\n<div class=\"abc\">\n foo <strong>FOO</strong>\n</div><div class=\"def\">\n bar\n</div>\n"
},
{
"answer_id": 11416247,
"author": "anewcomer",
"author_id": 526933,
"author_profile": "https://Stackoverflow.com/users/526933",
"pm_score": 4,
"selected": true,
"text": "var html = $mySet[0].outerHTML; // note HTML is all caps... that always burns me\n"
}
] | 2008/11/28 | [
"https://Stackoverflow.com/questions/325087",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9021/"
] |
325,099 | <p>I'd like to use visitor IP addresses into a company name. This will be used for displaying something like "Hello visitor from <strong>Apple Inc.</strong>" . Note I am looking for the company name, not the domain name. Extra points for determining the originating country. The app is written in Ruby on Rails, but examples in other languages will do. Thanks!</p>
| [
{
"answer_id": 325101,
"author": "Dustin",
"author_id": 39975,
"author_profile": "https://Stackoverflow.com/users/39975",
"pm_score": 0,
"selected": false,
"text": "whois -h whois.arin.net 17.18.19.20\n"
}
] | 2008/11/28 | [
"https://Stackoverflow.com/questions/325099",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
325,114 | <p>I have a Java file <code>TestThis.java</code> like the following:</p>
<pre><code>class A
{
public void foo()
{
System.out.println("Executing foo");
}
}
class B
{
public void bar()
{
System.out.println("Executing bar");
}
}
</code></pre>
<p>The above code file is compiling fine without any warnings/errors. Is there any way I could access any of class <code>A</code> or <code>B</code> without a top level class from any other external class?</p>
<p>If no then why does Java even permit compiling of such files without a top-level class?</p>
| [
{
"answer_id": 325121,
"author": "Ivan Dubrov",
"author_id": 31118,
"author_profile": "https://Stackoverflow.com/users/31118",
"pm_score": 4,
"selected": true,
"text": "public class Test {\n public static void main(String... args) {\n A a = new A();\n a.foo();\n B b = new B();\n b.bar();\n }\n}\n"
}
] | 2008/11/28 | [
"https://Stackoverflow.com/questions/325114",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/37626/"
] |
325,116 | <p>Here I am faced with an issue that I believe(or at least hope) was solved 1 million times already.
What I got as the input is a string that represents a length of an object in imperial units. It can go like this:</p>
<pre><code>$length = "3' 2 1/2\"";
</code></pre>
<p>or like this:</p>
<pre><code>$length = "1/2\"";
</code></pre>
<p>or in fact in any other way we normally would write it.</p>
<p>In effort to reduce global wheel invention, I wonder if there is some function, class, or regexp-ish thing that will allow me to convert Imperial length into Metric length?</p>
| [
{
"answer_id": 325131,
"author": "Claudiu",
"author_id": 15055,
"author_profile": "https://Stackoverflow.com/users/15055",
"pm_score": 1,
"selected": false,
"text": "\"([0-9]+)'\\s*([0-9]+)\\\"\"\n (int(grp1)*12+int(grp2))*2.54\n"
},
{
"answer_id": 325192,
"author": "Paige Ruten",
"author_id": 813,
"author_profile": "https://Stackoverflow.com/users/813",
"pm_score": 3,
"selected": true,
"text": "function imperial2metric($number) {\n // Get rid of whitespace on both ends of the string.\n $number = trim($number);\n\n // This results in the number of feet getting multiplied by 12 when eval'd\n // which converts them to inches.\n $number = str_replace(\"'\", '*12', $number);\n\n // We don't need the double quote.\n $number = str_replace('\"', '', $number);\n\n // Convert other whitespace into a plus sign.\n $number = preg_replace('/\\s+/', '+', $number);\n\n // Make sure they aren't making us eval() evil PHP code.\n if (preg_match('/[^0-9\\/\\.\\+\\*\\-]/', $number)) {\n return false;\n } else {\n // Evaluate the expression we've built to get the number of inches.\n $inches = eval(\"return ($number);\");\n\n // This is how you convert inches to meters according to Google calculator.\n $meters = $inches * 0.0254;\n\n // Returns it in meters. You may then convert to centimeters by\n // multiplying by 100, kilometers by dividing by 1000, etc.\n return $meters;\n }\n}\n 3' 2 1/2\"\n 3*12+2+1/2\n 38.5\n"
},
{
"answer_id": 325249,
"author": "Eran Galperin",
"author_id": 10585,
"author_profile": "https://Stackoverflow.com/users/10585",
"pm_score": 2,
"selected": false,
"text": "$unit = new Zend_Measure_Length($length,Zend_Measure_Length::YARD);\n$unit -> convertTo(Zend_Measure_Length::METER);\n"
},
{
"answer_id": 3301024,
"author": "Thomas",
"author_id": 398156,
"author_profile": "https://Stackoverflow.com/users/398156",
"pm_score": 2,
"selected": false,
"text": "string pattern = \"(([0-9]+)')*\\\\s*-*\\\\s*(([0-9])*\\\\s*([0-9]/[0-9])*\\\")*\";\nRegex regex = new Regex( pattern );\nMatch match = regex.Match(sourceValue);\nif( match.Success ) \n{\n int feet = 0;\n int.TryParse(match.Groups[2].Value, out feet);\n int inch = 0;\n int.TryParse(match.Groups[4].Value, out inch);\n double fracturalInch = 0.0;\n if (match.Groups[5].Value.Length == 3)\n fracturalInch = (double)(match.Groups[5].Value[0] - '0') / (double)(match.Groups[5].Value[2] - '0');\n\n resultValue = (feet * 12) + inch + fracturalInch;\n"
}
] | 2008/11/28 | [
"https://Stackoverflow.com/questions/325116",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/35520/"
] |
325,122 | <p>I'm following the sample code in <em>CFNetwork Programming Guide</em>, specifically the section on <strong>Preventing Blocking When Working with Streams</strong>. my code is nearly identical to theirs (below) but, when I connect to my server, I get posix error 14 (bad address -- is that bad IP address (except it's not)? Bad memory address for some call I made? or what?!.</p>
<p>I have no idea how to go about debugging this. I'm really pretty new to the whole CFNetworking thing, and was never particularly expert at networks in the first place (the one thing I really loved about Java: easy networks! :D)</p>
<p>Anyway, log follows, with code below. Any hints would be greatly appreciated.</p>
<p>Log:</p>
<pre><code>[6824:20b] [DEBUG] Compat version: 30000011
[6824:20b] [DEBUG] resovled host.
[6824:20b] [DEBUG] writestream opened.
[6824:20b] [DEBUG] readstream client assigned.
[6824:20b] [DEBUG] readstream opened.
[6824:20b] [DEBUG] *** Read stream reported kCFStreamEventErrorOccurred
[6824:20b] [DEBUG] *** POSIX error: 14 - Bad address
[6824:20b] Error closing readstream
[6824:20b] [DEBUG] Writing int: 0x09000000 (0x00000009)
</code></pre>
<p>Code:</p>
<pre><code>+ (BOOL) connectToServerNamed:(NSString*)name atPort:(int)port {
CFHostRef theHost = CFHostCreateWithName (NULL, (CFStringRef)name);
CFStreamError error;
if (CFHostStartInfoResolution (theHost, kCFHostReachability, &error))
{
NSLog (@"[DEBUG] resovled host.");
CFStreamCreatePairWithSocketToCFHost (NULL, theHost, port, &readStream, &writeStream);
if (CFWriteStreamOpen(writeStream))
{
NSLog (@"[DEBUG] writestream opened.");
CFStreamClientContext myContext = { 0, self, NULL, NULL, NULL };
CFOptionFlags registeredEvents = kCFStreamEventHasBytesAvailable |
kCFStreamEventErrorOccurred | kCFStreamEventEndEncountered;
if (CFReadStreamSetClient (readStream, registeredEvents, readCallBack, &myContext))
{
NSLog (@"[DEBUG] readstream client assigned.");
CFReadStreamScheduleWithRunLoop(readStream, CFRunLoopGetCurrent(),
kCFRunLoopCommonModes);
if (CFReadStreamOpen(readStream))
{
NSLog (@"[DEBUG] readstream opened.");
CFRunLoopRun();
// Lots of error condition handling snipped.
[...]
return YES;
}
void readCallBack (CFReadStreamRef stream, CFStreamEventType event, void *myPtr)
{
switch (event)
{
case kCFStreamEventHasBytesAvailable:
{
CFIndex bytesRead = CFReadStreamRead(stream, buffer, kNetworkyBitsBufferSize); // won't block
if (bytesRead > 0) // <= 0 leads to additional events
{
if (listener)
{
UInt8 *tmpBuffer = malloc (sizeof (UInt8) * bytesRead);
memcpy (buffer, tmpBuffer, bytesRead);
NSLog(@"[DEBUG] reveived %d bytes", bytesRead);
[listener networkDataArrived:tmpBuffer count:bytesRead];
}
NSLog(@"[DEBUG] reveived %d bytes; no listener", bytesRead);
}
}
break;
case kCFStreamEventErrorOccurred:
NSLog(@"[DEBUG] *** Read stream reported kCFStreamEventErrorOccurred");
CFStreamError error = CFReadStreamGetError(stream);
logError(error);
[NetworkyBits shutDownRead];
break;
case kCFStreamEventEndEncountered:
NSLog(@"[DEBUG] *** Read stream reported kCFStreamEventEndEncountered");
[NetworkyBits shutDownRead];
break;
}
}
void logError (CFStreamError error)
{
if (error.domain == kCFStreamErrorDomainPOSIX) // Interpret error.error as a UNIX errno.
{
NSLog (@"[DEBUG] *** POSIX error: %d - %s", (int) error.error, strerror(error.error));
}
else if (error.domain == kCFStreamErrorDomainMacOSStatus)
{
NSLog (@"[DEBUG] *** MacOS error: %d", (int) error.error);
}
else
{
NSLog (@"[DEBUG] *** Stream error domain: %d, error: %d", (int) error.error);
}
}
</code></pre>
| [
{
"answer_id": 325138,
"author": "Adam Rosenfield",
"author_id": 9530,
"author_profile": "https://Stackoverflow.com/users/9530",
"pm_score": 0,
"selected": false,
"text": "malloc()"
},
{
"answer_id": 325168,
"author": "Jason Coco",
"author_id": 34218,
"author_profile": "https://Stackoverflow.com/users/34218",
"pm_score": 3,
"selected": true,
"text": "buffer\n CFReadStreamRead()\n"
}
] | 2008/11/28 | [
"https://Stackoverflow.com/questions/325122",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/34820/"
] |
325,158 | <p>Like this: const void * test = sqlite3_column_blob(stat, 1);
Can I delete or delete[] test?</p>
| [
{
"answer_id": 325163,
"author": "Johannes Schaub - litb",
"author_id": 34509,
"author_profile": "https://Stackoverflow.com/users/34509",
"pm_score": 0,
"selected": false,
"text": "free"
}
] | 2008/11/28 | [
"https://Stackoverflow.com/questions/325158",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/26404/"
] |
325,165 | <p>Writing a python script and it needs to find out what language a block of code is written in. <strong>I could easily write this myself, but I'd like to know if a solution already exists.</strong></p>
<p>Pygments is insufficient and unreliable.</p>
| [
{
"answer_id": 325224,
"author": "Gaurav",
"author_id": 27310,
"author_profile": "https://Stackoverflow.com/users/27310",
"pm_score": 2,
"selected": false,
"text": "vim/vim71/filetype.vim"
},
{
"answer_id": 325296,
"author": "dbr",
"author_id": 745,
"author_profile": "https://Stackoverflow.com/users/745",
"pm_score": 2,
"selected": false,
"text": "print(\"blah\");\n #! $#somevar somevar.each do |another| ..... end *.pl print \"blah\""
},
{
"answer_id": 325521,
"author": "Ali Afshar",
"author_id": 28380,
"author_profile": "https://Stackoverflow.com/users/28380",
"pm_score": 4,
"selected": false,
"text": ">>> from pygments.lexers import guess_lexer, guess_lexer_for_filename\n\n>>> guess_lexer('#!/usr/bin/python\\nprint \"Hello World!\"')\n<pygments.lexers.PythonLexer>\n\n>>> guess_lexer_for_filename('test.py', 'print \"Hello World!\"')\n<pygments.lexers.PythonLexer>\n"
}
] | 2008/11/28 | [
"https://Stackoverflow.com/questions/325165",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/432/"
] |
325,171 | <p>I have a project built and packaged with a specific version of jsp-apiand servlet-api jar files. Now I want these jars to be loaded when deploying the web project on any application server for example tomcat, WAS, Weblogic etc.</p>
<p>The behaviour I have seen on tomcat is that it gives messages that the packaged version of these apis are not loaded along with an offending class.</p>
<p>Is there any way I could override these server settings or behaviour?</p>
<p>My concern is that letting the default behaviour of a server may allow different behaviour on different servers or even on different versions of same app server.</p>
| [
{
"answer_id": 325178,
"author": "OscarRyz",
"author_id": 20654,
"author_profile": "https://Stackoverflow.com/users/20654",
"pm_score": 3,
"selected": true,
"text": "java -Xbootclasspath/p:c:\\cutomjars\\myJar.jar;customjars\\myOtherJar.jar ..................... // the rest of the normal command line.\n"
},
{
"answer_id": 335283,
"author": "OscarRyz",
"author_id": 20654,
"author_profile": "https://Stackoverflow.com/users/20654",
"pm_score": 1,
"selected": false,
"text": "Servlet version: <%=application.getMajorVersion()%>.<%=application.getMinorVersion()%>\n SEVERE: Servlet.service() for servlet jsp threw exception\n\njavax.servlet.ServletException: javax.servlet.jsp.JspFactory.getJspApplicationContext(Ljavax/servlet/ServletContext;)Ljavax/servlet/jsp/JspApplicationContext;\n\nat org.apache.jasper.servlet.JspServlet.service(JspServlet.java:275)\n\nat javax.servlet.http.HttpServlet.service(HttpServlet.java:853)\n\nat org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290)\n\nat org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)\n\nat org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:233)\n\nat org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:191)\n\nat org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:128)\n\nat org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102)\n\nat org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109)\n\nat org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:286)\n\nat org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:845)\n\nat org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:583)\n\nat org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:447)\n\nat java.lang.Thread.run(Thread.java:619)\n"
}
] | 2008/11/28 | [
"https://Stackoverflow.com/questions/325171",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/37626/"
] |
325,186 | <p>While looking at the <code>syntax-case</code> section in R6RS, I saw the keyword <code>make-variable-transformer</code>, described as an <em>identifier macro</em>. The example given is very minimal, and I am not groking why it is necessary, or what use-cases require it. Finding additional examples of its use is also proving difficult. Presumably it makes some form of syntax transformation possible, or more elegant?</p>
| [
{
"answer_id": 336499,
"author": "Joel Borggrén-Franck",
"author_id": 38222,
"author_profile": "https://Stackoverflow.com/users/38222",
"pm_score": 2,
"selected": false,
"text": "mac (mac foo (bar baz)) (SOMETHING) (foo mac bar) mac (foo SOMETHING bar) (set! mac 'foo) mac (set! mac 'foo) mac"
}
] | 2008/11/28 | [
"https://Stackoverflow.com/questions/325186",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
325,190 | <p>Maybe this cannot be done, but please help or suggest how this can be achieved without writing something to disk.</p>
<p>Lets suppose there are two string values that I want to share between two independent applications.</p>
<p>You are welcome to provide code sample in any programming language.</p>
| [
{
"answer_id": 325195,
"author": "Greg Hewgill",
"author_id": 893,
"author_profile": "https://Stackoverflow.com/users/893",
"pm_score": 4,
"selected": true,
"text": "CreateFileMapping INVALID_HANDLE_VALUE OpenFileMapping std::string"
},
{
"answer_id": 325198,
"author": "atzz",
"author_id": 23252,
"author_profile": "https://Stackoverflow.com/users/23252",
"pm_score": 2,
"selected": false,
"text": "CreateFileMapping INVALID_HANDLE_VALUE #pragma data_seg"
}
] | 2008/11/28 | [
"https://Stackoverflow.com/questions/325190",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3535708/"
] |
325,200 | <p>I have 6 links on a page to an mp3.</p>
<p>The plugin I installed replaces those links with a swf and plays that mp3 inline.</p>
<p>The problem I <em>had</em> was that it was possible to activate all 6 links and have all audio playing at once. I <em>solved</em> that problem (I feel in a clumsy novice way though) by catching the <code><a></code> tag before it was replaced with the embed tag and then putting it back when another one was clicked.</p>
<p><strong>However, this is my problem now</strong>: the <code><a></code> tag I put back looses it's onClick event (i think that's what is happening) and so, if clicked a second time, fails to switch like the first time.</p>
<pre><code>$(".storyplayer a").bind("click", function() {
// replace the <a> tag from the previous media player installation
if (previousplayerlocation != null) {$("#" + previousplayerlocation + " .storyplayer").html(graboldcode);}
// now remember this installation's <a> tag before it's replaced
graboldcode = $(this).parent().html();
// remember where I grabbed this <a> tag from
previousplayerlocation = $(this).parents("div.storylisting").attr("id");
// replaces the <a> tag with the media player.
$(this).media({width: 190,height: 30});
return false;
});
</code></pre>
<p>Is a way to re-assign the click event to the <code>if</code> statement?</p>
| [
{
"answer_id": 325208,
"author": "strager",
"author_id": 39992,
"author_profile": "https://Stackoverflow.com/users/39992",
"pm_score": 1,
"selected": false,
"text": "function playerClicked() { \n // replace the <a> tag from the previous media player installation\n if (previousplayerlocation != null) {\n $(\"#\" + previousplayerlocation + \" .storyplayer\")\n .html(graboldcode)\n .click(playerClicked); // Re-add the onclick handler\n }\n\n // now remember this installation's <a> tag before it's replaced\n graboldcode = $(this).parent().html();\n // remember where I grabbed this <a> tag from\n previousplayerlocation = $(this).parents(\"div.storylisting\").attr(\"id\");\n\n // replaces the <a> tag with the media player.\n $(this).media({width: 190,height: 30});\n return false;\n}\n\n$(\".storyplayer a\").bind(\"click\", playerClicked);\n"
},
{
"answer_id": 325215,
"author": "redsquare",
"author_id": 6440,
"author_profile": "https://Stackoverflow.com/users/6440",
"pm_score": 2,
"selected": false,
"text": "$('#someContainer').click( function(ev){\n\n var $el=$(ev.target);\n if ( $el.is('a') ){\n //do your stuff\n }\n\n});\n"
},
{
"answer_id": 325886,
"author": "kgiannakakis",
"author_id": 24054,
"author_profile": "https://Stackoverflow.com/users/24054",
"pm_score": 0,
"selected": false,
"text": "$('a').livequery('click', function(){\n\n });\n $.livequery.run()\n $('a').livequery.expire('click')\n $('a').livequery(\nfunction(){ onmatchHandler},\nfunction(){ onmismatchHandler }\n);\n"
}
] | 2008/11/28 | [
"https://Stackoverflow.com/questions/325200",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
325,202 | <p>I have a Jar file, which contains other nested Jars. When I invoke the new <code>JarFile()</code> constructor on this file, I get an exception which says:</p>
<blockquote>
<p>java.util.zip.ZipException: error in opening zip file</p>
</blockquote>
<p>When I manually unzip the contents of this Jar file and zip it up again, it works fine.</p>
<p>I only see this exception on WebSphere 6.1.0.7 and higher versions. The same thing works fine on tomcat and WebLogic. </p>
<p>When I use JarInputStream instead of JarFile, I am able to read the contents of the Jar file without any exceptions.</p>
| [
{
"answer_id": 325206,
"author": "VonC",
"author_id": 6309,
"author_profile": "https://Stackoverflow.com/users/6309",
"pm_score": 3,
"selected": false,
"text": "Class-Path: one.jar two.jar three.jar\n"
},
{
"answer_id": 7508672,
"author": "JohnyCash",
"author_id": 486201,
"author_profile": "https://Stackoverflow.com/users/486201",
"pm_score": 4,
"selected": false,
"text": "public void unzipFileIntoDirectory(File archive, File destinationDir) \n throws Exception {\n final int BUFFER_SIZE = 1024;\n BufferedOutputStream dest = null;\n FileInputStream fis = new FileInputStream(archive);\n ZipInputStream zis = new ZipInputStream(new BufferedInputStream(fis));\n ZipEntry entry;\n File destFile;\n while ((entry = zis.getNextEntry()) != null) {\n destFile = FilesystemUtils.combineFileNames(destinationDir, entry.getName());\n if (entry.isDirectory()) {\n destFile.mkdirs();\n continue;\n } else {\n int count;\n byte data[] = new byte[BUFFER_SIZE];\n destFile.getParentFile().mkdirs();\n FileOutputStream fos = new FileOutputStream(destFile);\n dest = new BufferedOutputStream(fos, BUFFER_SIZE);\n while ((count = zis.read(data, 0, BUFFER_SIZE)) != -1) {\n dest.write(data, 0, count);\n }\n dest.flush();\n dest.close();\n fos.close();\n }\n }\n zis.close();\n fis.close();\n}\n"
},
{
"answer_id": 43117972,
"author": "radoh",
"author_id": 2020723,
"author_profile": "https://Stackoverflow.com/users/2020723",
"pm_score": 0,
"selected": false,
"text": "java.util.zip.ZipException: invalid entry CRC (expected 0x0 but got 0xdeadface)\n at java.util.zip.ZipInputStream.read(ZipInputStream.java:221)\n at java.util.zip.ZipInputStream.closeEntry(ZipInputStream.java:140)\n at java.util.zip.ZipInputStream.getNextEntry(ZipInputStream.java:118)\n...\n"
},
{
"answer_id": 48788415,
"author": "Yash",
"author_id": 5081877,
"author_profile": "https://Stackoverflow.com/users/5081877",
"pm_score": 0,
"selected": false,
"text": "commons-compress jarchivelib public static void main(String[] args) {\n String zipfilePath = \n \"E:/Selenium_Server/geckodriver-v0.19.0-linux64.tar.gz\";\n //\"E:/Selenium_Server/geckodriver-v0.19.0-win32.zip\";\n String outdir = \"E:/Selenium_Server/\";\n exratctFileList(zipfilePath, outdir );\n}\npublic void exratctFileList( String zipfilePath, String outdir ) throws IOException {\n File archive = new File( zipfilePath );\n File destinationDir = new File( outdir );\n\n Archiver archiver = null;\n if( zipfilePath.endsWith(\".zip\") ) {\n archiver = ArchiverFactory.createArchiver( ArchiveFormat.ZIP );\n } else if ( zipfilePath.endsWith(\".tar.gz\") ) {\n archiver = ArchiverFactory.createArchiver( ArchiveFormat.TAR, CompressionType.GZIP );\n }\n archiver.extract(archive, destinationDir);\n\n ArchiveStream stream = archiver.stream( archive );\n ArchiveEntry entry;\n\n while( (entry = stream.getNextEntry()) != null ) {\n String entryName = entry.getName();\n System.out.println(\"Entery Name : \"+ entryName );\n }\n stream.close();\n}\n <dependency>\n <groupId>org.rauschig</groupId>\n <artifactId>jarchivelib</artifactId>\n <version>0.7.1</version>\n</dependency>\n"
},
{
"answer_id": 51870550,
"author": "hatanooh",
"author_id": 2930417,
"author_profile": "https://Stackoverflow.com/users/2930417",
"pm_score": 0,
"selected": false,
"text": "-Dloader.path=\"lib\" mvn dependency:copy-dependencies lib"
}
] | 2008/11/28 | [
"https://Stackoverflow.com/questions/325202",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/41536/"
] |
325,213 | <p>I've seen lots of ways to backup a single repository in subversion. Is there any way to backup all the repositories in one go. I have lots of repositories for different projects and don't want to have to create a script every time.</p>
| [
{
"answer_id": 325230,
"author": "Greg Hewgill",
"author_id": 893,
"author_profile": "https://Stackoverflow.com/users/893",
"pm_score": 3,
"selected": false,
"text": "#!/bin/sh\nfor repo in /home/repositories/*; do\n backup-single-repository $repo\ndone\n"
}
] | 2008/11/28 | [
"https://Stackoverflow.com/questions/325213",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23230/"
] |
325,241 | <p>I currently have a list view which has several rows of data and I have a contextmenustrip in C# .NET.</p>
<p>What I am having problems with is when you click on the menu strip item I want to know which row has been selected.</p>
| [
{
"answer_id": 325280,
"author": "netadictos",
"author_id": 31791,
"author_profile": "https://Stackoverflow.com/users/31791",
"pm_score": 3,
"selected": true,
"text": "foreach (ListViewItem item in lvFiles.SelectedItems)\n{\n....................................\n}\n"
}
] | 2008/11/28 | [
"https://Stackoverflow.com/questions/325241",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/41541/"
] |
325,267 | <p>I have a question about using <code>new[]</code>.</p>
<p>Imagine this:</p>
<pre><code>Object.SomeProperty = new[] {"string1", "string2"};
</code></pre>
<p>Where SomeProperty expects an array of strings.</p>
<p>I know this code snippet will work. But i want to know what it does under the hood. Does <code>new[]</code> makes an instance of the class <code>object</code> and in <code>SomeProperty</code> it converts it automatically to a <code>string</code> object? </p>
<p>Thanks</p>
| [
{
"answer_id": 325274,
"author": "Konrad Rudolph",
"author_id": 1968,
"author_profile": "https://Stackoverflow.com/users/1968",
"pm_score": 4,
"selected": false,
"text": "Object.SomeProperty = new string[] {\"string1\", \"string2\"};\n new[]"
},
{
"answer_id": 325279,
"author": "Darin Dimitrov",
"author_id": 29407,
"author_profile": "https://Stackoverflow.com/users/29407",
"pm_score": 2,
"selected": false,
"text": "Object.SomeProperty = new[] {\"string1\", \"string2\"};\n Object.SomeProperty = new string[] {\"string1\", \"string2\"};\n"
},
{
"answer_id": 325284,
"author": "Simon Buchan",
"author_id": 20135,
"author_profile": "https://Stackoverflow.com/users/20135",
"pm_score": 2,
"selected": false,
"text": "string[] $temp = new string[2];\n$temp[0] = \"string1\";\n$temp[1] = \"string2\";\nObject.SomeProperty = $temp;\n var x = new[] { \"string1\", \"string2\" }; string[] var x = { \"string1\", \"string2\" };"
},
{
"answer_id": 325304,
"author": "ljs",
"author_id": 3394,
"author_profile": "https://Stackoverflow.com/users/3394",
"pm_score": 1,
"selected": false,
"text": "Object.SomeProperty = new string[] {\"string1\", \"string2\"};\n"
},
{
"answer_id": 325308,
"author": "Jon Skeet",
"author_id": 22656,
"author_profile": "https://Stackoverflow.com/users/22656",
"pm_score": 5,
"selected": true,
"text": "object o = new[] { \"string1\", \"string2\" };\n new[] { A, B, C, D, ... }\n new[] { new Form(), new MemoryStream() }\n MemoryStream Form new[] { GetSomeIDisposable(), new MemoryStream() }\n IDisposable[] MemoryStream IDisposable new[] { 0, 1, 3.5 } // double[]\nnew[] { 1, 3, 100L } // long[]\n"
}
] | 2008/11/28 | [
"https://Stackoverflow.com/questions/325267",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/40676/"
] |
325,273 | <p>I want to design a web page with a banner and an iframe. I hope the iframe can fill all the remaining page height and be resized automatically as the browser is resizing. Is it possible to get it done without writing JavaScript code, only with CSS?</p>
<p>I tried to set <code>height:100%</code> on iframe, the result is quite close but the iframe tried to fill the whole page height, including the <code>30px</code> height of banner div element, so I got unnecessary vertical scrollbar. It's not perfect.</p>
<p>I tried CSS margin, padding attribute on DIV to occupy the whole remaining height of a web page successfully, but the trick didn't work on iframe.</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code> <body>
<div style="width:100%; height:30px; background-color:#cccccc;">Banner</div>
<iframe src="http: //www.google.com.tw" style="width:100%; height:100%;"></iframe>
</body></code></pre>
</div>
</div>
</p>
| [
{
"answer_id": 325334,
"author": "Vilx-",
"author_id": 41360,
"author_profile": "https://Stackoverflow.com/users/41360",
"pm_score": 9,
"selected": true,
"text": "body, html {width: 100%; height: 100%; margin: 0; padding: 0}\n.row-container {display: flex; width: 100%; height: 100%; flex-direction: column; background-color: blue; overflow: hidden;}\n.first-row {background-color: lime; }\n.second-row { flex-grow: 1; border: none; margin: 0; padding: 0; } <div class=\"row-container\">\n <div class=\"first-row\">\n <p>Some text</p>\n <p>And some more text</p>\n </div>\n <iframe src=\"https://jsfiddle.net/about\" class=\"second-row\"></iframe>\n</div> html, body { height: 100% } min-height: 100% <!DOCTYPE html> body, html {width: 100%; height: 100%; margin: 0; padding: 0}\n.first-row {position: absolute;top: 0; left: 0; right: 0; height: 100px; background-color: lime;}\n.second-row {position: absolute; top: 100px; left: 0; right: 0; bottom: 0; background-color: red }\n.second-row iframe {display: block; width: 100%; height: 100%; border: none;} <div class=\"first-row\">\n <p>Some text</p>\n <p>And some more text</p>\n</div>\n<div class=\"second-row\">\n <iframe src=\"https://jsfiddle.net/about\"></iframe>\n</div> second-row bottom: 0 right: 0 width: 100% height: 100% display: block inline <table> display: table body, html {width: 100%; height: 100%; margin: 0; padding: 0}\n.row-container {display: table; empty-cells: show; border-collapse: collapse; width: 100%; height: 100%;}\n.first-row {display: table-row; overflow: auto; background-color: lime;}\n.second-row {display: table-row; height: 100%; background-color: red; overflow: hidden }\n.second-row iframe {width: 100%; height: 100%; border: none; margin: 0; padding: 0; display: block;} <div class=\"row-container\">\n <div class=\"first-row\">\n <p>Some text</p>\n <p>And some more text</p>\n </div>\n <div class=\"second-row\">\n <iframe src=\"https://jsfiddle.net/about\"></iframe>\n </div>\n</div> overflow: auto height: 100% body, html {width: 100%; height: 100%; margin: 0; padding: 0}\n.row-container {display: flex; width: 100%; height: 100%; flex-direction: column; background-color: blue; overflow: hidden;}\n.first-row {background-color: lime; }\n.second-row { flex-grow: 1; border: none; margin: 0; padding: 0; } <div class=\"row-container\">\n <div class=\"first-row\">\n <p>Some text</p>\n <p>And some more text</p>\n </div>\n <iframe src=\"https://jsfiddle.net/about\" class=\"second-row\"></iframe>\n</div> overflow: hidden display: block"
},
{
"answer_id": 325351,
"author": "ARemesal",
"author_id": 36599,
"author_profile": "https://Stackoverflow.com/users/36599",
"pm_score": 3,
"selected": false,
"text": "<body>\n <div style=\"width:100%; height:30px; background-color:#cccccc;\">Banner</div>\n <div style=\"width:100%; height:90%; background-color:transparent;\">\n <iframe src=\"http: //www.google.com.tw\" style=\"width:100%; height:100%;\">\n </iframe> \n </div>\n</body>\n"
},
{
"answer_id": 330006,
"author": "MichAdel",
"author_id": 1843828,
"author_profile": "https://Stackoverflow.com/users/1843828",
"pm_score": 6,
"selected": false,
"text": "var buffer = 20; //scroll bar buffer\nvar iframe = document.getElementById('ifm');\n\nfunction pageY(elem) {\n return elem.offsetParent ? (elem.offsetTop + pageY(elem.offsetParent)) : elem.offsetTop;\n}\n\nfunction resizeIframe() {\n var height = document.documentElement.clientHeight;\n height -= pageY(document.getElementById('ifm'))+ buffer ;\n height = (height < 0) ? 0 : height;\n document.getElementById('ifm').style.height = height + 'px';\n}\n\n// .onload doesn't work with IE8 and older.\nif (iframe.attachEvent) {\n iframe.attachEvent(\"onload\", resizeIframe);\n} else {\n iframe.onload=resizeIframe;\n}\n\nwindow.onresize = resizeIframe;\n ifm pageY()"
},
{
"answer_id": 696892,
"author": "Amir Arad",
"author_id": 11813,
"author_profile": "https://Stackoverflow.com/users/11813",
"pm_score": 0,
"selected": false,
"text": "<frameset rows=\"30,*\">\n <frame src=\"banner.swf\"/>\n <frame src=\"inner.html\" />\n</frameset>\n"
},
{
"answer_id": 1118715,
"author": "ducu",
"author_id": 45712,
"author_profile": "https://Stackoverflow.com/users/45712",
"pm_score": 5,
"selected": false,
"text": "DOCTYPE table <!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">\n<html xmlns=\"http://www.w3.org/1999/xhtml\" xml:lang=\"en\" lang=\"en\">\n<head>\n<style>\n*{margin:0;padding:0}\nhtml, body {height:100%;width:100%;overflow:hidden}\ntable {height:100%;width:100%;table-layout:static;border-collapse:collapse}\niframe {height:100%;width:100%}\n\n.header {border-bottom:1px solid #000}\n.content {height:100%}\n</style>\n</head>\n<body>\n<table>\n <tr><td class=\"header\"><div><h1>Header</h1></div></td></tr>\n <tr><td class=\"content\">\n <iframe src=\"http://google.com/\" frameborder=\"0\"></iframe></td></tr>\n</table>\n</body>\n</html>\n"
},
{
"answer_id": 2425694,
"author": "D1SoveR",
"author_id": 240202,
"author_profile": "https://Stackoverflow.com/users/240202",
"pm_score": 6,
"selected": false,
"text": "position: fixed; position: fixed; width: 100%; height: 100%; <iframe> width: 100%; height: 100%; body {\n margin: 0px;\n padding: 0px;\n }\n\n /* iframe's parent node */\n div#root {\n position: fixed;\n width: 100%;\n height: 100%;\n }\n\n /* iframe itself */\n div#root > iframe {\n display: block;\n width: 100%;\n height: 100%;\n border: none;\n } <html>\n <head>\n <title>iframe Test</title>\n <meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\">\n </head>\n <body>\n <div id=\"root\">\n <iframe src=\"http://stackoverflow.com/\">\n Your browser does not support inline frames.\n </iframe>\n </div>\n </body>\n </html>"
},
{
"answer_id": 3202972,
"author": "Tim Geerts",
"author_id": 221335,
"author_profile": "https://Stackoverflow.com/users/221335",
"pm_score": 4,
"selected": false,
"text": "$(\"iframe\").height($(\"#middle\").height());\n $(window).resize(function() {\n $(\"iframe\").height($(\"#middle\").height());\n});\n"
},
{
"answer_id": 3940802,
"author": "benb",
"author_id": 473101,
"author_profile": "https://Stackoverflow.com/users/473101",
"pm_score": 1,
"selected": false,
"text": "function iframeHeight() {\n var newHeight = $j(window).height();\n var buffer = 180; // space required for any other elements on the page \n var newIframeHeight = newHeight - buffer;\n $j('iframe').css('height',newIframeHeight); //this will aply to all iframes on the page, so you may want to make your jquery selector more specific.\n}\n\n// When DOM ready\n$(function() {\n window.onresize = iframeHeight;\n}\n"
},
{
"answer_id": 4524484,
"author": "asimrafi",
"author_id": 553032,
"author_profile": "https://Stackoverflow.com/users/553032",
"pm_score": 3,
"selected": false,
"text": "function pageY(elem) {\n return elem.offsetParent ? (elem.offsetTop + pageY(elem.offsetParent)) : elem.offsetTop;\n}\nvar buffer = 10; //scroll bar buffer\nfunction resizeIframe() {\n var height = window.innerHeight || document.body.clientHeight || document.documentElement.clientHeight;\n height -= pageY(document.getElementById('ifm'))+ buffer ;\n height = (height < 0) ? 0 : height;\n document.getElementById('ifm').style.height = height + 'px';\n}\nwindow.onresize = resizeIframe;\nwindow.onload = resizeIframe;\n"
},
{
"answer_id": 7925977,
"author": "Danut Milea",
"author_id": 1017849,
"author_profile": "https://Stackoverflow.com/users/1017849",
"pm_score": 3,
"selected": false,
"text": "<style type=\"text/css\">\n html, body, div, iframe { margin:0; padding:0; height:100%; }\n iframe { position:fixed; display:block; width:100%; border:none; }\n</style>\n"
},
{
"answer_id": 8362981,
"author": "vdbuilder",
"author_id": 1076318,
"author_profile": "https://Stackoverflow.com/users/1076318",
"pm_score": 2,
"selected": false,
"text": "<body>\n <div style=\"width:100%; height:30px; background-color:#cccccc;\">Banner</div>\n <iframe src=\"http: //www.google.com.tw\" style=\"position:fixed;top:30px;bottom:0px;width:100%;\"></iframe>\n</body>\n"
},
{
"answer_id": 13814736,
"author": "sree",
"author_id": 1823205,
"author_profile": "https://Stackoverflow.com/users/1823205",
"pm_score": 2,
"selected": false,
"text": "<iframe name=\"\" src=\"\" width=\"100%\" style=\"height: 100em\"/>\n"
},
{
"answer_id": 16085659,
"author": "pixelfe",
"author_id": 2291239,
"author_profile": "https://Stackoverflow.com/users/2291239",
"pm_score": 0,
"selected": false,
"text": "html, body, section, main-div {}\n #main-div {height:100%;}\n#iframe {height:300%;}\n"
},
{
"answer_id": 24666444,
"author": "unloco",
"author_id": 179545,
"author_profile": "https://Stackoverflow.com/users/179545",
"pm_score": 0,
"selected": false,
"text": "$(function(){\n\n if(window != top){\n var autoIframeHeight = function(){\n var url = location.href;\n $(top.jQuery.find('iframe[src=\"'+ url +'\"]')).css('height', $('body').height()+4);\n }\n $(window).on('resize',autoIframeHeight);\n autoIframeHeight();\n }\n\n}\n"
},
{
"answer_id": 25381873,
"author": "Pravin Abhale",
"author_id": 2229464,
"author_profile": "https://Stackoverflow.com/users/2229464",
"pm_score": 0,
"selected": false,
"text": "For eg.\n<html>\n<head>\n<style>\nhtml,body{height:100%}\n</style> \n</head>\n<body>\n<iframe src=\"http://www.quasarinfosystem.com\" height=\"100%\" width=\"100%\" ></iframe>\n</body>\n</html>\n"
},
{
"answer_id": 27689958,
"author": "Stefan Steiger",
"author_id": 155077,
"author_profile": "https://Stackoverflow.com/users/155077",
"pm_score": 2,
"selected": false,
"text": "<html style=\"width:100%; height:100%; margin: 0px; padding: 0px;\">\n<body style=\"width:100%; height:100%; margin: 0px; padding: 0px;\">\n<div style=\"width:100%; height:30px; background-color:#cccccc;\">Banner</div>\n<iframe src=\"http://www.google.com.tw\" style=\"width:100%; height: calc(100% - 30px);\"></iframe>\n</body>\n</html>\n"
},
{
"answer_id": 27914781,
"author": "Josh Crozier",
"author_id": 2680216,
"author_profile": "https://Stackoverflow.com/users/2680216",
"pm_score": 5,
"selected": false,
"text": "calc() calc(100vh - 30px) 100vh calc() body {\n margin: 0;\n}\n.banner {\n background: #f00;\n height: 30px;\n}\niframe {\n display: block;\n background: #000;\n border: none;\n height: calc(100vh - 30px);\n width: 100%;\n} <div class=\"banner\"></div>\n<iframe></iframe> calc() display flex flex-direction: column flex-grow: 1 iframe body {\n margin: 0;\n}\n.parent {\n display: flex;\n flex-direction: column;\n min-height: 100vh;\n}\n.parent .banner {\n background: #f00;\n width: 100%;\n height: 30px;\n}\n.parent iframe {\n background: #000;\n border: none;\n flex-grow: 1;\n} <div class=\"parent\">\n <div class=\"banner\"></div>\n <iframe></iframe>\n</div>"
},
{
"answer_id": 30211816,
"author": "mgr",
"author_id": 2668585,
"author_profile": "https://Stackoverflow.com/users/2668585",
"pm_score": 1,
"selected": false,
"text": "<iframe src=\"http: //www.google.com.tw\"style=\"position: absolute; height: 100%; border: none\"></iframe>\n"
},
{
"answer_id": 31009402,
"author": "Stephen",
"author_id": 691416,
"author_profile": "https://Stackoverflow.com/users/691416",
"pm_score": 0,
"selected": false,
"text": " $(window).resize(function() {\n $(parent.document)\n .find(\"iframe\")\n .css(\"height\", $(\"body\").css(\"height\")); \n }).trigger(\"resize\");\n"
},
{
"answer_id": 32118972,
"author": "Roy Shmuli",
"author_id": 3962211,
"author_profile": "https://Stackoverflow.com/users/3962211",
"pm_score": 1,
"selected": false,
"text": "<script type=\"text/javascript\">\n $(document).ready(function() {\n var $iframe = $('#iframe_id')[0];\n\n // Calculate the total offset top of given jquery element\n function totalOffsetTop($elem) {\n return $elem.offsetTop + ($elem.offsetParent ? totalOffsetTop($elem.offsetParent) : 0);\n }\n\n function resizeIframe() {\n var height = window.innerHeight || document.body.clientHeight || document.documentElement.clientHeight;\n height -= totalOffsetTop($iframe);\n $iframe.height = Math.max(0, height) + 'px';\n }\n\n $iframe.onload = resizeIframe();\n window.onresize = resizeIframe;\n });\n</script>\n iframe_id"
},
{
"answer_id": 35452481,
"author": "Jay Patel",
"author_id": 1286507,
"author_profile": "https://Stackoverflow.com/users/1286507",
"pm_score": 0,
"selected": false,
"text": ".container{\n width:100%;\n position:relative;\n height:500px;\n}\n\niframe{\n position:absolute;\n width:100%;\n height:100%;\n} <div class=\"container\">\n <iframe src=\"http://www.w3schools.com\">\n <p>Your browser does not support iframes.</p>\n </iframe>\n</div>"
},
{
"answer_id": 35881433,
"author": "daamsie",
"author_id": 887032,
"author_profile": "https://Stackoverflow.com/users/887032",
"pm_score": 2,
"selected": false,
"text": "<body>\n <div class=\"outer\">\n <div class=\"banner\">Banner</div>\n <div class=\"iframe-container\">\n <iframe src=\"http: //www.google.com.tw\" style=\"width:100%; height:100%;border:0;\"></iframe>\n </div>\n </div>\n</body>\n .outer {\n display: table;\n height: 100%;\n width: 100%;\n}\n .banner {\n display: table-row;\n height: 30px;\n background: #eee;\n}\n .iframe-container {\n display: table-row;\n height: 100%;\n}\n"
},
{
"answer_id": 42450941,
"author": "access_granted",
"author_id": 5812981,
"author_profile": "https://Stackoverflow.com/users/5812981",
"pm_score": 1,
"selected": false,
"text": "<script>\n var oF = document.getElementById(\"iframe1\");\n oF.style.height = document.body.clientHeight - oF.offsetTop - 0;\n</script>\n"
},
{
"answer_id": 64811457,
"author": "montrealmike",
"author_id": 454375,
"author_profile": "https://Stackoverflow.com/users/454375",
"pm_score": 3,
"selected": false,
"text": "vh <iframe src='/' style=\"display:block; border:none; height:100vh; width:100%;\"></iframe>\n"
}
] | 2008/11/28 | [
"https://Stackoverflow.com/questions/325273",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/288936/"
] |
325,278 | <p>What would be the best way to display & program simple game board (say chess, checkers and such) in C#? In terms of controls and underlying game logic. </p>
<p>An idea that came to my mind was to use <strong>Picture Box</strong> (or class inheriting from it) with Board & Field classes. </p>
<ul>
<li>Is that a decent solution after all? </li>
<li>How would I separate graphics from game logic using this solution (I believe Board & Field classes may not be enough)? </li>
<li>Is PictureBox efficient enough for such purpose? </li>
</ul>
<p>Googling some also brought me to solutions using button/label for each game field. But back to Board, Field and PictureBox. </p>
<p>Extendability - designing it properly would easily allow to implement any other board game (or even card game) as it's all about board with modifiable fields after all.</p>
| [
{
"answer_id": 325286,
"author": "Konrad Rudolph",
"author_id": 1968,
"author_profile": "https://Stackoverflow.com/users/1968",
"pm_score": 3,
"selected": true,
"text": "Graphics PictureBox"
}
] | 2008/11/28 | [
"https://Stackoverflow.com/questions/325278",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/36890/"
] |
325,299 | <p>I'm using Java 1.5 and I'd like to launch the associated application to open the file. I know that Java 1.6 introduced the <a href="http://java.sun.com/developer/technicalArticles/J2SE/Desktop/javase6/desktop_api/" rel="noreferrer">Desktop API</a>, but I need a solution for <strong>Java 1.5</strong>.</p>
<p>So far I found a way to do it in Windows:</p>
<pre><code>Runtime.getRuntime().exec(new String[]{ "rundll32",
"url.dll,FileProtocolHandler", fileName });
</code></pre>
<p>Is there a cross-platform way to do it? Or at least a similar solution for <strong>Linux</strong>?</p>
| [
{
"answer_id": 325319,
"author": "boutta",
"author_id": 15108,
"author_profile": "https://Stackoverflow.com/users/15108",
"pm_score": 2,
"selected": false,
"text": "final Program p = Program.findProgram(fileExtension);\np.execute(file.getAbsolutePath());\n"
},
{
"answer_id": 325517,
"author": "DaWilli",
"author_id": 33974,
"author_profile": "https://Stackoverflow.com/users/33974",
"pm_score": 4,
"selected": false,
"text": "public static boolean isWindows() {\n String os = System.getProperty(\"os.name\").toLowerCase();\n return os.indexOf(\"windows\") != -1 || os.indexOf(\"nt\") != -1;\n}\npublic static boolean isMac() {\n String os = System.getProperty(\"os.name\").toLowerCase();\n return os.indexOf(\"mac\") != -1;\n}\npublic static boolean isLinux() {\n String os = System.getProperty(\"os.name\").toLowerCase();\n return os.indexOf(\"linux\") != -1;\n}\npublic static boolean isWindows9X() {\n String os = System.getProperty(\"os.name\").toLowerCase();\n return os.equals(\"windows 95\") || os.equals(\"windows 98\");\n}\n if (isLinux())\n {\n cmds.add(String.format(\"gnome-open %s\", fileName));\n String subCmd = (exec) ? \"exec\" : \"openURL\";\n cmds.add(String.format(\"kfmclient \"+subCmd+\" %s\", fileName));\n }\n else if (isMac())\n {\n cmds.add(String.format(\"open %s\", fileName));\n }\n else if (isWindows() && isWindows9X())\n {\n cmds.add(String.format(\"command.com /C start %s\", fileName));\n }\n else if (isWindows())\n {\n cmds.add(String.format(\"cmd /c start %s\", fileName));\n }\n"
},
{
"answer_id": 326360,
"author": "OscarRyz",
"author_id": 20654,
"author_profile": "https://Stackoverflow.com/users/20654",
"pm_score": 5,
"selected": true,
"text": " Desktop desktop = Desktop.getDesktop();\n\n desktop.open( aFile );\n desktop.imaginaryAction( aFile );\n package your.pack.name;\n\nimport java.io.File;\n\npublic class Desktop{\n\n // hide the constructor.\n Desktop(){}\n\n // Created the appropriate instance\n public static Desktop getDesktop(){\n\n String os = System.getProperty(\"os.name\").toLowerCase();\n\n Desktop desktop = new Desktop();\n // This uf/elseif/else code is used only once: here\n if ( os.indexOf(\"windows\") != -1 || os.indexOf(\"nt\") != -1){\n\n desktop = new WindowsDesktop();\n\n } else if ( os.equals(\"windows 95\") || os.equals(\"windows 98\") ){\n\n desktop = new Windows9xDesktop();\n\n } else if ( os.indexOf(\"mac\") != -1 ) {\n\n desktop = new OSXDesktop();\n\n } else if ( os.indexOf(\"linux\") != -1 && isGnome() ) {\n\n desktop = new GnomeDesktop();\n\n } else if ( os.indexOf(\"linux\") != -1 && isKde() ) {\n\n desktop = new KdeDesktop();\n\n } else {\n throw new UnsupportedOperationException(String.format(\"The platform %s is not supported \",os) );\n }\n return desktop;\n }\n\n // default implementation :( \n public void open( File file ){\n throw new UnsupportedOperationException();\n }\n\n // default implementation :( \n public void imaginaryAction( File file ){\n throw new UnsupportedOperationException();\n }\n}\n\n// One subclass per platform below:\n// Each one knows how to handle its own platform \n\n\nclass GnomeDesktop extends Desktop{\n\n public void open( File file ){\n // Runtime.getRuntime().exec: execute gnome-open <file>\n }\n\n public void imaginaryAction( File file ){\n // Runtime.getRuntime().exec:gnome-something-else <file>\n }\n\n}\nclass KdeDesktop extends Desktop{\n\n public void open( File file ){\n // Runtime.getRuntime().exec: kfmclient exec <file>\n }\n\n public void imaginaryAction( File file ){\n // Runtime.getRuntime().exec: kfm-imaginary.sh <file>\n }\n}\nclass OSXDesktop extends Desktop{\n\n public void open( File file ){\n // Runtime.getRuntime().exec: open <file>\n }\n\n public void imaginaryAction( File file ){\n // Runtime.getRuntime().exec: wow!! <file>\n }\n}\nclass WindowsDesktop extends Desktop{\n\n public void open( File file ){\n // Runtime.getRuntime().exec: cmd /c start <file>\n }\n\n public void imaginaryAction( File file ){\n // Runtime.getRuntime().exec: ipconfig /relese /c/d/e\n }\n}\nclass Windows9xDesktop extends Desktop{\n\n public void open( File file ){\n //Runtime.getRuntime().exec: command.com /C start <file>\n }\n\n public void imaginaryAction( File file){\n //Runtime.getRuntime().exec: command.com /C otherCommandHere <file>\n }\n}\n"
},
{
"answer_id": 326914,
"author": "Torsten Marek",
"author_id": 9567,
"author_profile": "https://Stackoverflow.com/users/9567",
"pm_score": 3,
"selected": false,
"text": "gnome-open xdg-open gnome-open xdg-open"
},
{
"answer_id": 4208232,
"author": "Paul Lammertsma",
"author_id": 154306,
"author_profile": "https://Stackoverflow.com/users/154306",
"pm_score": 0,
"selected": false,
"text": "Program.launch(\"http://google.com/\");\n true Display Shell Display.syncExec(new Runnable() {\n public void run() {\n Program.launch(\"http://google.com/\");\n }\n});\n"
}
] | 2008/11/28 | [
"https://Stackoverflow.com/questions/325299",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21348/"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.