qid
int64
4
19.1M
question
stringlengths
18
48.3k
answers
list
date
stringlengths
10
10
metadata
list
102,056
<p>"The Google" is very helpful... unless your language is called "R," in which case it spits out tons of irrelevant stuff.</p> <p>Anyone have any search engine tricks for "R"? There are some specialized websites, like those below, but how can you tell Google you mean "R" the language? If I'm searching for something specific, I'll use an R-specific term, like "cbind." Are there other such tricks?</p> <ul> <li><a href="http://rweb.stat.umn.edu/R/doc/html/search/SearchEngine.html" rel="noreferrer">rweb.stat.umn.edu</a></li> <li><a href="http://www.rseek.org/" rel="noreferrer">www.rseek.org</a></li> <li><a href="http://search.r-project.org/" rel="noreferrer">search.r-project.org</a> </li> <li><a href="http://www.dangoldstein.com/search_r.html" rel="noreferrer">www.dangoldstein.com/search_r.html</a></li> </ul>
[ { "answer_id": 1098043, "author": "Frank", "author_id": 60628, "author_profile": "https://Stackoverflow.com/users/60628", "pm_score": 0, "selected": false, "text": "cran.r-project.org ifelse R ifelse site:cran.r-project.org\n" }, { "answer_id": 5745338, "author": "Andrie", "author_id": 602276, "author_profile": "https://Stackoverflow.com/users/602276", "pm_score": 4, "selected": false, "text": "[R] lm" }, { "answer_id": 5746388, "author": "Joshua Ulrich", "author_id": 271616, "author_profile": "https://Stackoverflow.com/users/271616", "pm_score": 3, "selected": false, "text": "+" }, { "answer_id": 11147504, "author": "David J.", "author_id": 109618, "author_profile": "https://Stackoverflow.com/users/109618", "pm_score": 2, "selected": false, "text": "language:R lubridate" } ]
2008/09/19
[ "https://Stackoverflow.com/questions/102056", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
102,057
<p>I've got a Fitnesse RowFixture that returns a list of business objects. The object has a field which is a float representing a percentage between 0 and 1. The <em>consumer</em> of the business object will be a web page or report that comes from a designer, so the formatting of the percentage will be up to the designer rather than the business object. </p> <p>It would be nicer if the page could emulate the designer when converting the number to a percentage, i.e. instead of displaying 0.5, it should display 50%. But I'd rather not pollute the business object with the display code. Is there a way to specify a format string in the RowFixture?</p>
[ { "answer_id": 105997, "author": "Josh", "author_id": 11702, "author_profile": "https://Stackoverflow.com/users/11702", "pm_score": 3, "selected": true, "text": "public class BusinessObject\n{\n public float Percent { get; private set; }\n}\n public class ReturnRowDTO\n{\n public String Percent { get; set; }\n}\n public class ExampleRowFixture: fit.RowFixture\n {\n private ISomeService _someService;\n\n public override object[] Query()\n {\n BusinessObject[] list = _someService.GetBusinessObjects();\n\n return Array.ConvertAll(list, new Converter<BusinessObject, ReturnRowDTO>(ConvertBusinessObjectToDTO));\n }\n\n public override Type GetTargetClass()\n {\n return typeof (ReturnRowDTO);\n }\n\n public ReturnRowDTO ConvertBusinessObjectToDTO(BusinessObject businessObject)\n {\n return new ReturnRowDTO() {Percent = businessObject.Percent.ToString(\"%\")};\n }\n }\n" } ]
2008/09/19
[ "https://Stackoverflow.com/questions/102057", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6902/" ]
102,058
<p>The server.xml which controls the startup of Apache Tomcat's servlet container contains a debug attribute for nearly every major component. The debug attribute is more or less verbose depending upon the number you give it, zero being least and 99 being most verbose. How does the debug level affect Tomcat's speed when servicing large numbers of users? I assume zero is fast and 99 is relatively slower, but is this true. If there are no errors being thrown, does it matter?</p>
[ { "answer_id": 105997, "author": "Josh", "author_id": 11702, "author_profile": "https://Stackoverflow.com/users/11702", "pm_score": 3, "selected": true, "text": "public class BusinessObject\n{\n public float Percent { get; private set; }\n}\n public class ReturnRowDTO\n{\n public String Percent { get; set; }\n}\n public class ExampleRowFixture: fit.RowFixture\n {\n private ISomeService _someService;\n\n public override object[] Query()\n {\n BusinessObject[] list = _someService.GetBusinessObjects();\n\n return Array.ConvertAll(list, new Converter<BusinessObject, ReturnRowDTO>(ConvertBusinessObjectToDTO));\n }\n\n public override Type GetTargetClass()\n {\n return typeof (ReturnRowDTO);\n }\n\n public ReturnRowDTO ConvertBusinessObjectToDTO(BusinessObject businessObject)\n {\n return new ReturnRowDTO() {Percent = businessObject.Percent.ToString(\"%\")};\n }\n }\n" } ]
2008/09/19
[ "https://Stackoverflow.com/questions/102058", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13930/" ]
102,059
<p>With previous versions of flash, entering the full screen mode increased the height and width of the stage to the dimensions of the screen. Now that hardware scaling has arrived, the height and width are set to the dimensions of the video (plus borders if the aspect ratio is different).</p> <p>That's fine, unless you have controls placed over the video. Before, you could control their size; but now they're blown up by the same scale as the video, and pixellated horribly. Controls are ugly and subtitles are unreadable.</p> <p>It's possible for the user to turn off hardware scaling, but all that achieves is to turn off anti-aliasing. The controls are still blown up to ugliness.</p> <p>Is there a way to get the old scaling behaviour back?</p>
[ { "answer_id": 106667, "author": "Brent", "author_id": 10680, "author_profile": "https://Stackoverflow.com/users/10680", "pm_score": -1, "selected": false, "text": "stage.align = StageAlign.TOP_LEFT; \nstage.scaleMode = StageScaleMode.NO_SCALE;\nstage.addEventListener(Event.RESIZE, onStageResize);\n\nfunction onStageResize(event:Event):void {\n //do whatever you want to re-position your controls and scale the video\n // here's an example\n myFLVPlayback.width = stage.stageWidth;\n myFLVPlayback.height = stage.stageHeight - controls.height;\n controls.y = stage.stageHeight - controls.height;\n}\n" }, { "answer_id": 113828, "author": "Simon", "author_id": 15371, "author_profile": "https://Stackoverflow.com/users/15371", "pm_score": 2, "selected": true, "text": "import fl.video.*;\nuse namespace flvplayback_internal;\n\npublic class CustomFLVPlayback\n{\n public function CustomFLVPlayback()\n {\n super();\n uiMgr = new CustomUIManager(this);\n }\n}\n import fl.video.*;\nimport flash.display.StageDisplayState;\n\npublic class CustomUIManager\n{\n public function CustomUIManager(vc:FLVPlayback)\n {\n super(vc);\n }\n\n public override function enterFullScreenDisplayState():void\n {\n if (!_fullScreen && _vc.stage != null)\n {\n try\n {\n _vc.stage.displayState = StageDisplayState.FULL_SCREEN;\n } catch (se:SecurityError) {\n }\n }\n }\n}\n var myFLVPLayback:FLVPlayback = new FLVPlayback();\n var myFLVPLayback:CustomFLVPlayback = new CustomFLVPlayback();\n" }, { "answer_id": 189958, "author": "aaaidan", "author_id": 26331, "author_profile": "https://Stackoverflow.com/users/26331", "pm_score": 2, "selected": false, "text": " myFLVPlayback.fullScreenTakeOver = false; fullScreenTakeOver FLVPlayback" } ]
2008/09/19
[ "https://Stackoverflow.com/questions/102059", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15371/" ]
102,064
<p>I've developed a Windows service which tracks business events. It uses the Windows clock to timestamp events. However, the underlying clock can drift quite dramatically (e.g. losing a few seconds per minute), particularly when the CPUs are working hard. Our servers use the Windows Time Service to stay in sync with domain controllers, which uses NTP under the hood, but the sync frequency is controlled by domain policy, and in any case even syncing every minute would still allow significant drift. Are there any techniques we can use to keep the clock more stable, other than using hardware clocks?</p>
[ { "answer_id": 102142, "author": "Nick Craver", "author_id": 13249, "author_profile": "https://Stackoverflow.com/users/13249", "pm_score": 0, "selected": false, "text": "HKEY_LOCAL_MACHINE\\SYSTEM\\CurrentControlSet\\Services\\W32Time\\TimeProviders\\NtpClient\\SpecialPollInterval\n" }, { "answer_id": 102355, "author": "JosephStyons", "author_id": 672, "author_profile": "https://Stackoverflow.com/users/672", "pm_score": 0, "selected": false, "text": "unit TimeHandler;\n\ninterface\n\ntype\n TTimeHandler = class\n private\n FServerName : widestring;\n public\n constructor Create(servername : widestring);\n function RemoteSystemTime : TDateTime;\n procedure SetLocalSystemTime(settotime : TDateTime);\n end;\n\nimplementation\n\nuses\n Windows, SysUtils, Messages;\n\nfunction NetRemoteTOD(ServerName :PWideChar; var buffer :pointer) : integer; stdcall; external 'netapi32.dll';\nfunction NetApiBufferFree(buffer : Pointer) : integer; stdcall; external 'netapi32.dll';\n\ntype\n //See MSDN documentation on the TIME_OF_DAY_INFO structure.\n PTime_Of_Day_Info = ^TTime_Of_Day_Info;\n TTime_Of_Day_Info = record\n ElapsedDate : integer;\n Milliseconds : integer;\n Hours : integer;\n Minutes : integer;\n Seconds : integer;\n HundredthsOfSeconds : integer;\n TimeZone : LongInt;\n TimeInterval : integer;\n Day : integer;\n Month : integer;\n Year : integer;\n DayOfWeek : integer;\n end;\n\nconstructor TTimeHandler.Create(servername: widestring);\nbegin\n inherited Create;\n FServerName := servername;\nend;\n\nfunction TTimeHandler.RemoteSystemTime: TDateTime;\nvar\n Buffer : pointer;\n Rek : PTime_Of_Day_Info;\n DateOnly, TimeOnly : TDateTime;\n timezone : integer;\nbegin\n //if the call is successful...\n if 0 = NetRemoteTOD(PWideChar(FServerName),Buffer) then begin\n //store the time of day info in our special buffer structure\n Rek := PTime_Of_Day_Info(Buffer);\n\n //windows time is in GMT, so we adjust for our current time zone\n if Rek.TimeZone <> -1 then\n timezone := Rek.TimeZone div 60\n else\n timezone := 0;\n\n //decode the date from integers into TDateTimes\n //assume zero milliseconds\n try\n DateOnly := EncodeDate(Rek.Year,Rek.Month,Rek.Day);\n TimeOnly := EncodeTime(Rek.Hours,Rek.Minutes,Rek.Seconds,0);\n except on e : exception do\n raise Exception.Create(\n 'Date retrieved from server, but it was invalid!' +\n #13#10 +\n e.Message\n );\n end;\n\n //translate the time into a TDateTime\n //apply any time zone adjustment and return the result\n Result := DateOnly + TimeOnly - (timezone / 24);\n end //if call was successful\n else begin\n raise Exception.Create('Time retrieval failed from \"'+FServerName+'\"');\n end;\n\n //free the data structure we created\n NetApiBufferFree(Buffer);\nend;\n\nprocedure TTimeHandler.SetLocalSystemTime(settotime: TDateTime);\nvar\n SystemTime : TSystemTime;\nbegin\n DateTimeToSystemTime(settotime,SystemTime);\n SetLocalTime(SystemTime);\n //tell windows that the time changed\n PostMessage(HWND_BROADCAST,WM_TIMECHANGE,0,0);\nend;\n\nend.\n" }, { "answer_id": 624339, "author": "Macke", "author_id": 72312, "author_profile": "https://Stackoverflow.com/users/72312", "pm_score": 4, "selected": false, "text": "wait() os::sleep()" }, { "answer_id": 9252652, "author": "seeker", "author_id": 891292, "author_profile": "https://Stackoverflow.com/users/891292", "pm_score": 2, "selected": false, "text": "-XX:+ForceTimeHighResolution" } ]
2008/09/19
[ "https://Stackoverflow.com/questions/102064", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16881/" ]
102,072
<p>A friend of mine was explaining how they do ping-pong pairing with TDD at his workplace and he said that they take an "adversarial" approach. That is, when the test writing person hands the keyboard over to the implementer, the implementer tries to do the bare simplest (and sometimes wrong thing) to make the test pass.</p> <p>For example, if they're testing a GetName() method and the test checks for "Sally", the implementation of the GetName method would simply be:</p> <pre><code>public string GetName(){ return "Sally"; } </code></pre> <p>Which would, of course, pass the test (naively).</p> <p>He explains that this helps eliminate naive tests that check for specific canned values rather than testing the actual behavior or expected state of components. It also helps drive the creation of more tests and ultimately better design and fewer bugs.</p> <p>It sounded good, but in a short session with him, it seemed like it took a lot longer to get through a single round of tests than otherwise and I didn't feel that a lot of extra value was gained.</p> <p>Do you use this approach, and if so, have you seen it pay off?</p>
[ { "answer_id": 102348, "author": "James A Wilson", "author_id": 13892, "author_profile": "https://Stackoverflow.com/users/13892", "pm_score": -1, "selected": true, "text": "return \"Sally\";" }, { "answer_id": 55129930, "author": "jamie", "author_id": 337881, "author_profile": "https://Stackoverflow.com/users/337881", "pm_score": 0, "selected": false, "text": "foo = new Thing(\"Sally\")\nassertEquals(\"Sally\", foo.getName())\n testGetNameReturnsNameField testGetNameReturnsSally testGetNameReturnsSally" } ]
2008/09/19
[ "https://Stackoverflow.com/questions/102072", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10862/" ]
102,082
<p>How to add child rows in datagrid c#.net windows forms?</p>
[ { "answer_id": 102280, "author": "NotDan", "author_id": 3291, "author_profile": "https://Stackoverflow.com/users/3291", "pm_score": 0, "selected": false, "text": "DataTable myDataTable = new DataTable();\nDataGridView myGridView = new DataGridView();\nmyGridView.DataSource = myDataTable;\nDataRow row = myDataTable.Rows.Add(1, 2, 3, 4, 5); //This adds the new row\n" }, { "answer_id": 45311984, "author": "sufisoft", "author_id": 8340754, "author_profile": "https://Stackoverflow.com/users/8340754", "pm_score": 0, "selected": false, "text": "DataTable DT= new DataTable();\n DataRow row = new DataRow();\n DT.Rows.Add(\"ID\",\"Name\",\"Addr\",\"number\");\n DataGrideView.DataSource = DT;\n" } ]
2008/09/19
[ "https://Stackoverflow.com/questions/102082", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
102,083
<p>Preferably free tools if possible.</p> <p>Also, the option of searching for multiple regular expressions and each replacing with different strings would be a bonus.</p>
[ { "answer_id": 102141, "author": "Alex Fort", "author_id": 12624, "author_profile": "https://Stackoverflow.com/users/12624", "pm_score": 6, "selected": true, "text": "perl -pi -e 's/something/somethingelse/g' *.log\n" }, { "answer_id": 102155, "author": "Craig Trader", "author_id": 12895, "author_profile": "https://Stackoverflow.com/users/12895", "pm_score": 3, "selected": false, "text": "for file in @filelist ; do\n perl -p -i -e \"s/pattern/result/g\" $file\ndone\n for file in @filelist ; do\n cat $file | sed \"s/pattern/result/\" > /tmp/newfile\n mv /tmp/newfile $file\ndone\n" }, { "answer_id": 102247, "author": "Zsolt Botykai", "author_id": 11621, "author_profile": "https://Stackoverflow.com/users/11621", "pm_score": 1, "selected": false, "text": "vim -c \"argdo! s:foo:bar:gci\" <list_of_files>\n vim <list_of_files>\n :bufdo! s:foo:bar:gci\n sed perl" }, { "answer_id": 102730, "author": "Frosty", "author_id": 7476, "author_profile": "https://Stackoverflow.com/users/7476", "pm_score": 5, "selected": false, "text": "sed sed -e \"s/pattern/result/\" <file list>\n find find <other find args> -exec sed -e \"s/pattern/result/\" \"{}\" \";\"\n" }, { "answer_id": 989066, "author": "jhw", "author_id": 2070346, "author_profile": "https://Stackoverflow.com/users/2070346", "pm_score": 1, "selected": false, "text": " sudo apt-get install regexxer\n" }, { "answer_id": 52634458, "author": "user742070", "author_id": 742070, "author_profile": "https://Stackoverflow.com/users/742070", "pm_score": 0, "selected": false, "text": "etags $ etags file1.txt file2.md dir1/*.yml dir2/*.json dir3/*.md\n tags-query-replace \\b\\(foo\\)\\b\n\\1bar\n" } ]
2008/09/19
[ "https://Stackoverflow.com/questions/102083", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13967/" ]
102,084
<p>I have learned quite a bit browsing through <a href="https://stackoverflow.com/questions/9033/hidden-features-of-c">Hidden Features of C#</a> and was surprised when I couldn't find something similar for VB.NET.</p> <p>So what are some of its hidden or lesser known features?</p>
[ { "answer_id": 102112, "author": "Jasha87", "author_id": 18874, "author_profile": "https://Stackoverflow.com/users/18874", "pm_score": 5, "selected": false, "text": "With ReallyLongClassName\n .Property1 = Value1\n .Property2 = Value2\n ...\nEnd With\n" }, { "answer_id": 102113, "author": "Sam Erwin", "author_id": 18224, "author_profile": "https://Stackoverflow.com/users/18224", "pm_score": 2, "selected": false, "text": "If ?: ?? Dim result = If(condition, valueWhenTrue, valueWhenFalse)\nDim value = If(obj, valueWhenObjNull)\n" }, { "answer_id": 102146, "author": "Konrad Rudolph", "author_id": 1968, "author_profile": "https://Stackoverflow.com/users/1968", "pm_score": 5, "selected": false, "text": "If If Dim x = If(a = b, c, d)\n\nDim hello As String = Nothing\nDim y = If(hello, \"World\")\n If() IIf() Dim x = If(b<>0,a/b,0)\n" }, { "answer_id": 102160, "author": "torial", "author_id": 13990, "author_profile": "https://Stackoverflow.com/users/13990", "pm_score": 7, "selected": false, "text": "Exception When Public Sub Login(host as string, user as String, password as string, _\n Optional bRetry as Boolean = False)\nTry\n ssh.Connect(host, user, password)\nCatch ex as TimeoutException When Not bRetry\n ''//Try again, but only once.\n Login(host, user, password, True)\nCatch ex as TimeoutException\n ''//Log exception\nEnd Try\nEnd Sub\n" }, { "answer_id": 102178, "author": "Nescio", "author_id": 14484, "author_profile": "https://Stackoverflow.com/users/14484", "pm_score": 5, "selected": false, "text": "Dim x as New MyClass With {.Prop1 = foo, .Prop2 = bar}\n" }, { "answer_id": 102212, "author": "torial", "author_id": 13990, "author_profile": "https://Stackoverflow.com/users/13990", "pm_score": 4, "selected": false, "text": "Import winf = System.Windows.Forms\n\n''Later\nDim x as winf.Form\n" }, { "answer_id": 102217, "author": "Konrad Rudolph", "author_id": 1968, "author_profile": "https://Stackoverflow.com/users/1968", "pm_score": 6, "selected": false, "text": "Enum completionlist Enum '\n''' <completionlist cref=\"RuleTemplates\"/>\nPublic Class Rule\n Private ReadOnly m_Expression As String\n Private ReadOnly m_Options As RegexOptions\n\n Public Sub New(ByVal expression As String)\n Me.New(expression, RegexOptions.None)\n End Sub\n\n Public Sub New(ByVal expression As String, ByVal options As RegexOptions)\n m_Expression = expression\n m_options = options\n End Sub\n\n Public ReadOnly Property Expression() As String\n Get\n Return m_Expression\n End Get\n End Property\n\n Public ReadOnly Property Options() As RegexOptions\n Get\n Return m_Options\n End Get\n End Property\nEnd Class\n\nPublic NotInheritable Class RuleTemplates\n Public Shared ReadOnly Whitespace As New Rule(\"\\s+\")\n Public Shared ReadOnly Identifier As New Rule(\"\\w+\")\n Public Shared ReadOnly [String] As New Rule(\"\"\"([^\"\"]|\"\"\"\")*\"\"\")\nEnd Class\n Rule RuleTemplates Enum" }, { "answer_id": 102229, "author": "torial", "author_id": 13990, "author_profile": "https://Stackoverflow.com/users/13990", "pm_score": 4, "selected": false, "text": "Using lockThis as New MyLocker(objToLock)\n\nEnd Using\n" }, { "answer_id": 102244, "author": "chrissie1", "author_id": 2936, "author_profile": "https://Stackoverflow.com/users/2936", "pm_score": 2, "selected": false, "text": "Imports Lan = Langauge\n" }, { "answer_id": 102251, "author": "Nescio", "author_id": 14484, "author_profile": "https://Stackoverflow.com/users/14484", "pm_score": 2, "selected": false, "text": "Private obj As MyProject.MyNamespace.MyClass\n" }, { "answer_id": 102267, "author": "torial", "author_id": 13990, "author_profile": "https://Stackoverflow.com/users/13990", "pm_score": 4, "selected": false, "text": "Public Sub GetISCSIAdmInfo(ByRef xDoc As System.Xml.XmlDocument) Implements IUnix.GetISCSIInfo\n\nEnd Sub\n" }, { "answer_id": 102321, "author": "Nescio", "author_id": 14484, "author_profile": "https://Stackoverflow.com/users/14484", "pm_score": 6, "selected": false, "text": "Dim contact2 = _\n <contact>\n <name>Patrick Hines</name>\n <%= From p In phoneNumbers2 _\n Select <phone type=<%= p.Type %>><%= p.Number %></phone> _\n %>\n </contact>\n" }, { "answer_id": 102369, "author": "Konrad Rudolph", "author_id": 1968, "author_profile": "https://Stackoverflow.com/users/1968", "pm_score": 6, "selected": false, "text": "typedef Import Imports S = System.String\n\nDim x As S = \"Hello\"\n Imports StringPair = System.Collections.Generic.KeyValuePair(Of String, String)\n" }, { "answer_id": 102435, "author": "torial", "author_id": 13990, "author_profile": "https://Stackoverflow.com/users/13990", "pm_score": 4, "selected": false, "text": "Class CodeException\nPublic [Error] as String\n''...\nEnd Class\n\n''later\nDim e as new CodeException\ne.Error = \"Invalid Syntax\"\n Class Timer\nPublic Sub Start()\n''...\nEnd Sub\n\nPublic Sub [Stop]()\n''...\nEnd Sub\n" }, { "answer_id": 102471, "author": "torial", "author_id": 13990, "author_profile": "https://Stackoverflow.com/users/13990", "pm_score": 3, "selected": false, "text": "StrConv(stringToTitleCase, VbStrConv.ProperCase,0) ''0 is localeID\n" }, { "answer_id": 103285, "author": "Konrad Rudolph", "author_id": 1968, "author_profile": "https://Stackoverflow.com/users/1968", "pm_score": 5, "selected": false, "text": "DirectCast DirectCast CType CType DirectCast Integer Double DirectCast CType DirectCast DirectCast CType CType CType" }, { "answer_id": 103589, "author": "Technobabble", "author_id": 19063, "author_profile": "https://Stackoverflow.com/users/19063", "pm_score": 4, "selected": false, "text": "Public Event SomethingHappened As EventHandler\n if(SomethingHappened != null)\n{\n ...\n}\n If Not SomethingHappenedEvent Is Nothing OrElse SomethingHappenedEvent.GetInvocationList.Length = 0 Then\n...\nEnd If\n" }, { "answer_id": 103836, "author": "Konrad Rudolph", "author_id": 1968, "author_profile": "https://Stackoverflow.com/users/1968", "pm_score": 5, "selected": false, "text": "Public Class ApplePie\n Private ReadOnly m_BakedEvent As New List(Of EventHandler)()\n\n Custom Event Baked As EventHandler\n AddHandler(ByVal value As EventHandler)\n Console.WriteLine(\"Adding a new subscriber: {0}\", value.Method)\n m_BakedEvent.Add(value)\n End AddHandler\n\n RemoveHandler(ByVal value As EventHandler)\n Console.WriteLine(\"Removing subscriber: {0}\", value.Method)\n m_BakedEvent.Remove(value)\n End RemoveHandler\n\n RaiseEvent(ByVal sender As Object, ByVal e As EventArgs)\n Console.WriteLine(\"{0} is raising an event.\", sender)\n For Each ev In m_BakedEvent\n ev.Invoke(sender, e)\n Next\n End RaiseEvent\n End Event\n\n Public Sub Bake()\n ''// 1. Add ingredients\n ''// 2. Stir\n ''// 3. Put into oven (heated, not pre-heated!)\n ''// 4. Bake\n RaiseEvent Baked(Me, EventArgs.Empty)\n ''// 5. Digest\n End Sub\nEnd Class\n Module Module1\n Public Sub Foo(ByVal sender As Object, ByVal e As EventArgs)\n Console.WriteLine(\"Hmm, freshly baked apple pie.\")\n End Sub\n\n Sub Main()\n Dim pie As New ApplePie()\n AddHandler pie.Baked, AddressOf Foo\n pie.Bake()\n RemoveHandler pie.Baked, AddressOf Foo\n End Sub\nEnd Module\n" }, { "answer_id": 167834, "author": "Joel Coehoorn", "author_id": 3043, "author_profile": "https://Stackoverflow.com/users/3043", "pm_score": 5, "selected": false, "text": "Function CleanString(byval input As String) As String\n Static pattern As New RegEx(\"...\")\n\n return pattern.Replace(input, \"\")\nEnd Function\n Function GetNextRandom() As Integer\n Static r As New Random(getSeed())\n\n Return r.Next()\nEnd Function \n" }, { "answer_id": 324153, "author": "dr. evil", "author_id": 40322, "author_profile": "https://Stackoverflow.com/users/40322", "pm_score": 4, "selected": false, "text": "Function CloseTheSystem(Optional ByVal msg AS String = \"Shutting down the system...\")\n Console.Writeline(msg)\n ''//do stuff\nEnd Function\n" }, { "answer_id": 337653, "author": "Rich", "author_id": 39691, "author_profile": "https://Stackoverflow.com/users/39691", "pm_score": 4, "selected": false, "text": "Sub MyFunc(Optional msg as String= \"\", Optional displayOrder As integer = 0)\n\n 'Do stuff\n\nEnd function\n Module Module1\n\n Sub Main()\n\n MyFunc() 'No params specified\n\n End Sub\n\nEnd Module\n MyFunc(displayOrder:=10, msg:=\"mystring\")\n" }, { "answer_id": 381331, "author": "torial", "author_id": 13990, "author_profile": "https://Stackoverflow.com/users/13990", "pm_score": 3, "selected": false, "text": "Private Shared m_Dictionary As IDictionary(Of String, Object) = _\n New Dictionary(Of String, Object)\n\nPublic Shared Property DictionaryElement(ByVal Key As String) As Object\n Get\n If m_Dictionary.ContainsKey(Key) Then\n Return m_Dictionary(Key)\n Else\n Return [String].Empty\n End If\n End Get\n Set(ByVal value As Object)\n If m_Dictionary.ContainsKey(Key) Then\n m_Dictionary(Key) = value\n Else\n m_Dictionary.Add(Key, value)\n End If\n\n End Set\nEnd Property\n" }, { "answer_id": 394200, "author": "torial", "author_id": 13990, "author_profile": "https://Stackoverflow.com/users/13990", "pm_score": 5, "selected": false, "text": "Select Case Role\n Case \"Admin\"\n ''//Do X\n Case \"Tester\"\n ''//Do Y\n Case \"Developer\"\n ''//Do Z\n Case Else\n ''//Exception case\nEnd Select\n Select Case Amount\n Case Is < 0\n ''//What!!\n Case 0 To 15\n Shipping = 2.0\n Case 16 To 59\n Shipping = 5.87\n Case Is > 59\n Shipping = 12.50\n Case Else\n Shipping = 9.99\n End Select\n Select Case True\n Case a = b\n ''//Do X\n Case a = c\n ''//Do Y\n Case b = c\n ''//Do Z\n Case Else\n ''//Exception case\n End Select\n" }, { "answer_id": 500642, "author": "Parsa", "author_id": 60996, "author_profile": "https://Stackoverflow.com/users/60996", "pm_score": 2, "selected": false, "text": "Interface I1\n Sub Foo()\n Sub TheFoo()\nEnd Interface\n\nInterface I2\n Sub Foo()\n Sub TheFoo()\nEnd Interface\n\nClass C\n Implements I1, I2\n\n Public Sub IAmFoo1() Implements I1.Foo\n ' Something happens here'\n End Sub\n\n Public Sub IAmFoo2() Implements I2.Foo\n ' Another thing happens here'\n End Sub\n\n Public Sub TheF() Implements I1.TheFoo, I2.TheFoo\n ' You shouldn't yell!'\n End Sub\nEnd Class\n" }, { "answer_id": 500655, "author": "Parsa", "author_id": 60996, "author_profile": "https://Stackoverflow.com/users/60996", "pm_score": 4, "selected": false, "text": "Dim x As New Something : x.CallAMethod\n" }, { "answer_id": 500667, "author": "Parsa", "author_id": 60996, "author_profile": "https://Stackoverflow.com/users/60996", "pm_score": 3, "selected": false, "text": "If True Then DoSomething()\n" }, { "answer_id": 500669, "author": "Parsa", "author_id": 60996, "author_profile": "https://Stackoverflow.com/users/60996", "pm_score": 2, "selected": false, "text": " \n\nOn Error Resume Next\n' Or'\nOn Error GoTo someline\n\n\n On Error Resume Next\n' Or'\nOn Error GoTo someline\n " }, { "answer_id": 500677, "author": "Parsa", "author_id": 60996, "author_profile": "https://Stackoverflow.com/users/60996", "pm_score": 6, "selected": false, "text": "\n Dim b As Boolean = \"file.txt\" Like \"*.txt\"\n Dim testCheck As Boolean\n\n' The following statement returns True (does \"F\" satisfy \"F\"?)'\ntestCheck = \"F\" Like \"F\"\n\n' The following statement returns False for Option Compare Binary'\n' and True for Option Compare Text (does \"F\" satisfy \"f\"?)'\ntestCheck = \"F\" Like \"f\"\n\n' The following statement returns False (does \"F\" satisfy \"FFF\"?)'\ntestCheck = \"F\" Like \"FFF\"\n\n' The following statement returns True (does \"aBBBa\" have an \"a\" at the'\n' beginning, an \"a\" at the end, and any number of characters in '\n' between?)'\ntestCheck = \"aBBBa\" Like \"a*a\"\n\n' The following statement returns True (does \"F\" occur in the set of'\n' characters from \"A\" through \"Z\"?)'\ntestCheck = \"F\" Like \"[A-Z]\"\n\n' The following statement returns False (does \"F\" NOT occur in the '\n' set of characters from \"A\" through \"Z\"?)'\ntestCheck = \"F\" Like \"[!A-Z]\"\n\n' The following statement returns True (does \"a2a\" begin and end with'\n' an \"a\" and have any single-digit number in between?)'\ntestCheck = \"a2a\" Like \"a#a\"\n\n' The following statement returns True (does \"aM5b\" begin with an \"a\",'\n' followed by any character from the set \"L\" through \"P\", followed'\n' by any single-digit number, and end with any character NOT in'\n' the character set \"c\" through \"e\"?)'\ntestCheck = \"aM5b\" Like \"a[L-P]#[!c-e]\"\n\n' The following statement returns True (does \"BAT123khg\" begin with a'\n' \"B\", followed by any single character, followed by a \"T\", and end'\n' with zero or more characters of any type?)'\ntestCheck = \"BAT123khg\" Like \"B?T*\"\n\n' The following statement returns False (does \"CAT123khg\" begin with'\n' a \"B\", followed by any single character, followed by a \"T\", and'\n' end with zero or more characters of any type?)'\ntestCheck = \"CAT123khg\" Like \"B?T*\"\n" }, { "answer_id": 500690, "author": "Parsa", "author_id": 60996, "author_profile": "https://Stackoverflow.com/users/60996", "pm_score": 3, "selected": false, "text": "Dim var" }, { "answer_id": 646188, "author": "torial", "author_id": 13990, "author_profile": "https://Stackoverflow.com/users/13990", "pm_score": 4, "selected": false, "text": "Dim Table As Hashtable = New Hashtable\nTable(\"Orange\") = \"A fruit\"\nTable(\"Broccoli\") = \"A vegetable\"\nTable(\"Pork\") = \"A meat\" \nConsole.WriteLine(Table(\"Pork\"))\n Dim Table As Hashtable = New Hashtable\nTable!Orange = \"A fruit\"\nTable!Broccoli = \"A vegetable\"\nTable!Pork = \"A meat\"\nConsole.WriteLine(Table!Pork)\n" }, { "answer_id": 884441, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "Function GetToString(obj as SimpleGeomertyClass) as String\n Select Case True\n Case TypeOf obj is PointClass\n Return String.Format(\"Point: Position = {0}\", _\n DirectCast(obj,Point).ToString)\n Case TypeOf obj is LineClass\n Dim Line = DirectCast(obj,LineClass)\n Return String.Format(\"Line: StartPosition = {0}, EndPosition = {1}\", _\n Line.StartPoint.ToString,Line.EndPoint.ToString)\n Case TypeOf obj is CircleClass\n Dim Line = DirectCast(obj,CircleClass)\n Return String.Format(\"Circle: CenterPosition = {0}, Radius = {1}\", _\n Circle.CenterPoint.ToString,Circle.Radius)\n Case Else\n Return String.Format(\"Unhandled Type {0}\",TypeName(obj))\n End Select\nEnd Function\n" }, { "answer_id": 940097, "author": "Joel Coehoorn", "author_id": 3043, "author_profile": "https://Stackoverflow.com/users/3043", "pm_score": 3, "selected": false, "text": "Dim sql As String = \"StoredProcedureName\"\nUsing cn As SqlConnection = getOpenConnection(), _\n cmd As New SqlCommand(sql, cn), _\n rdr As SqlDataReader = cmd.ExecuteReader()\n\n While rdr.Read()\n\n ''// Do Something\n\n End While\n\nEnd Using\n" }, { "answer_id": 940420, "author": "cjk", "author_id": 52201, "author_profile": "https://Stackoverflow.com/users/52201", "pm_score": 5, "selected": false, "text": "Microsoft.VisualBasic.FileIO.TextFieldParser\n" }, { "answer_id": 1058767, "author": "danlash", "author_id": 13072, "author_profile": "https://Stackoverflow.com/users/13072", "pm_score": 4, "selected": false, "text": "Dim independanceDay As DateTime = #7/4/1776#\n Dim independanceDay = #7/4/1776#\n Dim independanceDay as DateTime = New DateTime(1776, 7, 4)\n" }, { "answer_id": 1120271, "author": "Shimmy Weitzhandler", "author_id": 75500, "author_profile": "https://Stackoverflow.com/users/75500", "pm_score": 5, "selected": false, "text": "/ Double \\ Integer Sub Main()\n Dim x = 9 / 5 \n Dim y = 9 \\ 5 \n Console.WriteLine(\"item x of '{0}' equals to {1}\", x.GetType.FullName, x)\n Console.WriteLine(\"item y of '{0}' equals to {1}\", y.GetType.FullName, y)\n\n 'Results:\n 'item x of 'System.Double' equals to 1.8\n 'item y of 'System.Int32' equals to 1\nEnd Sub\n" }, { "answer_id": 1120393, "author": "Shimmy Weitzhandler", "author_id": 75500, "author_profile": "https://Stackoverflow.com/users/75500", "pm_score": 3, "selected": false, "text": "Imports <xmlns:xs=\"System\">\n\nModule Module1\n\n Sub Main()\n Dim xml =\n <root>\n <customer id=\"345\">\n <name>John</name>\n <age>17</age>\n </customer>\n <customer id=\"365\">\n <name>Doe</name>\n <age>99</age>\n </customer>\n </root>\n\n Dim id = 1\n Dim name = \"Beth\"\n DoIt(\n <param>\n <customer>\n <id><%= id %></id>\n <name><%= name %></name>\n </customer>\n </param>\n )\n\n Dim names = xml...<name>\n For Each n In names\n Console.WriteLine(n.Value)\n Next\n\n For Each customer In xml.<customer>\n Console.WriteLine(\"{0}: {1}\", customer.@id, customer.<age>.Value)\n Next\n\n Console.Read()\n End Sub\n\n Private Sub CreateClass()\n Dim CustomerSchema =\n XDocument.Load(CurDir() & \"\\customer.xsd\")\n\n Dim fields =\n From field In CustomerSchema...<xs:element>\n Where field.@type IsNot Nothing\n Select\n Name = field.@name,\n Type = field.@type\n\n Dim customer = \n <customer> Public Class Customer \n<%= From field In fields Select <f> \nPrivate m_<%= field.Name %> As <%= GetVBPropType(field.Type) %></f>.Value %>\n\n <%= From field In fields Select <p> \nPublic Property <%= field.Name %> As <%= GetVBPropType(field.Type) %>\n Get \nReturn m_<%= field.Name %> \nEnd Get\n Set(ByVal value As <%= GetVBPropType(field.Type) %>)\n m_<%= field.Name %> = value \nEnd Set\n End Property</p>.Value %> \nEnd Class</customer>\n\n My.Computer.FileSystem.WriteAllText(\"Customer.vb\",\n customer.Value,\n False,\n System.Text.Encoding.ASCII)\n\n End Sub\n\n Private Function GetVBPropType(ByVal xmlType As String) As String\n Select Case xmlType\n Case \"xs:string\"\n Return \"String\"\n Case \"xs:int\"\n Return \"Integer\"\n Case \"xs:decimal\"\n Return \"Decimal\"\n Case \"xs:boolean\"\n Return \"Boolean\"\n Case \"xs:dateTime\", \"xs:date\"\n Return \"Date\"\n Case Else\n Return \"'TODO: Define Type\"\n End Select\n End Function\n\n Private Sub DoIt(ByVal param As XElement)\n Dim customers =\n From customer In param...<customer>\n Select New Customer With\n {\n .ID = customer.<id>.Value,\n .FirstName = customer.<name>.Value\n }\n\n For Each c In customers\n Console.WriteLine(c.ToString())\n Next\n End Sub\n\n Private Class Customer\n Public ID As Integer\n Public FirstName As String\n Public Overrides Function ToString() As String\n Return <string>\nID : <%= Me.ID %>\nName : <%= Me.FirstName %>\n </string>.Value\n End Function\n\n End Class\nEnd Module\n'Results:\n\nID : 1\nName : Beth\nJohn\nDoe\n345: 17\n365: 99\n" }, { "answer_id": 1120501, "author": "Shimmy Weitzhandler", "author_id": 75500, "author_profile": "https://Stackoverflow.com/users/75500", "pm_score": 0, "selected": false, "text": "Sub Main()\n Select Case \"value to check\"\n 'Check for multiple items at once:'\n Case \"a\", \"b\", \"asdf\" \n Console.WriteLine(\"Nope...\")\n Case \"value to check\"\n Console.WriteLine(\"Oh yeah! thass what im talkin about!\")\n Case Else\n Console.WriteLine(\"Nah :'(\")\n End Select\n\n\n Dim jonny = False\n Dim charlie = True\n Dim values = New String() {\"asdff\", \"asdfasdf\"}\n Select Case \"asdfasdf\"\n 'You can perform boolean checks that has nothing to do with your var.,\n 'not that I would recommend that, but it exists.'\n Case values.Contains(\"ddddddddddddddddddddddd\")\n Case True\n Case \"No sense\"\n Case Else\n End Select\n\n Dim x = 56\n Select Case x\n Case Is > 56\n Case Is <= 5\n Case Is <> 45\n Case Else\n End Select\n\nEnd Sub\n" }, { "answer_id": 1120520, "author": "Shimmy Weitzhandler", "author_id": 75500, "author_profile": "https://Stackoverflow.com/users/75500", "pm_score": 2, "selected": false, "text": "Sub Main()\n 'Auto assigned to def value'\n Dim i As Integer '0'\n Dim dt As DateTime '#12:00:00 AM#'\n Dim a As Date '#12:00:00 AM#'\n Dim b As Boolean 'False'\n\n Dim s = i.ToString 'valid\nEnd Sub\n int x;\nvar y = x.ToString(); //Use of unassigned value\n" }, { "answer_id": 1120579, "author": "Shimmy Weitzhandler", "author_id": 75500, "author_profile": "https://Stackoverflow.com/users/75500", "pm_score": 3, "selected": false, "text": "IIf(False, MsgBox(\"msg1\"), MsgBox(\"msg2\"))\n If(False, MsgBox(\"msg1\"), MsgBox(\"msg2\"))\n Dim value = IIf(somthing, LoadAndGetValue1(), LoadAndGetValue2())\n" }, { "answer_id": 1120610, "author": "Shimmy Weitzhandler", "author_id": 75500, "author_profile": "https://Stackoverflow.com/users/75500", "pm_score": 3, "selected": false, "text": "Public Class Item\n Private Value As Integer\n Public Sub New(ByVal value As Integer)\n Me.Value = value\n End Sub\n\n Public ReadOnly Property [String]() As String\n Get\n Return Value\n End Get\n End Property\n\n Public ReadOnly Property [Integer]() As Integer\n Get\n Return Value\n End Get\n End Property\n\n Public ReadOnly Property [Boolean]() As Boolean\n Get\n Return Value\n End Get\n End Property\nEnd Class\n\n'Real examples:\nPublic Class PropertyException : Inherits Exception\n Public Sub New(ByVal [property] As String)\n Me.Property = [property]\n End Sub\n\n Private m_Property As String\n Public Property [Property]() As String\n Get\n Return m_Property\n End Get\n Set(ByVal value As String)\n m_Property = value\n End Set\n End Property\nEnd Class\n\nPublic Enum LoginLevel\n [Public] = 0\n Account = 1\n Admin = 2\n [Default] = Account\nEnd Enum\n" }, { "answer_id": 1124247, "author": "Shimmy Weitzhandler", "author_id": 75500, "author_profile": "https://Stackoverflow.com/users/75500", "pm_score": 2, "selected": false, "text": "Private Sub Button1_Click(ByVal sender As Button, ByVal e As System.EventArgs)\n Handles Button1.Click\n sender.Enabled = True\n DisableButton(sender)\nEnd Sub\n\nPrivate Sub Disable(button As Object)\n button.Enabled = false\nEnd Sub\n Private Sub control_Click(ByVal sender As Control, ByVal e As System.EventArgs)\n Handles TextBox1.Click, CheckBox1.Click, Button1.Click\n sender.Text = \"Got it?...\"\nEnd Sub\n" }, { "answer_id": 1124512, "author": "Shimmy Weitzhandler", "author_id": 75500, "author_profile": "https://Stackoverflow.com/users/75500", "pm_score": 1, "selected": false, "text": "Module Module1\n\n Sub Main()\n Dim str1 = \"initial\"\n Dim str2 = \"initial\"\n DoByVal(str1)\n DoByRef(str2)\n\n Console.WriteLine(str1)\n Console.WriteLine(str2)\n End Sub\n\n Sub DoByVal(ByVal str As String)\n str = \"value 1\"\n End Sub\n\n Sub DoByRef(ByRef str As String)\n str = \"value 2\"\n End Sub\nEnd Module\n\n'Results:\n'initial\n'value 2\n" }, { "answer_id": 1207521, "author": "Youssef", "author_id": 10968, "author_profile": "https://Stackoverflow.com/users/10968", "pm_score": 3, "selected": false, "text": "Public Function DoSomething(byval x as integer, optional y as boolean=True, optional z as boolean=False)\n' ......\nEnd Function\n DoSomething(x:=1, y:=false)\nDoSomething(x:=2, z:=true)\nor\nDoSomething(x:=3,y:=false,z:=true)\n DoSomething(1,true)\n" }, { "answer_id": 1296608, "author": "Craig Gidney", "author_id": 52239, "author_profile": "https://Stackoverflow.com/users/52239", "pm_score": 2, "selected": false, "text": "'''<summary>Returns true for reference types, false for struct types.</summary>'\nPublic Function IsReferenceType(Of T)() As Boolean\n Return DirectCast(Nothing, T) Is Nothing\nEnd Function\n" }, { "answer_id": 1446195, "author": "Eduardo Molteni", "author_id": 2385, "author_profile": "https://Stackoverflow.com/users/2385", "pm_score": 3, "selected": false, "text": "when Catch ex As IO.FileLoadException When attempt < 3 Do\n Dim attempt As Integer\n Try\n ''// something that might cause an error.\n Catch ex As IO.FileLoadException When attempt < 3\n If MsgBox(\"do again?\", MsgBoxStyle.YesNo) = MsgBoxResult.No Then\n Exit Do\n End If\n Catch ex As Exception\n ''// if any other error type occurs or the attempts are too many\n MsgBox(ex.Message)\n Exit Do\n End Try\n ''// increment the attempt counter.\n attempt += 1\nLoop\n" }, { "answer_id": 1612781, "author": "Marcus Andrén", "author_id": 135502, "author_profile": "https://Stackoverflow.com/users/135502", "pm_score": 3, "selected": false, "text": "Dim b(0 to 9) as byte 'Declares an array of 10 bytes\n Dim b(9) as byte 'Declares another array of 10 bytes\n Dim b(10) as byte 'Declares another array of 10 bytes\n Dim b As Byte() = New Byte(0 To 9) {} 'Another way to create a 10 byte array\nReDim b(0 to 9) 'Assigns a new 10 byte array to b\n" }, { "answer_id": 1925143, "author": "Ryan Lundy", "author_id": 5486, "author_profile": "https://Stackoverflow.com/users/5486", "pm_score": 4, "selected": false, "text": "Dim myString = _\n \"This string contains \"\"quotes\"\" and they're ugly.\"\n Dim myString = _\n <string>This string contains \"quotes\" and they're nice.</string>.Value\n Dim csvTestYuck = _\n \"\"\"Smith\"\", \"\"Bob\"\", \"\"123 Anywhere St\"\", \"\"Los Angeles\"\", \"\"CA\"\"\"\n\nDim csvTestMuchBetter = _\n <string>\"Smith\", \"Bob\", \"123 Anywhere St\", \"Los Angeles\", \"CA\"</string>.Value\n <string>" }, { "answer_id": 2837501, "author": "Chris Haas", "author_id": 231316, "author_profile": "https://Stackoverflow.com/users/231316", "pm_score": 4, "selected": false, "text": "Private Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load\n Dim R = 4\n Trace.WriteLine(R)\n Test(R)\n Trace.WriteLine(R)\n Test((R))\n Trace.WriteLine(R)\nEnd Sub\nPrivate Sub Test(ByRef i As Integer)\n i += 1\nEnd Sub\n" }, { "answer_id": 3934688, "author": "David T. Macknet", "author_id": 6850, "author_profile": "https://Stackoverflow.com/users/6850", "pm_score": 0, "selected": false, "text": "<System.ComponentModel.Browsable(False), _\nSystem.ComponentModel.DesignerSerializationVisibility(System.ComponentModel.DesignerSerializationVisibility.Hidden), _\nSystem.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Always), _\nSystem.ComponentModel.Category(\"Data\")> _\nPublic Property AUX_ID() As String\n <System.Diagnostics.DebuggerStepThrough()> _\n Get\n Return mAUX_ID\n End Get\n <System.Diagnostics.DebuggerStepThrough()> _\n Set(ByVal value As String)\n mAUX_ID = value\n End Set\nEnd Property\n DebuggerStepThrough()" }, { "answer_id": 3935361, "author": "David T. Macknet", "author_id": 6850, "author_profile": "https://Stackoverflow.com/users/6850", "pm_score": 2, "selected": false, "text": "Nullable(Of Date) <System.Diagnostics.DebuggerStepThrough> _\nProtected Function GP(ByVal strName As String, ByVal dtValue As Date) As SqlParameter\n Dim aParm As SqlParameter = New SqlParameter\n Dim unDate As Date\n With aParm\n .ParameterName = strName\n .Direction = ParameterDirection.Input\n .SqlDbType = SqlDbType.SmallDateTime\n If unDate = dtValue Then 'Unassigned variable\n .Value = \"1/1/1900 12:00:00 AM\" 'give it a default which is accepted by smalldatetime\n Else\n .Value = CDate(dtValue.ToShortDateString)\n End If\n End With\n Return aParm\nEnd Function\n<System.Diagnostics.DebuggerStepThrough()> _\nProtected Function GP(ByVal strName As String, ByVal dtValue As Nullable(Of Date)) As SqlParameter\n Dim aParm As SqlParameter = New SqlParameter\n Dim unDate As Date\n With aParm\n .ParameterName = strName\n .Direction = ParameterDirection.Input\n .SqlDbType = SqlDbType.SmallDateTime\n If dtValue.HasValue = False Then\n '// it's nullable, so has no value\n ElseIf unDate = dtValue.Value Then 'Unassigned variable\n '// still, it's nullable for a reason, folks!\n Else\n .Value = CDate(dtValue.Value.ToShortDateString)\n End If\n End With\n Return aParm\nEnd Function\n" }, { "answer_id": 4105681, "author": "Parsa", "author_id": 60996, "author_profile": "https://Stackoverflow.com/users/60996", "pm_score": 3, "selected": false, "text": "break Exit Continue For i As Integer = 0 To 100\n While True\n Exit While\n Select Case i\n Case 1\n Exit Select\n Case 2\n Exit For\n Case 3\n Exit While\n Case Else\n Exit Sub\n End Select\n Continue For\n End While\nNext\n" }, { "answer_id": 5508514, "author": "PdotWang", "author_id": 672995, "author_profile": "https://Stackoverflow.com/users/672995", "pm_score": 1, "selected": false, "text": "''' <summary>\n''' \n''' </summary>\n''' <remarks></remarks>\nSub use_3Apostrophe()\nEnd Sub\n" }, { "answer_id": 5942089, "author": "Hedi Guizani", "author_id": 630625, "author_profile": "https://Stackoverflow.com/users/630625", "pm_score": 0, "selected": false, "text": "Function DoSmtg(Optional a As string, b As Integer, c As String)\n 'DoSmtg\nEnd \n\n' Call\nDoSmtg(,,\"c argument\")\n\nDoSmtg(,\"b argument\")\n" } ]
2008/09/19
[ "https://Stackoverflow.com/questions/102084", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12842/" ]
102,093
<p>I wrote a small <code>PHP</code> application several months ago that uses the <code>WordPress XMLRPC library</code> to synchronize two separate WordPress blogs. I have a general "RPCRequest" function that packages the request, sends it, and returns the server response, and I have several more specific functions that customize the type of request that is sent.</p> <p>In this particular case, I am calling "getPostIDs" to retrieve the number of posts on the remote server and their respective postids. Here is the code:</p> <pre><code>$rpc = new WordRPC('http://mywordpressurl.com/xmlrpc.php', 'username', 'password'); $rpc-&gt;getPostIDs(); </code></pre> <p>I'm receiving the following error message:</p> <pre><code>expat reports error code 5 description: Invalid document end line: 1 column: 1 byte index: 0 total bytes: 0 data beginning 0 before byte index: </code></pre> <p>Kind of a cliffhanger ending, which is also strange. But since the error message isn't formatted in XML, my intuition is that it's the local XMLRPC library that is generating the error, not the remote server.</p> <p>Even stranger, if I change the "getPostIDs()" call to "getPostIDs(1)" or any other integer, it works just fine.</p> <p>Here is the code for the WordRPC class:</p> <pre><code>public function __construct($url, $user, $pass) { $this-&gt;url = $url; $this-&gt;username = $user; $this-&gt;password = $pass; $id = $this-&gt;RPCRequest("blogger.getUserInfo", array("null", $this-&gt;username, $this-&gt;password)); $this-&gt;blogID = $id['userid']; } public function RPCRequest($method, $params) { $request = xmlrpc_encode_request($method, $params); $context = stream_context_create(array('http' =&gt; array( 'method' =&gt; "POST", 'header' =&gt; "Content-Type: text/xml", 'content' =&gt; $request ))); $file = file_get_contents($this-&gt;url, false, $context); return xmlrpc_decode($file); } public function getPostIDs($num_posts = 0) { return $this-&gt;RPCRequest("mt.getRecentPostTitles", array($this-&gt;blogID, $this-&gt;username, $this-&gt;password, $num_posts)); } </code></pre> <p>As I mentioned, it works fine if "getPostIDs" is given a positive integer argument. Furthermore, this used to work perfectly well as is; the default parameter of 0 simply indicates to the RPC server that it should retrieve <em>all</em> posts, not just the most recent <code>$num_posts</code> posts. Only recently has this error started showing up.</p> <p>I've tried googling the error without much luck. My question, then, is <strong>what exactly does "expat reports error code 5" mean, and who is generating the error?</strong> Any details/suggestions/insights beyond that are welcome, too!</p>
[ { "answer_id": 104047, "author": "Novaktually", "author_id": 13243, "author_profile": "https://Stackoverflow.com/users/13243", "pm_score": 0, "selected": false, "text": "XML_ERROR_UNCLOSED_TOKEN file_get_contents xmlrpc_decode" } ]
2008/09/19
[ "https://Stackoverflow.com/questions/102093", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13604/" ]
102,102
<p>It should also support SSH2 and public key auth for starters. secondly on Mac/Windows it should have a decent installer.</p>
[ { "answer_id": 104682, "author": "Will Robertson", "author_id": 4161, "author_profile": "https://Stackoverflow.com/users/4161", "pm_score": 0, "selected": false, "text": "git-gui" } ]
2008/09/19
[ "https://Stackoverflow.com/questions/102102", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18769/" ]
102,128
<p>Sorry, I'm new to SVN and I looked around a little for this. How do you mark a major version in SVN, kind of like set up a restore point. Right now I just setup my server and added all my files- I've been intermittently committing different changes. When I have something in a stable state is there a way to mark this so I can easily revert back to it if necessary?</p>
[ { "answer_id": 102149, "author": "Stephen Deken", "author_id": 7154, "author_profile": "https://Stackoverflow.com/users/7154", "pm_score": 4, "selected": false, "text": "svn cp http://svn.example.com/trunk/ http://svn.example.com/tags/major-revision-01/\n" }, { "answer_id": 102180, "author": "Xetius", "author_id": 274, "author_profile": "https://Stackoverflow.com/users/274", "pm_score": 2, "selected": false, "text": "repository\n+--trunk\n+--releases\n +--v1.0\n +--v1.1\n +--v1.4\n +--v2.0\n+--branches\n+--tags\n" } ]
2008/09/19
[ "https://Stackoverflow.com/questions/102128", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17614/" ]
102,171
<p>I'm looking for a method that computes the line number of a given text position in a JTextPane with wrapping enabled.</p> <p>Example:</p> <blockquote> <p>This a very very very very very very very very very very very very very very very very very very very very very very long line.<br> This is another very very very very very very very very very very very very very very very very very very very very very very long line.<strong>|</strong></p> </blockquote> <p>The cursor is on line number four, not two.</p> <p>Can someone provide me with the implementation of the method:</p> <pre><code>int getLineNumber(JTextPane pane, int pos) { return ??? } </code></pre>
[ { "answer_id": 102737, "author": "Richard", "author_id": 16475, "author_profile": "https://Stackoverflow.com/users/16475", "pm_score": 4, "selected": true, "text": " /**\n * Return an int containing the wrapped line index at the given position\n * @param component JTextPane\n * @param int pos\n * @return int\n */\n public int getLineNumber(JTextPane component, int pos) \n {\n int posLine;\n int y = 0;\n\n try\n {\n Rectangle caretCoords = component.modelToView(pos);\n y = (int) caretCoords.getY();\n }\n catch (BadLocationException ex)\n {\n }\n\n int lineHeight = component.getFontMetrics(component.getFont()).getHeight();\n posLine = (y / lineHeight) + 1;\n return posLine;\n }\n" }, { "answer_id": 41419359, "author": "Morgan", "author_id": 6389372, "author_profile": "https://Stackoverflow.com/users/6389372", "pm_score": 1, "selected": false, "text": "public int getLineNumberAt(JTextPane pane, int pos) {\n return pane.getDocument().getDefaultRootElement().getElementIndex(pos);\n}\n" } ]
2008/09/19
[ "https://Stackoverflow.com/questions/102171", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8330/" ]
102,185
<p>MXML lets you do some really quite powerful data binding such as:</p> <pre><code>&lt;mx:Button id="myBtn" label="Buy an {itemName}" visible="{itemName!=null}"/&gt; </code></pre> <p>I've found that the BindingUtils class can bind values to simple properties, but neither of the bindings above do this. Is it possible to do the same in AS3 code, or is Flex silently generating many lines of code from my MXML? Can anyone duplicate the above in pure AS3, starting from:</p> <pre><code>var myBtn:Button = new Button(); myBtn.id="myBtn"; ??? </code></pre>
[ { "answer_id": 102924, "author": "Theo", "author_id": 1109, "author_profile": "https://Stackoverflow.com/users/1109", "pm_score": 2, "selected": false, "text": "bindSetter // assuming the itemName property is defined on this:\nBindingUtils.bindSetter(itemNameChanged, this, [\"itemName\"]);\n\n// ...\n\nprivate function itemNameChanged( newValue : String ) : void {\n myBtn.label = newValue;\n myBtn.visible = newValue != null;\n}\n" } ]
2008/09/19
[ "https://Stackoverflow.com/questions/102185", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13220/" ]
102,198
<p>Is there a way to "align" columns in a data repeater control? </p> <p>I.E currently it looks like this:</p> <pre><code>user1 - colA colB colC colD colE user2 - colD colE </code></pre> <p>I want it to look like:</p> <pre><code> user1 -colA -colB -colC -colD -colE user1 -colD -colE </code></pre> <p>I need to columns for each record to align properly when additional records might not have data for a given column.</p> <p>The requirements call for a repeater and not a grid control.</p> <p>Any ideas?</p>
[ { "answer_id": 102233, "author": "Nick Craver", "author_id": 13249, "author_profile": "https://Stackoverflow.com/users/13249", "pm_score": 2, "selected": false, "text": "<td colspan='<%# MissingCount(Contatiner.DataItem) %>'>\n" }, { "answer_id": 102367, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": " <tr class=\"RadGridItem\">\n <td width=\"100\">\n <asp:Label ID=\"lblFullName\" runat=\"server\" \n Text ='<%# DataBinder.Eval(Container.DataItem, \"FullName\") %>'\n ToolTip='<%# \"Current Grade: \" + DataBinder.Eval(Container.DataItem,\"CurrentGrade\") + \"%\" +\n \" Percent Complete: \" + DataBinder.Eval(Container.DataItem,\"PercentComplete\") + \"%\" %>' />\n </td>\n <asp:Repeater ID=\"rptAssessments\" runat=\"server\" DataSource='<%# DataBinder.Eval(Container.DataItem, \"EnrollmentAssessments\") %>'>\n <ItemTemplate>\n <td style=\"padding :0px 0px 0px 0px; width:20px; height: 20px;\">\n <asp:LinkButton ID=\"lnkEdit\" runat=\"server\"\n OnClick=\"AssessmentClick\" \n style=' <%# \"color:\" + this.GetAssessmentColor(Container.DataItem) %>'\n ToolTip='<%# DataBinder.Eval(Container.DataItem, \"AssessmentName\") + Environment.NewLine + \n DataBinder.Eval(Container.DataItem, \"EnrollmentAssessmentStateName\") + \"(\" + \n DataBinder.Eval(Container.DataItem, \"PercentGradeDisplay\") + \"%) \" + \n GetPointsPossible(Container.DataItem) + \" pts possible\" %>'\n CommandArgument='<%# DataBinder.Eval(Container.DataItem, \"EnrollmentAssessmentID\") %>'\n Text='<%# this.GetAssessmentDisplay(Container.DataItem) %>' />\n </td>\n </ItemTemplate>\n </asp:Repeater>\n </tr>\n</ItemTemplate>\n" }, { "answer_id": 104346, "author": "Wayne", "author_id": 8236, "author_profile": "https://Stackoverflow.com/users/8236", "pm_score": 1, "selected": false, "text": "<td> .collink {\n width: 20px; \n float: left; \n height: 20px;\n}\n <td style=\"padding :0px 0px 0px 0px;\">\n <div class=\"collink\">\n <asp:LinkButton ID=\"lnkEdit\" runat=\"server\" ... />\n </div>\n</td>\n" } ]
2008/09/19
[ "https://Stackoverflow.com/questions/102198", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
102,213
<p>I am getting ready to start a new asp.net web project, and I am going to LINQ-to-SQL. I have done a little bit of work getting my data layer setup using some info I found by <a href="http://mikehadlow.blogspot.com/" rel="nofollow noreferrer" title="Mike Hadlow">Mike Hadlow</a> that uses an Interface and generics to create a Repository for each table in the database. I thought this was an interesting approach at first. However, now I think it might make more sense to create a base Repository class and inherit from it to create a TableNameRepository class for the tables I need to access. </p> <p>Which approach will be allow me to add functionality specific to a Table in a clean testable way? Here is my Repository implementation for reference.</p> <pre><code>public class Repository&lt;T&gt; : IRepository&lt;T&gt; where T : class, new() { protected IDataConnection _dcnf; public Repository() { _dcnf = new DataConnectionFactory() as IDataConnection; } // Constructor injection for dependency on DataContext // to actually connect to a database public Repository(IDataConnection dc) { _dcnf = dc; } /// &lt;summary&gt; /// Return all instances of type T. /// &lt;/summary&gt; /// &lt;returns&gt;IEnumerable&lt;T&gt;&lt;/returns&gt; public virtual IEnumerable&lt;T&gt; GetAll() { return GetTable; } public virtual T GetById(int id) { var itemParam = Expression.Parameter(typeof(T), "item"); var whereExp = Expression.Lambda&lt;Func&lt;T, bool&gt;&gt; ( Expression.Equal( Expression.Property(itemParam, PrimaryKeyName), Expression.Constant(id) ), new ParameterExpression[] { itemParam } ); return _dcnf.Context.GetTable&lt;T&gt;().Where(whereExp).Single(); } /// &lt;summary&gt; /// Return all instances of type T that match the expression exp. /// &lt;/summary&gt; /// &lt;param name="exp"&gt;&lt;/param&gt; /// &lt;returns&gt;IEnumerable&lt;T&gt;&lt;/returns&gt; public virtual IEnumerable&lt;T&gt; FindByExp(Func&lt;T, bool&gt; exp) { return GetTable.Where&lt;T&gt;(exp); } /// &lt;summary&gt;See IRepository.&lt;/summary&gt; /// &lt;param name="exp"&gt;&lt;/param&gt;&lt;returns&gt;&lt;/returns&gt; public virtual T Single(Func&lt;T, bool&gt; exp) { return GetTable.Single(exp); } /// &lt;summary&gt;See IRepository.&lt;/summary&gt; /// &lt;param name="entity"&gt;&lt;/param&gt; public virtual void MarkForDeletion(T entity) { _dcnf.Context.GetTable&lt;T&gt;().DeleteOnSubmit(entity); } /// &lt;summary&gt; /// Create a new instance of type T. /// &lt;/summary&gt; /// &lt;returns&gt;T&lt;/returns&gt; public virtual T Create() { //T entity = Activator.CreateInstance&lt;T&gt;(); T entity = new T(); GetTable.InsertOnSubmit(entity); return entity; } /// &lt;summary&gt;See IRepository.&lt;/summary&gt; public virtual void SaveAll() { _dcnf.SaveAll(); } #region Properties private string PrimaryKeyName { get { return TableMetadata.RowType.IdentityMembers[0].Name; } } private System.Data.Linq.Table&lt;T&gt; GetTable { get { return _dcnf.Context.GetTable&lt;T&gt;(); } } private System.Data.Linq.Mapping.MetaTable TableMetadata { get { return _dcnf.Context.Mapping.GetTable(typeof(T)); } } private System.Data.Linq.Mapping.MetaType ClassMetadata { get { return _dcnf.Context.Mapping.GetMetaType(typeof(T)); } } #endregion } </code></pre>
[ { "answer_id": 103668, "author": "Squirrel", "author_id": 11835, "author_profile": "https://Stackoverflow.com/users/11835", "pm_score": 2, "selected": true, "text": "public class Home {\n public static IRepository<T> For<T> {\n get {\n return Container.Resolve<IRepository<T>>();\n }\n }\n}\n" } ]
2008/09/19
[ "https://Stackoverflow.com/questions/102213", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1203/" ]
102,215
<p>What is the best way to add "Expires" in http header for static content? eg. images, css, js</p> <p>The web server is IIS 6.0; the language is classical ASP</p>
[ { "answer_id": 102302, "author": "Aaron", "author_id": 7659, "author_profile": "https://Stackoverflow.com/users/7659", "pm_score": -1, "selected": false, "text": "<META HTTP-EQUIV=\"Pragma\" CONTENT=\"no-cache\">\n<META HTTP-EQUIV=\"Cache-Control\" CONTENT=\"no-store\">\n<META HTTP-EQUIV=\"Cache-Control\" CONTENT=\"no-cache\">\n<META HTTP-EQUIV=\"Expires\" CONTENT=\"0\">\n<META HTTP-EQUIV=\"Cache-Control\" CONTENT=\"max-age=0\">\n" }, { "answer_id": 104073, "author": "Christopher G. Lewis", "author_id": 13532, "author_profile": "https://Stackoverflow.com/users/13532", "pm_score": 4, "selected": true, "text": "@ECHO OFF \nREM ---------------------------------------------------------------------------\nREM Caching - sets the caching on static files in a web site\nREM syntax \nREM Caching.CMD 1 d:\\sites\\MySite\\WWWRoot\\*.CSS\nREM \nREM %1 is the WebSite ID\nREM %2 is the path & Wildcard - for example, d:\\sites\\MySite\\WWWRoot\\*.CSS\nREM _adsutil is the path to ADSUtil.VBS\nREM ---------------------------------------------------------------------------\n\nSETLOCAL\n\nSET _adsutil=D:\\Apps\\Scripts\\adsutil.vbs\n\nFOR %%i IN (%2) DO (\n ECHO Setting Caching on %%~ni%%~xi\n CSCRIPT %_adsutil% CREATE W3SVC/%1/root/%%~ni%%~xi \"IIsWebFile\"\n CSCRIPT %_adsutil% SET W3SVC/%1/root/%%~ni%%~xi/HttpExpires \"D, 0x69780\"\n ECHO.\n)\n Caching.CMD 1 \\site\\wwwroot\\*.css\nCaching.CMD 1 \\site\\wwwroot\\*.js\nCaching.CMD 1 \\site\\wwwroot\\*.html\nCaching.CMD 1 \\site\\wwwroot\\*.htm\nCaching.CMD 1 \\site\\wwwroot\\*.gif\nCaching.CMD 1 \\site\\wwwroot\\*.jpg\n AdsUtil.vbs ENUM W3SVC/1/root/File.txt\n" }, { "answer_id": 33717904, "author": "Miss.Vy", "author_id": 5234614, "author_profile": "https://Stackoverflow.com/users/5234614", "pm_score": 1, "selected": false, "text": "<staticContent>\n <clientCache cacheControlMode=\"UseMaxAge\" cacheControlMaxAge=\"7.00:00:00\" />\n</staticContent>\n" } ]
2008/09/19
[ "https://Stackoverflow.com/questions/102215", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1100/" ]
102,240
<p>I'd like to add a drop-down list to a Windows application. It will have two choices, neither of which are editable. What's the best control to use? Is it a combo box with the editing property set to No?</p> <p>I'm using Visual Studio 2008.</p>
[ { "answer_id": 102266, "author": "JP Richardson", "author_id": 10333, "author_profile": "https://Stackoverflow.com/users/10333", "pm_score": 2, "selected": false, "text": "yourComboBox.DropDownStyle = ComboBoxStyle.DropDownList" }, { "answer_id": 23814141, "author": "Scroude", "author_id": 3666273, "author_profile": "https://Stackoverflow.com/users/3666273", "pm_score": 0, "selected": false, "text": "Private Sub TextBox1_Keyup(ByVal KeyCode As MSForms.ReturnInteger, ByVal Shift As Integer)\nDim curtext As String\nDim k, where As Integer\nDim tmp As String\nDim bigtmp As String\ncurtext = TextBox1.Text\ncurtext = UCase(curtext)\nTextBox1.Text = curtext\nRange(\"b3\").Value = curtext\nIf Len(curtext) = 0 Then\nTextBox2.Visible = False\nExit Sub\nEnd If\n\nTextBox2.Visible = True\nApplication.ScreenUpdating = False\nFor k = 2 To 13303 ' YOUR LIST ROWS\n tmp = Sheets(\"General Lookup\").Range(\"Z\" & k).Value ' YOUR LIST RANGE\n where = InStr(1, tmp, TextBox1.Text, 1)\n If where = 1 Then\n bigtmp = bigtmp & tmp & Chr(13)\n End If\nNext\n\nTextBox2.Text = bigtmp\nApplication.ScreenUpdating = True\nEnd Sub\n\nPrivate Sub TextBox2_MouseUp(ByVal Button As Integer, ByVal Shift As Integer, ByVal X As Single, ByVal Y As Single)\n If Len(TextBox2.SelText) > 0 Then\n TextBox1.Text = TextBox2.SelText\n Range(\"b3\").Value = TextBox2.SelText\n TextBox2.Visible = False\n End If\nEnd Sub\n" } ]
2008/09/19
[ "https://Stackoverflow.com/questions/102240", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18891/" ]
102,261
<p>First off, I'm working on an app that's written such that some of your typical debugging tools can't be used (or at least I can't figure out how :). </p> <p>JavaScript, html, etc are all "cooked" and encoded (I think; I'm a little fuzzy on how the process works) before being deployed, so I can't attach VS 2005 to ie, and firebug lite doesn't work well. Also, the interface is in frames (yuck), so some other tools don't work as well.</p> <p>Firebug works great in Firefox, which isn't having this problem (nor is Safari), so I'm hoping someone might spot something "obviously" wrong with the way my code will play with IE. There's more information that can be given about its quirkiness, but let's start with this.</p> <p>Basically, I have a function that "collapses" tables into their headers by making normal table rows not visible. I have <code>"onclick='toggleDisplay("theTableElement", "theCollapseImageElement")'"</code> in the <code>&lt;tr&gt;</code> tags, and tables start off with "class='closed'". </p> <p>Single clicks collapse and expand tables in FF &amp; Safari, but IE tables require multiple clicks (a seemingly arbitrary number between 1 and 5) to expand. Sometimes after initially getting "opened", the tables will expand and collapse with a single click for a little while, only to eventually revert to requiring multiple clicks. I can tell from what little I can see in Visual Studio that the function is actually being reached each time. Thanks in advance for any advice!</p> <p>Here's the JS code:</p> <pre><code>bURL_RM_RID="some image prefix"; CLOSED_TBL="closed"; OPEN_TBL="open"; CLOSED_IMG= bURL_RM_RID+'166'; OPENED_IMG= bURL_RM_RID+'167'; //collapses/expands tbl (a table) and swaps out the image tblimg function toggleDisplay(tbl, tblimg) { var rowVisible; var tblclass = tbl.getAttribute("class"); var tblRows = tbl.rows; var img = tblimg; //Are we expanding or collapsing the table? if (tblclass == CLOSED_TBL) rowVisible = false; else rowVisible = true; for (i = 0; i &lt; tblRows.length; i++) { if (tblRows[i].className != "headerRow") { tblRows[i].style.display = (rowVisible) ? "none" : ""; } } //set the collapse images to the correct state and swap the class name rowVisible = !rowVisible; if (rowVisible) { img.setAttribute("src", CLOSED_IMG); tbl.setAttribute("class",OPEN_TBL); } else { img.setAttribute("src", OPENED_IMG); tbl.setAttribute("class",CLOSED_TBL); } } </code></pre> <p>­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­</p>
[ { "answer_id": 102295, "author": "Chris Marasti-Georg", "author_id": 96, "author_profile": "https://Stackoverflow.com/users/96", "pm_score": 2, "selected": false, "text": "tblRows[i].style.display = (rowVisible) ? \"none\" : \"\";\n tblRows[i].style.display = (rowVisible) ? \"none\" : \"table-row\";\n tblRows[i].style.display = (rowVisible) ? \"none\" : \"auto\";\n" }, { "answer_id": 102335, "author": "Lark", "author_id": 8804, "author_profile": "https://Stackoverflow.com/users/8804", "pm_score": 0, "selected": false, "text": "<tr> <th>" }, { "answer_id": 102456, "author": "JW.", "author_id": 4321, "author_profile": "https://Stackoverflow.com/users/4321", "pm_score": 0, "selected": false, "text": "<table>\n <tr style=\"display:none\"> ... </tr>\n <tr style=\"display:\"> ... </tr>\n</table>\n" }, { "answer_id": 102561, "author": "bobince", "author_id": 18936, "author_profile": "https://Stackoverflow.com/users/18936", "pm_score": 3, "selected": true, "text": "img.src= CLOSED_IMAGE;\ntbl.className= OPEN_TBL;\n table.closed tr { display: none; }\n" } ]
2008/09/19
[ "https://Stackoverflow.com/questions/102261", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18860/" ]
102,271
<p>More information from <a href="http://en.wikipedia.org/wiki/Perl_6#Junctions" rel="noreferrer">the Perl 6 Wikipedia entry</a></p> <p><strong>Junctions</strong></p> <p>Perl 6 introduces the concept of junctions: values that are composites of other values.[24] In the earliest days of Perl 6's design, these were called "superpositions", by analogy to the concept in quantum physics of quantum superpositions — waveforms that can simultaneously occupy several states until observation "collapses" them. A Perl 5 module released in 2000 by Damian Conway called Quantum::Superpositions[25] provided an initial proof of concept. While at first, such superpositional values seemed like merely a programmatic curiosity, over time their utility and intuitiveness became widely recognized, and junctions now occupy a central place in Perl 6's design.</p> <p>In their simplest form, junctions are created by combining a set of values with junctive operators:</p> <pre><code>my $any_even_digit = 0|2|4|6|8; # any(0, 2, 4, 6, 8) my $all_odd_digits = 1&amp;3&amp;5&amp;7&amp;9; # all(1, 3, 5, 7, 9) </code></pre> <p>| indicates a value which is equal to either its left or right-hand arguments. &amp; indicates a value which is equal to both its left and right-hand arguments. These values can be used in any code that would use a normal value. Operations performed on a junction act on all members of the junction equally, and combine according to the junctive operator. So, ("apple"|"banana") ~ "s" would yield "apples"|"bananas". In comparisons, junctions return a single true or false result for the comparison. "any" junctions return true if the comparison is true for any one of the elements of the junction. "all" junctions return true if the comparison is true for all of the elements of the junction.</p> <p>Junctions can also be used to more richly augment the type system by introducing a style of generic programming that is constrained to junctions of types:</p> <pre><code>sub get_tint ( RGB_Color|CMYK_Color $color, num $opacity) { ... } sub store_record (Record&amp;Storable $rec) { ... } </code></pre>
[ { "answer_id": 117746, "author": "Brad Gilbert", "author_id": 1337, "author_profile": "https://Stackoverflow.com/users/1337", "pm_score": 5, "selected": true, "text": "given( $month ){\n when any(qw'1 3 5 7 8 10 12') {\n $day = 31\n }\n when any(qw'4 6 9 11') {\n $day = 30\n }\n when 2 {\n $day = 29\n }\n}\n" }, { "answer_id": 118441, "author": "Eevee", "author_id": 17875, "author_profile": "https://Stackoverflow.com/users/17875", "pm_score": 3, "selected": false, "text": "for all(@files) -> $file {\n do_something($file);\n}\n @files" } ]
2008/09/19
[ "https://Stackoverflow.com/questions/102271", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18446/" ]
102,278
<p>OK, so practically every database based application has to deal with "non-active" records. Either, soft-deletions or marking something as "to be ignored". I'm curious as to whether there are any radical alternatives thoughts on an `active' column (or a status column).</p> <p>For example, if I had a list of people</p> <pre><code>CREATE TABLE people ( id INTEGER PRIMARY KEY, name VARCHAR(100), active BOOLEAN, ... ); </code></pre> <p>That means to get a list of active people, you need to use</p> <pre><code>SELECT * FROM people WHERE active=True; </code></pre> <p>Does anyone suggest that non active records would be moved off to a separate table and where appropiate a UNION is done to join the two?</p> <p>Curiosity striking...</p> <p><strong>EDIT:</strong> I should make clear, I'm coming at this from a purist perspective. I can see how data archiving might be necessary for large amounts of data, but that is not where I'm coming from. If you do a SELECT * FROM people it would make sense to me that those entries are in a sense "active"</p> <p>Thanks</p>
[ { "answer_id": 102333, "author": "Mike McAllister", "author_id": 16247, "author_profile": "https://Stackoverflow.com/users/16247", "pm_score": 6, "selected": true, "text": "CREATE TABLE people\n(\n id NUMBER(10),\n name VARCHAR2(100),\n active NUMBER(1)\n)\nPARTITION BY LIST(active)\n(\n PARTITION active_records VALUES (0)\n PARTITION inactive_records VALUES (1)\n);\n" }, { "answer_id": 5033792, "author": "Ralph Smith", "author_id": 2066143, "author_profile": "https://Stackoverflow.com/users/2066143", "pm_score": 0, "selected": false, "text": "ALTER TABLE users ADD INDEX index_users_on_active (id, active) ; \n" }, { "answer_id": 56963710, "author": "user1454926", "author_id": 1454926, "author_profile": "https://Stackoverflow.com/users/1454926", "pm_score": 0, "selected": false, "text": "SELECT * FROM people WHERE dateInactivated is NULL;\n" } ]
2008/09/19
[ "https://Stackoverflow.com/questions/102278", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1087/" ]
102,317
<p>I have two tables Organisation and Employee having one to many relation i.e one organisation can have multiple employees. Now I want to select all information of a particular organisation plus first name of all employees for this organisation. What’s the best way to do it? Can I get all of this in single record set or I will have to get multiple rows based on no. of employees? Here is a bit graphical demonstration of what I want:</p> <pre><code>Org_ID Org_Address Org_OtherDetails Employess 1 132A B Road List of details Emp1, Emp2, Emp3..... </code></pre>
[ { "answer_id": 102361, "author": "Mike McAllister", "author_id": 16247, "author_profile": "https://Stackoverflow.com/users/16247", "pm_score": 0, "selected": false, "text": "select\n o.org_id,\n o.org_address,\n o.org_otherdetails,\n org_employees( o.org_id ) as org_employees\nfrom\n organization o\n" }, { "answer_id": 102442, "author": "Adam", "author_id": 13320, "author_profile": "https://Stackoverflow.com/users/13320", "pm_score": 2, "selected": false, "text": "create function dbo.table2list (@input int)\nreturns varchar(8000)\nas\nBEGIN\ndeclare @putout varchar(8000)\nset @putout = ''\nselect @putout = @putout + ', ' + <employeename>\nfrom <employeetable>\nwhere <orgid> = @input\nreturn @putout\nend\n select * from org, dbo.table2list(orgid)\nfrom <organisationtable>\n" }, { "answer_id": 104964, "author": "mike", "author_id": 19217, "author_profile": "https://Stackoverflow.com/users/19217", "pm_score": 0, "selected": false, "text": "select *\nFROM\n users u\n LEFT JOIN organizations o ON (u.idorg = o.id);\n select o.*, group_concat(u.name)\nFROM\n users u\n LEFT JOIN organizations o ON (u.idorg = o.id)\nGROUP BY\n o.id\n" }, { "answer_id": 106149, "author": "igelkott", "author_id": 2052165, "author_profile": "https://Stackoverflow.com/users/2052165", "pm_score": 2, "selected": false, "text": "select Org_ID, Org_Address, Org_OtherDetails,\n GROUP_CONCAT(employees) as Employees\nfrom employees a, organization b\nwhere a.org_id=b.org_id\ngroup by b.org_id;\n" }, { "answer_id": 66589552, "author": "Dylan Kennard", "author_id": 15094747, "author_profile": "https://Stackoverflow.com/users/15094747", "pm_score": 0, "selected": false, "text": "SELECT attribute1, STRING_AGG (attribute2, '|') AS Attribute2\nFROM table\nGROUP BY attribute\n" } ]
2008/09/19
[ "https://Stackoverflow.com/questions/102317", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
102,325
<p>Since Java 6 there is a class <code>java.awt.Desktop</code>. There are some nice methods but the class is not supported on all platforms. The methods <a href="http://java.sun.com/javase/6/docs/api/java/awt/Desktop.html#getDesktop()" rel="nofollow noreferrer"><code>java.awt.Desktop.getDesktop()</code></a> throws an </p> <blockquote> <p>java.lang.UnsupportedOperationException: Desktop API is not supported on the current platform</p> </blockquote> <p>on some platforms. Or the method <a href="http://java.sun.com/javase/6/docs/api/java/awt/Desktop.html#isDesktopSupported()" rel="nofollow noreferrer"><code>java.awt.Desktop.isDesktopSupported()</code></a> return false.</p> <p>I know that it work on Windows XP, Windows 2003 and also Windows Vista. The question is on which platform is it not supported?</p>
[ { "answer_id": 19537699, "author": "Kishan Bheemajiyani", "author_id": 2762311, "author_profile": "https://Stackoverflow.com/users/2762311", "pm_score": 2, "selected": false, "text": "java.lang.UnsupportedOperationException: The system tray is not supported on the current platform.\n" }, { "answer_id": 23515984, "author": "Carlos", "author_id": 3611876, "author_profile": "https://Stackoverflow.com/users/3611876", "pm_score": 2, "selected": false, "text": "apt-get install libgnome2-0\n" } ]
2008/09/19
[ "https://Stackoverflow.com/questions/102325", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12631/" ]
102,343
<p>I have a need to open a popup detail window from a gridview (VS 2005 / 2008). What I am trying to do is in the markup for my TemplateColumn have an asp:Button control, sort of like this:</p> <pre><code>&lt;asp:Button ID="btnShowDetails" runat="server" CausesValidation="false" CommandName="Details" Text="Order Details" onClientClick="window.open('PubsOrderDetails.aspx?OrderId=&lt;%# Eval("order_id") %&gt;', '','scrollbars=yes,resizable=yes, width=350, height=550');" </code></pre> <p>Of course, what isn't working is the appending of the &lt;%# Eval...%> section to set the query string variable.</p> <p>Any suggestions? Or is there a far better way of achieving the same result?</p>
[ { "answer_id": 102373, "author": "Tom Ritter", "author_id": 8435, "author_profile": "https://Stackoverflow.com/users/8435", "pm_score": 5, "selected": true, "text": "onClientClick=<%# string.Format(\"window.open('PubsOrderDetails.aspx?OrderId={0}',scrollbars=yes,resizable=yes, width=350, height=550);\", Eval(\"order_id\")) %>\n" }, { "answer_id": 102479, "author": "EndangeredMassa", "author_id": 106, "author_profile": "https://Stackoverflow.com/users/106", "pm_score": 2, "selected": false, "text": "Private Sub gvBoxes_RowDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles gvBoxes.RowDataBound\n Select Case e.Row.RowType\n Case DataControlRowType.DataRow\n Dim btn As Button = e.Row.FindControl(\"btnShowDetails\")\n btn.OnClientClick = \"window.open('PubsOrderDetails.aspx?OrderId=\" & DataItem.Eval(\"OrderId\") & \"','','scrollbars=yes,resizable=yes, width=350, height=550');\"\n End Select \nEnd Sub\n" } ]
2008/09/19
[ "https://Stackoverflow.com/questions/102343", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12253/" ]
102,382
<p>I use ssh-agent with password-protected keys on Linux. Every time I log into a certain machine, I do this:</p> <pre><code>eval `ssh-agent` &amp;&amp; ssh-add </code></pre> <p>This works well enough, but every time I log in and do this, I create another ssh-agent. Once in a while, I will do a <code>killall ssh-agent</code> to reap them. Is there a simple way to reuse the same ssh-agent process across different sessions?</p>
[ { "answer_id": 102420, "author": "Blair Conrad", "author_id": 1199, "author_profile": "https://Stackoverflow.com/users/1199", "pm_score": 2, "selected": false, "text": "SSH_ENV=\"$HOME/.ssh/environment\"\n\nfunction start_agent {\n echo \"Initialising new SSH agent...\"\n /usr/bin/ssh-agent | sed 's/^echo/#echo/' > \"${SSH_ENV}\"\n echo succeeded\n chmod 600 \"${SSH_ENV}\"\n . \"${SSH_ENV}\" > /dev/null\n /usr/bin/ssh-add;\n}\n\n# Source SSH settings, if applicable\n\nif [ -f \"${SSH_ENV}\" ]; then\n . \"${SSH_ENV}\" > /dev/null\n #ps ${SSH_AGENT_PID} doesn’t work under cywgin\n ps -ef | grep ${SSH_AGENT_PID} | grep ssh-agent$ > /dev/null || {\n start_agent;\n }\nelse\n start_agent;\nfi \n" }, { "answer_id": 106720, "author": "jfm3", "author_id": 11138, "author_profile": "https://Stackoverflow.com/users/11138", "pm_score": 0, "selected": false, "text": ".bashrc .bash_login" }, { "answer_id": 106727, "author": "Greg Hewgill", "author_id": 893, "author_profile": "https://Stackoverflow.com/users/893", "pm_score": 2, "selected": false, "text": "ssh-agent $SHELL\n" } ]
2008/09/19
[ "https://Stackoverflow.com/questions/102382", "https://Stackoverflow.com", "https://Stackoverflow.com/users/742/" ]
102,384
<p>I have looked at the ability to use tabs in Vim (with <code>:tabe</code>, <code>:tabnew</code>, etc.) as a replacement for my current practice of having many files open in the same window in hidden buffers.</p> <p>I would like every distinct file that I have open to always be in its own tab. However, there are some things that get in the way of this. How do I fix these:</p> <ol> <li><p>When commands like <code>gf</code> and <code>^]</code> jump to a location in another file, the file opens in a new buffer in the current tab. Is there a way to have all of these sorts of commands open the file in a new tab, or switch to the existing tab with the file if it is already open?</p></li> <li><p>When switching buffers I can use <code>:b &lt;part of filename&gt;&lt;tab&gt;</code> and it will complete the names of files in existing buffers. <code>&lt;part of filename&gt;</code> can even be the middle of a filename instead of the beginning. Is there an equivalent for switching tabs?</p></li> </ol>
[ { "answer_id": 102486, "author": "Lucas Oman", "author_id": 6726, "author_profile": "https://Stackoverflow.com/users/6726", "pm_score": 2, "selected": false, "text": "map gf :tabe <cfile><CR>\n" }, { "answer_id": 103590, "author": "Zathrus", "author_id": 16220, "author_profile": "https://Stackoverflow.com/users/16220", "pm_score": 10, "selected": true, "text": ":make :grep :helpgrep :set hidden :bn :bp :b # :b name ctrl-6 ctrl-6 #ctrl-6 # :ls" }, { "answer_id": 106224, "author": "jkramer", "author_id": 12523, "author_profile": "https://Stackoverflow.com/users/12523", "pm_score": 2, "selected": false, "text": "\" CTRL+b opens the buffer list\nmap <C-b> <esc>:BufExplorer<cr>\n\n\" gz in command mode closes the current buffer\nmap gz :bdelete<cr>\n\n\" g[bB] in command mode switch to the next/prev. buffer\nmap gb :bnext<cr>\nmap gB :bprev<cr>\n" }, { "answer_id": 3476411, "author": "robince", "author_id": 136194, "author_profile": "https://Stackoverflow.com/users/136194", "pm_score": 8, "selected": false, "text": ":tab sball :help switchbuf :set switchbuf=usetab,newtab" }, { "answer_id": 8973705, "author": "crenate", "author_id": 1129848, "author_profile": "https://Stackoverflow.com/users/1129848", "pm_score": 8, "selected": false, "text": ":help window help: tab-page" }, { "answer_id": 13328832, "author": "Zenexer", "author_id": 1188377, "author_profile": "https://Stackoverflow.com/users/1188377", "pm_score": 6, "selected": false, "text": "<C-w>gf gf <C-PageUp> <C-PageDown> gt gT <C-w>T :set switchbuf=usetab newtab :set switchbuf=usetab,newtab split :set mouse=a + :help tab-page <C-w>T :help windows vim -p file1 file2 ... -p vim vim -p" }, { "answer_id": 43125465, "author": "icc97", "author_id": 327074, "author_profile": "https://Stackoverflow.com/users/327074", "pm_score": 3, "selected": false, "text": ":help window :help window" }, { "answer_id": 71926217, "author": "Good Pen", "author_id": 14972148, "author_profile": "https://Stackoverflow.com/users/14972148", "pm_score": 0, "selected": false, "text": " nno \\ <Cmd>call To_global_mark()<cr>\n fun! To_global_mark()\n -tab drop /tmp/useless.md\n exe 'normal! `' .. toupper(input(\"To global mark: \"))\n endf\n" } ]
2008/09/19
[ "https://Stackoverflow.com/questions/102384", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7706/" ]
102,394
<p>I am trying to sort a dict based on its key and return an iterator to the values from within an overridden iter method in a class. Is there a nicer and more efficient way of doing this than creating a new list, inserting into the list as I sort through the keys?</p>
[ { "answer_id": 102438, "author": "Thomas Wouters", "author_id": 17624, "author_profile": "https://Stackoverflow.com/users/17624", "pm_score": 2, "selected": false, "text": "def sorted_dict(d):\n keys = d.keys()\n keys.sort()\n for key in keys:\n yield d[key]\n" }, { "answer_id": 102443, "author": "dF.", "author_id": 3002, "author_profile": "https://Stackoverflow.com/users/3002", "pm_score": 4, "selected": true, "text": "def itersorted(d):\n for key in sorted(d):\n yield d[key]\n" }, { "answer_id": 102480, "author": "LJ.", "author_id": 4849, "author_profile": "https://Stackoverflow.com/users/4849", "pm_score": -1, "selected": false, "text": "sorted(list) list.sort() def compareTwo(a, b):\n if a > b:\n return 1\n if a == b:\n return 0\n if a < b:\n return -1\n\nList.Sort(compareTwo)\nprint a\n" }, { "answer_id": 103187, "author": "Jerub", "author_id": 14648, "author_profile": "https://Stackoverflow.com/users/14648", "pm_score": 2, "selected": false, "text": "def sortedDict(dictobj):\n return (value for key, value in sorted(dictobj.iteritems()))\n" } ]
2008/09/19
[ "https://Stackoverflow.com/questions/102394", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18909/" ]
102,398
<p>I am looking for a .NET implementation of a priority queue or heap data structure</p> <blockquote> <p>Priority queues are data structures that provide more flexibility than simple sorting, because they allow new elements to enter a system at arbitrary intervals. It is much more cost-effective to insert a new job into a priority queue than to re-sort everything on each such arrival.</p> <p>The basic priority queue supports three primary operations:</p> <ul> <li>Insert(Q,x). Given an item x with key k, insert it into the priority queue Q.</li> <li>Find-Minimum(Q). Return a pointer to the item whose key value is smaller than any other key in the priority queue Q.</li> <li>Delete-Minimum(Q). Remove the item from the priority queue Q whose key is minimum</li> </ul> </blockquote> <p>Unless I am looking in the wrong place, there isn't one in the framework. Is anyone aware of a good one, or should I roll my own?</p>
[ { "answer_id": 102434, "author": "Ben Hoffstein", "author_id": 4482, "author_profile": "https://Stackoverflow.com/users/4482", "pm_score": 7, "selected": true, "text": "OrderedBag OrderedSet" }, { "answer_id": 1114323, "author": "functor", "author_id": 77609, "author_profile": "https://Stackoverflow.com/users/77609", "pm_score": 6, "selected": false, "text": "IntervalHeap<T> IPriorityQueue<T> FindMin FindMax DeleteMin DeleteMax > var heap = new C5.IntervalHeap<int>();\n> heap.Add(10);\n> heap.Add(5);\n> heap.FindMin();\n5\n" }, { "answer_id": 4994931, "author": "kobi7", "author_id": 588613, "author_profile": "https://Stackoverflow.com/users/588613", "pm_score": 5, "selected": false, "text": "using System;\nusing System.Diagnostics;\nusing System.Collections;\nusing System.Collections.Generic;\n\nnamespace PrioQueue\n{\n public class PrioQueue\n {\n int total_size;\n SortedDictionary<int, Queue> storage;\n\n public PrioQueue ()\n {\n this.storage = new SortedDictionary<int, Queue> ();\n this.total_size = 0;\n }\n\n public bool IsEmpty ()\n {\n return (total_size == 0);\n }\n\n public object Dequeue ()\n {\n if (IsEmpty ()) {\n throw new Exception (\"Please check that priorityQueue is not empty before dequeing\");\n } else\n foreach (Queue q in storage.Values) {\n // we use a sorted dictionary\n if (q.Count > 0) {\n total_size--;\n return q.Dequeue ();\n }\n }\n\n Debug.Assert(false,\"not supposed to reach here. problem with changing total_size\");\n\n return null; // not supposed to reach here.\n }\n\n // same as above, except for peek.\n\n public object Peek ()\n {\n if (IsEmpty ())\n throw new Exception (\"Please check that priorityQueue is not empty before peeking\");\n else\n foreach (Queue q in storage.Values) {\n if (q.Count > 0)\n return q.Peek ();\n }\n\n Debug.Assert(false,\"not supposed to reach here. problem with changing total_size\");\n\n return null; // not supposed to reach here.\n }\n\n public object Dequeue (int prio)\n {\n total_size--;\n return storage[prio].Dequeue ();\n }\n\n public void Enqueue (object item, int prio)\n {\n if (!storage.ContainsKey (prio)) {\n storage.Add (prio, new Queue ());\n }\n storage[prio].Enqueue (item);\n total_size++;\n\n }\n }\n}\n" }, { "answer_id": 13776636, "author": "Ohad Schneider", "author_id": 67824, "author_profile": "https://Stackoverflow.com/users/67824", "pm_score": 6, "selected": false, "text": "public abstract class Heap<T> : IEnumerable<T>\n{\n private const int InitialCapacity = 0;\n private const int GrowFactor = 2;\n private const int MinGrow = 1;\n\n private int _capacity = InitialCapacity;\n private T[] _heap = new T[InitialCapacity];\n private int _tail = 0;\n\n public int Count { get { return _tail; } }\n public int Capacity { get { return _capacity; } }\n\n protected Comparer<T> Comparer { get; private set; }\n protected abstract bool Dominates(T x, T y);\n\n protected Heap() : this(Comparer<T>.Default)\n {\n }\n\n protected Heap(Comparer<T> comparer) : this(Enumerable.Empty<T>(), comparer)\n {\n }\n\n protected Heap(IEnumerable<T> collection)\n : this(collection, Comparer<T>.Default)\n {\n }\n\n protected Heap(IEnumerable<T> collection, Comparer<T> comparer)\n {\n if (collection == null) throw new ArgumentNullException(\"collection\");\n if (comparer == null) throw new ArgumentNullException(\"comparer\");\n\n Comparer = comparer;\n\n foreach (var item in collection)\n {\n if (Count == Capacity)\n Grow();\n\n _heap[_tail++] = item;\n }\n\n for (int i = Parent(_tail - 1); i >= 0; i--)\n BubbleDown(i);\n }\n\n public void Add(T item)\n {\n if (Count == Capacity)\n Grow();\n\n _heap[_tail++] = item;\n BubbleUp(_tail - 1);\n }\n\n private void BubbleUp(int i)\n {\n if (i == 0 || Dominates(_heap[Parent(i)], _heap[i])) \n return; //correct domination (or root)\n\n Swap(i, Parent(i));\n BubbleUp(Parent(i));\n }\n\n public T GetMin()\n {\n if (Count == 0) throw new InvalidOperationException(\"Heap is empty\");\n return _heap[0];\n }\n\n public T ExtractDominating()\n {\n if (Count == 0) throw new InvalidOperationException(\"Heap is empty\");\n T ret = _heap[0];\n _tail--;\n Swap(_tail, 0);\n BubbleDown(0);\n return ret;\n }\n\n private void BubbleDown(int i)\n {\n int dominatingNode = Dominating(i);\n if (dominatingNode == i) return;\n Swap(i, dominatingNode);\n BubbleDown(dominatingNode);\n }\n\n private int Dominating(int i)\n {\n int dominatingNode = i;\n dominatingNode = GetDominating(YoungChild(i), dominatingNode);\n dominatingNode = GetDominating(OldChild(i), dominatingNode);\n\n return dominatingNode;\n }\n\n private int GetDominating(int newNode, int dominatingNode)\n {\n if (newNode < _tail && !Dominates(_heap[dominatingNode], _heap[newNode]))\n return newNode;\n else\n return dominatingNode;\n }\n\n private void Swap(int i, int j)\n {\n T tmp = _heap[i];\n _heap[i] = _heap[j];\n _heap[j] = tmp;\n }\n\n private static int Parent(int i)\n {\n return (i + 1)/2 - 1;\n }\n\n private static int YoungChild(int i)\n {\n return (i + 1)*2 - 1;\n }\n\n private static int OldChild(int i)\n {\n return YoungChild(i) + 1;\n }\n\n private void Grow()\n {\n int newCapacity = _capacity*GrowFactor + MinGrow;\n var newHeap = new T[newCapacity];\n Array.Copy(_heap, newHeap, _capacity);\n _heap = newHeap;\n _capacity = newCapacity;\n }\n\n public IEnumerator<T> GetEnumerator()\n {\n return _heap.Take(Count).GetEnumerator();\n }\n\n IEnumerator IEnumerable.GetEnumerator()\n {\n return GetEnumerator();\n }\n}\n\npublic class MaxHeap<T> : Heap<T>\n{\n public MaxHeap()\n : this(Comparer<T>.Default)\n {\n }\n\n public MaxHeap(Comparer<T> comparer)\n : base(comparer)\n {\n }\n\n public MaxHeap(IEnumerable<T> collection, Comparer<T> comparer)\n : base(collection, comparer)\n {\n }\n\n public MaxHeap(IEnumerable<T> collection) : base(collection)\n {\n }\n\n protected override bool Dominates(T x, T y)\n {\n return Comparer.Compare(x, y) >= 0;\n }\n}\n\npublic class MinHeap<T> : Heap<T>\n{\n public MinHeap()\n : this(Comparer<T>.Default)\n {\n }\n\n public MinHeap(Comparer<T> comparer)\n : base(comparer)\n {\n }\n\n public MinHeap(IEnumerable<T> collection) : base(collection)\n {\n }\n\n public MinHeap(IEnumerable<T> collection, Comparer<T> comparer)\n : base(collection, comparer)\n {\n }\n\n protected override bool Dominates(T x, T y)\n {\n return Comparer.Compare(x, y) <= 0;\n }\n}\n [TestClass]\npublic class HeapTests\n{\n [TestMethod]\n public void TestHeapBySorting()\n {\n var minHeap = new MinHeap<int>(new[] {9, 8, 4, 1, 6, 2, 7, 4, 1, 2});\n AssertHeapSort(minHeap, minHeap.OrderBy(i => i).ToArray());\n\n minHeap = new MinHeap<int> { 7, 5, 1, 6, 3, 2, 4, 1, 2, 1, 3, 4, 7 };\n AssertHeapSort(minHeap, minHeap.OrderBy(i => i).ToArray());\n\n var maxHeap = new MaxHeap<int>(new[] {1, 5, 3, 2, 7, 56, 3, 1, 23, 5, 2, 1});\n AssertHeapSort(maxHeap, maxHeap.OrderBy(d => -d).ToArray());\n\n maxHeap = new MaxHeap<int> {2, 6, 1, 3, 56, 1, 4, 7, 8, 23, 4, 5, 7, 34, 1, 4};\n AssertHeapSort(maxHeap, maxHeap.OrderBy(d => -d).ToArray());\n }\n\n private static void AssertHeapSort(Heap<int> heap, IEnumerable<int> expected)\n {\n var sorted = new List<int>();\n while (heap.Count > 0)\n sorted.Add(heap.ExtractDominating());\n\n Assert.IsTrue(sorted.SequenceEqual(expected));\n }\n}\n" }, { "answer_id": 14114073, "author": "cdiggins", "author_id": 184528, "author_profile": "https://Stackoverflow.com/users/184528", "pm_score": -1, "selected": false, "text": "PriorityQueue SortedSet using System;\nusing System.Collections.Generic;\n\nnamespace CDiggins\n{\n interface IPriorityQueue<T, K> where K : IComparable<K>\n {\n bool Empty { get; }\n void Enqueue(T x, K key);\n void Dequeue();\n T Top { get; }\n }\n\n class PriorityQueue<T, K> : IPriorityQueue<T, K> where K : IComparable<K>\n {\n SortedSet<Tuple<T, K>> set;\n\n class Comparer : IComparer<Tuple<T, K>> {\n public int Compare(Tuple<T, K> x, Tuple<T, K> y) {\n return x.Item2.CompareTo(y.Item2);\n }\n }\n\n PriorityQueue() { set = new SortedSet<Tuple<T, K>>(new Comparer()); }\n public bool Empty { get { return set.Count == 0; } }\n public void Enqueue(T x, K key) { set.Add(Tuple.Create(x, key)); }\n public void Dequeue() { set.Remove(set.Max); }\n public T Top { get { return set.Max.Item1; } }\n }\n}\n" }, { "answer_id": 33888482, "author": "Shimou Dong", "author_id": 5598590, "author_profile": "https://Stackoverflow.com/users/5598590", "pm_score": 3, "selected": false, "text": "class PriorityQueue<T>\n{\n IComparer<T> comparer;\n T[] heap;\n public int Count { get; private set; }\n public PriorityQueue() : this(null) { }\n public PriorityQueue(int capacity) : this(capacity, null) { }\n public PriorityQueue(IComparer<T> comparer) : this(16, comparer) { }\n public PriorityQueue(int capacity, IComparer<T> comparer)\n {\n this.comparer = (comparer == null) ? Comparer<T>.Default : comparer;\n this.heap = new T[capacity];\n }\n public void push(T v)\n {\n if (Count >= heap.Length) Array.Resize(ref heap, Count * 2);\n heap[Count] = v;\n SiftUp(Count++);\n }\n public T pop()\n {\n var v = top();\n heap[0] = heap[--Count];\n if (Count > 0) SiftDown(0);\n return v;\n }\n public T top()\n {\n if (Count > 0) return heap[0];\n throw new InvalidOperationException(\"优先队列为空\");\n }\n void SiftUp(int n)\n {\n var v = heap[n];\n for (var n2 = n / 2; n > 0 && comparer.Compare(v, heap[n2]) > 0; n = n2, n2 /= 2) heap[n] = heap[n2];\n heap[n] = v;\n }\n void SiftDown(int n)\n {\n var v = heap[n];\n for (var n2 = n * 2; n2 < Count; n = n2, n2 *= 2)\n {\n if (n2 + 1 < Count && comparer.Compare(heap[n2 + 1], heap[n2]) > 0) n2++;\n if (comparer.Compare(v, heap[n2]) >= 0) break;\n heap[n] = heap[n2];\n }\n heap[n] = v;\n }\n}\n" }, { "answer_id": 38657269, "author": "ChaseMedallion", "author_id": 1142970, "author_profile": "https://Stackoverflow.com/users/1142970", "pm_score": 1, "selected": false, "text": "ICollection<T> IReadOnlyCollection<T> IComparer<T> DebuggerTypeProxy" }, { "answer_id": 39131454, "author": "Patryk Golebiowski", "author_id": 4610370, "author_profile": "https://Stackoverflow.com/users/4610370", "pm_score": 3, "selected": false, "text": "var comparer = Comparer<int>.Default;\nvar heap = new PairingHeap<int, string>(comparer);\n\nheap.Add(3, \"your\");\nheap.Add(5, \"of\");\nheap.Add(7, \"disturbing.\");\nheap.Add(2, \"find\");\nheap.Add(1, \"I\");\nheap.Add(6, \"faith\");\nheap.Add(4, \"lack\");\n\nwhile (!heap.IsEmpty)\n Console.WriteLine(heap.Pop().Value);\n" }, { "answer_id": 41974651, "author": "Bharathkumar V", "author_id": 4817250, "author_profile": "https://Stackoverflow.com/users/4817250", "pm_score": 2, "selected": false, "text": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\n\nnamespace AlgorithmsMadeEasy\n{\n class MaxHeap\n {\n private static int capacity = 10;\n private int size = 0;\n int[] items = new int[capacity];\n\n private int getLeftChildIndex(int parentIndex) { return 2 * parentIndex + 1; }\n private int getRightChildIndex(int parentIndex) { return 2 * parentIndex + 2; }\n private int getParentIndex(int childIndex) { return (childIndex - 1) / 2; }\n\n private int getLeftChild(int parentIndex) { return this.items[getLeftChildIndex(parentIndex)]; }\n private int getRightChild(int parentIndex) { return this.items[getRightChildIndex(parentIndex)]; }\n private int getParent(int childIndex) { return this.items[getParentIndex(childIndex)]; }\n\n private bool hasLeftChild(int parentIndex) { return getLeftChildIndex(parentIndex) < size; }\n private bool hasRightChild(int parentIndex) { return getRightChildIndex(parentIndex) < size; }\n private bool hasParent(int childIndex) { return getLeftChildIndex(childIndex) > 0; }\n\n private void swap(int indexOne, int indexTwo)\n {\n int temp = this.items[indexOne];\n this.items[indexOne] = this.items[indexTwo];\n this.items[indexTwo] = temp;\n }\n\n private void hasEnoughCapacity()\n {\n if (this.size == capacity)\n {\n Array.Resize(ref this.items,capacity*2);\n capacity *= 2;\n }\n }\n\n public void Add(int item)\n {\n this.hasEnoughCapacity();\n this.items[size] = item;\n this.size++;\n heapifyUp();\n }\n\n public int Remove()\n {\n int item = this.items[0];\n this.items[0] = this.items[size-1];\n this.items[this.size - 1] = 0;\n size--;\n heapifyDown();\n return item;\n }\n\n private void heapifyUp()\n {\n int index = this.size - 1;\n while (hasParent(index) && this.items[index] > getParent(index))\n {\n swap(index, getParentIndex(index));\n index = getParentIndex(index);\n }\n }\n\n private void heapifyDown()\n {\n int index = 0;\n while (hasLeftChild(index))\n {\n int bigChildIndex = getLeftChildIndex(index);\n if (hasRightChild(index) && getLeftChild(index) < getRightChild(index))\n {\n bigChildIndex = getRightChildIndex(index);\n }\n\n if (this.items[bigChildIndex] < this.items[index])\n {\n break;\n }\n else\n {\n swap(bigChildIndex,index);\n index = bigChildIndex;\n }\n }\n }\n }\n}\n\n/*\nCalling Code:\n MaxHeap mh = new MaxHeap();\n mh.Add(10);\n mh.Add(5);\n mh.Add(2);\n mh.Add(1);\n mh.Add(50);\n int maxVal = mh.Remove();\n int newMaxVal = mh.Remove();\n*/\n" } ]
2008/09/19
[ "https://Stackoverflow.com/questions/102398", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11173/" ]
102,425
<p>I have a properties file in java, in which I store all information of my app, like logo image filename, database name, database user and database password.</p> <p>I can store the password encrypted on the properties file. But, the key or passphrase can be read out of the jar using a decompiler.</p> <p>Is there a way to store the db pass in a properties file securely?</p>
[ { "answer_id": 102827, "author": "jjnguy", "author_id": 2598, "author_profile": "https://Stackoverflow.com/users/2598", "pm_score": 2, "selected": false, "text": "getBytes() /**\n * Returns the hash value of the given chars\n * \n * Uses the default hash algorithm described above\n * \n * @param in\n * the byte[] to hash\n * @return a byte[] of hashed values\n */\n public static byte[] getHashedBytes(byte[] in)\n {\n MessageDigest msg;\n try\n {\n msg = MessageDigest.getInstance(hashingAlgorithmUsed);\n }\n catch (NoSuchAlgorithmException e)\n {\n throw new AssertionError(\"Someone chose to use a hashing algorithm that doesn't exist. Epic fail, go change it in the Util file. SHA(1) or MD5\");\n }\n msg.update(in);\n return msg.digest();\n }\n" }, { "answer_id": 102920, "author": "David Webb", "author_id": 3171, "author_profile": "https://Stackoverflow.com/users/3171", "pm_score": 0, "selected": false, "text": "root root -r--------" } ]
2008/09/19
[ "https://Stackoverflow.com/questions/102425", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13116/" ]
102,427
<p>I'm working on a .Net applications with multiple threads doing all sorts of things. When something goes wrong in production I want to be able to see which threads are running (by their managed name) and also be able to pause / kill them.</p> <p>Anyway to achieve this ?</p> <p>VS isn't always available (although a good option when is), and WinDbg UI isn't for the lite hearted.</p> <p>I considered a in-program threads window, like VS has while debugging, but couldn't find a programmatic way to do this. Process.GetThreads returns very little usable data.</p>
[ { "answer_id": 1569519, "author": "rosenfield", "author_id": 184897, "author_profile": "https://Stackoverflow.com/users/184897", "pm_score": 2, "selected": false, "text": "using System.Diagnostics;\n\nProcessThreadCollection threads = Process.GetCurrentProcess().Threads;\n" } ]
2008/09/19
[ "https://Stackoverflow.com/questions/102427", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18910/" ]
102,453
<p>I got pretty big webflow definition, which I do not want to copy/paste for reusing. There are references to action bean in XML, which is kind natural.</p> <p>I want to use same flow definiton twice: second time with actions configured differently (inject different implementation of service to it). </p> <p>Is there easy way to do this?</p> <hr> <p>Problem is I want to use same flow with different beans at once, in the same app. Copy/Paste is bad, but I dont see other solution for now.</p>
[ { "answer_id": 4057210, "author": "bobtins", "author_id": 338552, "author_profile": "https://Stackoverflow.com/users/338552", "pm_score": 1, "selected": false, "text": "<action-state id=\"checkForParams\">\n <on-entry>\n <set name=\"flowScope.clientKey\" value=\"requestParameters.clientKey\"/>\n <set name=\"flowScope.viewReportBean\" \n value=\"reportActionFactory.getViewBean(reportUnit)\"/>\n </on-entry>\n <evaluate expression=\"viewReportBean\"/>\n" } ]
2008/09/19
[ "https://Stackoverflow.com/questions/102453", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
102,457
<p>Given an existing valid SVG document, what's the best way to create "informational popups", so that when you hover or click on certain elements (let's say ) you popup a box with an arbitrary amount (i.e. not just a single line tooltip) of extra information?</p> <p>This should display correctly at least in Firefox and be invisible if the image was rasterized to a bitmap format.</p>
[ { "answer_id": 105636, "author": "Sparr", "author_id": 13675, "author_profile": "https://Stackoverflow.com/users/13675", "pm_score": 6, "selected": true, "text": "<svg>\n <text id=\"thingyouhoverover\" x=\"50\" y=\"35\" font-size=\"14\">Mouse over me!</text>\n <text id=\"thepopup\" x=\"250\" y=\"100\" font-size=\"30\" fill=\"black\" visibility=\"hidden\">Change me\n <set attributeName=\"visibility\" from=\"hidden\" to=\"visible\" begin=\"thingyouhoverover.mouseover\" end=\"thingyouhoverover.mouseout\"/>\n </text>\n</svg>\n" }, { "answer_id": 4831948, "author": "Peter Collingridge", "author_id": 566920, "author_profile": "https://Stackoverflow.com/users/566920", "pm_score": 2, "selected": false, "text": "<set> <script type=\"text/ecmascript\"> <![CDATA[\n\n function init(evt) {\n if ( window.svgDocument == null ) {\n // Define SGV\n svgDocument = evt.target.ownerDocument;\n }\n tooltip = svgDocument.getElementById('tooltip');\n }\n\n function ShowTooltip(evt) {\n // Put tooltip in the right position, change the text and make it visible\n tooltip.setAttributeNS(null,\"x\",evt.clientX+10);\n tooltip.setAttributeNS(null,\"y\",evt.clientY+30);\n tooltip.firstChild.data = evt.target.getAttributeNS(null,\"mouseovertext\");\n tooltip.setAttributeNS(null,\"visibility\",\"visible\");\n }\n\n function HideTooltip(evt) {\n tooltip.setAttributeNS(null,\"visibility\",\"hidden\");\n }\n ]]></script>\n onload=\"init(evt)\" <text id=\"tooltip\" x=\"0\" y=\"0\" visibility=\"hidden\">Tooltip</text>\n onmousemove=\"ShowTooltip(evt)\"\nonmouseout=\"HideTooltip(evt)\"\nmouseovertext=\"Whatever text you want to show\"\n <tspan>" }, { "answer_id": 12904788, "author": "Neil Fraser", "author_id": 154079, "author_profile": "https://Stackoverflow.com/users/154079", "pm_score": 6, "selected": false, "text": "<title>" }, { "answer_id": 18352578, "author": "Aravind Cheekkallur", "author_id": 2549636, "author_profile": "https://Stackoverflow.com/users/2549636", "pm_score": 1, "selected": false, "text": "nodeEnter.append(\"svg:element\")\n .style(\"fill\", function(d) { return d._children ? \"lightsteelblue\" : \"#fff\"; })\n .append(\"svg:title\")\n .text(function(d) {return d.Name+\"\\n\"+d.Age+\"\\n\"+d.Dept;}); // It shows the tool tip box with item [Name,Age,Dept] and upend to the svg dynamicaly\n" } ]
2008/09/19
[ "https://Stackoverflow.com/questions/102457", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2846/" ]
102,464
<p>Is their a way to access a web server such as windows server 2003 installed on a virtual box such as vmware from the host machine?</p>
[ { "answer_id": 59373777, "author": "slowlert", "author_id": 7071915, "author_profile": "https://Stackoverflow.com/users/7071915", "pm_score": 0, "selected": false, "text": "192.168.0.37 some.url-you.need\n" } ]
2008/09/19
[ "https://Stackoverflow.com/questions/102464", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18159/" ]
102,466
<p>We create thumb images on our server and I'm looking for a way to save metadata (text) in that image. Is that possible?</p> <p>At this moment we use <code>PHP</code> and we create <code>JPG</code> images.</p>
[ { "answer_id": 17890619, "author": "Matías Cánepa", "author_id": 702353, "author_profile": "https://Stackoverflow.com/users/702353", "pm_score": 2, "selected": false, "text": "<?\ndefine(\"IPTC_OBJECT_NAME\", \"005\");\ndefine(\"IPTC_EDIT_STATUS\", \"007\");\ndefine(\"IPTC_PRIORITY\", \"010\");\ndefine(\"IPTC_CATEGORY\", \"015\");\ndefine(\"IPTC_SUPPLEMENTAL_CATEGORY\", \"020\");\ndefine(\"IPTC_FIXTURE_IDENTIFIER\", \"022\");\ndefine(\"IPTC_KEYWORDS\", \"025\");\ndefine(\"IPTC_RELEASE_DATE\", \"030\");\ndefine(\"IPTC_RELEASE_TIME\", \"035\");\ndefine(\"IPTC_SPECIAL_INSTRUCTIONS\", \"040\");\ndefine(\"IPTC_REFERENCE_SERVICE\", \"045\");\ndefine(\"IPTC_REFERENCE_DATE\", \"047\");\ndefine(\"IPTC_REFERENCE_NUMBER\", \"050\");\ndefine(\"IPTC_CREATED_DATE\", \"055\");\ndefine(\"IPTC_CREATED_TIME\", \"060\");\ndefine(\"IPTC_ORIGINATING_PROGRAM\", \"065\");\ndefine(\"IPTC_PROGRAM_VERSION\", \"070\");\ndefine(\"IPTC_OBJECT_CYCLE\", \"075\");\ndefine(\"IPTC_BYLINE\", \"080\");\ndefine(\"IPTC_BYLINE_TITLE\", \"085\");\ndefine(\"IPTC_CITY\", \"090\");\ndefine(\"IPTC_PROVINCE_STATE\", \"095\");\ndefine(\"IPTC_COUNTRY_CODE\", \"100\");\ndefine(\"IPTC_COUNTRY\", \"101\");\ndefine(\"IPTC_ORIGINAL_TRANSMISSION_REFERENCE\", \"103\");\ndefine(\"IPTC_HEADLINE\", \"105\");\ndefine(\"IPTC_CREDIT\", \"110\");\ndefine(\"IPTC_SOURCE\", \"115\");\ndefine(\"IPTC_COPYRIGHT_STRING\", \"116\");\ndefine(\"IPTC_CAPTION\", \"120\");\ndefine(\"IPTC_LOCAL_CAPTION\", \"121\");\n\nclass IPTC\n{\n var $meta = [];\n var $file = null;\n\n function __construct($filename)\n {\n $info = null;\n\n $size = getimagesize($filename, $info);\n\n if(isset($info[\"APP13\"])) $this->meta = iptcparse($info[\"APP13\"]);\n\n $this->file = $filename;\n }\n\n function getValue($tag)\n {\n return isset($this->meta[\"2#$tag\"]) ? $this->meta[\"2#$tag\"][0] : \"\";\n }\n\n function setValue($tag, $data)\n {\n $this->meta[\"2#$tag\"] = [$data];\n\n $this->write();\n }\n\n private function write()\n {\n $mode = 0;\n\n $content = iptcembed($this->binary(), $this->file, $mode); \n\n $filename = $this->file;\n\n if(file_exists($this->file)) unlink($this->file);\n\n $fp = fopen($this->file, \"w\");\n fwrite($fp, $content);\n fclose($fp);\n } \n\n private function binary()\n {\n $data = \"\";\n\n foreach(array_keys($this->meta) as $key)\n {\n $tag = str_replace(\"2#\", \"\", $key);\n $data .= $this->iptc_maketag(2, $tag, $this->meta[$key][0]);\n } \n\n return $data;\n }\n\n function iptc_maketag($rec, $data, $value)\n {\n $length = strlen($value);\n $retval = chr(0x1C) . chr($rec) . chr($data);\n\n if($length < 0x8000)\n {\n $retval .= chr($length >> 8) . chr($length & 0xFF);\n }\n else\n {\n $retval .= chr(0x80) . \n chr(0x04) . \n chr(($length >> 24) & 0xFF) . \n chr(($length >> 16) & 0xFF) . \n chr(($length >> 8) & 0xFF) . \n chr($length & 0xFF);\n }\n\n return $retval . $value; \n } \n\n function dump()\n {\n echo \"<pre>\";\n print_r($this->meta);\n echo \"</pre>\";\n }\n\n #requires GD library installed\n function removeAllTags()\n {\n $this->meta = [];\n $img = imagecreatefromstring(implode(file($this->file)));\n if(file_exists($this->file)) unlink($this->file);\n imagejpeg($img, $this->file, 100);\n }\n}\n\n$file = \"photo.jpg\";\n$objIPTC = new IPTC($file);\n\n//set title\n$objIPTC->setValue(IPTC_HEADLINE, \"A title for this picture\");\n\n//set description\n$objIPTC->setValue(IPTC_CAPTION, \"Some words describing what can be seen in this picture.\");\n\necho $objIPTC->getValue(IPTC_HEADLINE);\n?>\n" } ]
2008/09/19
[ "https://Stackoverflow.com/questions/102466", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
102,468
<p>I'm trying to write a piece of code that will do the following:</p> <p>Take the numbers 0 to 9 and assign one or more letters to this number. For example:</p> <pre><code>0 = N, 1 = L, 2 = T, 3 = D, 4 = R, 5 = V or F, 6 = B or P, 7 = Z, 8 = H or CH or J, 9 = G </code></pre> <p>When I have a code like 0123, it's an easy job to encode it. It will obviously make up the code NLTD. When a number like 5,6 or 8 is introduced, things get different. A number like 051 would result in more than one possibility:</p> <p>NVL and NFL</p> <p>It should be obvious that this gets even &quot;worse&quot; with longer numbers that include several digits like 5,6 or 8.</p> <p>Being pretty bad at mathematics, I have not yet been able to come up with a decent solution that will allow me to feed the program a bunch of numbers and have it spit out all the possible letter combinations. So I'd love some help with it, 'cause I can't seem to figure it out. Dug up some information about permutations and combinations, but no luck.</p> <p>Thanks for any suggestions/clues. The language I need to write the code in is PHP, but any general hints would be highly appreciated.</p> <h3>Update:</h3> <p>Some more background: (and thanks a lot for the quick responses!)</p> <p>The idea behind my question is to build a script that will help people to easily convert numbers they want to remember to words that are far more easily remembered. This is sometimes referred to as &quot;pseudo-numerology&quot;.</p> <p>I want the script to give me all the possible combinations that are then held against a database of stripped words. These stripped words just come from a dictionary and have all the letters I mentioned in my question stripped out of them. That way, the number to be encoded can usually easily be related to a one or more database records. And when that happens, you end up with a list of words that you can use to remember the number you wanted to remember.</p>
[ { "answer_id": 102664, "author": "jdmichal", "author_id": 12275, "author_profile": "https://Stackoverflow.com/users/12275", "pm_score": 0, "selected": false, "text": "pn s nth pn+1 digit = s[n+1];\nforeach(letter l that digit maps to)\n{\n foreach(entry e in p(n))\n {\n newEntry = append l to e;\n add newEntry to p(n+1);\n }\n}\n p(0) = {N}\n digit = 5\nforeach({V, F})\n{\n foreach(p(0) = {N})\n {\n newEntry = N + V or N + F\n p(1) = {NV, NF}\n }\n}\n digit = 1\nforeach({L})\n{\n foreach(p(1) = {NV, NF})\n {\n newEntry = NV + L or NF + L\n p(2) = {NVL, NFL}\n }\n}\n" }, { "answer_id": 102676, "author": "Matthew Scharley", "author_id": 15537, "author_profile": "https://Stackoverflow.com/users/15537", "pm_score": 3, "selected": true, "text": "// 0 = N, 1 = L, 2 = T, 3 = D, 4 = R, 5 = V or F, 6 = B or P, 7 = Z, \n// 8 = H or CH or J, 9 = G\n$numberMap = new Array (\n 0 => new Array(\"N\"),\n 1 => new Array(\"L\"),\n 2 => new Array(\"T\"),\n 3 => new Array(\"D\"),\n 4 => new Array(\"R\"),\n 5 => new Array(\"V\", \"F\"),\n 6 => new Array(\"B\", \"P\"),\n 7 => new Array(\"Z\"),\n 8 => new Array(\"H\", \"CH\", \"J\"),\n 9 => new Array(\"G\"),\n);\n function GetEncoding($number) {\n $ret = new Array();\n for ($i = 0; $i < strlen($number); $i++) {\n // We're just translating here, nothing special.\n // $var + 0 is a cheap way of forcing a variable to be numeric\n $ret[] = $numberMap[$number[$i]+0];\n }\n}\n\nfunction PrintEncoding($enc, $string = \"\") {\n // If we're at the end of the line, then print!\n if (count($enc) === 0) {\n print $string.\"\\n\";\n return;\n }\n\n // Otherwise, soldier on through the possible values.\n // Grab the next 'letter' and cycle through the possibilities for it.\n foreach ($enc[0] as $letter) {\n // And call this function again with it!\n PrintEncoding(array_slice($enc, 1), $string.$letter);\n }\n}\n PrintEncoding(GetEncoding(\"052384\"));\n" }, { "answer_id": 102696, "author": "HenryR", "author_id": 2827, "author_profile": "https://Stackoverflow.com/users/2827", "pm_score": 0, "selected": false, "text": "function combinations( $str ){\n$l = len( $str );\n$results = array( );\nif ($l == 0) { return $results; }\nif ($l == 1)\n{ \n foreach( $codes[ $str[0] ] as $code )\n {\n $results[] = $code;\n }\n return $results;\n}\n$cur = $str[0];\n$combs = combinations( substr( $str, 1, $l ) );\nforeach ($codes[ $cur ] as $code)\n{\n foreach ($combs as $comb)\n {\n $results[] = $code.$comb;\n }\n}\nreturn $results;}\n" }, { "answer_id": 102886, "author": "J Miller", "author_id": 16976, "author_profile": "https://Stackoverflow.com/users/16976", "pm_score": 1, "selected": false, "text": "#!/usr/bin/env/python\n\nimport sys\n\nENCODING = {'0':['N'],\n '1':['L'],\n '2':['T'],\n '3':['D'],\n '4':['R'],\n '5':['V', 'F'],\n '6':['B', 'P'],\n '7':['Z'],\n '8':['H', 'CH', 'J'],\n '9':['G']\n }\n\ndef decode(str):\n if len(str) == 0:\n return ''\n elif len(str) == 1:\n return ENCODING[str]\n else:\n result = []\n for prefix in ENCODING[str[0]]:\n result.extend([prefix + suffix for suffix in decode(str[1:])])\n return result\n\nif __name__ == '__main__':\n print decode(sys.argv[1])\n $ ./demo 1\n['L']\n$ ./demo 051\n['NVL', 'NFL']\n$ ./demo 0518\n['NVLH', 'NVLCH', 'NVLJ', 'NFLH', 'NFLCH', 'NFLJ']\n" }, { "answer_id": 102957, "author": "ljorquera", "author_id": 9132, "author_profile": "https://Stackoverflow.com/users/9132", "pm_score": 2, "selected": false, "text": "@values = Hash.new([])\n\n\n@values[\"0\"] = [\"N\"] \n@values[\"1\"] = [\"L\"] \n@values[\"2\"] = [\"T\"] \n@values[\"3\"] = [\"D\"] \n@values[\"4\"] = [\"R\"] \n@values[\"5\"] = [\"V\",\"F\"] \n@values[\"6\"] = [\"B\",\"P\"] \n@values[\"7\"] = [\"Z\"] \n@values[\"8\"] = [\"H\",\"CH\",\"J\"] \n@values[\"9\"] = [\"G\"]\n\ndef find_valid_combinations(buffer,number)\n first_char = number.shift\n @values[first_char].each do |key|\n if(number.length == 0) then\n puts buffer + key\n else\n find_valid_combinations(buffer + key,number.dup)\n end\n end\nend\n\nfind_valid_combinations(\"\",ARGV[0].split(\"\"))\n $ ruby r.rb 051\nNVL\nNFL\n" }, { "answer_id": 103709, "author": "Nick Johnson", "author_id": 12030, "author_profile": "https://Stackoverflow.com/users/12030", "pm_score": 2, "selected": false, "text": "0 = N,\n1 = L,\n2 = T,\n3 = D,\n4 = R,\n5 = V or F,\n6 = B or P,\n7 = Z,\n8 = H or CH or J,\n9 = G\n N = 0,\nL = 1,\nT = 2,\nD = 3,\nR = 4,\nV = 5,\nF = 5,\nB = 6,\nP = 6,\nZ = 7,\nH = 8,\nJ = 8,\nG = 9\n" } ]
2008/09/19
[ "https://Stackoverflow.com/questions/102468", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18922/" ]
102,472
<p>When a branch is reintegrated to the trunk, is that branch effectively dead? </p> <p>Can you make modifications to the branch after the reintegration and merge those back into the trunk at a later date?</p>
[ { "answer_id": 113925, "author": "Mauli", "author_id": 917, "author_profile": "https://Stackoverflow.com/users/917", "pm_score": 2, "selected": false, "text": "/your_project\n /trunk\n /branches\n /tags\n /your_project\n /trunk\n /branches\n /1.0.0-bugfixes\n /tags\n /1.0.0\n /your_project\n /trunk\n /branches\n /1.0.0-bugfixes\n /tags\n /1.0.0\n /1.0.1\n /1.0.2\n svn merge http://rep/your_project/tag/1.0.0 http://rep/your_project/tag/1.0.2 .\n /your_project\n /trunk\n /branches\n /1.0.0-bugfixes\n /tags\n /1.0.0\n /1.0.1\n /1.0.2\n /1.0.3\n /1.0.4\n svn merge http://rep/your_project/tag/1.0.2 http://rep/your_project/tag/1.0.4 .\n /your_project\n /trunk\n /branches\n /1.0.0-bugfixes\n /1.1.0-bugfixes\n /tags\n /1.0.0\n /1.0.1\n /1.0.2\n /1.0.3\n /1.0.4\n /1.1.0\n" }, { "answer_id": 2330325, "author": "JW.", "author_id": 4321, "author_profile": "https://Stackoverflow.com/users/4321", "pm_score": 3, "selected": false, "text": "svn merge --record-only -c X url-to-trunk" }, { "answer_id": 2912394, "author": "krico", "author_id": 350836, "author_profile": "https://Stackoverflow.com/users/350836", "pm_score": 4, "selected": false, "text": "--record-only --reintegrate $ cd trunk\n$ svn merge --reintegrate ^my-branch \n$ svn commit\n\nCommitted revision 555. \n# This revision is ^^^^ important\n $ cd my-branch\n$ svn merge --record-only -c 555 ^trunk \n$ svn commit\n" }, { "answer_id": 34808241, "author": "bahrep", "author_id": 761095, "author_profile": "https://Stackoverflow.com/users/761095", "pm_score": 1, "selected": false, "text": "--reintegrate" } ]
2008/09/19
[ "https://Stackoverflow.com/questions/102472", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12969/" ]
102,483
<p>I am adding some user controls dynamically to a PlaceHolder server control. My user control consists of some labels and some textbox controls. </p> <p>When I submit the form and try to view the contents of the textboxes (within each user control) on the server, they are empty.</p> <p>When the postback completes, the textboxes have the data that I entered prior to postback. This tells me that the text in the boxes are being retained through ViewState. I just don't know why I can't find them when I'm debugging. </p> <p>Can someone please tell me why I would not be seeing the data the user entered on the server?</p> <p>Thanks for any help.</p>
[ { "answer_id": 102619, "author": "Chris Porter", "author_id": 13495, "author_profile": "https://Stackoverflow.com/users/13495", "pm_score": 1, "selected": false, "text": "Private dynControl As ASP.MyNamespace_MyControl_ascx\n dynControl = CType(LoadControl(\"~/MyNamespace/MyControl/MyControl.ascx\"), ASP.MyNamespace_MyControl_ascx)\n" }, { "answer_id": 1137518, "author": "Middletone", "author_id": 35331, "author_profile": "https://Stackoverflow.com/users/35331", "pm_score": 2, "selected": false, "text": "Protected Overrides Sub LoadViewState(ByVal savedState As Object)\n MyBase.LoadViewState(savedState)\n If IsPostBack Then\n CreateMyControls()\n End If\nEnd Sub\n" } ]
2008/09/19
[ "https://Stackoverflow.com/questions/102483", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10589/" ]
102,496
<p>We're developing a service that will accept a <code>POST</code> request. Some of the <code>POST</code> data will need to be encrypted before the <code>POST</code> as it will be stored in hidden fields on a form.</p> <p>The application is written in C#, but we want third party clients to be able to easily integrate with it. We find that most clients use PHP, Classic ASP or VB.Net.</p> <p>The third parties should only be doing the encryption. We'd do the decryption. There is no two-way communication.</p> <p>What are the most compatible combinations of encryption algorithm, padding mode and other options?</p>
[ { "answer_id": 108664, "author": "Ian P", "author_id": 10853, "author_profile": "https://Stackoverflow.com/users/10853", "pm_score": 1, "selected": false, "text": "function XOREncryption($InputString, $KeyPhrase){\n\n $KeyPhraseLength = strlen($KeyPhrase);\n\n for ($i = 0; $i < strlen($InputString); $i++){\n\n $rPos = $i % $KeyPhraseLength;\n\n $r = ord($InputString[$i]) ^ ord($KeyPhrase[$rPos]);\n\n $InputString[$i] = chr($r);\n }\n\n return $InputString;\n}\n" }, { "answer_id": 108754, "author": "Peter Boughton", "author_id": 9360, "author_profile": "https://Stackoverflow.com/users/9360", "pm_score": 1, "selected": false, "text": "Key = generateSecretKey( 'AES' , 128 )\n\nEncryptedText = encrypt( Text , Key , 'AES' , 'Hex' )\n\nText = decrypt( EncryptedText , Key, 'AES' , 'Hex' )\n" } ]
2008/09/19
[ "https://Stackoverflow.com/questions/102496", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11503/" ]
102,521
<p>I know that <a href="http://wiki.lessthandot.com/index.php/How_to_find_the_first_and_last_days_in_years,_months_etc" rel="nofollow noreferrer">Sql Server has some handy built-in quarterly</a> stuff, but what about the .Net native <a href="http://msdn.microsoft.com/en-us/library/system.datetime_members(VS.80).aspx" rel="nofollow noreferrer">DateTime</a> object? What is the best way to add, subtract, and traverse quarters?</p> <p>Is it a <em>bad thing</em>™ to use the VB-specific <a href="http://msdn.microsoft.com/en-us/library/hcxe65wz(VS.80).aspx" rel="nofollow noreferrer">DateAdd()</a> function? e.g.:</p> <pre><code>Dim nextQuarter As DateTime = DateAdd(DateInterval.Quarter, 1, DateTime.Now) </code></pre> <p>Edit: Expanding @bslorence's function:</p> <pre><code>Public Shared Function AddQuarters(ByVal originalDate As DateTime, ByVal quarters As Integer) As Datetime Return originalDate.AddMonths(quarters * 3) End Function </code></pre> <p>Expanding @Matt's function:</p> <pre><code>Public Shared Function GetQuarter(ByVal fromDate As DateTime) As Integer Return ((fromDate.Month - 1) \ 3) + 1 End Function </code></pre> <p>Edit: here's a couple more functions that were handy:</p> <pre><code>Public Shared Function GetFirstDayOfQuarter(ByVal originalDate As DateTime) As DateTime Return AddQuarters(New DateTime(originalDate.Year, 1, 1), GetQuarter(originalDate) - 1) End Function Public Shared Function GetLastDayOfQuarter(ByVal originalDate As DateTime) As DateTime Return AddQuarters(New DateTime(originalDate.Year, 1, 1), GetQuarter(originalDate)).AddDays(-1) End Function </code></pre>
[ { "answer_id": 102712, "author": "Ben Dunlap", "author_id": 8722, "author_profile": "https://Stackoverflow.com/users/8722", "pm_score": 2, "selected": false, "text": "Dim nextQuarter As DateTime = DateTime.Now.AddMonths(3);\n" }, { "answer_id": 102834, "author": "Matt Blaine", "author_id": 16272, "author_profile": "https://Stackoverflow.com/users/16272", "pm_score": 4, "selected": true, "text": "Dim quarter As Integer = (someDate.Month - 1) \\ 3 + 1\n" }, { "answer_id": 14160623, "author": "Brian Schmidt", "author_id": 1902195, "author_profile": "https://Stackoverflow.com/users/1902195", "pm_score": 1, "selected": false, "text": "Public Function GetLastQuarterStart() As Date\n\n GetLastQuarterStart = DateAdd(DateInterval.Quarter, -1, DateTime.Now).ToString(\"MM/01/yyyy\")\n\nEnd Function\n\nPublic Function GetLastQuarterEnd() As Date\n\n Dim LastQuarterStart As Date = DateAdd(DateInterval.Quarter, -1, DateTime.Now).ToString(\"MM/01/yyyy\")\n Dim MM As String = LastQuarterStart.Month\n Dim DD As Integer = 0\n Dim YYYY As String = LastQuarterStart.Year\n Select Case MM\n Case \"01\", \"03\", \"05\", \"07\", \"08\", \"10\", \"12\"\n DD = 31\n Case \"02\"\n Select Case YYYY\n Case \"2012\", \"2016\", \"2020\", \"2024\", \"2028\", \"2032\"\n DD = 29\n Case Else\n DD = 28\n End Select\n Case Else\n DD = 30\n End Select\n\n Dim LastQuarterEnd As Date = DateAdd(DateInterval.Month, 2, LastQuarterStart)\n\n MM = LastQuarterEnd.Month\n YYYY = LastQuarterEnd.Year\n\n Return String.Format(\"{0}/{1}/{2}\", MM, DD, YYYY)\n\nEnd Function\n" }, { "answer_id": 21579910, "author": "Jamie Barker", "author_id": 2117156, "author_profile": "https://Stackoverflow.com/users/2117156", "pm_score": 1, "selected": false, "text": "Dim intQuarter As Integer = Math.Ceiling(MyDate.Month / 3)\n" } ]
2008/09/19
[ "https://Stackoverflow.com/questions/102521", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1414/" ]
102,523
<p>I am a big fan of the light colors on a dark background color scheme for programming - which is unfortunately not what Quest's Toad comes with by default. </p> <p>I notice that it is possible to export and import settings under the language management window, and I know that Toad has a large level of community involvement. So I assume there must be some location where people are posting their custom coloring schemes. However, in part because I don't know what the Toad guys call them (skins? colorization? themes?) and in part because its so hard to Google Toad +skins I cannot for the life of me find them.</p> <p>Does anyone know if there is such a place so I don't have to set the colors by hand?</p>
[ { "answer_id": 8763905, "author": "one.beat.consumer", "author_id": 146610, "author_profile": "https://Stackoverflow.com/users/146610", "pm_score": 4, "selected": true, "text": ".dvtcolortheme \"Color Theme\" \"DWT Color Theme\" .dwtcolortheme" }, { "answer_id": 54554825, "author": "ylondono", "author_id": 4143968, "author_profile": "https://Stackoverflow.com/users/4143968", "pm_score": 2, "selected": false, "text": "C:\\Users\\[YOUR_USER]\\AppData\\Roaming\\Quest Software\\Toad for Oracle\\13.1\\User Files\n" } ]
2008/09/19
[ "https://Stackoverflow.com/questions/102523", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5056/" ]
102,531
<p>Within an XSLT document, is it possible to loop over a set of files in the current directory?</p> <p>I have a situation where I have a directory full of xml files that need some analysis done to generate a report. I have my stylesheet operating on a single document fine, but I'd like to extend that without going to another tool to merge the xml documents. </p> <p>I was thinking along these lines:</p> <pre><code>&lt;xsl:for-each select="{IO Selector Here}"&gt; &lt;xsl:variable select="document(@url)" name="contents" /&gt; &lt;!--More stuff here--&gt; &lt;/xsl:for-each&gt; </code></pre>
[ { "answer_id": 102944, "author": "Dave DuPlantis", "author_id": 8174, "author_profile": "https://Stackoverflow.com/users/8174", "pm_score": 0, "selected": false, "text": "document()" }, { "answer_id": 104760, "author": "JeniT", "author_id": 6739, "author_profile": "https://Stackoverflow.com/users/6739", "pm_score": 4, "selected": true, "text": "collection() <xsl:for-each select=\"file:///path/to/directory\">\n <!-- process the documents -->\n</xsl:for-each>\n" } ]
2008/09/19
[ "https://Stackoverflow.com/questions/102531", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1672/" ]
102,534
<p>Here is the situation: I have 2 pages.</p> <p>What I want is to have a number of text links(<code>&lt;a href=""&gt;</code>) on page 1 all directing to page 2, but I want each link to send a different value.</p> <p>On page 2 I want to show that value like this: </p> <blockquote> <p>Hello you clicked {value}</p> </blockquote> <p>Another point to take into account is that I can't use any php in this situation, just html.</p>
[ { "answer_id": 102565, "author": "Craig", "author_id": 7861, "author_profile": "https://Stackoverflow.com/users/7861", "pm_score": 2, "selected": false, "text": "var qs = new Querystring();\nvar v1 = qs.get(\"ValueName\")\n" }, { "answer_id": 102577, "author": "Stephen Wrighton", "author_id": 7516, "author_profile": "https://Stackoverflow.com/users/7516", "pm_score": 1, "selected": false, "text": "var tabvalue = getQueryVariable(\"foo\"); \n\nfunction getQueryVariable(variable)\n{\nvar query = window.location.search.substring(1);\nvar vars = query.split(\"&\");\nfor (var i=0;i<vars.length;i++)\n{\nvar pair = vars[i].split(\"=\");\nif (pair[0] == variable)\n{\nreturn pair[1];\n}\n}\n}\n" }, { "answer_id": 102651, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "http://www.example.com/example.html?argument=value\n\nvar queryString = document.location.search();\nvar parts = queryString.split('=');\ndocument.write(parts[0]); // The argument name\ndocument.write(parts[1]); // The value\n" }, { "answer_id": 102660, "author": "jelmer", "author_id": 16499, "author_profile": "https://Stackoverflow.com/users/16499", "pm_score": 0, "selected": false, "text": "localhost/index.php?myvar=Hello World\n $myvar =$_GET['myvar'];\n" }, { "answer_id": 23451965, "author": "user3555228", "author_id": 3555228, "author_profile": "https://Stackoverflow.com/users/3555228", "pm_score": 0, "selected": false, "text": "<?\n\n$passthis = \"See you on the other side\";\n\necho '<form action=\"whereyouwantittogo.php\" target=\"_blank\" method=\"post\">'.\n'<input type=\"text\" name=\"passthis1\" value=\"'.\n$passthis .' \" /> '.\n'<button type=\"Submit\" value=\"Submit\" >Submit</button>'.\n'</form>';\n\n?>\n <?\n\n$thispassed = $_POST['passthis1'];\n\necho '<textarea>'. $thispassed .'</textarea>';\necho $thispassed;\n\n?>\n" } ]
2008/09/19
[ "https://Stackoverflow.com/questions/102534", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
102,535
<p>I'm starting to learn Python and I've come across generator functions, those that have a yield statement in them. I want to know what types of problems that these functions are really good at solving.</p>
[ { "answer_id": 102632, "author": "Thomas Wouters", "author_id": 17624, "author_profile": "https://Stackoverflow.com/users/17624", "pm_score": 9, "selected": true, "text": "big_list = list(the_generator)\n" }, { "answer_id": 102634, "author": "nosklo", "author_id": 17160, "author_profile": "https://Stackoverflow.com/users/17160", "pm_score": 7, "selected": false, "text": "# function version\ndef fibon(n):\n a = b = 1\n result = []\n for i in xrange(n):\n result.append(a)\n a, b = b, a + b\n return result\n # generator version\ndef fibon(n):\n a = b = 1\n for i in xrange(n):\n yield a\n a, b = b, a + b\n for x in fibon(1000000):\n print x,\n" }, { "answer_id": 102667, "author": "S.Lott", "author_id": 10661, "author_profile": "https://Stackoverflow.com/users/10661", "pm_score": 4, "selected": false, "text": "def filter2sharps( aSequence ):\n for l in aSequence:\n if l.startswith(\"##\"):\n yield l\n source= file( ... )\nfor line in filter2sharps( source.readlines() ):\n print line\nsource.close()\n <Location>...</Location> def reduceLocation( aSequence ):\n keep= False\n block= None\n for line in aSequence:\n if line.startswith(\"</Location\"):\n block.append( line )\n yield block\n block= None\n keep= False\n elif line.startsWith(\"<Location\"):\n block= [ line ]\n keep= True\n elif keep:\n block.append( line )\n else:\n pass\n if block is not None:\n yield block # A partial block, icky\n source = file( ... )\nfor b in reduceLocation( source.readlines() ):\n print b\nsource.close()\n" }, { "answer_id": 102674, "author": "Rafał Dowgird", "author_id": 12166, "author_profile": "https://Stackoverflow.com/users/12166", "pm_score": 5, "selected": false, "text": "def bufferedFetch():\n while True:\n buffer = getBigChunkOfData()\n # insert some code to break on 'end of data'\n for i in buffer: \n yield i\n" }, { "answer_id": 102679, "author": "Nick Johnson", "author_id": 12030, "author_profile": "https://Stackoverflow.com/users/12030", "pm_score": 2, "selected": false, "text": "def primes():\n primes_found = set()\n primes_found.add(2)\n yield 2\n for i in itertools.count(1):\n candidate = i * 2 + 1\n if not all(candidate % prime for prime in primes_found):\n primes_found.add(candidate)\n yield candidate\n def prime_products():\n primeiter = primes()\n prev = primeiter.next()\n for prime in primeiter:\n yield prime * prev\n prev = prime\n" }, { "answer_id": 102682, "author": "dF.", "author_id": 3002, "author_profile": "https://Stackoverflow.com/users/3002", "pm_score": 4, "selected": false, "text": "for for item in iterable:\n do_stuff()\n iterable for command in user_input():\n do_stuff_with(command)\n def user_input():\n while True:\n wait_for_command()\n cmd = get_command()\n yield cmd\n" }, { "answer_id": 740763, "author": "Andz", "author_id": 89848, "author_profile": "https://Stackoverflow.com/users/89848", "pm_score": 5, "selected": false, "text": "def fib():\n first = 0\n second = 1\n yield first\n yield second\n\n while 1:\n next = first + second\n yield next\n first = second\n second = next\n\nfibgen1 = fib()\nfibgen2 = fib()\n >>> fibgen1.next(); fibgen1.next(); fibgen1.next(); fibgen1.next()\n0\n1\n1\n2\n>>> fibgen2.next(); fibgen2.next()\n0\n1\n>>> fibgen1.next(); fibgen1.next()\n3\n5\n for" }, { "answer_id": 14394854, "author": "Mirage", "author_id": 767244, "author_profile": "https://Stackoverflow.com/users/767244", "pm_score": 6, "selected": false, "text": "Generators yield resume the function generators yield function def generate_integers(N):\n for i in xrange(N):\n yield i\n In [1]: gen = generate_integers(3)\n In [2]: gen\n <generator object at 0x8117f90>\n In [3]: gen.next()\n 0\n In [4]: gen.next()\n 1\n In [5]: gen.next()\n return yield yield" }, { "answer_id": 23334878, "author": "John Damen", "author_id": 2829389, "author_profile": "https://Stackoverflow.com/users/2829389", "pm_score": 3, "selected": false, "text": "def test():\n for i in xrange(5):\n val = yield\n print(val)\n\nt = test()\n\n# Proceed to 'yield' statement\nnext(t)\n\n# Send value to yield\nt.send(1)\nt.send('2')\nt.send([3])\n yield" }, { "answer_id": 23530101, "author": "PrivateUser", "author_id": 736037, "author_profile": "https://Stackoverflow.com/users/736037", "pm_score": 6, "selected": false, "text": "domains domain SELECT domain FROM domains def ResultGenerator(cursor, batchsize=1000):\n while True:\n results = cursor.fetchmany(batchsize)\n if not results:\n break\n for result in results:\n yield result\n yield return yield return - returns only once\nyield - returns multiple times\n yield db = MySQLdb.connect(host=\"localhost\", user=\"root\", passwd=\"root\", db=\"domains\")\ncursor = db.cursor()\ncursor.execute(\"SELECT domain FROM domains\")\nfor result in ResultGenerator(cursor):\n doSomethingWith(result)\ndb.close()\n" }, { "answer_id": 26074771, "author": "Pithikos", "author_id": 474563, "author_profile": "https://Stackoverflow.com/users/474563", "pm_score": 4, "selected": false, "text": "class Rect():\n\n def __init__(self, x, y, width, height):\n self.l_top = (x, y)\n self.r_top = (x+width, y)\n self.r_bot = (x+width, y+height)\n self.l_bot = (x, y+height)\n\n def __iter__(self):\n yield self.l_top\n yield self.r_top\n yield self.r_bot\n yield self.l_bot\n myrect=Rect(50, 50, 100, 100)\nfor corner in myrect:\n print(corner)\n __iter__ iter_corners for corner in myrect.iter_corners() __iter__ for" }, { "answer_id": 46366711, "author": "Sébastien Wieckowski", "author_id": 8275142, "author_profile": "https://Stackoverflow.com/users/8275142", "pm_score": 0, "selected": false, "text": "def genprime(n=10):\n for num in range(3, n+1):\n for factor in range(2, num):\n if num%factor == 0:\n break\n else:\n yield(num)\n\nfor prime_num in genprime(100):\n print(prime_num)\n" } ]
2008/09/19
[ "https://Stackoverflow.com/questions/102535", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4834/" ]
102,547
<p>I am trying to add a new hello world service to amfphp, I am developing locally</p> <pre><code>&lt;?php /** * First tutorial class */ class HelloWorld { /** * first simple method * @returns a string saying 'Hello World!' */ function sayHello() { return "Hello World!"; } } ?&gt; </code></pre> <p>when exploring in the amfphp browser i get a "TypeError: Error #1009: Cannot access a property or method of a null object reference." need help...</p>
[ { "answer_id": 104232, "author": "defmeta", "author_id": 10875, "author_profile": "https://Stackoverflow.com/users/10875", "pm_score": 1, "selected": false, "text": "<?php\n\nclass Products {\n\n public function __construct() {\n mysql_connect(\"localhost\", \"myuser\", \"mypass\");\n mysql_select_db(\"mydb\");\n }\n /** \n * Retrieves data\n * @returns data\n */\n function getProduct() {\n $sql = 'SELECT * FROM `content_type_product`'; \n return mysql_query($sql);\n }\n}\n?>\n" } ]
2008/09/19
[ "https://Stackoverflow.com/questions/102547", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
102,558
<p>What are some of the advantages of using one over the other?</p>
[ { "answer_id": 2535340, "author": "En.", "author_id": 298793, "author_profile": "https://Stackoverflow.com/users/298793", "pm_score": 1, "selected": false, "text": "bool IMyView.IsAdminSectionVisible{\n get{return pnlAdmin.Visible;}\n get{pnlAdmin.Visible=value;}\n }\n" }, { "answer_id": 5997449, "author": "Jason", "author_id": 752994, "author_profile": "https://Stackoverflow.com/users/752994", "pm_score": 2, "selected": false, "text": " [HttpGet]\n public ActionResult DetailList(ImportDetailSearchModel model)\n {\n Data.ImportDataAccess ida = new Data.ImportDataAccess();\n List<Data.ImportDetailData> data = ida.GetImportDetails(model.FileId, model.FailuresOnly);\n\n return PartialView(\"ImportSummaryDetailPartial\", data);\n }\n <table class=\"sortable\">\n<thead>\n <tr><th>Unique Id</th><th class=\"left\">Error Type</th><th class=\"left\">Field</th><th class=\"left\">Message</th><th class=\"left\">State</th></tr>\n</thead>\n<tbody>\n @foreach (Data.ImportDetailData detail in Model)\n {\n <tr><th>@detail.UniqueID</th><th class=\"left\">@detail.ErrorType</th><th class=\"left\">@detail.FieldName</th><th class=\"left\">@detail.Message</th><th class=\"left\">@detail.ItemState</th></tr>\n }\n</tbody></table>\n" }, { "answer_id": 7539822, "author": "Nitin Sawant", "author_id": 223752, "author_profile": "https://Stackoverflow.com/users/223752", "pm_score": 0, "selected": false, "text": "CODE BLOCKS HTML" } ]
2008/09/19
[ "https://Stackoverflow.com/questions/102558", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18931/" ]
102,567
<p>What's the best way to shut down the computer from a C# program?</p> <p>I've found a few methods that work - I'll post them below - but none of them are very elegant. I'm looking for something that's simpler and natively .net.</p>
[ { "answer_id": 102580, "author": "RichS", "author_id": 6247, "author_profile": "https://Stackoverflow.com/users/6247", "pm_score": 3, "selected": false, "text": "shutdown -s -t 0 shutdown -r -t 0" }, { "answer_id": 102583, "author": "roomaroo", "author_id": 3464, "author_profile": "https://Stackoverflow.com/users/3464", "pm_score": 7, "selected": true, "text": "using System.Management;\n\nvoid Shutdown()\n{\n ManagementBaseObject mboShutdown = null;\n ManagementClass mcWin32 = new ManagementClass(\"Win32_OperatingSystem\");\n mcWin32.Get();\n\n // You can't shutdown without security privileges\n mcWin32.Scope.Options.EnablePrivileges = true;\n ManagementBaseObject mboShutdownParams =\n mcWin32.GetMethodParameters(\"Win32Shutdown\");\n\n // Flag 1 means we want to shut down the system. Use \"2\" to reboot.\n mboShutdownParams[\"Flags\"] = \"1\";\n mboShutdownParams[\"Reserved\"] = \"0\";\n foreach (ManagementObject manObj in mcWin32.GetInstances())\n {\n mboShutdown = manObj.InvokeMethod(\"Win32Shutdown\", \n mboShutdownParams, null);\n }\n}\n" }, { "answer_id": 102596, "author": "roomaroo", "author_id": 3464, "author_profile": "https://Stackoverflow.com/users/3464", "pm_score": 4, "selected": false, "text": " using System.Diagnostics;\n\n void Shutdown()\n {\n Process.Start(\"shutdown.exe\", \"-s -t 00\");\n }\n" }, { "answer_id": 102598, "author": "Stephen Wrighton", "author_id": 7516, "author_profile": "https://Stackoverflow.com/users/7516", "pm_score": 5, "selected": false, "text": "using System.Runtime.InteropServices;\n\n[StructLayout(LayoutKind.Sequential, Pack=1)]\ninternal struct TokPriv1Luid\n{\n public int Count;\n public long Luid;\n public int Attr;\n}\n\n[DllImport(\"kernel32.dll\", ExactSpelling=true) ]\ninternal static extern IntPtr GetCurrentProcess();\n\n[DllImport(\"advapi32.dll\", ExactSpelling=true, SetLastError=true) ]\ninternal static extern bool OpenProcessToken( IntPtr h, int acc, ref IntPtr\nphtok );\n\n[DllImport(\"advapi32.dll\", SetLastError=true) ]\ninternal static extern bool LookupPrivilegeValue( string host, string name,\nref long pluid );\n\n[DllImport(\"advapi32.dll\", ExactSpelling=true, SetLastError=true) ]\ninternal static extern bool AdjustTokenPrivileges( IntPtr htok, bool disall,\nref TokPriv1Luid newst, int len, IntPtr prev, IntPtr relen );\n\n[DllImport(\"user32.dll\", ExactSpelling=true, SetLastError=true) ]\ninternal static extern bool ExitWindowsEx( int flg, int rea );\n\ninternal const int SE_PRIVILEGE_ENABLED = 0x00000002;\ninternal const int TOKEN_QUERY = 0x00000008;\ninternal const int TOKEN_ADJUST_PRIVILEGES = 0x00000020;\ninternal const string SE_SHUTDOWN_NAME = \"SeShutdownPrivilege\";\ninternal const int EWX_LOGOFF = 0x00000000;\ninternal const int EWX_SHUTDOWN = 0x00000001;\ninternal const int EWX_REBOOT = 0x00000002;\ninternal const int EWX_FORCE = 0x00000004;\ninternal const int EWX_POWEROFF = 0x00000008;\ninternal const int EWX_FORCEIFHUNG = 0x00000010;\n\nprivate void DoExitWin( int flg )\n{\n bool ok;\n TokPriv1Luid tp;\n IntPtr hproc = GetCurrentProcess();\n IntPtr htok = IntPtr.Zero;\n ok = OpenProcessToken( hproc, TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, ref htok );\n tp.Count = 1;\n tp.Luid = 0;\n tp.Attr = SE_PRIVILEGE_ENABLED;\n ok = LookupPrivilegeValue( null, SE_SHUTDOWN_NAME, ref tp.Luid );\n ok = AdjustTokenPrivileges( htok, false, ref tp, 0, IntPtr.Zero, IntPtr.Zero );\n ok = ExitWindowsEx( flg, 0 );\n }\n DoExitWin( EWX_SHUTDOWN );\n DoExitWin( EWX_REBOOT );\n" }, { "answer_id": 102628, "author": "roomaroo", "author_id": 3464, "author_profile": "https://Stackoverflow.com/users/3464", "pm_score": 4, "selected": false, "text": "ExitWindowsEx using System.Runtime.InteropServices;\n\nvoid Shutdown2()\n{\n const string SE_SHUTDOWN_NAME = \"SeShutdownPrivilege\";\n const short SE_PRIVILEGE_ENABLED = 2;\n const uint EWX_SHUTDOWN = 1;\n const short TOKEN_ADJUST_PRIVILEGES = 32;\n const short TOKEN_QUERY = 8;\n IntPtr hToken;\n TOKEN_PRIVILEGES tkp;\n\n // Get shutdown privileges...\n OpenProcessToken(Process.GetCurrentProcess().Handle, \n TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, out hToken);\n tkp.PrivilegeCount = 1;\n tkp.Privileges.Attributes = SE_PRIVILEGE_ENABLED;\n LookupPrivilegeValue(\"\", SE_SHUTDOWN_NAME, out tkp.Privileges.pLuid);\n AdjustTokenPrivileges(hToken, false, ref tkp, 0U, IntPtr.Zero, \n IntPtr.Zero);\n\n // Now we have the privileges, shutdown Windows\n ExitWindowsEx(EWX_SHUTDOWN, 0);\n}\n\n// Structures needed for the API calls\nprivate struct LUID\n{\n public int LowPart;\n public int HighPart;\n}\nprivate struct LUID_AND_ATTRIBUTES\n{\n public LUID pLuid;\n public int Attributes;\n}\nprivate struct TOKEN_PRIVILEGES\n{\n public int PrivilegeCount;\n public LUID_AND_ATTRIBUTES Privileges;\n}\n\n[DllImport(\"advapi32.dll\")]\nstatic extern int OpenProcessToken(IntPtr ProcessHandle, \n int DesiredAccess, out IntPtr TokenHandle);\n\n[DllImport(\"advapi32.dll\", SetLastError = true)]\n[return: MarshalAs(UnmanagedType.Bool)]\nstatic extern bool AdjustTokenPrivileges(IntPtr TokenHandle,\n [MarshalAs(UnmanagedType.Bool)]bool DisableAllPrivileges,\n ref TOKEN_PRIVILEGES NewState,\n UInt32 BufferLength,\n IntPtr PreviousState,\n IntPtr ReturnLength);\n\n[DllImport(\"advapi32.dll\")]\nstatic extern int LookupPrivilegeValue(string lpSystemName, \n string lpName, out LUID lpLuid);\n\n[DllImport(\"user32.dll\", SetLastError = true)]\nstatic extern int ExitWindowsEx(uint uFlags, uint dwReason);\n" }, { "answer_id": 104258, "author": "Pop Catalin", "author_id": 4685, "author_profile": "https://Stackoverflow.com/users/4685", "pm_score": 8, "selected": false, "text": "Process.Start(\"shutdown\",\"/s /t 0\");\n var psi = new ProcessStartInfo(\"shutdown\",\"/s /t 0\");\npsi.CreateNoWindow = true;\npsi.UseShellExecute = false;\nProcess.Start(psi);\n" }, { "answer_id": 665422, "author": "lakshmanaraj", "author_id": 44541, "author_profile": "https://Stackoverflow.com/users/44541", "pm_score": 5, "selected": false, "text": "System.Diagnostics.Process.Start(\"Shutdown\", \"-s -t 10\");" }, { "answer_id": 948656, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "Using System.Diagnostics;\n {\n Process.Start(\"Shutdown\",\"-i\");\n}\n" }, { "answer_id": 5109179, "author": "MisterEd", "author_id": 632931, "author_profile": "https://Stackoverflow.com/users/632931", "pm_score": 2, "selected": false, "text": "[STAThread]\npublic static void Main(string[] args) {\n Shutdown();\n}\n using System.Management;\nusing System.Threading;\n\npublic static class Program {\n\n [STAThread]\n public static void Main(string[] args) {\n Thread t = new Thread(new ThreadStart(Program.Shutdown));\n t.SetApartmentState(ApartmentState.STA);\n t.Start();\n ...\n }\n\n public static void Shutdown() {\n // roomaroo's code\n }\n}\n" }, { "answer_id": 6929504, "author": "unbob", "author_id": 876993, "author_profile": "https://Stackoverflow.com/users/876993", "pm_score": 3, "selected": false, "text": "shutdown.exe InitiateSystemShutdownEx ExitWindowsEx" }, { "answer_id": 6956451, "author": "Fazil Mir", "author_id": 880588, "author_profile": "https://Stackoverflow.com/users/880588", "pm_score": 2, "selected": false, "text": "using System;\nusing System.Collections.Generic;\nusing System.ComponentModel;\nusing System.Data;\nusing System.Drawing;\nusing System.Text;\nusing System.Windows.Forms;\n// Remember to add a reference to the System.Management assembly\nusing System.Management;\nusing System.Diagnostics;\n\nnamespace ShutDown\n{\n public partial class Form1 : Form\n {\n public Form1()\n {\n InitializeComponent();\n }\n\n private void btnShutDown_Click(object sender, EventArgs e)\n {\n ManagementBaseObject mboShutdown = null;\n ManagementClass mcWin32 = new ManagementClass(\"Win32_OperatingSystem\");\n mcWin32.Get();\n\n // You can't shutdown without security privileges\n mcWin32.Scope.Options.EnablePrivileges = true;\n ManagementBaseObject mboShutdownParams = mcWin32.GetMethodParameters(\"Win32Shutdown\");\n\n // Flag 1 means we want to shut down the system\n mboShutdownParams[\"Flags\"] = \"1\";\n mboShutdownParams[\"Reserved\"] = \"0\";\n\n foreach (ManagementObject manObj in mcWin32.GetInstances())\n {\n mboShutdown = manObj.InvokeMethod(\"Win32Shutdown\", mboShutdownParams, null);\n }\n }\n }\n}\n" }, { "answer_id": 10683826, "author": "m3z", "author_id": 289545, "author_profile": "https://Stackoverflow.com/users/289545", "pm_score": 3, "selected": false, "text": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\nusing System.Management;\nusing System.Runtime.InteropServices;\nusing System.Security;\nusing System.Diagnostics;\n\nnamespace PowerControl\n{\n public class PowerControl_Main\n {\n\n\n public void Shutdown()\n {\n ManagementBaseObject mboShutdown = null;\n ManagementClass mcWin32 = new ManagementClass(\"Win32_OperatingSystem\");\n mcWin32.Get();\n\n if (!TokenAdjuster.EnablePrivilege(\"SeShutdownPrivilege\", true))\n {\n Console.WriteLine(\"Could not enable SeShutdownPrivilege\");\n }\n else\n {\n Console.WriteLine(\"Enabled SeShutdownPrivilege\");\n }\n\n // You can't shutdown without security privileges\n mcWin32.Scope.Options.EnablePrivileges = true;\n ManagementBaseObject mboShutdownParams = mcWin32.GetMethodParameters(\"Win32Shutdown\");\n\n // Flag 1 means we want to shut down the system\n mboShutdownParams[\"Flags\"] = \"1\";\n mboShutdownParams[\"Reserved\"] = \"0\";\n\n foreach (ManagementObject manObj in mcWin32.GetInstances())\n {\n try\n {\n mboShutdown = manObj.InvokeMethod(\"Win32Shutdown\",\n mboShutdownParams, null);\n }\n catch (ManagementException mex)\n {\n Console.WriteLine(mex.ToString());\n Console.ReadKey();\n }\n }\n }\n\n\n }\n\n\n public sealed class TokenAdjuster\n {\n // PInvoke stuff required to set/enable security privileges\n [DllImport(\"advapi32\", SetLastError = true),\n SuppressUnmanagedCodeSecurityAttribute]\n static extern int OpenProcessToken(\n System.IntPtr ProcessHandle, // handle to process\n int DesiredAccess, // desired access to process\n ref IntPtr TokenHandle // handle to open access token\n );\n\n [DllImport(\"kernel32\", SetLastError = true),\n SuppressUnmanagedCodeSecurityAttribute]\n static extern bool CloseHandle(IntPtr handle);\n\n [DllImport(\"advapi32.dll\", CharSet = CharSet.Auto, SetLastError = true)]\n static extern int AdjustTokenPrivileges(\n IntPtr TokenHandle,\n int DisableAllPrivileges,\n IntPtr NewState,\n int BufferLength,\n IntPtr PreviousState,\n ref int ReturnLength);\n\n [DllImport(\"advapi32.dll\", CharSet = CharSet.Auto, SetLastError = true)]\n static extern bool LookupPrivilegeValue(\n string lpSystemName,\n string lpName,\n ref LUID lpLuid);\n\n [StructLayout(LayoutKind.Sequential)]\n internal struct LUID\n {\n internal int LowPart;\n internal int HighPart;\n }\n\n [StructLayout(LayoutKind.Sequential)]\n struct LUID_AND_ATTRIBUTES\n {\n LUID Luid;\n int Attributes;\n }\n\n [StructLayout(LayoutKind.Sequential)]\n struct _PRIVILEGE_SET\n {\n int PrivilegeCount;\n int Control;\n [MarshalAs(UnmanagedType.ByValArray, SizeConst = 1)] // ANYSIZE_ARRAY = 1\n LUID_AND_ATTRIBUTES[] Privileges;\n }\n\n [StructLayout(LayoutKind.Sequential)]\n internal struct TOKEN_PRIVILEGES\n {\n internal int PrivilegeCount;\n [MarshalAs(UnmanagedType.ByValArray, SizeConst = 3)]\n internal int[] Privileges;\n }\n const int SE_PRIVILEGE_ENABLED = 0x00000002;\n const int TOKEN_ADJUST_PRIVILEGES = 0X00000020;\n const int TOKEN_QUERY = 0X00000008;\n const int TOKEN_ALL_ACCESS = 0X001f01ff;\n const int PROCESS_QUERY_INFORMATION = 0X00000400;\n\n public static bool EnablePrivilege(string lpszPrivilege, bool\n bEnablePrivilege)\n {\n bool retval = false;\n int ltkpOld = 0;\n IntPtr hToken = IntPtr.Zero;\n TOKEN_PRIVILEGES tkp = new TOKEN_PRIVILEGES();\n tkp.Privileges = new int[3];\n TOKEN_PRIVILEGES tkpOld = new TOKEN_PRIVILEGES();\n tkpOld.Privileges = new int[3];\n LUID tLUID = new LUID();\n tkp.PrivilegeCount = 1;\n if (bEnablePrivilege)\n tkp.Privileges[2] = SE_PRIVILEGE_ENABLED;\n else\n tkp.Privileges[2] = 0;\n if (LookupPrivilegeValue(null, lpszPrivilege, ref tLUID))\n {\n Process proc = Process.GetCurrentProcess();\n if (proc.Handle != IntPtr.Zero)\n {\n if (OpenProcessToken(proc.Handle, TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY,\n ref hToken) != 0)\n {\n tkp.PrivilegeCount = 1;\n tkp.Privileges[2] = SE_PRIVILEGE_ENABLED;\n tkp.Privileges[1] = tLUID.HighPart;\n tkp.Privileges[0] = tLUID.LowPart;\n const int bufLength = 256;\n IntPtr tu = Marshal.AllocHGlobal(bufLength);\n Marshal.StructureToPtr(tkp, tu, true);\n if (AdjustTokenPrivileges(hToken, 0, tu, bufLength, IntPtr.Zero, ref ltkpOld) != 0)\n {\n // successful AdjustTokenPrivileges doesn't mean privilege could be changed\n if (Marshal.GetLastWin32Error() == 0)\n {\n retval = true; // Token changed\n }\n }\n TOKEN_PRIVILEGES tokp = (TOKEN_PRIVILEGES)Marshal.PtrToStructure(tu,\n typeof(TOKEN_PRIVILEGES));\n Marshal.FreeHGlobal(tu);\n }\n }\n }\n if (hToken != IntPtr.Zero)\n {\n CloseHandle(hToken);\n }\n return retval;\n }\n\n }\n}\n" }, { "answer_id": 27726215, "author": "Micah Vertal", "author_id": 4254572, "author_profile": "https://Stackoverflow.com/users/4254572", "pm_score": 3, "selected": false, "text": "System.Diagnostics.Process.Start(\"shutdown\", \"/s /t 0\")\n" }, { "answer_id": 38656759, "author": "user1785960", "author_id": 1785960, "author_profile": "https://Stackoverflow.com/users/1785960", "pm_score": 1, "selected": false, "text": "using System.Management.Automation;\n...\nusing (PowerShell PowerShellInstance = PowerShell.Create())\n{\n PowerShellInstance.AddScript(\"shutdown -a; shutdown -r -t 100;\");\n // invoke execution on the pipeline (collecting output)\n Collection<PSObject> PSOutput = PowerShellInstance.Invoke();\n} \n" }, { "answer_id": 44614907, "author": "man", "author_id": 7877399, "author_profile": "https://Stackoverflow.com/users/7877399", "pm_score": 3, "selected": false, "text": "Process.Start(new ProcessStartInfo(\"shutdown\", \"/s /t 0\") {\n CreateNoWindow = true, UseShellExecute = false\n});\n" }, { "answer_id": 65347291, "author": "NthDeveloper", "author_id": 1844220, "author_profile": "https://Stackoverflow.com/users/1844220", "pm_score": 1, "selected": false, "text": "//This did not work for me\nProcess.Start(\"shutdown\", \"/s /t 0\");\n\n//But this worked\nProcess.Start(\"shutdown\", \"/s /f /t 0\");\n" } ]
2008/09/19
[ "https://Stackoverflow.com/questions/102567", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3464/" ]
102,568
<p>I'm trying to understand someone else's Perl code without knowing much Perl myself. I would appreciate your help.</p> <p>I've encountered a Perl function along these lines:</p> <pre><code>MyFunction($arg1,$arg2__size,$arg3) </code></pre> <p>Is there a meaning to the double-underscore syntax in <code>$arg2</code>, or is it just part of the name of the second argument?</p>
[ { "answer_id": 103936, "author": "Drew Stephens", "author_id": 17339, "author_profile": "https://Stackoverflow.com/users/17339", "pm_score": 2, "selected": false, "text": "__FILE__ __LINE__ $ % @" } ]
2008/09/19
[ "https://Stackoverflow.com/questions/102568", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10261/" ]
102,587
<p>I'm working on a drop in assembly that has predefined pages and usable controls. I am having no difficulties with creating server controls, but I'm wondering what the "best practices" are with dealing with pages in an assembly. Can you compile a page into an assembly and release it as just a dll? How would this be accessed from the client browser's perspective as far as the address they would type or be directed to with a link? As an example, I have a simple login page with the standard username and password text boxes, and the log in button and a "remember me" checkbox, with a "I can't remember my username and/or password" hyperlink. Can I access that page as like a webresource? such as "<a href="http://www.site.name/webresource.axd?related_resource_id_codes" rel="nofollow noreferrer">http://www.site.name/webresource.axd?related_resource_id_codes</a>"</p>
[ { "answer_id": 102709, "author": "Mark Brackett", "author_id": 2199, "author_profile": "https://Stackoverflow.com/users/2199", "pm_score": 1, "selected": false, "text": "<httpHandlers>\n <add verb=\"*\" path=\"login.aspx\" type=\"MyPages.LoginPage, MyPages\" />\n</httpHandlers>\n" } ]
2008/09/19
[ "https://Stackoverflow.com/questions/102587", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18893/" ]
102,591
<p>In my database (SQL 2005) I have a field which holds a comment but in the comment I have an id and I would like to strip out just the id, and IF possible convert it to an int:</p> <p><code>activation successful of id 1010101</code></p> <p>The line above is the exact structure of the data in the db field.</p> <p>And no I don't want to do this in the code of the application, I actually don't want to touch it, just in case you were wondering ;-)</p>
[ { "answer_id": 102687, "author": "Cervo", "author_id": 16219, "author_profile": "https://Stackoverflow.com/users/16219", "pm_score": 0, "selected": false, "text": "-- Test table, you will probably use some query \nDECLARE @testTable TABLE(comment VARCHAR(255)) \nINSERT INTO @testTable(comment) \n VALUES ('activation successful of id 1010101')\n\n-- Use Charindex to find \"id \" then isolate the numeric part \n-- Finally check to make sure the number is numeric before converting \nSELECT CASE WHEN ISNUMERIC(JUSTNUMBER)=1 THEN CAST(JUSTNUMBER AS INTEGER) ELSE -1 END \nFROM ( \n select right(comment, len(comment) - charindex('id ', comment)-2) as justnumber \n from @testtable) TT\n @chvComment" }, { "answer_id": 102688, "author": "Matt Blaine", "author_id": 16272, "author_profile": "https://Stackoverflow.com/users/16272", "pm_score": 0, "selected": false, "text": "select convert(int, substring(fieldName, len('activation successful of id '), len(fieldName) - len('activation successful of id '))) from tableName\n" }, { "answer_id": 102706, "author": "njr101", "author_id": 9625, "author_profile": "https://Stackoverflow.com/users/9625", "pm_score": 2, "selected": true, "text": "SELECT SUBSTRING(column, PATINDEX('%[0-9]%', column), 999)\nFROM table\n" }, { "answer_id": 102732, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "select replace(comment_col, 'activation successful of id ', '') as id from ....\n select replace(replace(comment_col, 'activation not successful of id ', ''), 'activation successful of id ', '') as id from ....\n" }, { "answer_id": 102750, "author": "Rick Glos", "author_id": 16008, "author_profile": "https://Stackoverflow.com/users/16008", "pm_score": 0, "selected": false, "text": "declare @myColumn varchar(100)\nset @myColumn = 'activation successful of id 1010102'\n\n\nSELECT\n @myColumn as [OriginalColumn]\n, CONVERT(int, REVERSE(LEFT(REVERSE(@myColumn), CHARINDEX(' ', REVERSE(@myColumn))))) as [DesiredColumn]\n OriginalColumn DesiredColumn\n---------------------------------------- -------------\nactivation successful of id 1010102 1010102\n\n(1 row(s) affected)\n" }, { "answer_id": 102823, "author": "Dan Roberts", "author_id": 8345, "author_profile": "https://Stackoverflow.com/users/8345", "pm_score": 0, "selected": false, "text": "CAST(REVERSE(LEFT(REVERSE(@Test),CHARINDEX(' ',REVERSE(@Test))-1)) AS INTEGER)\n" }, { "answer_id": 102840, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "select cast(right(column_name,charindex(' ',reverse(column_name))) as int)\n" } ]
2008/09/19
[ "https://Stackoverflow.com/questions/102591", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1841427/" ]
102,605
<p>I would like to use client-side Javascript to perform a DNS lookup (hostname to IP address) as seen from the client's computer. Is that possible?</p>
[ { "answer_id": 102662, "author": "Alex Fort", "author_id": 12624, "author_profile": "https://Stackoverflow.com/users/12624", "pm_score": -1, "selected": false, "text": "ipAddress = java.net.InetAddress.getLocalHost().getHostAddress();\n" }, { "answer_id": 102681, "author": "Zach", "author_id": 9128, "author_profile": "https://Stackoverflow.com/users/9128", "pm_score": 6, "selected": false, "text": "<script type=\"application/javascript\">\nfunction getip(json){\n alert(json.ip); // alerts the ip address\n}\n</script>\n\n<script type=\"application/javascript\" src=\"http://jsonip.appspot.com/?callback=getip\"> </script>\n" }, { "answer_id": 7113498, "author": "tcole", "author_id": 355944, "author_profile": "https://Stackoverflow.com/users/355944", "pm_score": 4, "selected": false, "text": "<?php\nheader('content-type: application/json; charset=utf-8');\n\n$data = json_encode($_SERVER['REMOTE_ADDR']);\necho $_GET['callback'] . '(' . $data . ');';\n?>\n <script type=\"application/javascript\">\nfunction getip(ip){\n alert('IP Address: ' + ip);\n}\n</script>\n\n<script type=\"application/javascript\" src=\"http://www.anotherdomain.com/file.php?callback=getip\"> </script>\n" }, { "answer_id": 18646791, "author": "Bill S", "author_id": 2752409, "author_profile": "https://Stackoverflow.com/users/2752409", "pm_score": -1, "selected": false, "text": " var clientipaddress = '178.32.21.45';\n" }, { "answer_id": 23937989, "author": "Joeri", "author_id": 2240824, "author_profile": "https://Stackoverflow.com/users/2240824", "pm_score": -1, "selected": false, "text": "<?php\n header('content-type: application/json; charset=utf-8');\n\n $data = json_encode($_SERVER['REMOTE_ADDR']);\n\n\n $callback = filter_input(INPUT_GET, \n 'callback',\n FILTER_SANITIZE_STRING, \n FILTER_FLAG_ENCODE_HIGH|FILTER_FLAG_ENCODE_LOW);\n echo $callback . '(' . $data . ');';\n?>\n var self = this;\n$.ajax({\n url: this.url + \"getip.php\",\n data: null,\n type: 'GET',\n crossDomain: true,\n dataType: 'jsonp'\n\n}).done( function( json ) {\n\n self.ip = json;\n\n});\n" }, { "answer_id": 25962226, "author": "earizon", "author_id": 1197682, "author_profile": "https://Stackoverflow.com/users/1197682", "pm_score": 5, "selected": false, "text": "// NOTE: window.RTCPeerConnection is \"not a constructor\" in FF22/23\nvar RTCPeerConnection = /*window.RTCPeerConnection ||*/ window.webkitRTCPeerConnection || window.mozRTCPeerConnection;\n\nif (RTCPeerConnection) (function () {\n var rtc = new RTCPeerConnection({iceServers:[]});\n if (window.mozRTCPeerConnection) { // FF needs a channel/stream to proceed\n rtc.createDataChannel('', {reliable:false});\n }; \n\n rtc.onicecandidate = function (evt) {\n if (evt.candidate) grepSDP(evt.candidate.candidate);\n }; \n rtc.createOffer(function (offerDesc) {\n grepSDP(offerDesc.sdp);\n rtc.setLocalDescription(offerDesc);\n }, function (e) { console.warn(\"offer failed\", e); }); \n\n\n var addrs = Object.create(null);\n addrs[\"0.0.0.0\"] = false;\n function updateDisplay(newAddr) {\n if (newAddr in addrs) return;\n else addrs[newAddr] = true;\n var displayAddrs = Object.keys(addrs).filter(function (k) { return addrs[k]; }); \n document.getElementById('list').textContent = displayAddrs.join(\" or perhaps \") || \"n/a\";\n } \n\n function grepSDP(sdp) {\n var hosts = []; \n sdp.split('\\r\\n').forEach(function (line) { // c.f. http://tools.ietf.org/html/rfc4566#page-39\n if (~line.indexOf(\"a=candidate\")) { // http://tools.ietf.org/html/rfc4566#section-5.13\n var parts = line.split(' '), // http://tools.ietf.org/html/rfc5245#section-15.1\n addr = parts[4],\n type = parts[7];\n if (type === 'host') updateDisplay(addr);\n } else if (~line.indexOf(\"c=\")) { // http://tools.ietf.org/html/rfc4566#section-5.7\n var parts = line.split(' '), \n addr = parts[2];\n updateDisplay(addr);\n } \n }); \n } \n})(); else {\n document.getElementById('list').innerHTML = \"<code>ifconfig | grep inet | grep -v inet6 | cut -d\\\" \\\" -f2 | tail -n1</code>\";\n document.getElementById('list').nextSibling.textContent = \"In Chrome and Firefox your IP should display automatically, by the power of WebRTCskull.\";\n} \n" }, { "answer_id": 29793108, "author": "Neville Hillyer", "author_id": 3179345, "author_profile": "https://Stackoverflow.com/users/3179345", "pm_score": 2, "selected": false, "text": "<script type=\"text/javascript\">function z (x){ document.getElementById('y').innerHTML=x.query }</script>\n<script type='text/javascript' src='http://ip-api.com/json/zero.eu.org?callback=z'></script>\n" }, { "answer_id": 48297500, "author": "Havok", "author_id": 439494, "author_profile": "https://Stackoverflow.com/users/439494", "pm_score": 1, "selected": false, "text": "[GET] /ipv6/[domain] {\n \"addresses\": [\n \"2a01:91ff::f03c:7e01:51bd:fe1f\"\n ]\n }\n [GET] /ipv4/[domain] {\n \"addresses\": [\n \"139.180.232.162\"\n ]\n }\n" }, { "answer_id": 55475761, "author": "Yassine Farroud", "author_id": 8903278, "author_profile": "https://Stackoverflow.com/users/8903278", "pm_score": 0, "selected": false, "text": "browser.dns.resolve(\"example.com\");" }, { "answer_id": 57498563, "author": "Fiach Reid", "author_id": 466048, "author_profile": "https://Stackoverflow.com/users/466048", "pm_score": 1, "selected": false, "text": "DNS.Query(\"dns-js.com\",\n DNS.QueryType.A,\n function(data) {\n console.log(data);\n});\n" }, { "answer_id": 58299823, "author": "kimbo", "author_id": 9638991, "author_profile": "https://Stackoverflow.com/users/9638991", "pm_score": 6, "selected": false, "text": "var response = await fetch('https://dns.google/resolve?name=example.com');\nvar json = await response.json();\nconsole.log(json);\n" } ]
2008/09/19
[ "https://Stackoverflow.com/questions/102605", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13172/" ]
102,606
<p>Below is part of the XML which I am processing with <a href="http://php.net/XSLTProcessor" rel="nofollow noreferrer">PHP's XSLTProcessor</a>:</p> <pre><code>&lt;result&gt; &lt;uf x="20" y="0"/&gt; &lt;uf x="22" y="22"/&gt; &lt;uf x="4" y="3"/&gt; &lt;uf x="15" y="15"/&gt; &lt;/result&gt; </code></pre> <p>I need to know how many "uf" nodes exist where x == y.</p> <p>In the above example, that would be 2.</p> <p>I've tried looping and incrementing a counter variable, but I can't redefine variables.</p> <p>I've tried lots of combinations of xsl:number, with count/from, but couldn't get the XPath expression right.</p> <p>Thanks!</p>
[ { "answer_id": 102707, "author": "Oliver Mellet", "author_id": 12001, "author_profile": "https://Stackoverflow.com/users/12001", "pm_score": 1, "selected": false, "text": "count('/result/uf[@x = @y]')\n" }, { "answer_id": 102708, "author": "Mike Tunnicliffe", "author_id": 13956, "author_profile": "https://Stackoverflow.com/users/13956", "pm_score": 4, "selected": true, "text": "<xsl:value-of select=\"count(/result/uf[@y=@x])\" />\n" } ]
2008/09/19
[ "https://Stackoverflow.com/questions/102606", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14645/" ]
102,614
<p>I am looking for a way to have some control over the shape of a simple MessageBox in Winforms. I would like to control where the passed in text wraps so that the dialog rect is narrower. Windows seems to want to make the dialog as wide as possible before wrapping the text. Is there an easy way to control the maximum width of the dialog without resorting to creating my own custom form?</p>
[ { "answer_id": 102622, "author": "Ferruccio", "author_id": 4086, "author_profile": "https://Stackoverflow.com/users/4086", "pm_score": 3, "selected": true, "text": "\"message text...\\nmore text...\"\n" } ]
2008/09/19
[ "https://Stackoverflow.com/questions/102614", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12281/" ]
102,626
<p>I get this error when I do a <strong>bulk insert</strong> with <code>select * from [table_name]</code>, and another table name:</p> <pre><code>the locale id '0' of the source column 'PAT_NUM_ADT' and the locale id '1033' of the destination column 'PAT_ID_OLD' do not match </code></pre> <p>I tried resetting my db collation but this did not help. </p> <p>Has anyone seen this error?</p>
[ { "answer_id": 8257390, "author": "Deepak Dwivedi", "author_id": 1063944, "author_profile": "https://Stackoverflow.com/users/1063944", "pm_score": 3, "selected": false, "text": "SqlConnectionStringBuilder cb = new SqlConnectionStringBuilder(\"Data Source=ServerName;User Id=userid;Password=****;Initial Catalog=Deepak; Pooling=true; Max pool size=200; Min pool size=0\");\n\n SqlConnection con = new SqlConnection(cb.ConnectionString);\n\n SqlCommand cmd = new SqlCommand(\"select Name,Class,Section,RollNo from Student\", con);\n\n con.Open();\n\n SqlDataReader rdr = cmd.ExecuteReader();\n\n SqlBulkCopy sbc = new SqlBulkCopy(\"Data Source=DestinationServer;User Id=destinationserveruserid;Password=******;Initial Catalog=DeepakTransfer; Pooling=true; Max pool size=200; Min pool size=0\");\n\n sbc.DestinationTableName = \"StudentTrans\";\n\n\n sbc.WriteToServer(rdr);\n\n\n sbc.Close();\n rdr.Close();\n con.Close();\n SqlConnectionStringBuilder cb = new SqlConnectionStringBuilder(\"Data Source=ServerName;User Id=userid;Password=****;Initial Catalog=Deepak;\");\n\n SqlConnection con = new SqlConnection(cb.ConnectionString);\n\n SqlCommand cmd = new SqlCommand(\"select Name,Class,Section,RollNo from Student\", con);\n\n con.Open();\n\n SqlDataReader rdr = cmd.ExecuteReader();\n\n\n SqlBulkCopy sbc = new SqlBulkCopy(\"Data Source=DestinationServer;User Id=destinationserveruserid;Password=******;Initial Catalog=DeepakTransfer;\");\n\n sbc.DestinationTableName = \"StudentTrans\";\n\n sbc.ColumnMappings.Add(\"Name\", \"Name\");\n sbc.ColumnMappings.Add(\"Class\", \"Class\");\n sbc.ColumnMappings.Add(\"Section\", \"Section\");\n sbc.ColumnMappings.Add(\"RollNo\", \"RollNo\");\n\n sbc.WriteToServer(rdr);\n sbc.Close();\n rdr.Close();\n con.Close();\n" }, { "answer_id": 53719833, "author": "TheRealZing", "author_id": 7127621, "author_profile": "https://Stackoverflow.com/users/7127621", "pm_score": 0, "selected": false, "text": "select * from [table_name] select * into newTable from [table_name]" }, { "answer_id": 59682767, "author": "user2046901", "author_id": 2046901, "author_profile": "https://Stackoverflow.com/users/2046901", "pm_score": 0, "selected": false, "text": "SqlConnectionStringBuilder cb = new SqlConnectionStringBuilder(\"Data Source=ServerName;User Id=userid;Password=****;Initial Catalog=Deepak;\");\nSqlConnection con = new SqlConnection(cb.ConnectionString);\nSqlCommand cmd = new SqlCommand(\"select Name COLLATE DATABASE_DEFAULT Name ,Class COLLATE DATABASE_DEFAULT Class ,Section COLLATE DATABASE_DEFAULT Section ,RollNo COLLATE DATABASE_DEFAULT RollNo from Student\", con);\ncon.Open();\nSqlDataReader rdr = cmd.ExecuteReader();\nSqlBulkCopy sbc = new SqlBulkCopy(\"Data Source=DestinationServer;User Id=destinationserveruserid;Password=******;Initial Catalog=DeepakTransfer;\");\n\nsbc.DestinationTableName = \"StudentTrans\";\n\nsbc.ColumnMappings.Add(\"Name\", \"Name\");\nsbc.ColumnMappings.Add(\"Class\", \"Class\");\nsbc.ColumnMappings.Add(\"Section\", \"Section\");\nsbc.ColumnMappings.Add(\"RollNo\", \"RollNo\");\n\nsbc.WriteToServer(rdr);\nsbc.Close();\nrdr.Close();\ncon.Close();\n" } ]
2008/09/19
[ "https://Stackoverflow.com/questions/102626", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
102,631
<p>I have had thoughts of trying to write a simple crawler that might crawl and produce a list of its findings for our NPO's websites and content.</p> <p>Does anybody have any thoughts on how to do this? Where do you point the crawler to get started? How does it send back its findings and still keep crawling? How does it know what it finds, etc,etc.</p>
[ { "answer_id": 102820, "author": "slim", "author_id": 7512, "author_profile": "https://Stackoverflow.com/users/7512", "pm_score": 7, "selected": false, "text": "while(list of unvisited URLs is not empty) {\n take URL from list\n remove it from the unvisited list and add it to the visited list\n fetch content\n record whatever it is you want to about the content\n if content is HTML {\n parse out URLs from links\n foreach URL {\n if it matches your rules\n and it's not already in either the visited or unvisited list\n add it to the unvisited list\n }\n }\n}\n" }, { "answer_id": 13843277, "author": "alienCoder", "author_id": 1723861, "author_profile": "https://Stackoverflow.com/users/1723861", "pm_score": 3, "selected": false, "text": " public void add(String site) {\n synchronized (this) {\n if (!linksVisited.contains(site)) {\n linksToBeVisited.add(site);\n }\n }\n }\n\n public String next() {\n if (linksToBeVisited.size() == 0) {\n return null;\n }\n synchronized (this) {\n // Need to check again if size has changed\n if (linksToBeVisited.size() > 0) {\n String s = linksToBeVisited.get(0);\n linksToBeVisited.remove(0);\n linksVisited.add(s);\n return s;\n }\n return null;\n }\n }\n" }, { "answer_id": 16977478, "author": "Misterhex", "author_id": 1610747, "author_profile": "https://Stackoverflow.com/users/1610747", "pm_score": 0, "selected": false, "text": "public class Crawler\n {\n class ReceivingCrawledUri : ObservableBase<Uri>\n {\n public int _numberOfLinksLeft = 0;\n\n private ReplaySubject<Uri> _subject = new ReplaySubject<Uri>();\n private Uri _rootUri;\n private IEnumerable<IUriFilter> _filters;\n\n public ReceivingCrawledUri(Uri uri)\n : this(uri, Enumerable.Empty<IUriFilter>().ToArray())\n { }\n\n public ReceivingCrawledUri(Uri uri, params IUriFilter[] filters)\n {\n _filters = filters;\n\n CrawlAsync(uri).Start();\n }\n\n protected override IDisposable SubscribeCore(IObserver<Uri> observer)\n {\n return _subject.Subscribe(observer);\n }\n\n private async Task CrawlAsync(Uri uri)\n {\n using (HttpClient client = new HttpClient() { Timeout = TimeSpan.FromMinutes(1) })\n {\n IEnumerable<Uri> result = new List<Uri>();\n\n try\n {\n string html = await client.GetStringAsync(uri);\n result = CQ.Create(html)[\"a\"].Select(i => i.Attributes[\"href\"]).SafeSelect(i => new Uri(i));\n result = Filter(result, _filters.ToArray());\n\n result.ToList().ForEach(async i =>\n {\n Interlocked.Increment(ref _numberOfLinksLeft);\n _subject.OnNext(i);\n await CrawlAsync(i);\n });\n }\n catch\n { }\n\n if (Interlocked.Decrement(ref _numberOfLinksLeft) == 0)\n _subject.OnCompleted();\n }\n }\n\n private static List<Uri> Filter(IEnumerable<Uri> uris, params IUriFilter[] filters)\n {\n var filtered = uris.ToList();\n foreach (var filter in filters.ToList())\n {\n filtered = filter.Filter(filtered);\n }\n return filtered;\n }\n }\n\n public IObservable<Uri> Crawl(Uri uri)\n {\n return new ReceivingCrawledUri(uri, new ExcludeRootUriFilter(uri), new ExternalUriFilter(uri), new AlreadyVisitedUriFilter());\n }\n\n public IObservable<Uri> Crawl(Uri uri, params IUriFilter[] filters)\n {\n return new ReceivingCrawledUri(uri, filters);\n }\n}\n Crawler crawler = new Crawler();\nIObservable observable = crawler.Crawl(new Uri(\"http://www.codinghorror.com/\"));\nobservable.Subscribe(onNext: Console.WriteLine, \nonCompleted: () => Console.WriteLine(\"Crawling completed\"));\n" } ]
2008/09/19
[ "https://Stackoverflow.com/questions/102631", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
102,640
<p>So essentially does margin collapsing occur when you don't set any margin or padding or border to a given div element?</p>
[ { "answer_id": 102755, "author": "Jim", "author_id": 8427, "author_profile": "https://Stackoverflow.com/users/8427", "pm_score": 7, "selected": true, "text": "<div>" } ]
2008/09/19
[ "https://Stackoverflow.com/questions/102640", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1368/" ]
102,683
<p>I have a legacy app I am currently supporting that is having problems when people copy large quantities of data from a datasheet view. </p> <p>The App is built in MS Access and the amount of rows being copied can get pretty large (sometimes in the thousands). </p> <p>The funny thing about it is, you can paste the data out, but then Access keeps "rendering" the data into different formats and becomes CPU bound for LONG periods of time.</p> <p>The Status message beside the progress bar at the bottom right of the MS Access Window is </p> <blockquote> <p>Rendering Data to format: Biff5</p> </blockquote> <p>Biff5 is a "Binary Interchange File Format (BIFF) version 5" According to <a href="http://support.microsoft.com/kb/150447" rel="nofollow noreferrer">Source</a></p> <p>The app code doesn't use BIFF5 anywhere so I don't think this is an app problem.</p> <p>I cannot find any data on this error anywhere on the web so I thought it would be a good question for stackoverflow.</p> <p>So, can anyone help please?</p>
[ { "answer_id": 22442133, "author": "Yayo", "author_id": 3426665, "author_profile": "https://Stackoverflow.com/users/3426665", "pm_score": 0, "selected": false, "text": "RunCommand acCmdCopy\n\n Dim xlApp As Object \n Set xlApp = CreateObject(Class:=\"Excel.Application\")\n\n 'New Excel Workbook\n Dim xlWbook As Object 'Excel.Workbook\n Set xlWbook = xlApp.Workbooks.Add\n\n 'Paste in excel\n xlWSheet.Range(\"A1\").Select\n xlWSheet.PasteSpecial Link:=False, DisplayAsIcon:=False, Format:=\"Biff5\"\n" } ]
2008/09/19
[ "https://Stackoverflow.com/questions/102683", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2806/" ]
102,690
<p>This question comes out of the discussion on <a href="https://stackoverflow.com/questions/101825/whats-the-best-way-of-using-a-pair-triple-etc-of-values-as-one-value-in-c">tuples</a>.</p> <p>I started thinking about the hash code that a tuple should have. What if we will accept KeyValuePair class as a tuple? It doesn't override the GetHashCode() method, so probably it won't be aware of the hash codes of it's "children"... So, run-time will call Object.GetHashCode(), which is not aware of the real object structure.</p> <p>Then we can make two instances of some reference type, which are actually Equal, because of the overloaded GetHashCode() and Equals(). And use them as "children" in tuples to "cheat" the dictionary.</p> <p>But it doesn't work! Run-time somehow figures out the structure of our tuple and calls the overloaded GetHashCode of our class!</p> <p>How does it work? What's the analysis made by Object.GetHashCode()? </p> <p>Can it affect the performance in some bad scenario, when we use some complicated keys? (probably, impossible scenario... but still)</p> <p>Consider this code as an example:</p> <pre><code>namespace csharp_tricks { class Program { class MyClass { int keyValue; int someInfo; public MyClass(int key, int info) { keyValue = key; someInfo = info; } public override bool Equals(object obj) { MyClass other = obj as MyClass; if (other == null) return false; return keyValue.Equals(other.keyValue); } public override int GetHashCode() { return keyValue.GetHashCode(); } } static void Main(string[] args) { Dictionary&lt;object, object&gt; dict = new Dictionary&lt;object, object&gt;(); dict.Add(new KeyValuePair&lt;MyClass,object&gt;(new MyClass(1, 1), 1), 1); //here we get the exception -- an item with the same key was already added //but how did it figure out the hash code? dict.Add(new KeyValuePair&lt;MyClass,object&gt;(new MyClass(1, 2), 1), 1); return; } } } </code></pre> <p><strong>Update</strong> I think I've found an explanation for this as stated below in my answer. The main outcomes of it are:</p> <ul> <li>Be careful with your keys and their hash codes :-)</li> <li>For complicated dictionary keys you must override Equals() and GetHashCode() correctly.</li> </ul>
[ { "answer_id": 103114, "author": "Cory R. King", "author_id": 16742, "author_profile": "https://Stackoverflow.com/users/16742", "pm_score": -1, "selected": false, "text": "MyClass 1 KeyValuePair Key Value Object.GetHashCode() public class HappyClass\n{\n\n enum TheUnit\n {\n Points,\n Picas,\n Inches\n }\n\n class MyDistanceClass\n {\n int distance;\n TheUnit units;\n\n public MyDistanceClass(int theDistance, TheUnit unit)\n {\n distance = theDistance;\n\n units = unit;\n }\n public static int ConvertDistance(int oldDistance, TheUnit oldUnit, TheUnit newUnit)\n {\n // insert real unit conversion code here :-)\n return oldDistance * 100;\n }\n\n /// <summary>\n /// Figure out if we are equal distance, converting into the same units of measurement if we have to\n /// </summary>\n /// <param name=\"obj\">the other guy</param>\n /// <returns>true if we are the same distance</returns>\n public override bool Equals(object obj)\n {\n MyDistanceClass other = obj as MyDistanceClass;\n if (other == null) return false;\n\n if (other.units != this.units)\n {\n int newDistance = MyDistanceClass.ConvertDistance(other.distance, other.units, this.units);\n return distance.Equals(newDistance);\n }\n else\n {\n return distance.Equals(other.distance);\n }\n\n\n }\n\n public override int GetHashCode()\n {\n // even if the distance is equal in spite of the different units, the objects are not\n return distance.GetHashCode() * units.GetHashCode();\n }\n }\n static void Main(string[] args)\n {\n\n // these are the same distance... 72 points = 1 inch\n MyDistanceClass distPoint = new MyDistanceClass(72, TheUnit.Points);\n MyDistanceClass distInch = new MyDistanceClass(1, TheUnit.Inch);\n\n Debug.Assert(distPoint.Equals(distInch), \"these should be true!\");\n Debug.Assert(distPoint.GetHashCode() != distInch.GetHashCode(), \"But yet they are fundimentally different values\");\n\n Dictionary<object, object> dict = new Dictionary<object, object>();\n\n dict.Add(new KeyValuePair<MyDistanceClass, object>(distPoint, 1), 1);\n\n //this should not barf\n dict.Add(new KeyValuePair<MyDistanceClass, object>(distInch, 1), 1);\n\n return;\n }\n\n}\n" }, { "answer_id": 103587, "author": "Max Galkin", "author_id": 2351099, "author_profile": "https://Stackoverflow.com/users/2351099", "pm_score": 2, "selected": true, "text": "using System.Collections.Generic;\n\nnamespace csharp_tricks\n{\n class Program\n {\n class MyClass\n {\n int keyValue;\n int someInfo;\n\n public MyClass(int key, int info)\n {\n keyValue = key;\n someInfo = info;\n }\n\n public override bool Equals(object obj)\n {\n MyClass other = obj as MyClass;\n if (other == null) return false;\n\n return keyValue.Equals(other.keyValue);\n }\n\n public override int GetHashCode()\n {\n return keyValue.GetHashCode();\n }\n }\n\n class Pair<T, R>\n {\n public T First { get; set; }\n public R Second { get; set; }\n }\n\n static void Main(string[] args)\n {\n var dict = new Dictionary<Pair<int, MyClass>, object>();\n\n dict.Add(new Pair<int, MyClass>() { First = 1, Second = new MyClass(1, 2) }, 1);\n\n //this is a pair of the same values as previous! but... no exception this time...\n dict.Add(new Pair<int, MyClass>() { First = 1, Second = new MyClass(1, 3) }, 1);\n\n return;\n }\n }\n}\n" }, { "answer_id": 154081, "author": "Rinat Abdullin", "author_id": 47366, "author_profile": "https://Stackoverflow.com/users/47366", "pm_score": 2, "selected": false, "text": "public override bool Equals(object obj)\n{\n if (ReferenceEquals(null, obj))\n throw new NullReferenceException(\"obj is null\");\n if (ReferenceEquals(this, obj)) return true;\n if (obj.GetType() != typeof (Quad<T1, T2, T3, T4>)) return false;\n return Equals((Quad<T1, T2, T3, T4>) obj);\n}\n\npublic bool Equals(Quad<T1, T2, T3, T4> obj)\n{\n if (ReferenceEquals(null, obj)) return false;\n if (ReferenceEquals(this, obj)) return true;\n return Equals(obj.Item1, Item1)\n && Equals(obj.Item2, Item2)\n && Equals(obj.Item3, Item3)\n && Equals(obj.Item4, Item4);\n}\n\npublic override int GetHashCode()\n{\n unchecked\n {\n int result = Item1.GetHashCode();\n result = (result*397) ^ Item2.GetHashCode();\n result = (result*397) ^ Item3.GetHashCode();\n result = (result*397) ^ Item4.GetHashCode();\n return result;\n }\n}\npublic static bool operator ==(Quad<T1, T2, T3, T4> left, Quad<T1, T2, T3, T4> right)\n{\n return Equals(left, right);\n}\n\n\npublic static bool operator !=(Quad<T1, T2, T3, T4> left, Quad<T1, T2, T3, T4> right)\n{\n return !Equals(left, right);\n}\n" } ]
2008/09/19
[ "https://Stackoverflow.com/questions/102690", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2351099/" ]
102,720
<p>I just finished a medium sized web site and one thing I noticed about my css organization was that I have a lot of hard coded colour values throughout. This obviously isn't great for maintainability. Generally, when I design a site I pick 3-5 main colours for a theme. I end up setting some default values for paragraphs, links, etc... at the beginning of my main css, but some components will change the colour (like the legend tag for example) and require me to restyle with the colour I wanted. How do you avoid this? I was thinking of creating separate rules for each colour and just use those when I need to restyle.</p> <p>i.e.</p> <pre><code>.color1 { color: #3d444d; } </code></pre>
[ { "answer_id": 102817, "author": "Josh Millard", "author_id": 13600, "author_profile": "https://Stackoverflow.com/users/13600", "pm_score": 2, "selected": false, "text": "h1 { \n padding...\n margin...\n font-family...\n}\n\np {\n ...\n}\n\ncode {\n ...\n}\n\n/* time passes */\n\n/* these elements are semantically grouped by color in the design */\nh1, p, code { \n color: #ff0000;\n}\n" }, { "answer_id": 102838, "author": "naspinski", "author_id": 14777, "author_profile": "https://Stackoverflow.com/users/14777", "pm_score": 3, "selected": true, "text": ".main_text {color:#444444;}\n.secondary_text{color:#765123;}\n.main_color {background:#343434;}\n.secondary_color {background:#765sda;}\n <body class='main_text'>\n <div class='main_color secondary_text'>\n <span class='secondary color main_text'>bla bla bla</span>\n </div>\n <div class='main_color secondary_text>\n You get the idea...\n </div>\n</body>\n" }, { "answer_id": 102930, "author": "rampion", "author_id": 9859, "author_profile": "https://Stackoverflow.com/users/9859", "pm_score": 1, "selected": false, "text": "p .frog tr.mango {\n color: blue;\n margin: 1px 3em 2.5em 4px;\n position: static;\n}\n#eta .beta span.pi {\n background: green;\n color: red;\n font-size: small;\n float: left;\n}\n// ...\n p .frog tr.mango {\n color: blue;\n}\n#eta .beta span.pi {\n background: green;\n color: red;\n}\n//...\np .frog tr.mango {\n margin: 1px 3em 2.5em 4px;\n position: static;\n}\n#eta .beta span.pi {\n font-size: small;\n float: left;\n}\n// ...\n" }, { "answer_id": 103888, "author": "Matthew Rapati", "author_id": 15000, "author_profile": "https://Stackoverflow.com/users/15000", "pm_score": 1, "selected": false, "text": "<?php \n header(\"Content-Type: text/css\");\n $colour1 = '#ff9'; \n?>\n.username {color: <?=$colour1;?>; }\n" }, { "answer_id": 104205, "author": "neuroguy123", "author_id": 12529, "author_profile": "https://Stackoverflow.com/users/12529", "pm_score": 0, "selected": false, "text": "h1, p, code {\n color: #ff0000;\n}\n .color1 {\n color: #ff0000;\n}\n" } ]
2008/09/19
[ "https://Stackoverflow.com/questions/102720", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12529/" ]
102,759
<p>Everyone has accidentally forgotten the <code>WHERE</code> clause on a <code>DELETE</code> query and blasted some un-backed up data once or twice. I was pondering that problem, and I was wondering if the solution I came up with is practical.</p> <p>What if, in place of actual <code>DELETE</code> queries, the application and maintenance scripts did something like:</p> <pre><code>UPDATE foo SET to_be_deleted=1 WHERE blah = 50; </code></pre> <p>And then a cron job was set to go through and actually delete everything with the flag? The downside would be that pretty much every other query would need to have <code>WHERE to_be_deleted != 1</code> appended to it, but the upside would be that you'd never mistakenly lose data again. You could see "2,349,325 rows affected" and say, "Hmm, looks like I forgot the <code>WHERE</code> clause," and reset the flags. You could even make the to_be_deleted field a <code>DATE</code> column, so the cron job would check to see if a row's time had come yet.</p> <p>Also, you could remove <code>DELETE</code> permission from the production database user, so even if someone managed to inject some SQL into your site, they wouldn't be able to remove anything.</p> <p>So, my question is: Is this a good idea, or are there pitfalls I'm not seeing? </p>
[ { "answer_id": 102915, "author": "yukondude", "author_id": 726, "author_profile": "https://Stackoverflow.com/users/726", "pm_score": 2, "selected": false, "text": "DELETE UPDATE DELETE DELETE to_be_deleted != 1" }, { "answer_id": 105978, "author": "David Schmitt", "author_id": 4918, "author_profile": "https://Stackoverflow.com/users/4918", "pm_score": 2, "selected": false, "text": "DELETE SELECT WHERE DELETE" } ]
2008/09/19
[ "https://Stackoverflow.com/questions/102759", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16034/" ]
102,788
<p>I would like to encrypt strings which could potentially only be about three or four characters but run to about twenty characters. A hashing function (<a href="http://www.php.net/md5" rel="noreferrer">md5</a>, <a href="http://www.php.net/sha1" rel="noreferrer">sha1</a>, <a href="http://www.php.net/crypt" rel="noreferrer">crypt</a> etc) is not suitable as I would like to be able to decrypt the information as well. The <a href="http://au.php.net/mcrypt" rel="noreferrer">mcrypt</a> extension has a thoroughly daunting array of possibilities. </p> <p>Does anyone have any ideas about the best way to safely encrypt short strings and <em>why</em>? Does anyone have any links to any material introducing a casual programmer to practical encryption scenarios?</p>
[ { "answer_id": 25953310, "author": "Nasz Njoka Sr.", "author_id": 1688471, "author_profile": "https://Stackoverflow.com/users/1688471", "pm_score": 0, "selected": false, "text": "function encryptstring($string) {\n\n$string_length=strlen($string);\n$encrychars=\"\"; \n/**\n*For each character of the given string generate the code\n*/\nfor ($position = 0;$position<$string_length;$position++){ \n $key = (($string_length+$position)+1);\n $key = (255+$key) % 255;\n $get_char_to_be_encrypted = SUBSTR($string, $position, 1);\n $ascii_char = ORD($get_char_to_be_encrypted);\n $xored_char = $ascii_char ^ $key; //xor operation\n $encrypted_char = CHR($xored_char);\n $encrychars .= $encrypted_char;\n} \n/**\n*Return the encrypted/decrypted string\n*/\nreturn $encrychars;\n}\n /**\n *While passing the unique value to a link\n *Do the following steps\n */\n\n $id=57;//or if you are fetching it automatically just pass it here\n /**\n *For more security multiply some value\n *You can set the multiplication value in config file\n */\n $passstring=$id*346244;\n $encrypted_string=encryptstring($passstring);\n $param=urlencode($encrypted_string);\n /**\n *Derive the url for the link\n */\n echo '<a href=\"target_file.php?aZ98#9A_KL='.$param.'\">something</a>' ;\n /**\n *Retriving the value in the target file\n *Do the following steps\n */\n $fetchid=$_GET['aZ98#9A_KL'];\n $passstring=urldecode(stripslashes($fetchid));\n $decrypted_string= encryptstring($passstring);\n /**\n *Divide the decrypted value with the same value we used for the multiplication\n */\n $actual_id= $decrypted_string/346244;\n" } ]
2008/09/19
[ "https://Stackoverflow.com/questions/102788", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15004/" ]
102,829
<p>I am looking for a text editor that will be able to load a 4+ Gigabyte file into it. Textpad doesn't work. I own a copy of it and have been to its support site, it just doesn't do it. Maybe I need new hardware, but that's a different question. The editor needs to be free OR, if its going to cost me, then no more than $30. For Windows.</p>
[ { "answer_id": 163941, "author": "VonC", "author_id": 6309, "author_profile": "https://Stackoverflow.com/users/6309", "pm_score": 7, "selected": true, "text": "Main Search Quick Find Quick Find" }, { "answer_id": 858117, "author": "Aaron Digulla", "author_id": 34088, "author_profile": "https://Stackoverflow.com/users/34088", "pm_score": 4, "selected": false, "text": "grep tail gawk" } ]
2008/09/19
[ "https://Stackoverflow.com/questions/102829", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14728/" ]
102,832
<p>I have a query form that I would like to submit as a GET request so the result page may be bookmarked and otherwise RESTful. It's your classical text field with a submit button. How do I induce Seam/JSF to use GET and include the query expression as a parameter rather than POST, the default?</p>
[ { "answer_id": 2239602, "author": "Shervin Asgari", "author_id": 37298, "author_profile": "https://Stackoverflow.com/users/37298", "pm_score": 1, "selected": false, "text": "s:button s:link" } ]
2008/09/19
[ "https://Stackoverflow.com/questions/102832", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4893/" ]
102,846
<p>OK, this might sound a bit confusing and complicated, so bear with me.</p> <p>We've written a framework that allows us to define friendly URLs. If you surf to any arbitrary URL, IIS tries to display a 404 error (or, in some cases, 403;14 or 405). However, IIS is set up so that anything directed to those specific errors is sent to an .aspx file. This allows us to implement an HttpHandler to handle the request and do stuff, which involves finding the an associated template and then executing whatever's associated with it.</p> <p>Now, this all works in IIS 5 and 6 and, to an extent, on IIS7 - but for one catch, which happens when you post a form.</p> <p>See, when you post a form to a non-existent URL, IIS says "ah, but that url doesn't exist" and throws a 405 "method not allowed" error. Since we're telling IIS to redirect those errors to our .aspx page and therefore handling it with our HttpHandler, this normally isn't a problem. But as of IIS7, all POST information has gone missing after being redirected to the 405. And so you can no longer do the most trivial of things involving forms.</p> <p>To solve this we've tried using a HttpModule, which preserves POST data but appears to not have an initialized Session at the right time (when it's needed). We also tried using a HttpModule for all requests, not just the missing requests that hit 404/403;14/405, but that means stuff like images, css, js etc are being handled by .NET code, which is terribly inefficient.</p> <p>Which brings me to the actual question: has anyone ever encountered this, and does anyone have any advice or know what to do to get things working again? So far someone has suggested using Microsoft's own <a href="http://learn.iis.net/page.aspx/460/using-url-rewrite-module/" rel="nofollow noreferrer">URL Rewriting module</a>. Would this help solve our problem?</p> <p>Thanks.</p>
[ { "answer_id": 109172, "author": "Stefan Rusek", "author_id": 19704, "author_profile": "https://Stackoverflow.com/users/19704", "pm_score": 2, "selected": false, "text": "using System.Web;\nusing System.Web.UI;\n\nclass Smart404Module : IHttpModule\n{\n public void Dispose() {}\n\n public void Init(HttpApplication context)\n {\n context.BeginRequest += new System.EventHandler(DoMapping);\n }\n\n void DoMapping(object sender, System.EventArgs e)\n {\n HttpApplication app = (HttpApplication)sender;\n\n if (IsMissing(app.Context))\n app.Context.Handler = PageParser.GetCompiledPageInstance(\n \"~/404.aspx\", app.Request.MapPath(\"~/404.aspx\"), app.Context);\n }\n\n bool IsMissing(HttpContext context)\n {\n string path = context.Request.MapPath(context.Request.Url.AbsolutePath);\n\n if (System.IO.File.Exists(path) || (System.IO.Directory.Exists(path)\n && System.IO.File.Exists(System.IO.Path.Combine(path, \"default.aspx\"))))\n return true;\n return false;\n }\n}\n" } ]
2008/09/19
[ "https://Stackoverflow.com/questions/102846", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16308/" ]
102,850
<p>Doesn't work with other modules, but to give an example. I installed Text::CSV_XS with a CPAN setting:</p> <pre><code>'makepl_arg' =&gt; q[PREFIX=~/lib], </code></pre> <p>When I try running a test.pl script:</p> <blockquote> <p>$ perl test.pl</p> </blockquote> <pre><code>#!/usr/bin/perl use lib "/homes/foobar/lib/lib64/perl5/site_perl/5.8.8/x86_64-linux-thread-multi"; use Text::CSV_XS; print "test"; </code></pre> <p>I get</p> <pre> Can't load '/homes/foobar/lib/lib64/perl5/site_perl/5.8.8/x86_64-linux-thread-multi/auto/Text/CSV_XS/CSV_XS.so' for module Text::CSV_XS: /homes/foobar/lib/lib64/perl5/site_perl/5.8.8/x86_64-linux-thread-multi/auto/Text/CSV_XS/CSV_XS.so: cannot open shared object file: No such file or directory at /www/common/perl/lib/5.8.2/i686-linux/DynaLoader.pm line 229. at test.pl line 6 Compilation failed in require at test.pl line 6. BEGIN failed--compilation aborted at test.pl line 6. </pre> <p>I traced the error back to DynaLoader.pm it happens at this line:</p> <pre><code># Many dynamic extension loading problems will appear to come from # this section of code: XYZ failed at line 123 of DynaLoader.pm. # Often these errors are actually occurring in the initialisation # C code of the extension XS file. Perl reports the error as being # in this perl code simply because this was the last perl code # it executed. my $libref = dl_load_file($file, $module-&gt;dl_load_flags) or croak("Can't load '$file' for module $module: ".dl_error()); </code></pre> <p><b>CSV_XS.so exists in the above directory</b></p>
[ { "answer_id": 103018, "author": "Frosty", "author_id": 7476, "author_profile": "https://Stackoverflow.com/users/7476", "pm_score": 2, "selected": false, "text": "'makepl_arg' => q[PREFIX=~/]\n 'makepl_arg' => q[PREFIX=/home/users/foobar]\n" }, { "answer_id": 103501, "author": "Frosty", "author_id": 7476, "author_profile": "https://Stackoverflow.com/users/7476", "pm_score": 0, "selected": false, "text": "set |grep PERL\n" }, { "answer_id": 103987, "author": "brian d foy", "author_id": 2766176, "author_profile": "https://Stackoverflow.com/users/2766176", "pm_score": 3, "selected": false, "text": "use lib % find ~/lib -name CSV_XS.so\n use lib lib/lib PREFIX" } ]
2008/09/19
[ "https://Stackoverflow.com/questions/102850", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10523/" ]
102,866
<p>I have one <code>JSON</code> that is coming in a <code>string</code> format. I need to store it in a <code>key-pair</code> value or something like that. I am using <code>asp.net 2.0</code> and can not use 3rd party <code>DLL</code> like <code>Newtonsoft.Json.dll</code>. I guess last option will be to use <code>regular expression</code>. </p> <p><em>Can anybody please help me in this?</em></p>
[ { "answer_id": 405416, "author": "Dan Herbert", "author_id": 392, "author_profile": "https://Stackoverflow.com/users/392", "pm_score": 2, "selected": false, "text": "using Microsoft.JScript;\nusing Microsoft.JScript.Vsa;\n Page VsaEngine Engine = VsaEngine.CreateEngine();\n object EvalJScript(string JScript)\n{\n object result = null;\n try\n {\n result = Microsoft.JScript.Eval.JScriptEvaluate(JScript, Engine);\n }\n catch (Exception ex)\n {\n return ex.Message;\n }\n\n return result;\n}\n object JSObject string json = \"({Name:\\\"Dan\\\",Occupation:\\\"Developer\\\"})\";\n\nJSObject o = EvalJScript(json) as JSObject;\n\nstring name = o[\"Name\"] as string; // Value of 'name' will be 'Dan'\n" } ]
2008/09/19
[ "https://Stackoverflow.com/questions/102866", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1312208/" ]
102,877
<p>I need to create a PRIVATE message queue on a remote machine and I have resolved to fact that I can't do this with the .NET Framework in a straight forward manner. I can create a public message queue on a remote machine, but not a PRIVATE one. I can create a message queue (public or private) locally.</p> <p>I am wondering if anyone knows how to access MSMQ through WMI.</p> <p><strong>Edit:</strong> I don't see anything to do it with using the MSMQ Provider. May have to get tricky and use PSExec to log onto a remote server and execute some code.</p>
[ { "answer_id": 287206, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "set qinfo = CreateObject(\"MSMQ.MSMQQueueInfo\")\nqinfo.PathName = \".\\Private$\\TestQueue\"\nqinfo.Label = \".\\Private$\\TestQueue\"\nqinfo.Journal = \"1\"\nqinfo.Create\n .vb" } ]
2008/09/19
[ "https://Stackoverflow.com/questions/102877", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18475/" ]
102,881
<p>I am running some queries to track down a problem with our backup logs and would like to display datetime fields in 24-hour military time. Is there a simple way to do this? I've tried googling and could find nothing.</p>
[ { "answer_id": 102909, "author": "Joe Skora", "author_id": 14057, "author_profile": "https://Stackoverflow.com/users/14057", "pm_score": 5, "selected": true, "text": "select to_char(sysdate,'DD/MM/YYYY HH24:MI:SS') from dual;\n" }, { "answer_id": 102918, "author": "Grant Johnson", "author_id": 12518, "author_profile": "https://Stackoverflow.com/users/12518", "pm_score": 1, "selected": false, "text": "to_char(field,'YYYYMMDD HH24MISS')" }, { "answer_id": 107044, "author": "Matthew Watson", "author_id": 3839, "author_profile": "https://Stackoverflow.com/users/3839", "pm_score": 2, "selected": false, "text": "alter session set NLS_DATE_FORMAT='DD/MM/YYYY HH24:MI:SS'\n" } ]
2008/09/19
[ "https://Stackoverflow.com/questions/102881", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5056/" ]
102,913
<p>I have an MVC-based site, which is using a Repository/Service pattern for data access. The Services are written to be using in a majority of applications (console, winform, and web). Currently, the controllers communicate directly to the services. This has limited the ability to apply proper caching.</p> <p>I see my options as the following:</p> <ul> <li>Write a wrapper for the web app, which implements the IWhatEverService which does caching. </li> <li>Apply caching in each controller by cache the ViewData for each Action.</li> <li>Don't worry about data caching and just implement OutputCaching for each Action.</li> </ul> <p>I can see the pros and cons of each. What is/should the best practice be for caching with Repository/Service </p>
[ { "answer_id": 6232477, "author": "Brendan Enrick", "author_id": 22381, "author_profile": "https://Stackoverflow.com/users/22381", "pm_score": 5, "selected": false, "text": "public class CachedAlbumRepository : IAlbumRepository\n{\n private readonly IAlbumRepository _albumRepository;\n\n public CachedAlbumRepository(IAlbumRepository albumRepository)\n {\n _albumRepository = albumRepository;\n }\n\n private static readonly object CacheLockObject = new object();\n\n public IEnumerable<Album> GetTopSellingAlbums(int count)\n {\n Debug.Print(\"CachedAlbumRepository:GetTopSellingAlbums\");\n string cacheKey = \"TopSellingAlbums-\" + count;\n var result = HttpRuntime.Cache[cacheKey] as List<Album>;\n if (result == null)\n {\n lock (CacheLockObject)\n {\n result = HttpRuntime.Cache[cacheKey] as List<Album>;\n if (result == null)\n {\n result = _albumRepository.GetTopSellingAlbums(count).ToList();\n HttpRuntime.Cache.Insert(cacheKey, result, null, \n DateTime.Now.AddSeconds(60), TimeSpan.Zero);\n }\n }\n }\n return result;\n }\n}\n" }, { "answer_id": 39043414, "author": "Alexei - check Codidact", "author_id": 2780791, "author_profile": "https://Stackoverflow.com/users/2780791", "pm_score": 3, "selected": false, "text": "public interface IRepository<T> : IRepository\n where T : class\n{\n IQueryable<T> AllNoTracking { get; }\n\n IQueryable<T> All { get; }\n DbSet<T> GetSet { get; }\n\n T Get(int id);\n\n void Insert(T entity);\n void BulkInsert(IEnumerable<T> entities);\n void Delete(T entity);\n void RemoveRange(IEnumerable<T> range);\n void Update(T entity);\n}\n public class Repository<T> : IRepository<T> where T : class, new()\n{\n private readonly IEfDbContext _context;\n\n public Repository(IEfDbContext context)\n {\n _context = context;\n }\n\n public IQueryable<T> All => _context.Set<T>().AsQueryable();\n\n public IQueryable<T> AllNoTracking => _context.Set<T>().AsNoTracking();\n\n public IQueryable AllNoTrackingGeneric(Type t)\n {\n return _context.GetSet(t).AsNoTracking();\n }\n\n public DbSet<T> GetSet => _context.Set<T>();\n\n public DbSet GetSetNonGeneric(Type t)\n {\n return _context.GetSet(t);\n }\n\n public IQueryable AllNonGeneric(Type t)\n {\n return _context.GetSet(t);\n }\n\n public T Get(int id)\n {\n return _context.Set<T>().Find(id);\n }\n\n public void Delete(T entity)\n {\n if (_context.Entry(entity).State == EntityState.Detached)\n _context.Set<T>().Attach(entity);\n\n _context.Set<T>().Remove(entity);\n }\n\n public void RemoveRange(IEnumerable<T> range)\n {\n _context.Set<T>().RemoveRange(range);\n }\n\n public void Insert(T entity)\n {\n _context.Set<T>().Add(entity);\n }\n\n public void BulkInsert(IEnumerable<T> entities)\n {\n _context.BulkInsert(entities);\n }\n\n public void Update(T entity)\n {\n _context.Set<T>().Attach(entity);\n _context.Entry(entity).State = EntityState.Modified;\n }\n public interface ICachedRepository<T> where T : class, new()\n{\n string CacheKey { get; }\n\n void InvalidateCache();\n void InsertIntoCache(T item);\n}\n\npublic class CachedRepository<T> : ICachedRepository<T>, IRepository<T> where T : class, new()\n{\n private readonly IRepository<T> _modelRepository;\n private static readonly object CacheLockObject = new object();\n\n private IList<T> ThreadSafeCacheAccessAction(Action<IList<T>> action = null)\n {\n // refresh cache if necessary\n var list = HttpRuntime.Cache[CacheKey] as IList<T>;\n if (list == null)\n {\n lock (CacheLockObject)\n {\n list = HttpRuntime.Cache[CacheKey] as IList<T>;\n if (list == null)\n {\n list = _modelRepository.All.ToList();\n //TODO: remove hardcoding\n HttpRuntime.Cache.Insert(CacheKey, list, null, DateTime.UtcNow.AddMinutes(10), Cache.NoSlidingExpiration);\n }\n }\n }\n\n // execute custom action, if one is required\n if (action != null)\n {\n lock (CacheLockObject)\n {\n action(list);\n }\n }\n\n return list;\n }\n\n public IList<T> GetCachedItems()\n {\n IList<T> ret = ThreadSafeCacheAccessAction();\n return ret;\n }\n\n /// <summary>\n /// returns value without using cache, to allow Queryable usage\n /// </summary>\n public IQueryable<T> All => _modelRepository.All;\n\n public IQueryable<T> AllNoTracking\n {\n get\n {\n var cachedItems = GetCachedItems();\n return cachedItems.AsQueryable();\n }\n }\n\n // other methods come here\n public void BulkInsert(IEnumerable<T> entities)\n {\n var enumerable = entities as IList<T> ?? entities.ToList();\n _modelRepository.BulkInsert(enumerable);\n\n // also inserting items within the cache\n ThreadSafeCacheAccessAction((list) =>\n {\n foreach (var item in enumerable)\n list.Add(item);\n });\n }\n\n public void Delete(T entity)\n {\n _modelRepository.Delete(entity);\n\n ThreadSafeCacheAccessAction((list) =>\n {\n list.Remove(entity);\n });\n }\n}\n // IRepository<T> should be solved using Repository<T>, by default\nkernel.Bind(typeof(IRepository<>)).To(typeof(Repository<>));\n\n// IRepository<T> must be solved to Repository<T>, if used in CachedRepository<T>\nkernel.Bind(typeof(IRepository<>)).To(typeof(Repository<>)).WhenInjectedInto(typeof(CachedRepository<>));\n\n // explicit repositories using caching\n var cachedTypes = new List<Type>\n {\n typeof(ImportingSystem), typeof(ImportingSystemLoadInfo), typeof(Environment)\n };\n\n cachedTypes.ForEach(type =>\n {\n // allow access as normal repository\n kernel\n .Bind(typeof(IRepository<>).MakeGenericType(type))\n .To(typeof(CachedRepository<>).MakeGenericType(type));\n\n // allow access as a cached repository\n kernel\n .Bind(typeof(ICachedRepository<>).MakeGenericType(type))\n .To(typeof(CachedRepository<>).MakeGenericType(type));\n });\n ICacheRepository<>" } ]
2008/09/19
[ "https://Stackoverflow.com/questions/102913", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1296/" ]
102,964
<p>I have a Java bean like this:</p> <pre><code>class Person { int age; String name; } </code></pre> <p>I'd like to iterate over a collection of these beans in a JSP, showing each person in a HTML table row, and in the last row of the table I'd like to show the total of all the ages.</p> <p>The code to generate the table rows will look something like this:</p> <pre><code>&lt;c:forEach var="person" items="${personList}"&gt; &lt;tr&gt;&lt;td&gt;${person.name}&lt;td&gt;&lt;td&gt;${person.age}&lt;/td&gt;&lt;/tr&gt; &lt;/c:forEach&gt; </code></pre> <p>However, I'm struggling to find a way to calculate the age total that will be shown in the final row <strong>without resorting to scriptlet code</strong>, any suggestions?</p>
[ { "answer_id": 103065, "author": "ScArcher2", "author_id": 1310, "author_profile": "https://Stackoverflow.com/users/1310", "pm_score": 3, "selected": false, "text": "<c:set var=\"ageTotal\" value=\"${0}\" />\n<c:forEach var=\"person\" items=\"${personList}\">\n <c:set var=\"ageTotal\" value=\"${ageTotal + person.age}\" />\n <tr><td>${person.name}<td><td>${person.age}</td></tr>\n</c:forEach>\n${ageTotal}\n" }, { "answer_id": 103219, "author": "James Schek", "author_id": 17871, "author_profile": "https://Stackoverflow.com/users/17871", "pm_score": 1, "selected": false, "text": "class MySum {\npublic double sum(List list) {...}\n}\n <function>\n<name>sum</name>\n<function-class>my.MySum</function-class>\n<function-signature>double sum(List)</function-signature>\n</function>\n <%@ taglib uri=\"/myfunc\" prefix=\"f\" %>\n\n${f:sum(personList)}\n" }, { "answer_id": 103973, "author": "Jon-Erik", "author_id": 15832, "author_profile": "https://Stackoverflow.com/users/15832", "pm_score": 6, "selected": true, "text": "<c:set var=\"ageTotal\" value=\"${0}\" />\n<c:forEach var=\"person\" items=\"${personList}\">\n <c:set var=\"ageTotal\" value=\"${ageTotal + person.age}\" />\n <tr><td>${person.name}<td><td>${person.age}</td></tr>\n</c:forEach>\n${ageTotal}\n <c:forEach var=\"person\" items=\"${personList}\">\n <tr><td>${person.name}<td><td>${person.age}</td></tr>\n</c:forEach>\n${personList.stream().map(person -> person.age).sum()}\n <function>\n <name>sum</name>\n <function-class>com.example.PersonUtils</function-class>\n <function-signature>int sum(java.util.List people)</function-signature>\n</function> \n <%@ taglib prefix=\"f\" uri=\"/your-tld-uri\"%>\n...\n<c:out value=\"${f:sum(personList)}\"/>\n public PersonSumTag extends TagSupport {\n\n private List personList;\n\n public List getPersonList(){\n return personList;\n }\n\n public void setPersonList(List personList){\n this.personList = personList;\n }\n\n public int doStartTag() throws JspException {\n try {\n int sum = 0;\n for(Iterator it = personList.iterator(); it.hasNext()){\n Person p = (Person)it.next();\n sum+=p.getAge();\n } \n pageContext.getOut().print(\"\"+sum);\n } catch (Exception ex) {\n throw new JspTagException(\"SimpleTag: \" + \n ex.getMessage());\n }\n return SKIP_BODY;\n }\n public int doEndTag() {\n return EVAL_PAGE;\n }\n}\n <tag>\n <name>personSum</name>\n <tag-class>example.PersonSumTag</tag-class>\n <body-content>empty</body-content>\n ...\n <attribute>\n <name>personList</name>\n <required>true</required>\n <rtexprvalue>true</rtexprvalue>\n <type>java.util.List</type>\n </attribute>\n ...\n</tag>\n <%@ taglib uri=\"/you-taglib-uri\" prefix=\"p\" %>\n <c:forEach var=\"person\" items=\"${personList}\">\n <tr><td>${person.name}<td><td>${person.age}</td></tr>\n</c:forEach>\n<p:personSum personList=\"${personList}\"/>\n" }, { "answer_id": 10442349, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<c:forEach items=\"${numList}\" var=\"item\">\n ${item}\n</c:forEach>\n <c:forEach items=\"${numMap}\" var=\"entry\">\n ${entry.key},${entry.value}<br/>\n</c:forEach>\n" }, { "answer_id": 15715507, "author": "Thomas W", "author_id": 768795, "author_profile": "https://Stackoverflow.com/users/768795", "pm_score": 0, "selected": false, "text": "class PersonList_Controller implements Controller {\n ...\n protected void renderModel (List<Person> items, Map model) {\n int totalAge = 0;\n for (Person person : items) {\n totalAge += person.getAge();\n }\n model.put(\"items\", items);\n model.put(\"totalAge\", totalAge);\n }\n}\n" } ]
2008/09/19
[ "https://Stackoverflow.com/questions/102964", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2648/" ]
103,000
<p>I need to retrieve a record from a database, display it on a web page (I'm using ASP.NET) but store the ID (primary key) from that record somewhere so I can go back to the database later with that ID (perhaps to do an update).</p> <p>I know there are probably a few ways to do this, such as storing the ID in ViewState or a hidden field, but what is the best method and what are the reasons I might choose this method over any others?</p>
[ { "answer_id": 103024, "author": "Chris James", "author_id": 3193, "author_profile": "https://Stackoverflow.com/users/3193", "pm_score": -1, "selected": false, "text": "Session[\"MyId\"]=myval;\n" }, { "answer_id": 103103, "author": "blowdart", "author_id": 2525, "author_profile": "https://Stackoverflow.com/users/2525", "pm_score": 4, "selected": true, "text": "<pages enableViewState=\"true\" enableViewStateMac=\"true\" />\n<machineKey ... validation=\"3DES\" />\n" }, { "answer_id": 103124, "author": "Loofer", "author_id": 5552, "author_profile": "https://Stackoverflow.com/users/5552", "pm_score": -1, "selected": false, "text": " <asp:label runat=server id=lblThingID visible=false />\n" }, { "answer_id": 103145, "author": "digiguru", "author_id": 5055, "author_profile": "https://Stackoverflow.com/users/5055", "pm_score": 2, "selected": false, "text": "public int CustomerID {\n get { return ViewState(\"CustomerID\"); }\n set { ViewState(\"CustomerID\") = value; }\n}\n Public Property CustomerID() As Integer\n Get\n Return ViewState(\"CustomerID\")\n End Get\n Set(ByVal value As Integer)\n ViewState(\"CustomerID\") = value\n End Set\n End Property\n" } ]
2008/09/19
[ "https://Stackoverflow.com/questions/103000", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4605/" ]
103,005
<p>Here is my situation:</p> <p>Table one contains a set of data that uses an id for an unique identifier. This table has a one to many relationship with about 6 other tables such that.</p> <p>Given Table 1 with Id of 001: Table 2 might have 3 rows with foreign key: 001 Table 3 might have 12 rows with foreign key: 001 Table 4 might have 0 rows with foreign key: 001 Table 5 might have 28 rows with foreign key: 001</p> <p>I need to write a report that lists all of the rows from Table 1 for a specified time frame followed by all of the data contained in the handful of tables that reference it.</p> <p>My current approach in pseudo code would look like this:</p> <pre><code>select * from table 1 foreach(result) { print result; select * from table 2 where id = result.id; foreach(result2) { print result2; } select * from table 3 where id = result.id foreach(result3) { print result3; } //continued for each table } </code></pre> <p>This means that the single report can run in the neighbor hood of 1000 queries. I know this is excessive however my sql-fu is a little weak and I could use some help. </p>
[ { "answer_id": 103044, "author": "Forgotten Semicolon", "author_id": 1960, "author_profile": "https://Stackoverflow.com/users/1960", "pm_score": 2, "selected": false, "text": "SELECT Table1.*, Table2.*, Table3.*, Table4.*, Table5.*\nFROM Table1\nLEFT OUTER JOIN Table2 ON Table1.ID = Table2.ID\nLEFT OUTER JOIN Table3 ON Table1.ID = Table3.ID\nLEFT OUTER JOIN Table4 ON Table1.ID = Table4.ID\nLEFT OUTER JOIN Table5 ON Table1.ID = Table5.ID\nWHERE (CRITERIA)\n" }, { "answer_id": 103048, "author": "Tom Ritter", "author_id": 8435, "author_profile": "https://Stackoverflow.com/users/8435", "pm_score": 1, "selected": false, "text": "Insert Into #rows Select id from Table1 where date between '12/30' and '12/31'\nSelect * from Table1 t join #rows r on t.id = r.id\nSelect * from Table2 t join #rows r on t.id = r.id\n--etc\n" }, { "answer_id": 103067, "author": "Josh Bush", "author_id": 1672, "author_profile": "https://Stackoverflow.com/users/1672", "pm_score": 0, "selected": false, "text": "select * from table_1 left join table_2 using(id) left join table_3 using(id);\n" }, { "answer_id": 103109, "author": "evilhomer", "author_id": 2806, "author_profile": "https://Stackoverflow.com/users/2806", "pm_score": 1, "selected": false, "text": "SELECT * FROM table1 t1\nINNER JOIN table2 t2 ON t1.id = t2.resultid -- this could be a left join if the table is not guaranteed to have entries for t1.id\nINNER JOIN table2 t3 ON t1.id = t3.resultid -- etc\n SELECT cola,colb FROM table1 WHERE id = @id\nUNION ALL\nSELECT cola,colb FROM table2 WHERE resultid = @id\nUNION ALL\nSELECT cola,colb FROM table3 WHERE resultid = @id\n" }, { "answer_id": 103137, "author": "Amy B", "author_id": 8155, "author_profile": "https://Stackoverflow.com/users/8155", "pm_score": 2, "selected": false, "text": "INSERT INTO @LocalCollection (theKey)\nSELECT id\nFROM Table1\nWHERE ...\n\n\nSELECT * FROM Table1 WHERE id in (SELECT theKey FROM @LocalCollection)\n\nSELECT * FROM Table2 WHERE id in (SELECT theKey FROM @LocalCollection)\n\nSELECT * FROM Table3 WHERE id in (SELECT theKey FROM @LocalCollection)\n\nSELECT * FROM Table4 WHERE id in (SELECT theKey FROM @LocalCollection)\n\nSELECT * FROM Table5 WHERE id in (SELECT theKey FROM @LocalCollection)\n" }, { "answer_id": 103153, "author": "user11318", "author_id": 11318, "author_profile": "https://Stackoverflow.com/users/11318", "pm_score": 0, "selected": false, "text": "SELECT * from table1 order by id\nSELECT * from table1 r, table2 t where t.table1_id = r.id order by r.id\nSELECT * from table1 r, table3 t where t.table1_id = r.id order by r.id\n" }, { "answer_id": 103215, "author": "Cervo", "author_id": 16219, "author_profile": "https://Stackoverflow.com/users/16219", "pm_score": 0, "selected": false, "text": "n create temporary table from\nselect * from table1 where rows within time frame\n\nx integer\nsql varchar(something)\nx = 1\nwhile x <= numresults {\n sql = 'SELECT * from table' + CAST(X as varchar) + ' where id in (select id from temporary table'\n execute sql\n x = x + 1\n}\n select * from tablex insert into" } ]
2008/09/19
[ "https://Stackoverflow.com/questions/103005", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2246765/" ]
103,006
<p>I've got a CSV file containing latitude and longitude values, such as:</p> <blockquote> <p>"25°36'55.57""E","45°39'12.52""N"</p> </blockquote> <p>Anyone have a quick and simple piece of C# code to convert this to double values?</p> <p>Thanks</p>
[ { "answer_id": 103057, "author": "ine", "author_id": 4965, "author_profile": "https://Stackoverflow.com/users/4965", "pm_score": 5, "selected": true, "text": "String hour = \"25\";\nString minute = \"36\";\nString second = \"55.57\";\nDouble result = (hour) + (minute) / 60 + (second) / 3600;\n" }, { "answer_id": 103357, "author": "Nick Randell", "author_id": 5932, "author_profile": "https://Stackoverflow.com/users/5932", "pm_score": 3, "selected": false, "text": "/// <summary>The regular expression parser used to parse the lat/long</summary>\nprivate static Regex Parser = new Regex(\"^(?<deg>[-+0-9]+)[^0-9]+(?<min>[0-9]+)[^0-9]+(?<sec>[0-9.,]+)[^0-9.,ENSW]+(?<pos>[ENSW]*)$\");\n\n/// <summary>Parses the lat lon value.</summary>\n/// <param name=\"value\">The value.</param>\n/// <remarks>It must have at least 3 parts 'degrees' 'minutes' 'seconds'. If it \n/// has E/W and N/S this is used to change the sign.</remarks>\n/// <returns></returns>\npublic static double ParseLatLonValue(string value)\n{\n // If it starts and finishes with a quote, strip them off\n if (value.StartsWith(\"\\\"\") && value.EndsWith(\"\\\"\"))\n {\n value = value.Substring(1, value.Length - 2).Replace(\"\\\"\\\"\", \"\\\"\");\n }\n\n // Now parse using the regex parser\n Match match = Parser.Match(value);\n if (!match.Success)\n {\n throw new ArgumentException(string.Format(CultureInfo.CurrentUICulture, \"Lat/long value of '{0}' is not recognised\", value));\n }\n\n // Convert - adjust the sign if necessary\n double deg = double.Parse(match.Groups[\"deg\"].Value);\n double min = double.Parse(match.Groups[\"min\"].Value);\n double sec = double.Parse(match.Groups[\"sec\"].Value);\n double result = deg + (min / 60) + (sec / 3600);\n if (match.Groups[\"pos\"].Success)\n {\n char ch = match.Groups[\"pos\"].Value[0];\n result = ((ch == 'S') || (ch == 'W')) ? -result : result;\n }\n return result;\n}\n" } ]
2008/09/19
[ "https://Stackoverflow.com/questions/103006", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5932/" ]
103,059
<p>Anyone have any suggestions on where to start for a newbie wanting to try out some sort of source-control along with a new journey into ASP.NET? SVN, VSS, CVS...I dont even know where to start!</p>
[ { "answer_id": 103545, "author": "Thiago Arrais", "author_id": 17801, "author_profile": "https://Stackoverflow.com/users/17801", "pm_score": 2, "selected": false, "text": "init" } ]
2008/09/19
[ "https://Stackoverflow.com/questions/103059", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18953/" ]
103,118
<p>For years, one of my most important tools has been incremental copy utility that compares the contents of two directories and shows me which files are newer / older / added / deleted. Every day I find myself copying folders of source code between my two desktop machines and the server, and such a utility is critical to avoid overwriting newer files with older ones and also to save time by only copying changed files. In addition, the utility allows me to see new files in the source folder that I don't necessarily want to copy (like temp files) that I instead can delete.</p> <p>Like anyone who subscribes to the <a href="http://en.wikipedia.org/wiki/Not_Invented_Here" rel="nofollow noreferrer">NIH</a> way of thinking, I wrote my own utility to compare the contents of two folders and let me mark files to be copied, deleted, diffed or ignored. I've had many versions of this utility going back to DOS, OS/2 and Win32.</p> <p>I use this utility on a daily basis, and it leaves me wondering: What do others use? Surely there are similar programs out there to do this... My utility doesn't have a diff screen, and it would be occasionally nice to see what the difference is between two changed files.</p> <p>What do you use for comparing and incrementally copying between folders?</p>
[ { "answer_id": 278948, "author": "Ola", "author_id": 31990, "author_profile": "https://Stackoverflow.com/users/31990", "pm_score": 1, "selected": false, "text": "robocopy source destination /MIR" } ]
2008/09/19
[ "https://Stackoverflow.com/questions/103118", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8752/" ]
103,136
<p>I am trying to execute some stored procedures in groovy way. I am able to do it quite easily by using straight JDBC but this does not seem in the spirit of Grails.</p> <p>I am trying to call the stored procedure as:</p> <pre><code>sql.query( "{call web_GetCityStateByZip(?,?,?,?,?)}",[params.postalcode, sql.out(java.sql.Types.VARCHAR), sql.out(java.sql.Types.VARCHAR), sql.out(java.sql.Types.INTEGER), sql.out(java.sql.Types.VARCHAR)]) { rs -&gt; params.city = rs.getString(2) params.state = rs.getString(3) } </code></pre> <p>I tried various ways like <code>sql.call</code>. I was trying to get output variable value after this.</p> <p>Everytime error:</p> <pre><code>Message: Cannot register out parameter. Caused by: java.sql.SQLException: Cannot register out parameter. Class: SessionExpirationFilter </code></pre> <p>but this does not seem to work.</p> <p>Can anyone point me in the right direction?</p>
[ { "answer_id": 116620, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": " Sql sql = new Sql(dataSource)\nConnection conn\nResultSet rs\ntry {\n conn = sql.createConnection()\n CallableStatement callable = conn.prepareCall(\n \"{call web_GetCityStateByZip(?,?,?,?,?)}\")\n callable.setString(\"@p_Zip\",params.postalcode)\n callable.registerOutParameter(\"@p_City\",java.sql.Types.VARCHAR)\n callable.registerOutParameter(\"@p_State\",java.sql.Types.VARCHAR)\n callable.registerOutParameter(\"@p_RetCode\",java.sql.Types.INTEGER)\n callable.registerOutParameter(\"@p_Msg\",java.sql.Types.VARCHAR)\n callable.execute()\n params.city = callable.getString(2)\n params.state = callable.getString(3)\n }\n" }, { "answer_id": 681588, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "def getHours(java.sql.Date date, User user) throws CallProceduresServiceException {\n\n log.info \"Calling stored procedure for getting hours statistics.\"\n def procedure\n def hour\n try {\n def sql = Sql.newInstance(dataSource.url, user.username, user.password, dataSource.driverClassName)\n log.debug \"Date(first param): '${date}'\"\n\n procedure = \"call ${dbPrefixName}.GK_WD_GET_SCHEDULED_TIME_SUM(?, ?, ?, ?)\"\n log.debug \"procedure: ${procedure}\"\n\n sql.call(\"{${procedure}}\", [date, Sql.out(Sql.VARCHAR.getType()), Sql.out(Sql.VARCHAR.getType()), Sql.out(Sql.VARCHAR.getType())]) {\n hourInDay, hourInWeek, hourInMonth -> \n log.debug \"Hours in day: '${hourInDay}'\"\n log.debug \"Hours in week: '${hourInWeek}'\"\n log.debug \"Hours in month: '${hourInMonth}'\"\n hour = new Hour(hourInDay, hourInWeek, hourInMonth)\n }\n log.info \"Procedure was executed.\"\n } \n catch (SQLException e) {\n throw new CallProceduresServiceException(\"Executing sql procedure failed!\"\n + \"\\nProcedure: ${procedure}\", e)\n } \n return hour \n}\n" } ]
2008/09/19
[ "https://Stackoverflow.com/questions/103136", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
103,157
<p>Can someone please remind me how to create a .Net class from an XML file?<br></p> <p>I would prefer the batch commands, or a way to integrate it into the shell.<br></p> <p>Thanks!</p>
[ { "answer_id": 104260, "author": "Nescio", "author_id": 14484, "author_profile": "https://Stackoverflow.com/users/14484", "pm_score": 2, "selected": false, "text": "@Echo off\nSet XsdExePath=\"C:\\Program Files\\Microsoft Visual Studio 8\\SDK\\v2.0\\Bin\\XSD.exe\"\nSet Language=VB\n%~d1\nCD %~d1%~p1 \n%XsdExePath% \"%~n1.xml\" /nologo\n%XsdExePath% \"%~n1.xsd\" /nologo /c /language:%Language%\n" } ]
2008/09/19
[ "https://Stackoverflow.com/questions/103157", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14484/" ]
103,177
<p>How do you enumerate the fields of a certificate help in a store. Specifically, I am trying to enumerate the fields of personal certificates issued to the logged on user.</p>
[ { "answer_id": 103228, "author": "Duncan Smart", "author_id": 1278, "author_profile": "https://Stackoverflow.com/users/1278", "pm_score": 1, "selected": false, "text": "using System.Security.Cryptography.X509Certificates;\n...\nvar store = new X509Store(StoreName.My);\nforeach(var cert in store.Certificates)\n...\n" } ]
2008/09/19
[ "https://Stackoverflow.com/questions/103177", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
103,178
<p>I figured someone can answer the question generally but if anyone wants to get specific I am trying to use:</p> <p>using System.Web.Security.SingleSignOn; using System.Web.Security.SingleSignOn.Authorization;</p> <p>I've googled my brains out and this is the closest answer I found:</p> <p>"We discussed this offline, but it looks like the ADFS assembly is GACed, but not installed on the file system or registered with VS.NET so that it shows up in the .NET tab. I'm guessing MS may need to beef up the installer for this scenario. In the meantime, you probably need to do this yourself."</p> <p>What on earth, do WHAT myself?</p>
[ { "answer_id": 103539, "author": "Travis Illig", "author_id": 8116, "author_profile": "https://Stackoverflow.com/users/8116", "pm_score": 0, "selected": false, "text": "HKEY_CURRENT_USER\\SOFTWARE\\Microsoft\\.NETFramework\\AssemblyFolders %WINDIR%\\Assembly C:\\WINDOWS\\Assembly" } ]
2008/09/19
[ "https://Stackoverflow.com/questions/103178", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18309/" ]
103,179
<p>I know I can specify one for each form, or for the root form and then it'll cascade through to all of the children forms, but I'd like to have a way of overriding the default Java Coffee Cup for all forms even those I might forget.</p> <p>Any suggestions?</p>
[ { "answer_id": 103295, "author": "Paul Brinkley", "author_id": 18160, "author_profile": "https://Stackoverflow.com/users/18160", "pm_score": 4, "selected": true, "text": "JFrame JFrame this.setIconImage(STANDARD_ICON);\n JFrame JFrame setIconImage" } ]
2008/09/19
[ "https://Stackoverflow.com/questions/103179", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2443/" ]
103,184
<p>We have a system where we want to prevent the same credit card number being registered for two different accounts. As we don't store the credit card number internally - just the last four digits and expiration date - we cannot simply compare credit card numbers and expiration dates.</p> <p>Our current idea is to store a hash (SHA-1) in our system of the credit card information when the card is registered, and to compare hashes to determine if a card has been used before.</p> <p>Usually, a salt is used to avoid dictionary attacks. I assume we are vulnerable in this case, so we should probably store a salt along with the hash.</p> <p>Do you guys see any flaws in this method? Is this a standard way of solving this problem?</p>
[ { "answer_id": 1267757, "author": "MiniQuark", "author_id": 38626, "author_profile": "https://Stackoverflow.com/users/38626", "pm_score": 3, "selected": false, "text": "hash(stored_CC1_salt+CC2)==stored_CC1_hash" }, { "answer_id": 25833770, "author": "Michael", "author_id": 599912, "author_profile": "https://Stackoverflow.com/users/599912", "pm_score": 0, "selected": false, "text": "fingerprint unique_number_identifier string" } ]
2008/09/19
[ "https://Stackoverflow.com/questions/103184", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6120/" ]
103,203
<p>We recently had a security audit and it exposed several weaknesses in the systems that are in place here. One of the tasks that resulted from it is that we need to update our partner credentials system make it more secure. </p> <p>The "old" way of doing things was to generate a (bad) password, give it to the partner with an ID and then they would send that ID and a Base 64 encoded copy of that password in with all of their XML requests over https. We then decode them and validate them.</p> <p>These passwords won't change (because then our partners would have to make coding/config changes to change them and coordinating password expirations with hundreds of partners for multiple environments would be a nightmare) and they don't have to be entered by a human or human readable. I am open to changing this if there is a better but still relatively simple implementation for our partners.</p> <p>Basically it comes down to two things: I need a more secure Java password generation system and to ensure that they are transmitted in a secure way.</p> <p>I've found a few hand-rolled password generators but nothing that really stood out as a standard way to do this (maybe for good reason). There may also be a more secure way to transmit them than simple Base 64 encoding over https. </p> <p>What would you do for the password generator and do you think that the transmission method in place is secure enough for it?</p> <p>Edit: The XML comes in a SOAP message and the credentials are in the header not in the XML itself. Also, since the passwords are a one-off operation for each partner when we set them up we're not too worried about efficiency of the generator.</p>
[ { "answer_id": 103768, "author": "erickson", "author_id": 3474, "author_profile": "https://Stackoverflow.com/users/3474", "pm_score": 4, "selected": true, "text": " SecureRandom rnd = new SecureRandom();\n /* Byte array length is multiple of LCM(log2(64), 8) / 8 = 3. */\n byte[] password = new byte[18];\n rnd.nextBytes(password);\n String encoded = Base64.encode(password);\n SecureRandom rnd = new SecureRandom();\n/* Bit length is multiple of log2(32) = 5. */\nString encoded = new BigInteger(130, rnd).toString(32); \n" } ]
2008/09/19
[ "https://Stackoverflow.com/questions/103203", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12662/" ]
103,240
<p>I have a table in a RDLC report which is utilized as a subreport, and the first column of this table is a static string. Does anyone know how I can determine if a row is the first in the table. I tried using "=First("My String")" but it didn't work.</p>
[ { "answer_id": 104361, "author": "Stephen Wrighton", "author_id": 7516, "author_profile": "https://Stackoverflow.com/users/7516", "pm_score": 2, "selected": false, "text": "=IIf(RowNumber(Nothing)=1,\"myString\", \"\")\n" } ]
2008/09/19
[ "https://Stackoverflow.com/questions/103240", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7516/" ]
103,261
<p>I recently inherited an old visual basic 6/ crystal reports project which connects to a sql server database. The error message I get (Error# -2147191803 A String is required here) when I attempt to run the project seems to be narrowed down to the .Printout command in the following code: </p> <pre> 'Login to database Set Tables = Report.Database.Tables Set Table = Tables.Item(1) Table.SetLogOnInfo ConnName, DBName, user, pass DomainName = CStr(selected) 'Set parameter Fields 'Declare parameter holders Set ParamDefs = Report.ParameterFields 'Store parameter objects For Each ParamDef In ParamDefs With ParamDef MsgBox("DomainName : " + DomainName) Select Case .ParameterFieldName Case "Company Name" .SetCurrentValue DomainName End Select Select Case .Name Case "{?Company Name}" .SetCurrentValue DomainName End Select 'Flag to see what is assigned to Current value MsgBox("paramdef: " + ParamDef.Value) End With Next Report.EnableParameterPrompting = False Screen.MousePointer = vbHourglass 'CRViewer1.ReportSource = Report 'CRViewer1.ViewReport test = 1 **Report.PrintOut** test = test + 3 currenttime = Str(Now) currenttime = Replace(currenttime, "/", "-") currenttime = Replace(currenttime, ":", "-") DomainName = Replace(DomainName, ".", "") startName = mPath + "\crysta~1.pdf" endName = mPath + "\" + DomainName + "\" + DomainName + " " + currenttime + ".pdf" rc = MsgBox("Wait for PDF job to finish", vbInformation, "H/W Report") Name startName As endName Screen.MousePointer = vbDefault End If </pre> <p>During the run, the form shows up, the ParamDef variable sets the "company name" and when it gets to the <strong>Report.PrintOut</strong> line which prompts to print, it throws the error. I'm guessing the crystal report isn't receiving the "Company Name" to properly run the crystal report. Does any one know how to diagnose this...either on the vb6 or crystal reports side to determine what I'm missing here? </p> <p><strong>UPDATE:</strong> </p> <ul> <li>inserted CStr(selected) to force DomainName to be a string</li> <li>inserted msgboxes into the for loop above and below the .setcurrentvalue line </li> <li>inserted Case "{?Company Name}" statement to see if that helps setting the value</li> <li>tried .AddCurrentValue and .SetCurrentValue functions as suggested by other forum websites</li> <li>ruled out that it was my development environement..loaded it on another machine with the exact same vb6 crystal reports 8.5 running on winxp prof sp2 and the same errors come up. </li> </ul> <p>and when I run the MsgBox(ParamDef.Value) and it also turns up blank with the same missing string error. I also can't find any documentation on the craxdrt.ParameterFieldDefinition class to see what other hidden functions are available. When I see the list of methods and property variables, it doesn't list SetCurrentValue as one of the functions. Any ideas on this?</p>
[ { "answer_id": 104259, "author": "nathaniel", "author_id": 11947, "author_profile": "https://Stackoverflow.com/users/11947", "pm_score": 1, "selected": false, "text": "Dim dv As New ParameterDiscreteValue\ndv.Value = showphone\nrpt.ParameterFields(\"showphone\").CurrentValues.Add(dv)\n" }, { "answer_id": 223789, "author": "smbarbour", "author_id": 29115, "author_profile": "https://Stackoverflow.com/users/29115", "pm_score": 0, "selected": false, "text": "For Each CRXParamDef In CrystalReport.ParameterFields\n Select Case CRXParamDef.ParameterFieldName\n Case \"@start\"\n CRXParamDef.AddCurrentValue CDate(\"1/18/2002 12:00:00AM\")\n Case \"@end\"\n CRXParamDef.AddCurrentValue Now\n End Select\nNext\n" } ]
2008/09/19
[ "https://Stackoverflow.com/questions/103261", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18853/" ]
103,280
<p>If by some miracle a segfault occurs in our program, I want to catch the SIGSEGV and let the user (possibly a GUI client) know with a single return code that a serious problem has occurred. At the same time I would like to display information on the command line to show which signal was caught.</p> <p>Today our signal handler looks as follows:</p> <pre><code>void catchSignal (int reason) { std :: cerr &lt;&lt; "Caught a signal: " &lt;&lt; reason &lt;&lt; std::endl; exit (1); } </code></pre> <p>I can hear the screams of horror with the above, as I have read from this <a href="http://groups.google.com/group/gnu.gcc.help/browse_thread/thread/6184795b39508519/f775c1f48284b212?lnk=gst&amp;q=deadlock#" rel="nofollow noreferrer">thread</a> that it is evil to call a non-reentrant function from a signal handler.</p> <p>Is there a portable way to handle the signal and provide information to users?</p> <p><strong>EDIT:</strong> Or at least portable within the POSIX framework?</p>
[ { "answer_id": 103926, "author": "Richard Corden", "author_id": 11698, "author_profile": "https://Stackoverflow.com/users/11698", "pm_score": 5, "selected": true, "text": "#include <csignal>\n\n#ifdef _WINDOWS_\n#define _exit _Exit\n#else\n#include <unistd.h>\n#endif\n\n#define PRINT_SIGNAL(X) case X: \\\n write (STDERR_FILENO, #X \")\\n\" , sizeof(#X \")\\n\")-1); \\\n break;\n\nvoid catchSignal (int reason) {\n char s[] = \"Caught signal: (\";\n write (STDERR_FILENO, s, sizeof(s) - 1);\n switch (reason)\n {\n // These are the handlers that we catch\n PRINT_SIGNAL(SIGUSR1);\n PRINT_SIGNAL(SIGHUP);\n PRINT_SIGNAL(SIGINT);\n PRINT_SIGNAL(SIGQUIT);\n PRINT_SIGNAL(SIGABRT);\n PRINT_SIGNAL(SIGILL);\n PRINT_SIGNAL(SIGFPE);\n PRINT_SIGNAL(SIGBUS);\n PRINT_SIGNAL(SIGSEGV);\n PRINT_SIGNAL(SIGTERM);\n }\n\n _Exit (1); // 'exit' is not async-signal-safe\n}\n #include <io.h>\n#define STDIO_FILENO 2\n" }, { "answer_id": 104849, "author": "fizzer", "author_id": 18167, "author_profile": "https://Stackoverflow.com/users/18167", "pm_score": 1, "selected": false, "text": "#ifdef SIGUSR1 /* or whatever */\n" } ]
2008/09/19
[ "https://Stackoverflow.com/questions/103280", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11698/" ]
103,298
<p>From managed C++, I am calling an unmanaged C++ method which returns a double. How can I convert this double into a managed string?</p>
[ { "answer_id": 103350, "author": "Scott Nichols", "author_id": 4299, "author_profile": "https://Stackoverflow.com/users/4299", "pm_score": 2, "selected": false, "text": "double d = 123.45;\nstd::ostringstream oss;\noss << d;\nstd::string s = oss.str();\n double d = 123.45\nString^ s = System::Convert::ToString(d);\n" }, { "answer_id": 103381, "author": "DrPizza", "author_id": 2131, "author_profile": "https://Stackoverflow.com/users/2131", "pm_score": 4, "selected": true, "text": "(gcnew System::Double(d))->ToString()\n" } ]
2008/09/19
[ "https://Stackoverflow.com/questions/103298", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18170/" ]
103,312
<p>How can I test for the <code>EOF</code> flag in R? </p> <p>For example:</p> <pre><code>f &lt;- file(fname, "rb") while (???) { a &lt;- readBin(f, "int", n=1) } </code></pre>
[ { "answer_id": 1204916, "author": "ars", "author_id": 2611, "author_profile": "https://Stackoverflow.com/users/2611", "pm_score": 3, "selected": false, "text": "while (length(a <- readBin(f, 'int', n=1)) > 0) {\n # do something\n}\n" } ]
2008/09/19
[ "https://Stackoverflow.com/questions/103312", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
103,316
<p>In bash, environmental variables will tab-expand correctly when placed after an echo command, for example:</p> <pre><code>echo $HOME </code></pre> <p>But after cd or cat, bash places a \ before the $ sign, like so:</p> <pre><code>cd \$HOME </code></pre> <p>If I use a variable as the second argument to a command, it won't expand at all:</p> <pre><code>cp somefile $HOM </code></pre> <p>What mysterious option do I have in my .bashrc or .inputrc file that is causing me such distress?</p>
[ { "answer_id": 103463, "author": "Brent ", "author_id": 3764, "author_profile": "https://Stackoverflow.com/users/3764", "pm_score": 2, "selected": false, "text": "help complete\n" }, { "answer_id": 110181, "author": "bd808", "author_id": 8171, "author_profile": "https://Stackoverflow.com/users/8171", "pm_score": 3, "selected": true, "text": "cd cd" }, { "answer_id": 6848382, "author": "kynan", "author_id": 396967, "author_profile": "https://Stackoverflow.com/users/396967", "pm_score": 3, "selected": false, "text": "complete" }, { "answer_id": 42326792, "author": "RaamEE", "author_id": 317460, "author_profile": "https://Stackoverflow.com/users/317460", "pm_score": 1, "selected": false, "text": "$ shopt -s direxpand $FOO_PATH/" } ]
2008/09/19
[ "https://Stackoverflow.com/questions/103316", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14102/" ]
103,325
<p>Given this XML, what XPath returns all elements whose <code>prop</code> attribute contains <code>Foo</code> (the first three nodes):</p> <pre><code>&lt;bla&gt; &lt;a prop="Foo1"/&gt; &lt;a prop="Foo2"/&gt; &lt;a prop="3Foo"/&gt; &lt;a prop="Bar"/&gt; &lt;/bla&gt; </code></pre>
[ { "answer_id": 103417, "author": "evilhomer", "author_id": 2806, "author_profile": "https://Stackoverflow.com/users/2806", "pm_score": 10, "selected": true, "text": "//a[contains(@prop,'Foo')]\n <bla>\n <a prop=\"Foo1\">a</a>\n <a prop=\"Foo2\">b</a>\n <a prop=\"3Foo\">c</a>\n <a prop=\"Bar\">a</a>\n</bla>\n /bla/a[contains(@prop,'Foo')]\n //a[contains(@prop,'Foo')] \n" }, { "answer_id": 103432, "author": "Metro Smurf", "author_id": 9664, "author_profile": "https://Stackoverflow.com/users/9664", "pm_score": 3, "selected": false, "text": "/bla/a[contains(@prop, 'Foo')]\n" }, { "answer_id": 103464, "author": "1729", "author_id": 4319, "author_profile": "https://Stackoverflow.com/users/4319", "pm_score": 4, "selected": false, "text": "descendant-or-self::*[contains(@prop,'Foo')]\n /bla/a[contains(@prop,'Foo')]\n /bla/a[position() <= 3]\n descendant-or-self::\n * or /bla/a\n [contains(@prop,'Foo')] or [position() <= 3]\n" }, { "answer_id": 2336985, "author": "Alex Beynenson", "author_id": 1138, "author_profile": "https://Stackoverflow.com/users/1138", "pm_score": 5, "selected": false, "text": "//attribute::*[contains(., 'Foo')]/..\n //attribute::*[contains(., 'Foo')]\n" }, { "answer_id": 15413875, "author": "SomeDudeSomewhere", "author_id": 332032, "author_profile": "https://Stackoverflow.com/users/332032", "pm_score": 3, "selected": false, "text": "//a[contains(@href,\"/some_link\")][text()=\"Click here\"]" } ]
2008/09/19
[ "https://Stackoverflow.com/questions/103325", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11236/" ]
103,366
<p>I've been playing around with <code>OpenGL ES</code> development on Android. <code>OpenGL ES</code> applications seem to run slowly in the Emulator on my development machine. Does this reflect likely performance of actual hardware? I'm concerned about spending too much time developing an application if the graphics performance is going to be sluggish.</p>
[ { "answer_id": 103428, "author": "taudep", "author_id": 8531, "author_profile": "https://Stackoverflow.com/users/8531", "pm_score": 3, "selected": false, "text": "Mobile Intel Pentium M 725, 1600 MHz" }, { "answer_id": 32769331, "author": "Satyavrat", "author_id": 4969037, "author_profile": "https://Stackoverflow.com/users/4969037", "pm_score": 1, "selected": false, "text": "<sdk>/extras/intel/Hardware_Accelerated_Execution_Manager/IntelHAXM.exe sc query intelhaxm\n intelhaxm ...\n STATE : 4 RUNNING\n\n ...\n emulator -avd <avd_name>\n" } ]
2008/09/19
[ "https://Stackoverflow.com/questions/103366", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
103,382
<p>I'm using managed c++ to implement a method that returns a string. I declare the method in my header file using the following signature:</p> <pre><code>String^ GetWindowText() </code></pre> <p>However, when I'm using this method from C#, the signature is:</p> <pre><code>string GetWindowTextW(); </code></pre> <p>How do I get rid of the extra "W" at the end of the method's name?</p>
[ { "answer_id": 103398, "author": "Shog9", "author_id": 811, "author_profile": "https://Stackoverflow.com/users/811", "pm_score": 3, "selected": true, "text": "#undef GetWindowText\nString^ GetWindowText()\n GetWindowText() GetWindowTextW()" } ]
2008/09/19
[ "https://Stackoverflow.com/questions/103382", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15157/" ]
103,395
<p>I've got an open-source app that is hosted at code.google.com. It is cross platform ( Linux / Windows / Mac ). I uploaded the code initially from a WinXP machine using TortoiseSVN and it seems that none of the "configure" batch files that are used for the linux build have their "execute" bits set. </p> <p>What would be the easiest way to set these for the files that need them? Using TortoiseSVN would be easier, I suppose, but if that can't be used, then I could also use the command line SVN on my linux machine.</p>
[ { "answer_id": 103498, "author": "bmdhacks", "author_id": 14032, "author_profile": "https://Stackoverflow.com/users/14032", "pm_score": 6, "selected": false, "text": "for file in `find . -name configure`; do\n svn ps svn:executable yes ${file}\ndone\n configure svn ps svn:executable yes configure\n" }, { "answer_id": 1723303, "author": "Tim Ottinger", "author_id": 15929, "author_profile": "https://Stackoverflow.com/users/15929", "pm_score": 2, "selected": false, "text": "find . -type f -name \"*.bat\" -exec svn propset svn:executable yes \"${}\" \\;\n" }, { "answer_id": 4624864, "author": "Erik", "author_id": 566792, "author_profile": "https://Stackoverflow.com/users/566792", "pm_score": 3, "selected": false, "text": "find . -type f -name \"*.bat\" -exec svn propset svn:executable yes '{}' \\;\n" }, { "answer_id": 27128735, "author": "ldgorman", "author_id": 862973, "author_profile": "https://Stackoverflow.com/users/862973", "pm_score": 1, "selected": false, "text": "find . -type f | xargs -I {} chmod --reference {} ../version1/{}\n for file in `find . -executable -type f`; do\n svn ps svn:executable yes ${file}\ndone\n" } ]
2008/09/19
[ "https://Stackoverflow.com/questions/103395", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13676/" ]
103,402
<p>In SharePoint, it is easy to set up a List webpart consisting of Links to other documents, folders, sites, etc. Unfortunately, when clicking these links, the default behavior is for the page to open in the current browser window. That is, it does NOT open the page in a new instance of the browser. This has proven annoying for a number of the users on my site.</p> <p>Does anyone know of a way to have the default behavior be to open in a NEW browser window? </p> <p>I'm hoping this is something that can be set in SharePoint rather than having users need to adjust some sort of setting in their browser.</p>
[ { "answer_id": 103541, "author": "vitule", "author_id": 1287, "author_profile": "https://Stackoverflow.com/users/1287", "pm_score": 2, "selected": false, "text": "A target=\"_blank\"" } ]
2008/09/19
[ "https://Stackoverflow.com/questions/103402", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6602/" ]
103,407
<p>When attempting to call functions in <code>math.h</code>, I'm getting link errors like the following </p> <pre><code>undefined reference to sqrt </code></pre> <p>But I'm doing a <code>#include &lt;math.h&gt;</code><br> I'm using gcc and compiling as follows:</p> <pre><code>gcc -Wall -D_GNU_SOURCE blah.c -o blah </code></pre> <p>Why can't the linker find the definition for <code>sqrt</code>?</p>
[ { "answer_id": 103411, "author": "FreeMemory", "author_id": 2132, "author_profile": "https://Stackoverflow.com/users/2132", "pm_score": 2, "selected": false, "text": "-lm libm.a" }, { "answer_id": 45885013, "author": "Billy Raseman", "author_id": 6451035, "author_profile": "https://Stackoverflow.com/users/6451035", "pm_score": 2, "selected": false, "text": "-lm gcc -Wall -D_GNU_SOURCE blah.c -o blah -lm\n -lm math.h" } ]
2008/09/19
[ "https://Stackoverflow.com/questions/103407", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2132/" ]
103,421
<p>I have a sprite loaded as a texture and I need to animate it, allowing it to "face" left or right -- essentially sometimes I need to "flip" it. I know that OpenGL has a gltranslate which repositions an object, and glrotate which rotates it. Is there a method that simply flips it across one axis? If not, how would you accomplish this?</p>
[ { "answer_id": 311849, "author": "Ivan Vučica", "author_id": 39974, "author_profile": "https://Stackoverflow.com/users/39974", "pm_score": 4, "selected": true, "text": "glTranslatef() glScalef() glRotatef() glScalef(-1,1,1); glMatrixMode(GL_TEXTURE);" } ]
2008/09/19
[ "https://Stackoverflow.com/questions/103421", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13968/" ]
103,422
<p>A lot of contact management programs do this - you type in a name (<em>e.g.</em>, "John W. Smith") and it automatically breaks it up internally into:</p> <p><strong>First name:</strong> John<br> <strong>Middle name:</strong> W.<br> <strong>Last name:</strong> Smith</p> <p>Likewise, it figures out things like "Mrs. Jane W. Smith" and "Dr. John Doe, Jr." correctly as well (assuming you allow for fields like "prefix" and "suffix" in names). </p> <p>I assume this is a fairly common things that people would want to do... so the question is... how would you do it? Is there a <em>simple</em> algorithm for this? Maybe a regular expression?</p> <p>I'm after a .NET solution, but I'm not picky.</p> <p><strong>Update:</strong> I appreciate that there is no simple solution for this that covers ALL edge cases and cultures... but let's say for the sake of argument that you need the name in pieces (filling out forms - as in, say, tax or other government forms - is one case where you are bound to enter the name into fixed fields, whether you like it or not), but you don't necessarily want to force the user to enter their name into discrete fields (less typing = easier for novice users). </p> <p>You'd want to have the program "guess" (as best it can) on what's first, middle, last, etc. If you can, look at how Microsoft Outlook does this for contacts - it lets you type in the name, but if you need to clarify, there's an extra little window you can open. I'd do the same thing - give the user the window in case they want to enter the name in discrete pieces - but allow for entering the name in one box and doing a "best guess" that covers <em>most</em> common names.</p>
[ { "answer_id": 103513, "author": "Vincent McNabb", "author_id": 16299, "author_profile": "https://Stackoverflow.com/users/16299", "pm_score": 3, "selected": false, "text": " Name = Name.Trim();\n\n arrNames = Name.Split(' ');\n\n if (arrNames.Length > 0) {\n GivenName = arrNames[0];\n }\n if (arrNames.Length > 1) {\n FamilyName = arrNames[arrNames.Length - 1];\n }\n if (arrNames.Length > 2) {\n MiddleName = string.Join(\" \", arrNames, 1, arrNames.Length - 2);\n }\n" }, { "answer_id": 394309, "author": "Thelema", "author_id": 12874, "author_profile": "https://Stackoverflow.com/users/12874", "pm_score": 2, "selected": false, "text": "/^ \\s*\n (?:((?:Dr.)|(?:Mr.)|(?:Mr?s.)|(?:Miss)|(?:2nd\\sLt.)|(?:Sen\\.?))\\s+)? # prefix\n ((?:\\w+)|(?:\\w\\.)) # first name\n(?: \\s+ ((?:\\w\\.?)|(?:\\w\\w+)) )? # middle initial\n(?: \\s+ ((?:[OD]['’]\\s?)?[-\\w]+)) # last name\n(?: ,? \\s+ ( (?:[JS]r\\.?) | (?:Esq\\.?) | (?: (?:M)|(?:Ph)|(?:Ed) \\.?\\s*D\\.?) | \n (?: R\\.?N\\.?) | (?: I+) ) )? # suffix\n\\s* $/x\n" }, { "answer_id": 7276135, "author": "Micah B.", "author_id": 172207, "author_profile": "https://Stackoverflow.com/users/172207", "pm_score": 1, "selected": false, "text": "Name Parts | Correct | Percent of Names in DB\n 2 100% 48%\n 3 98% 42%\n 4 70% 9%\n 5 45% 0.25%\n" }, { "answer_id": 8147970, "author": "user1049064", "author_id": 1049064, "author_profile": "https://Stackoverflow.com/users/1049064", "pm_score": 1, "selected": false, "text": "<cfset var nameString = REReplace(LCase(nameString), \"(^[[:alpha:]]|[[:blank:]][[:alpha:]])\", \"\\U\\1\\E\", \"ALL\")>\n" }, { "answer_id": 9508787, "author": "Aeryes", "author_id": 1241526, "author_profile": "https://Stackoverflow.com/users/1241526", "pm_score": 2, "selected": false, "text": "To Me, _______________________ (standard subscribed corrospondence)\nTo Me ( Myself | I ), ________ (standard recipient instigated corrospondence)\nTo Me Myself I, ______________ (look out, its your mother, and you're in big trouble;\n nobody addresses a person by their actual full name)\n\nDear *(Mr./Mrs./Ms./Dr./Hon./Sen.) Me M. I *(I),\nTo Whom it may Concern;\n" }, { "answer_id": 16241930, "author": "eselk", "author_id": 1042232, "author_profile": "https://Stackoverflow.com/users/1042232", "pm_score": 4, "selected": false, "text": " public static void ParseName(this string s, out string prefix, out string first, out string middle, out string last, out string suffix)\n {\n prefix = \"\";\n first = \"\";\n middle = \"\";\n last = \"\";\n suffix = \"\";\n\n // Split on period, commas or spaces, but don't remove from results.\n List<string> parts = Regex.Split(s, @\"(?<=[., ])\").ToList();\n\n // Remove any empty parts\n for (int x = parts.Count - 1; x >= 0; x--)\n if (parts[x].Trim() == \"\")\n parts.RemoveAt(x);\n\n if (parts.Count > 0)\n {\n // Might want to add more to this list\n string[] prefixes = { \"mr\", \"mrs\", \"ms\", \"dr\", \"miss\", \"sir\", \"madam\", \"mayor\", \"president\" };\n\n // If first part is a prefix, set prefix and remove part\n string normalizedPart = parts.First().Replace(\".\", \"\").Replace(\",\", \"\").Trim().ToLower();\n if (prefixes.Contains(normalizedPart))\n {\n prefix = parts[0].Trim();\n parts.RemoveAt(0);\n }\n }\n\n if (parts.Count > 0)\n {\n // Might want to add more to this list, or use code/regex for roman-numeral detection\n string[] suffixes = { \"jr\", \"sr\", \"i\", \"ii\", \"iii\", \"iv\", \"v\", \"vi\", \"vii\", \"viii\", \"ix\", \"x\", \"xi\", \"xii\", \"xiii\", \"xiv\", \"xv\" };\n\n // If last part is a suffix, set suffix and remove part\n string normalizedPart = parts.Last().Replace(\".\", \"\").Replace(\",\", \"\").Trim().ToLower();\n if (suffixes.Contains(normalizedPart))\n {\n suffix = parts.Last().Replace(\",\", \"\").Trim();\n parts.RemoveAt(parts.Count - 1);\n }\n }\n\n // Done, if no more parts\n if (parts.Count == 0)\n return;\n\n // If only one part left...\n if (parts.Count == 1)\n {\n // If no prefix, assume first name, otherwise last\n // i.e.- \"Dr Jones\", \"Ms Jones\" -- likely to be last\n if(prefix == \"\")\n first = parts.First().Replace(\",\", \"\").Trim();\n else\n last = parts.First().Replace(\",\", \"\").Trim();\n }\n\n // If first part ends with a comma, assume format:\n // Last, First [...First...]\n else if (parts.First().EndsWith(\",\"))\n {\n last = parts.First().Replace(\",\", \"\").Trim();\n for (int x = 1; x < parts.Count; x++)\n first += parts[x].Replace(\",\", \"\").Trim() + \" \";\n first = first.Trim();\n }\n\n // Otherwise assume format:\n // First [...Middle...] Last\n\n else\n {\n first = parts.First().Replace(\",\", \"\").Trim();\n last = parts.Last().Replace(\",\", \"\").Trim();\n for (int x = 1; x < parts.Count - 1; x++)\n middle += parts[x].Replace(\",\", \"\").Trim() + \" \";\n middle = middle.Trim();\n }\n }\n string name = \"Miss Jessica Dark-Angel Alba\";\nstring prefix, first, middle, last, suffix;\nname.ParseName(out prefix, out first, out middle, out last, out suffix);\n" }, { "answer_id": 53732462, "author": "PKD", "author_id": 3066592, "author_profile": "https://Stackoverflow.com/users/3066592", "pm_score": 2, "selected": false, "text": "public class FullNameDTO\n{\n public string Prefix { get; set; }\n public string FirstName { get; set; }\n public string MiddleName { get; set; }\n public string LastName { get; set; }\n public string Suffix { get; set; }\n}\n\npublic static class FullName\n{\n public static FullNameDTO GetFullNameDto(string fullName)\n {\n string[] knownPrefixes = { \"mr\", \"mrs\", \"ms\", \"miss\", \"dr\", \"sir\", \"madam\", \"master\", \"fr\", \"rev\", \"atty\", \"hon\", \"prof\", \"pres\", \"vp\", \"gov\", \"ofc\" };\n string[] knownSuffixes = { \"jr\", \"sr\", \"ii\", \"iii\", \"iv\", \"v\", \"esq\", \"cpa\", \"dc\", \"dds\", \"vm\", \"jd\", \"md\", \"phd\" };\n string[] lastNamePrefixes = { \"da\", \"de\", \"del\", \"dos\", \"el\", \"la\", \"st\", \"van\", \"von\" };\n\n var prefix = string.Empty;\n var firstName = string.Empty;\n var middleName = string.Empty;\n var lastName = string.Empty;\n var suffix = string.Empty;\n\n var fullNameDto = new FullNameDTO\n {\n Prefix = prefix,\n FirstName = firstName,\n MiddleName = middleName,\n LastName = lastName,\n Suffix = suffix\n };\n\n // Split on period, commas or spaces, but don't remove from results.\n var namePartsList = Regex.Split(fullName, \"(?<=[., ])\").ToList();\n\n #region Clean out the crap.\n for (var x = namePartsList.Count - 1; x >= 0; x--)\n {\n if (namePartsList[x].Trim() == string.Empty)\n {\n namePartsList.RemoveAt(x);\n }\n }\n #endregion\n\n #region Trim all of the parts in the list\n for (var x = namePartsList.Count - 1; x >= 0; x--)\n {\n namePartsList[x] = namePartsList[x].Trim();\n }\n #endregion\n\n #region Only one Name Part - assume a name like \"Cher\"\n if (namePartsList.Count == 1)\n {\n firstName = namePartsList.First().Replace(\",\", string.Empty).Trim();\n fullNameDto.FirstName = firstName;\n\n namePartsList.RemoveAt(0);\n }\n #endregion\n\n #region Get the Prefix\n if (namePartsList.Count > 0)\n {\n //If we find a prefix, save it and drop it from the overall parts\n var cleanedPart = namePartsList.First()\n .Replace(\".\", string.Empty)\n .Replace(\",\", string.Empty)\n .Trim()\n .ToLower();\n\n if (knownPrefixes.Contains(cleanedPart))\n {\n prefix = namePartsList[0].Trim();\n fullNameDto.Prefix = prefix;\n\n namePartsList.RemoveAt(0);\n }\n }\n #endregion\n\n #region Get the Suffix\n if (namePartsList.Count > 0)\n {\n #region Scan the full parts list for a potential Suffix\n foreach (var namePart in namePartsList)\n {\n var cleanedPart = namePart.Replace(\",\", string.Empty)\n .Trim()\n .ToLower();\n\n if (!knownSuffixes.Contains(cleanedPart.Replace(\".\", string.Empty))) { continue; }\n\n if (namePart.ToLower() == \"jr\" && namePart != namePartsList.Last()) { continue; }\n\n suffix = namePart.Replace(\",\", string.Empty).Trim();\n fullNameDto.Suffix = suffix;\n\n namePartsList.Remove(namePart);\n break;\n }\n #endregion\n }\n #endregion\n\n //If, strangely, there's nothing else in the overall parts... we're done here.\n if (namePartsList.Count == 0) { return fullNameDto; }\n\n #region Prefix/Suffix taken care of - only one \"part\" left.\n if (namePartsList.Count == 1)\n {\n //If no prefix, assume first name (e.g. \"Cher\"), otherwise last (e.g. \"Dr Jones\", \"Ms Jones\")\n if (prefix == string.Empty)\n {\n firstName = namePartsList.First().Replace(\",\", string.Empty).Trim();\n fullNameDto.FirstName = firstName;\n }\n else\n {\n lastName = namePartsList.First().Replace(\",\", string.Empty).Trim();\n fullNameDto.LastName = lastName;\n }\n }\n #endregion\n\n #region First part ends with a comma\n else if (namePartsList.First().EndsWith(\",\") || (namePartsList.Count >= 3 && namePartsList.Any(n => n == \",\") && namePartsList.Last() != \",\"))\n {\n #region Assume format: \"Last, First\"\n if (namePartsList.First().EndsWith(\",\"))\n {\n lastName = namePartsList.First().Replace(\",\", string.Empty).Trim();\n fullNameDto.LastName = lastName;\n namePartsList.Remove(namePartsList.First());\n\n firstName = namePartsList.First();\n fullNameDto.FirstName = firstName;\n namePartsList.Remove(namePartsList.First());\n\n if (!namePartsList.Any()) { return fullNameDto; }\n\n foreach (var namePart in namePartsList)\n {\n middleName += namePart.Trim() + \" \";\n }\n fullNameDto.MiddleName = middleName;\n\n return fullNameDto;\n }\n #endregion\n\n #region Assume strange scenario like \"Last Suffix, First\"\n var indexOfComma = namePartsList.IndexOf(\",\");\n\n #region Last Name is the first thing in the list\n if (indexOfComma == 1)\n {\n namePartsList.Remove(namePartsList[indexOfComma]);\n\n lastName = namePartsList.First().Replace(\",\", string.Empty).Trim();\n fullNameDto.LastName = lastName;\n namePartsList.Remove(namePartsList.First());\n\n firstName = namePartsList.First();\n fullNameDto.FirstName = firstName;\n namePartsList.Remove(namePartsList.First());\n\n if (!namePartsList.Any()) { return fullNameDto; }\n\n foreach (var namePart in namePartsList)\n {\n middleName += namePart.Trim() + \" \";\n }\n fullNameDto.MiddleName = middleName;\n\n return fullNameDto;\n }\n #endregion\n\n #region Last Name might be a prefixed one, like \"da Vinci\"\n if (indexOfComma == 2)\n {\n var possibleLastPrefix = namePartsList.First()\n .Replace(\".\", string.Empty)\n .Replace(\",\", string.Empty)\n .Trim()\n .ToLower();\n\n if (lastNamePrefixes.Contains(possibleLastPrefix))\n {\n namePartsList.Remove(namePartsList[indexOfComma]);\n\n var lastPrefix = namePartsList.First().Trim();\n namePartsList.Remove(lastPrefix);\n\n lastName = $\"{lastPrefix} {namePartsList.First().Replace(\",\", string.Empty).Trim()}\";\n fullNameDto.LastName = lastName;\n namePartsList.Remove(namePartsList.First());\n }\n else\n {\n lastName = namePartsList.First().Replace(\",\", string.Empty).Trim();\n namePartsList.Remove(namePartsList.First());\n\n lastName = lastName + \" \" + namePartsList.First().Replace(\",\", string.Empty).Trim();\n namePartsList.Remove(namePartsList.First());\n\n fullNameDto.LastName = lastName;\n }\n\n namePartsList.Remove(\",\");\n\n firstName = namePartsList.First();\n fullNameDto.FirstName = firstName;\n namePartsList.Remove(namePartsList.First());\n\n if (!namePartsList.Any()) { return fullNameDto; }\n\n foreach (var namePart in namePartsList)\n {\n middleName += namePart.Trim() + \" \";\n }\n fullNameDto.MiddleName = middleName;\n\n return fullNameDto;\n }\n #endregion\n #endregion\n }\n #endregion\n\n #region Everything else\n else\n {\n if (namePartsList.Count >= 3)\n {\n firstName = namePartsList.First().Replace(\",\", string.Empty).Trim();\n fullNameDto.FirstName = firstName;\n namePartsList.RemoveAt(0);\n\n //Check for possible last name prefix\n\n var possibleLastPrefix = namePartsList[namePartsList.Count - 2]\n .Replace(\".\", string.Empty)\n .Replace(\",\", string.Empty)\n .Trim()\n .ToLower();\n\n if (lastNamePrefixes.Contains(possibleLastPrefix))\n {\n lastName = $\"{namePartsList[namePartsList.Count - 2].Trim()} {namePartsList[namePartsList.Count -1].Replace(\",\", string.Empty).Trim()}\";\n fullNameDto.LastName = lastName;\n\n namePartsList.RemoveAt(namePartsList.Count - 1);\n namePartsList.RemoveAt(namePartsList.Count - 1);\n }\n else\n {\n lastName = namePartsList.Last().Replace(\",\", string.Empty).Trim();\n fullNameDto.LastName = lastName;\n\n namePartsList.RemoveAt(namePartsList.Count - 1);\n }\n\n middleName = string.Join(\" \", namePartsList).Trim();\n fullNameDto.MiddleName = middleName;\n\n namePartsList.Clear();\n }\n else\n {\n if (namePartsList.Count == 1)\n {\n lastName = namePartsList.First().Replace(\",\", string.Empty).Trim();\n fullNameDto.LastName = lastName;\n\n namePartsList.RemoveAt(0);\n }\n else\n {\n var possibleLastPrefix = namePartsList.First()\n .Replace(\".\", string.Empty)\n .Replace(\",\", string.Empty)\n .Trim()\n .ToLower();\n\n if (lastNamePrefixes.Contains(possibleLastPrefix))\n {\n lastName = $\"{namePartsList.First().Replace(\",\", string.Empty).Trim()} {namePartsList.Last().Replace(\",\", string.Empty).Trim()}\";\n fullNameDto.LastName = lastName;\n\n namePartsList.Clear();\n }\n else\n {\n firstName = namePartsList.First().Replace(\",\", string.Empty).Trim();\n fullNameDto.FirstName = firstName;\n\n namePartsList.RemoveAt(0);\n\n lastName = namePartsList.Last().Replace(\",\", string.Empty).Trim();\n fullNameDto.LastName = lastName;\n\n namePartsList.Clear();\n }\n }\n }\n }\n #endregion\n\n namePartsList.Clear();\n\n fullNameDto.Prefix = prefix;\n fullNameDto.FirstName = firstName;\n fullNameDto.MiddleName = middleName;\n fullNameDto.LastName = lastName;\n fullNameDto.Suffix = suffix;\n\n return fullNameDto;\n }\n}\n" }, { "answer_id": 62421134, "author": "Ali Bayat", "author_id": 3427324, "author_profile": "https://Stackoverflow.com/users/3427324", "pm_score": 0, "selected": false, "text": "HumanNameParser Install-Package HumanNameParser\n string name = \"Mr Ali R Von Bayat III\";\n\nvar result = name.Parse();\n\n//result = new Name()\n//{\n// Salutation = \"Mr\",\n// FirstName = \"Ali\",\n// MiddleInitials = \"R\",\n// LastName = \"Von Bayat\",\n// Suffix = \"III\"\n//};\n" } ]
2008/09/19
[ "https://Stackoverflow.com/questions/103422", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5956/" ]
103,423
<p>I've always taken the approach of first deploying the database with a minimal set of indexes and then adding/changing indexes as performance dictates.</p> <p>This approach works reasonably well. However, it still doesn't tell me where I could improve performance. It only tells me where performance is so bad that users complain about it.</p> <p>Currently, I'm in the process of refactoring database objects on a lot of our applications. </p> <p>So should I not bother to look for performance improvements since "premature optimization is the root of all evil"? </p> <p>When refactoring application code, the developer is constantly looking for ways to improve the code quality. Is there a way to constantly be looking for improvements in database performance as well? If so, what tools and techniques have you found to be most helpful? </p> <p>I've briefly played around with the "Database engine tuning advisor" but didn't find it to be helpful at all. Maybe I just need more experience interpreting the results.</p>
[ { "answer_id": 45939640, "author": "Dhyan Mohandas", "author_id": 5323907, "author_profile": "https://Stackoverflow.com/users/5323907", "pm_score": 1, "selected": false, "text": "SELECT Cash, Age, Amount FROM Investments; \n SELECT * FROM Investments;\n SELECT Name, count (Name) FROM Investments WHERE Name!= ‘Test’ AND Name!= ‘Value’ GROUP BY Name;\n SELECT Name, count (Name) FROM Investments GROUP BY Name HAVING Name!= ‘Test’ AND Name!= ‘Value’ ;\n SELECT Amount FROM Investments WHERE (Cash, Fixed) = (SELECT MAX (Cash), MAX (Fixed) FROM Retirements) AND Goal = 1; \n SELECT Amount FROM Investments WHERE Cash = (SELECT MAX (Cash) FROM Retirements) AND Fixed = (SELECT MAX (Fixed) FROM Retirements) AND Goal = 1;\n SELECT COUNT(*) FROM [dbo].[PercentageForGoal]\n SELECT rows FROM sysindexes\nWHERE id = OBJECT_ID('[dbo].[PercentageForGoal]') AND indid< 2\n" } ]
2008/09/19
[ "https://Stackoverflow.com/questions/103423", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5458/" ]
103,453
<p>Is there an easy way of finding out the host name of a machine that generated a user mode dump file via WinDbg? </p> <p>Or at least any piece of identifying information to try and confirm that two dump files came from the same system.</p>
[ { "answer_id": 103492, "author": "Kris Kumler", "author_id": 4281, "author_profile": "https://Stackoverflow.com/users/4281", "pm_score": 1, "selected": false, "text": "0: kd> x srv!SrvComputerName\nbe8ce2e8 srv!SrvComputerName = _UNICODE_STRING \"AIGM-MYCOMP-PUB01\"\n" }, { "answer_id": 103496, "author": "Martin Cote", "author_id": 9936, "author_profile": "https://Stackoverflow.com/users/9936", "pm_score": 4, "selected": true, "text": "!peb COMPUTERNAME" }, { "answer_id": 27472963, "author": "Andy", "author_id": 1018484, "author_profile": "https://Stackoverflow.com/users/1018484", "pm_score": 0, "selected": false, "text": "d3d58450 \"127.0.0.1\" \n3: kd> du\nffffe001 d3d5846c \"169.254.66.248\"\n3: kd>\nffffe001 d3d5848c \"fe80::f0cb:5439:f12f:42f8\"\n3: kd>\nffffe001 d3d584c2 \"192.168.104.249\"\n3: kd> \nffffe001" }, { "answer_id": 49765700, "author": "Kevin", "author_id": 1170023, "author_profile": "https://Stackoverflow.com/users/1170023", "pm_score": 0, "selected": false, "text": "10: kd> !envvar COMPUTERNAME\nCOMPUTERNAME = a-host-name\n EXTS.dll !envvar 10: kd> !peb\nPEB NULL...\n !process 0b110001 !process 0 0x31 wininit.exe\n 10: kd> !process 0 0x31 wininit.exe\nPROCESS ffffc485c82655c0\n SessionId: 0 Cid: 02d0 Peb: 8d04c6b000 ParentCid: 0258\n DirBase: 40452f000 ObjectTable: ffffe30b1150fb40 HandleCount: 163.\n Image: wininit.exe\n VadRoot ffffc485c862b990 Vads 61 Clone 0 Private 326. Modified 12. Locked 2.\n DeviceMap ffffe30b0a817880\n Token ffffe30b1150f060\n ElapsedTime 00:00:18.541\n UserTime 00:00:00.000\n KernelTime 00:00:00.015\n QuotaPoolUsage[PagedPool] 121696\n QuotaPoolUsage[NonPagedPool] 11448\n Working Set Sizes (now,min,max) (1750, 50, 345) (7000KB, 200KB, 1380KB)\n PeakWorkingSetSize 1697\n VirtualSize 2097239 Mb\n PeakVirtualSize 2097239 Mb\n PageFaultCount 2104\n MemoryPriority BACKGROUND\n BasePriority 13\n CommitCharge 470\n\n PEB at 0000008d04c6b000 \n InheritedAddressSpace: No\n ReadImageFileExecOptions: No\n BeingDebugged: No\n ImageBaseAddress: 00007ff7be3d0000\n Ldr 00007ff8dff4f3a0\n Ldr.Initialized: Yes\n Ldr.InInitializationOrderModuleList: 000001be470e1c10 . 000001be47128d60\n Ldr.InLoadOrderModuleList: 000001be470e1d80 . 000001be47128d40\n Ldr.InMemoryOrderModuleList: 000001be470e1d90 . 000001be47128d50\n Base TimeStamp Module\n 7ff7be3d0000 600d94df Jan 24 10:40:15 2021 C:\\Windows\\system32\\wininit.exe\n 7ff8dfdf0000 493793ea Dec 04 03:25:14 2008 C:\\Windows\\SYSTEM32\\ntdll.dll\n...\n SubSystemData: 0000000000000000\n ProcessHeap: 000001be470e0000\n ProcessParameters: 000001be470e1460\n CurrentDirectory: 'C:\\Windows\\system32\\'\n WindowTitle: '< Name not readable >'\n ImageFile: 'C:\\Windows\\system32\\wininit.exe'\n CommandLine: 'wininit.exe'\n DllPath: '< Name not readable >'\n Environment: 000001be47104460\n ALLUSERSPROFILE=C:\\ProgramData\n CommonProgramFiles=C:\\Program Files\\Common Files\n CommonProgramFiles(x86)=C:\\Program Files (x86)\\Common Files\n CommonProgramW6432=C:\\Program Files\\Common Files\n COMPUTERNAME=a-host-name\n ComSpec=C:\\Windows\\system32\\cmd.exe\n NUMBER_OF_PROCESSORS=16\n OS=Windows_NT\n Path=C:\\Windows\\system32;C:\\Windows;C:\\Windows\\System32\\Wbem;C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\\n PATHEXT=.COM;.EXE;.BAT;.CMD;.VBS;.VBE;.JS;.JSE;.WSF;.WSH;.MSC\n PROCESSOR_ARCHITECTURE=AMD64\n PROCESSOR_IDENTIFIER=AMD64 Family 23 Model 1 Stepping 1, AuthenticAMD\n PROCESSOR_LEVEL=23\n PROCESSOR_REVISION=0101\n ProgramData=C:\\ProgramData\n ProgramFiles=C:\\Program Files\n ProgramFiles(x86)=C:\\Program Files (x86)\n ProgramW6432=C:\\Program Files\n PSModulePath=%ProgramFiles%\\WindowsPowerShell\\Modules;C:\\Windows\\system32\\WindowsPowerShell\\v1.0\\Modules\n PUBLIC=C:\\Users\\Public\n SystemDrive=C:\n SystemRoot=C:\\Windows\n TEMP=C:\\temp\n TMP=C:\\temp\n USERNAME=SYSTEM\n USERPROFILE=C:\\Windows\\system32\\config\\systemprofile\n windir=C:\\Windows\n .process /p <PROCESS_ADDRESS> !envvar COMPUTERNAME" } ]
2008/09/19
[ "https://Stackoverflow.com/questions/103453", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3631/" ]
103,460
<p>I need to get the name of the machine my .NET app is running on. What is the best way to do this?</p>
[ { "answer_id": 103468, "author": "Billy Jo", "author_id": 3447, "author_profile": "https://Stackoverflow.com/users/3447", "pm_score": 3, "selected": false, "text": "System.Environment.MachineName" }, { "answer_id": 104154, "author": "Ray Hayes", "author_id": 7093, "author_profile": "https://Stackoverflow.com/users/7093", "pm_score": 4, "selected": true, "text": "MAX_COMPUTERNAME_LENGTH \n class Class1\n{\n enum COMPUTER_NAME_FORMAT\n {\n ComputerNameNetBIOS,\n ComputerNameDnsHostname,\n ComputerNameDnsDomain,\n ComputerNameDnsFullyQualified,\n ComputerNamePhysicalNetBIOS,\n ComputerNamePhysicalDnsHostname,\n ComputerNamePhysicalDnsDomain,\n ComputerNamePhysicalDnsFullyQualified\n }\n\n [DllImport(\"kernel32.dll\", SetLastError=true, CharSet=CharSet.Auto)]\n static extern bool GetComputerNameEx(COMPUTER_NAME_FORMAT NameType,\n [Out] StringBuilder lpBuffer, ref uint lpnSize);\n\n [STAThread]\n static void Main(string[] args)\n {\n bool success;\n StringBuilder name = new StringBuilder(260);\n uint size = 260;\n success = GetComputerNameEx(COMPUTER_NAME_FORMAT.ComputerNameDnsDomain,\n name, ref size);\n Console.WriteLine(name.ToString());\n }\n}\n" } ]
2008/09/19
[ "https://Stackoverflow.com/questions/103460", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14101/" ]
103,489
<p>Below is the code I use to build an HTML table on the fly (using JSON data received from the server).</p> <p>I display an animated pleasewait (.gif) graphic while the data is loading. However, the graphic freezes while the JavaScript function is building the table. At first, I was just happy to make this happen (display the table), I guess now I need to work on efficiency. At the very least I need to stop the animated graphic from freezing. I can go to a static "Loading" display, but I would rather make this method work.</p> <p>Suggestions for my pleasewait display? And efficiency? Possibly a better way to build the table? Or maybe not a table, but some other "table" like display</p> <pre><code>var t = eval( "(" + request + ")" ) ; var myTable = '' ; myTable += '&lt;table id="myTable" cellspacing=0 cellpadding=2 border=1&gt;' ; myTable += "&lt;thead&gt;" ; myTable += "&lt;tr&gt;"; for (var i = 0; i &lt; t.hdrs.length; i++) { myTable += "&lt;th&gt;" + header + "&lt;/th&gt;"; } myTable += "&lt;/tr&gt;" ; myTable += "&lt;/thead&gt;" ; myTable += "&lt;tbody&gt;" ; for (var i = 0; i &lt; t.data.length; i++) { myTable += '&lt;tr&gt;'; for (var j = 0; j &lt; t.hdrs.length; j++) { myTable += '&lt;td&gt;'; if (t.data[i][t.hdrs[j]] == "") { myTable += "&amp;nbsp;" ; } else { myTable += t.data[i][t.hdrs[j]] ; } myTable += "&lt;/td&gt;"; } myTable += "&lt;/tr&gt;"; } myTable += "&lt;/tbody&gt;" ; myTable += "&lt;/table&gt;" ; $("#result").append(myTable) ; $("#PleaseWaitGraphic").addClass("hide"); $(".rslt").removeClass("hide") ; </code></pre>
[ { "answer_id": 103527, "author": "Jim", "author_id": 8427, "author_profile": "https://Stackoverflow.com/users/8427", "pm_score": 2, "selected": false, "text": "$(\"<table>\")" }, { "answer_id": 104053, "author": "Lasar", "author_id": 9438, "author_profile": "https://Stackoverflow.com/users/9438", "pm_score": -1, "selected": false, "text": "$(\"#result\").append('<table id=\"myTable\" cellspacing=0 cellpadding=2 border=1></table>');\n$('#myTable').append('<thead><tr></tr></thead>');\n$('#myTable').append('<tbody></tbody>');\n\nfor (var i = 0; i < t.hdrs.length; i++) { \n $('#myTable thead tr').append('<th>'+header+'</th>');\n}\n\nfor (var i = 0; i < t.data.length; i++) { \n myTr = '<tr>';\n for (var j = 0; j < t.hdrs.length; j++) { \n myTr += '<td>';\n if (t.data[i][t.hdrs[j]] == \"\") { \n myTr += \"&nbsp;\" ; \n }\n else { \n myTr += t.data[i][t.hdrs[j]] ; \n }\n myTr += \"</td>\";\n }\n myTr += \"</tr>\";\n $('#myTable tbody').append(myTr);\n}\n\n$(\"#PleaseWaitGraphic\").addClass(\"hide\");\n$(\".rslt\").removeClass(\"hide\") ;\n" }, { "answer_id": 106624, "author": "Andrew Hedges", "author_id": 11577, "author_profile": "https://Stackoverflow.com/users/11577", "pm_score": 6, "selected": true, "text": "function doSomething (progressFn [, additional arguments]) {\n // Initialize a few things here...\n (function () {\n // Do a little bit of work here...\n if (continuation condition) {\n // Inform the application of the progress\n progressFn(value, total);\n // Process next chunk\n setTimeout(arguments.callee, 0);\n }\n })();\n}\n var t = eval('(' + request + ')') ;\nvar templates = {\n tr : '<tr>#{row}</tr>',\n th : '<th>#{header}</th>',\n td : '<td>#{cell}</td>'\n};\nvar table = '<table><thead><tr>';\n$.each(t.hdrs, function (key, val) {\n table += $.tmpl(templates.th, {header: val});\n});\n...\n" }, { "answer_id": 345372, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": ".append + innerHTML" } ]
2008/09/19
[ "https://Stackoverflow.com/questions/103489", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2755/" ]
103,512
<p>I've heard that the <code>static_cast</code> function should be preferred to C-style or simple function-style casting. Is this true? Why?</p>
[ { "answer_id": 103529, "author": "prakash", "author_id": 123, "author_profile": "https://Stackoverflow.com/users/123", "pm_score": 3, "selected": false, "text": "double d = 3.14159265;\nint i = static_cast<int>(d);\n" }, { "answer_id": 103612, "author": "DrPizza", "author_id": 2131, "author_profile": "https://Stackoverflow.com/users/2131", "pm_score": 5, "selected": false, "text": "static_cast const_cast reinterpret_cast" }, { "answer_id": 103619, "author": "Pitarou", "author_id": 1260685, "author_profile": "https://Stackoverflow.com/users/1260685", "pm_score": 3, "selected": false, "text": "(bar) foo reinterpret_cast<bar> foo static_cast<bar> foo" }, { "answer_id": 103868, "author": "Euro Micelli", "author_id": 2230, "author_profile": "https://Stackoverflow.com/users/2230", "pm_score": 10, "selected": true, "text": "static_cast<>() reinterpret_cast<>() const_cast<>() dynamic_cast<>() static_cast<>() dynamic_cast<>() reinterpret_cast<>() const_cast<>() foo class CDerivedClass : public CMyBase {...};\nclass CMyOtherStuff {...} ;\n\nCMyBase *pSomething; // filled somewhere\n CDerivedClass *pMyObject;\npMyObject = static_cast<CDerivedClass*>(pSomething); // Safe; as long as we checked\n\npMyObject = (CDerivedClass*)(pSomething); // Same as static_cast<>\n // Safe; as long as we checked\n // but harder to read\n CMyOtherStuff *pOther;\npOther = static_cast<CMyOtherStuff*>(pSomething); // Compiler error: Can't convert\n\npOther = (CMyOtherStuff*)(pSomething); // No compiler error.\n // Same as reinterpret_cast<>\n // and it's wrong!!!\n pOther = reinterpret_cast<CMyOtherStuff*>(pSomething);\n // No compiler error.\n // but the presence of a reinterpret_cast<> is \n // like a Siren with Red Flashing Lights in your code.\n // The mere typing of it should cause you to feel VERY uncomfortable.\n" }, { "answer_id": 103871, "author": "Dusty Campbell", "author_id": 2174, "author_profile": "https://Stackoverflow.com/users/2174", "pm_score": 5, "selected": false, "text": "static_cast<> static_cast<> int i;\ndouble d = (double)i; //C-style cast\ndouble d2 = static_cast<double>( i ); //C++ cast\n class A {};\nclass B : public A {};\n\nA* a = new B;\nB* b = (B*)a; //(1) what is this supposed to do?\n\nchar* c = (char*)new int( 5 ); //(2) that weird?\nchar* c1 = static_cast<char*>( new int( 5 ) ); //(3) compile time error\n a static_cast<> dynamic_cast<> reintrepret_cast<> const const_cast<>" }, { "answer_id": 26269263, "author": "Hossein", "author_id": 2736559, "author_profile": "https://Stackoverflow.com/users/2736559", "pm_score": 7, "selected": false, "text": "static_cast<>() static_cast<>() char c = 10; // 1 byte\nint *p = (int*)&c; // 4 bytes\n *p = 5; // run-time error: stack corruption\n int *q = static_cast<int*>(&c); // compile-time error\n" } ]
2008/09/19
[ "https://Stackoverflow.com/questions/103512", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11575/" ]