qid int64 4 19.1M | question stringlengths 18 48.3k | answers list | date stringlengths 10 10 | metadata list |
|---|---|---|---|---|
290,227 | <p>What is the equivalent of Java's <code>System.currentTimeMillis()</code> in C#?</p>
| [
{
"answer_id": 290265,
"author": "Jon Skeet",
"author_id": 22656,
"author_profile": "https://Stackoverflow.com/users/22656",
"pm_score": 7,
"selected": false,
"text": "private static readonly DateTime Jan1st1970 = new DateTime\n (1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);\n\npublic static long CurrentTimeMillis()\n{\n return (long) (DateTime.UtcNow - Jan1st1970).TotalMilliseconds;\n}\n"
},
{
"answer_id": 290278,
"author": "Hath",
"author_id": 5186,
"author_profile": "https://Stackoverflow.com/users/5186",
"pm_score": 3,
"selected": false,
"text": "System.currentTimeMillis() public static double GetCurrentMilli()\n {\n DateTime Jan1970 = new DateTime(1970, 1, 1, 0, 0,0,DateTimeKind.Utc);\n TimeSpan javaSpan = DateTime.UtcNow - Jan1970;\n return javaSpan.TotalMilliseconds;\n }\n"
},
{
"answer_id": 290301,
"author": "gimel",
"author_id": 6491,
"author_profile": "https://Stackoverflow.com/users/6491",
"pm_score": 2,
"selected": false,
"text": "double long TimeSpan ts = (DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc));\nlong millis = (long)ts.TotalMilliseconds;\nConsole.WriteLine(\"millis={0}\", millis);\n millis=1226674125796\n"
},
{
"answer_id": 290353,
"author": "Joel Coehoorn",
"author_id": 3043,
"author_profile": "https://Stackoverflow.com/users/3043",
"pm_score": 3,
"selected": false,
"text": "public static class DateTimeExtensions\n{\n private static DateTime Jan1st1970 = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);\n public static long currentTimeMillis(this DateTime d)\n {\n return (long) ((DateTime.UtcNow - Jan1st1970).TotalMilliseconds);\n }\n}\n"
},
{
"answer_id": 5703212,
"author": "Barend",
"author_id": 49489,
"author_profile": "https://Stackoverflow.com/users/49489",
"pm_score": 6,
"selected": false,
"text": "currentTimeMillis() currentTimeMillis() Environment.TickCount"
},
{
"answer_id": 6194429,
"author": "bstabile",
"author_id": 778481,
"author_profile": "https://Stackoverflow.com/users/778481",
"pm_score": 4,
"selected": false,
"text": "var sw = Stopwatch.StartNew();\n...\nvar elapsedStage1 = sw.ElapsedMilliseconds;\n...\nvar elapsedStage2 = sw.ElapsedMilliseconds;\n...\nsw.Stop();\n"
},
{
"answer_id": 15093666,
"author": "Bitterblue",
"author_id": 1442225,
"author_profile": "https://Stackoverflow.com/users/1442225",
"pm_score": 1,
"selected": false,
"text": "[DllImport(\"kernel32.dll\")]\nstatic extern uint GetTickCount();\n\n// call\nuint ticks = GetTickCount();\n"
},
{
"answer_id": 27124904,
"author": "TechCrap",
"author_id": 1158652,
"author_profile": "https://Stackoverflow.com/users/1158652",
"pm_score": 2,
"selected": false,
"text": "DateTime.Now.Ticks / TimeSpan.TicksPerMillisecond\n"
},
{
"answer_id": 44136945,
"author": "Aubin",
"author_id": 1624376,
"author_profile": "https://Stackoverflow.com/users/1624376",
"pm_score": 2,
"selected": false,
"text": "private static long nanoTime() {\n long nano = 10000L * Stopwatch.GetTimestamp();\n nano /= TimeSpan.TicksPerMillisecond;\n nano *= 100L;\n return nano;\n}\n java.lang.System.nanoTime();\n static int64_t hpms_nano() {\n struct timespec t;\n clock_gettime( CLOCK_MONOTONIC, &t );\n int64_t nano = t.tv_sec;\n nano *= 1000;\n nano *= 1000;\n nano *= 1000;\n nano += t.tv_nsec;\n return nano;\n}\n static int64_t hpms_nano() {\n static LARGE_INTEGER ticksPerSecond;\n if( ticksPerSecond.QuadPart == 0 ) {\n QueryPerformanceFrequency( &ticksPerSecond );\n }\n LARGE_INTEGER ticks;\n QueryPerformanceCounter( &ticks );\n uint64_t nano = ( 1000*1000*10UL * ticks.QuadPart ) / ticksPerSecond.QuadPart;\n nano *= 100UL;\n return nano;\n}\n"
},
{
"answer_id": 50603116,
"author": "Ramunas",
"author_id": 3667714,
"author_profile": "https://Stackoverflow.com/users/3667714",
"pm_score": 4,
"selected": false,
"text": "DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()\n"
}
] | 2008/11/14 | [
"https://Stackoverflow.com/questions/290227",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
290,238 | <p>I'm trying to do something that gets a cs file in runtime from user make it meaningful to assembly get its properties, methods etc. </p>
<p>Is there a way to do this by reflection in C#?</p>
| [
{
"answer_id": 290269,
"author": "edosoft",
"author_id": 6399,
"author_profile": "https://Stackoverflow.com/users/6399",
"pm_score": 4,
"selected": true,
"text": "CodeDomProvider codeProvider = new CSharpCodeProvider();\nICodeCompiler compiler = codeProvider.CreateCompiler();\n\n// add compiler parameters\nCompilerParameters compilerParams = new CompilerParameters();\ncompilerParams.CompilerOptions = \"/target:library /optimize\";\ncompilerParams.GenerateExecutable = false;\ncompilerParams.GenerateInMemory = true; \ncompilerParams.IncludeDebugInformation = false;\ncompilerParams.ReferencedAssemblies.Add(\"mscorlib.dll\");\ncompilerParams.ReferencedAssemblies.Add(\"System.dll\");\n\n// compile the code\nCompilerResults results = compiler.CompileAssemblyFromSource(compilerParams, sourceCode);\n"
}
] | 2008/11/14 | [
"https://Stackoverflow.com/questions/290238",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4215/"
] |
290,254 | <p>Lets say I have a web app which has a page that may contain 4 script blocks - the script I write may be found in one of those blocks, but I do not know which one, that is handled by the controller. </p>
<p>I bind some <code>onclick</code> events to a button, but I find that they sometimes execute in an order I did not expect. </p>
<p>Is there a way to ensure order, or how have you handled this problem in the past?</p>
| [
{
"answer_id": 290294,
"author": "dowski",
"author_id": 21712,
"author_profile": "https://Stackoverflow.com/users/21712",
"pm_score": 7,
"selected": false,
"text": "$('#mydiv').click(function(e) {\n // maniplate #mydiv ...\n $('#mydiv').trigger('mydiv-manipulated');\n});\n\n$('#mydiv').bind('mydiv-manipulated', function(e) {\n // do more stuff now that #mydiv has been manipulated\n return;\n});\n"
},
{
"answer_id": 4671782,
"author": "wildblue",
"author_id": 573098,
"author_profile": "https://Stackoverflow.com/users/573098",
"pm_score": 2,
"selected": false,
"text": "/**\n * Guarantee that a event handler allways be the last to execute\n * @param owner The jquery object with any others events handlers $(selector)\n * @param event The event descriptor like 'click'\n * @param handler The event handler to be executed allways at the end.\n**/\nfunction bindAtTheEnd(owner,event,handler){\n var aux=function(){owner.unbind(event,handler);owner.bind(event,handler);};\n bindAtTheStart(owner,event,aux,true);\n\n}\n/**\n * Bind a event handler at the start of all others events handlers.\n * @param owner Jquery object with any others events handlers $(selector);\n * @param event The event descriptor for example 'click';\n * @param handler The event handler to bind at the start.\n * @param one If the function only be executed once.\n**/\nfunction bindAtTheStart(owner,event,handler,one){\n var eventos,index;\n var handlers=new Array();\n owner.unbind(event,handler);\n eventos=owner.data(\"events\")[event];\n for(index=0;index<eventos.length;index+=1){\n handlers[index]=eventos[index];\n }\n owner.unbind(event);\n if(one){\n owner.one(event,handler);\n }\n else{\n owner.bind(event,handler);\n }\n for(index=0;index<handlers.length;index+=1){\n owner.bind(event,ownerhandlers[index]);\n } \n}\n"
},
{
"answer_id": 4700103,
"author": "robin",
"author_id": 576770,
"author_profile": "https://Stackoverflow.com/users/576770",
"pm_score": 3,
"selected": false,
"text": "function bindFirst(owner, event, handler) {\n owner.unbind(event, handler);\n owner.bind(event, handler);\n\n var events = owner.data('events')[event];\n events.unshift(events.pop());\n\n owner.data('events')[event] = events;\n}\n"
},
{
"answer_id": 5524001,
"author": "Daniel Lewis",
"author_id": 563811,
"author_profile": "https://Stackoverflow.com/users/563811",
"pm_score": 5,
"selected": false,
"text": "event.stopPropagation() event.preventDefault() $( '#mybutton' ).click( function(e) { \n // Do stuff first\n} );\n\n$( '#mybutton' ).click( function(e) { \n // Do other stuff first\n} );\n\n$( document ).delegate( '#mybutton', 'click', function(e) {\n // Do stuff last\n} );\n"
},
{
"answer_id": 6152570,
"author": "Ed .",
"author_id": 124426,
"author_profile": "https://Stackoverflow.com/users/124426",
"pm_score": 6,
"selected": true,
"text": "(function($) {\n $.fn.bindFirst = function(/*String*/ eventType, /*[Object])*/ eventData, /*Function*/ handler) {\n var indexOfDot = eventType.indexOf(\".\");\n var eventNameSpace = indexOfDot > 0 ? eventType.substring(indexOfDot) : \"\";\n\n eventType = indexOfDot > 0 ? eventType.substring(0, indexOfDot) : eventType;\n handler = handler == undefined ? eventData : handler;\n eventData = typeof eventData == \"function\" ? {} : eventData;\n\n return this.each(function() {\n var $this = $(this);\n var currentAttrListener = this[\"on\" + eventType];\n\n if (currentAttrListener) {\n $this.bind(eventType, function(e) {\n return currentAttrListener(e.originalEvent); \n });\n\n this[\"on\" + eventType] = null;\n }\n\n $this.bind(eventType + eventNameSpace, eventData, handler);\n\n var allEvents = $this.data(\"events\") || $._data($this[0], \"events\");\n var typeEvents = allEvents[eventType];\n var newEvent = typeEvents.pop();\n typeEvents.unshift(newEvent);\n });\n };\n})(jQuery);\n"
},
{
"answer_id": 8468868,
"author": "tomasbedrich",
"author_id": 570503,
"author_profile": "https://Stackoverflow.com/users/570503",
"pm_score": 3,
"selected": false,
"text": "element.data('events').action.reverse();\n $('#mydiv').data('events').click.reverse();\n"
},
{
"answer_id": 19228333,
"author": "cage rattler",
"author_id": 2568974,
"author_profile": "https://Stackoverflow.com/users/2568974",
"pm_score": 3,
"selected": false,
"text": "$(\"button\").click(function(e){\n if(bSomeConditional)\n e.stopImmediatePropagation();//Don't execute the widget's handler\n}).each(function () {\n var aClickListeners = $._data(this, \"events\").click;\n aClickListeners.reverse();\n});\n"
},
{
"answer_id": 25242201,
"author": "mightyiam",
"author_id": 359072,
"author_profile": "https://Stackoverflow.com/users/359072",
"pm_score": 0,
"selected": false,
"text": "// Binds a jQuery event to elements at the start of the event chain for that type.\njQuery.extend({\n _bindEventHandlerAtStart: function ($elements, eventType, handler) {\n var _data;\n\n $elements.bind(eventType, handler);\n // This bound the event, naturally, at the end of the event chain. We\n // need it at the start.\n\n if (typeof jQuery._data === 'function') {\n // Since jQuery 1.8.1, it seems, that the events object isn't\n // available through the public API `.data` method.\n // Using `$._data, where it exists, seems to work.\n _data = true;\n }\n\n $elements.each(function (index, element) {\n var events;\n\n if (_data) {\n events = jQuery._data(element, 'events')[eventType];\n } else {\n events = jQuery(element).data('events')[eventType];\n }\n\n events.unshift(events.pop());\n\n if (_data) {\n jQuery._data(element, 'events')[eventType] = events;\n } else {\n jQuery(element).data('events')[eventType] = events;\n }\n });\n }\n});\n"
},
{
"answer_id": 27433119,
"author": "Tanya Sweeney",
"author_id": 4351837,
"author_profile": "https://Stackoverflow.com/users/4351837",
"pm_score": -1,
"selected": false,
"text": "$.when( $('#myDiv').css('background-color', 'red') )\n .then( alert('hi!') )\n .then( myClickFunction( $('#myID') ) )\n .then( myThingToRunAfterClick() );\n"
},
{
"answer_id": 35472362,
"author": "Linh Dam",
"author_id": 1815779,
"author_profile": "https://Stackoverflow.com/users/1815779",
"pm_score": 0,
"selected": false,
"text": "<span onclick=\"yourEventHandler(event)\">Button</span>\n"
},
{
"answer_id": 37841905,
"author": "9nix00",
"author_id": 576472,
"author_profile": "https://Stackoverflow.com/users/576472",
"pm_score": 1,
"selected": false,
"text": "$('form').submit(handle);\n bindAtTheStart($('form'),'submit',handle);\n"
}
] | 2008/11/14 | [
"https://Stackoverflow.com/questions/290254",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/26188/"
] |
290,285 | <p>I have a module that sends an email to a specified email address but I want to default the email recipient to the portal administrator. How can I retrieve this information?</p>
| [
{
"answer_id": 290416,
"author": "Douglas Anderson",
"author_id": 5678,
"author_profile": "https://Stackoverflow.com/users/5678",
"pm_score": 2,
"selected": false,
"text": "' get the current portal\nDim portSettings As PortalSettings = PortalController.GetCurrentPortalSettings\n\n' get email address\nDim email as string = portSettings.Email\n"
},
{
"answer_id": 290572,
"author": "bdukes",
"author_id": 2688,
"author_profile": "https://Stackoverflow.com/users/2688",
"pm_score": 4,
"selected": true,
"text": "PortalModuleBase PortalSettings PortalSettings.Email\n"
}
] | 2008/11/14 | [
"https://Stackoverflow.com/questions/290285",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/35165/"
] |
290,287 | <p>I need to determine which pages of a Word document that a keyword occurs on. I have some tools that can get me the text of the document, but nothing that tells me which pages the text occurs on. Does anyone have a good starting place for me? I'm using .NET</p>
<p>Thanks!</p>
<p>edit: Additional constraint: I can't use any of the Interop stuff.</p>
<p>edit2: If anybody knows of stable libraries that can do this, that'd also be helpful. I use Aspose, but as far as I know that doesn't have anything.</p>
| [
{
"answer_id": 290357,
"author": "Douglas Anderson",
"author_id": 5678,
"author_profile": "https://Stackoverflow.com/users/5678",
"pm_score": 3,
"selected": true,
"text": "Microsoft.Office.Interop.Word.Application wordApplication = new Microsoft.Office.Interop.Word.Application();\nobject missing = Type.Missing;\nobject fileName = @\"c:\\file.doc\";\nobject objFalse = false;\n\nwordApplication.DisplayAlerts = Microsoft.Office.Interop.Word.WdAlertLevel.wdAlertsNone;\nMicrosoft.Office.Interop.Word.Document doc = wordApplication.Documents.Open(ref fileName, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing,ref objFalse, ref missing, ref missing, ref missing, ref missing);\n\n//I belevie you can define a SelectionRange and insert here\ndoc.ActiveWindow.Selection.WholeStory();\ndoc.ActiveWindow.Selection.Copy();\n\nIDataObject data = Clipboard.GetDataObject();\nstring text = data.GetData(DataFormats.Text).ToString();\n\ndoc.Close(ref missing, ref missing, ref missing);\ndoc = null;\n\nwordApplication.Quit(ref missing, ref missing, ref missing);\nwordApplication = null;\n"
}
] | 2008/11/14 | [
"https://Stackoverflow.com/questions/290287",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/37685/"
] |
290,296 | <p>I'm working on a website that uses lots of png24 files, for transparency.</p>
<p>I need to replace them with png8 files, as all the png fix style javascript workarounds for png24 cause IE6 to lock up randomly. </p>
<p>See this link to get an idea of the symptoms IE6 displays - <a href="http://blogs.cozi.com/tech/2008/03/transparent-pngs-can-deadlock-ie6.html" rel="noreferrer">http://blogs.cozi.com/tech/2008/03/transparent-pngs-can-deadlock-ie6.html</a></p>
<p>Does anybody know an easy way of targeting existing png24 files, to replace them with the png8s?</p>
<p>I'm using a OS X, and file browsers like Adobe bridge don't show this, nor can I find the info on the commandline, or the finder.</p>
<p>Help!</p>
| [
{
"answer_id": 290365,
"author": "Alnitak",
"author_id": 6782,
"author_profile": "https://Stackoverflow.com/users/6782",
"pm_score": 4,
"selected": true,
"text": "file % file foo.png \nfoo.png: PNG image data, 1514 x 1514, 8-bit grayscale, non-interlaced\n"
},
{
"answer_id": 8547143,
"author": "Kornel",
"author_id": 27009,
"author_profile": "https://Stackoverflow.com/users/27009",
"pm_score": 2,
"selected": false,
"text": "pngquant pngquant -v -f --ext .png 256 *.png\n"
},
{
"answer_id": 31447710,
"author": "user1938976",
"author_id": 1938976,
"author_profile": "https://Stackoverflow.com/users/1938976",
"pm_score": 1,
"selected": false,
"text": "pngcheck.exe a.png\nOK: a.png (1024x1024, 32-bit RGB+alpha, non-interlaced, 80.7%).\n\npngcheck.exe b.png\nOK: b.png (1024x1024, 8-bit palette+trns, non-interlaced, 83.1%).\n"
}
] | 2008/11/14 | [
"https://Stackoverflow.com/questions/290296",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15479/"
] |
290,304 | <p>After reading <a href="http://www.onlamp.com/pub/a/apache/2005/02/10/database_logs.html" rel="noreferrer">an article about the subject from O'Reilly</a>, I wanted to ask Stack Overflow for their thoughts on the matter.</p>
| [
{
"answer_id": 23537177,
"author": "Piotr Perak",
"author_id": 679340,
"author_profile": "https://Stackoverflow.com/users/679340",
"pm_score": 2,
"selected": false,
"text": "select * from logs\nwhere log_name = 'wcf' and log_level = 'error'\n select * from logs\nwhere contextId = 'what you get from previous select' order by timestamp\n"
}
] | 2008/11/14 | [
"https://Stackoverflow.com/questions/290304",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/572/"
] |
290,305 | <p>I have a problem trying to model a many-to-one relationship in NHibernate, where the object on the 'one' side has a unique constraint on a column. The problem is as follows:</p>
<p>I have two tables, 'Person' and 'Country'. Each Person has one and only one Country associated with it. A Country can have many Persons (really! :)) and a Countries' Name is unique. The following is the mapping on the Person side:</p>
<pre><code><many-to-one Name="Country">
<column Name="CountryId"/>
</many-to-one>
</code></pre>
<p>On the Country side:</p>
<pre><code><property name="Name" unique="true">
<column name="Name" length="50">
</property>
</code></pre>
<p>Now in the database I have added a unique constraint on the Name column in the Country table. If I call Save() on a Person instance NHibernate just tries to do INSERTS, whereas I would expect it to check if a Country Name exists and use its ID in the CountryID column in the Person table. Instead, an exception is thrown that results from violation of the unique constraint in the database. </p>
<p>It seems to me Nibernate should have enough mapping metadata to do the right thing (or does the unique attribute on the property not ensure this?). Does anyone know how to do this or have a workaround?</p>
<p>Thanks, </p>
<p>Martijn </p>
| [
{
"answer_id": 291533,
"author": "Sean Carpenter",
"author_id": 729,
"author_profile": "https://Stackoverflow.com/users/729",
"pm_score": 3,
"selected": false,
"text": "Person p = new Person();\np.Country = session.Load<Country>(countryId);\nsession.Save(p);\n"
}
] | 2008/11/14 | [
"https://Stackoverflow.com/questions/290305",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
290,309 | <p>I have SSRS Report being accessed from a Report Server. Is there any way I can give an error message of my own, if my report fails to open there? </p>
| [
{
"answer_id": 291533,
"author": "Sean Carpenter",
"author_id": 729,
"author_profile": "https://Stackoverflow.com/users/729",
"pm_score": 3,
"selected": false,
"text": "Person p = new Person();\np.Country = session.Load<Country>(countryId);\nsession.Save(p);\n"
}
] | 2008/11/14 | [
"https://Stackoverflow.com/questions/290309",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
290,320 | <p>I have a web server on port 80 and port 81. IE can connect to the server on either port. This worked fine until I installed an application with a file type (.TPJ) that had a MIME type of text/xml on the client PC. At that point IE no longer opened the web site, but offered to download a file <em>serverName.TPJ</em>. The file contained the correct information from the web site.</p>
<p>I changed the installer for the application so it didn't register the MIME type. Now IE on the client PC offers to download a file with unknown file type. Note that the application has never been installed on the server PC.</p>
<p>The problem occurs with IE7. It doesn't occur with Firefox, Safari, or Chrome.</p>
<p>Does anyone know how to work around this?</p>
| [
{
"answer_id": 290681,
"author": "Wayne Johnston",
"author_id": 37691,
"author_profile": "https://Stackoverflow.com/users/37691",
"pm_score": 2,
"selected": false,
"text": "regsvr32 msxml3.dll\n"
}
] | 2008/11/14 | [
"https://Stackoverflow.com/questions/290320",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/37691/"
] |
290,322 | <p>I'm trying to hide the "Title" field in a list.
This doesn't seem to work:</p>
<pre><code>SPList myList;
...
SPField titleField = myList.Fields.GetField("Title");
//titleField.PushChangesToLists = true; <-- doesn't seem to make a difference
titleField.ShowInEditForm = false;
titleField.ShowInDisplayForm = false;
titleField.ShowInNewForm = false;
titleField.Update();
//myList.Update(); <-- make no difference
</code></pre>
<p>What am I doing wrong?</p>
| [
{
"answer_id": 290350,
"author": "Brian Liang",
"author_id": 5853,
"author_profile": "https://Stackoverflow.com/users/5853",
"pm_score": 0,
"selected": false,
"text": "using (SPSite site = new SPSite(webUrl))\n{\n using (SPWeb web = site.OpenWeb())\n {\n try\n {\n //... Get SPList ...\n }\n }\n}\n"
},
{
"answer_id": 290412,
"author": "Brian Liang",
"author_id": 5853,
"author_profile": "https://Stackoverflow.com/users/5853",
"pm_score": 5,
"selected": true,
"text": "field.Hidden = true;\nfield.Update();\n"
},
{
"answer_id": 4253213,
"author": "varun",
"author_id": 517049,
"author_profile": "https://Stackoverflow.com/users/517049",
"pm_score": 0,
"selected": false,
"text": "SPView view = list.DefaultView; \nif(view.ViewFields.Exists(\"LinkTitle\")) \n{ \n view.ViewFields.Delete(\"LinkTitle\"); \n view.Update(); \n}\n"
},
{
"answer_id": 21901726,
"author": "Wout",
"author_id": 192327,
"author_profile": "https://Stackoverflow.com/users/192327",
"pm_score": 0,
"selected": false,
"text": "myList.FieldLinks[\"SomeField\"].Hidden = true;\n"
},
{
"answer_id": 25081169,
"author": "user3785010",
"author_id": 3785010,
"author_profile": "https://Stackoverflow.com/users/3785010",
"pm_score": 2,
"selected": false,
"text": "if(field.CanToggleHidden) {\n field.Hidden = false;\n}\nelse\n{\n // display an error message or write to your favorite logging location\n // explaining that there is no hope of changing the value of Hidden until\n // CanToggleHidden changes to TRUE first.\n}\n"
}
] | 2008/11/14 | [
"https://Stackoverflow.com/questions/290322",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1287/"
] |
290,326 | <p>Is it possible using StAX (specifically woodstox) to format the output xml with newlines and tabs, i.e. in the form:</p>
<pre>
<element1>
<element2>
someData
</element2>
</element1>
</pre>
<p>instead of:</p>
<pre><element1><element2>someData</element2></element1></pre>
<p>If this is not possible in woodstox, is there any other lightweight libs that can do this?</p>
| [
{
"answer_id": 290507,
"author": "Josh",
"author_id": 2204759,
"author_profile": "https://Stackoverflow.com/users/2204759",
"pm_score": 4,
"selected": true,
"text": "transformer.setOutputProperty(OutputKeys.INDENT, \"yes\");"
},
{
"answer_id": 485126,
"author": "StaxMan",
"author_id": 59501,
"author_profile": "https://Stackoverflow.com/users/59501",
"pm_score": 2,
"selected": false,
"text": "SMOutputFactory sf = new SMOutputFactory(XMLOutputFactory.newInstance());\nSMOutputDocument doc = sf.createOutputDocument(new FileOutputStream(\"output.xml\"));\ndoc.setIndentation(\"\\n \", 1, 2); // for unix linefeed, 2 spaces per level \n// write doc like: \nSMOutputElement root = doc.addElement(\"element1\"); \nroot.addElement(\"element2\").addCharacters(\"someData\"); \ndoc.closeRoot(); // important, flushes, closes output\n"
},
{
"answer_id": 3625359,
"author": "Juha Syrjälä",
"author_id": 1431,
"author_profile": "https://Stackoverflow.com/users/1431",
"pm_score": 5,
"selected": false,
"text": "XMLOutputFactory xmlof = XMLOutputFactory.newInstance();\nXMLStreamWriter writer = new IndentingXMLStreamWriter(xmlof.createXMLStreamWriter(out));\n"
},
{
"answer_id": 18876209,
"author": "Sebastien Lorber",
"author_id": 82609,
"author_profile": "https://Stackoverflow.com/users/82609",
"pm_score": 0,
"selected": false,
"text": "public class IndentingStaxEventItemWriter<T> extends StaxEventItemWriter<T> {\n\n @Setter\n @Getter\n private boolean indenting = true;\n\n @Override\n protected XMLEventWriter createXmlEventWriter( XMLOutputFactory outputFactory, Writer writer) throws XMLStreamException {\n if ( isIndenting() ) {\n return new IndentingXMLEventWriter( super.createXmlEventWriter( outputFactory, writer ) );\n }\n else {\n return super.createXmlEventWriter( outputFactory, writer );\n }\n }\n\n}\n <dependency>\n <groupId>net.java.dev.stax-utils</groupId>\n <artifactId>stax-utils</artifactId>\n <version>20070216</version>\n</dependency>\n"
},
{
"answer_id": 38371920,
"author": "Roland",
"author_id": 480894,
"author_profile": "https://Stackoverflow.com/users/480894",
"pm_score": 3,
"selected": false,
"text": "public String transform(String xml) throws XMLStreamException, TransformerException\n{\n Transformer t = TransformerFactory.newInstance().newTransformer();\n t.setOutputProperty(OutputKeys.INDENT, \"yes\");\n t.setOutputProperty(\"{http://xml.apache.org/xslt}indent-amount\", \"2\");\n Writer out = new StringWriter();\n t.transform(new StreamSource(new StringReader(xml)), new StreamResult(out));\n return out.toString();\n}\n"
},
{
"answer_id": 51123218,
"author": "Nh Wh",
"author_id": 9924820,
"author_profile": "https://Stackoverflow.com/users/9924820",
"pm_score": 1,
"selected": false,
"text": "XMLOutputFactory outputFactory = XMLOutputFactory.newInstance();\n XMLEventWriter writer = outputFactory.createXMLEventWriter(w);\n XMLEventFactory eventFactory = XMLEventFactory.newInstance();\n Characters newLine = eventFactory.createCharacters(\"\\n\"); \n writer.add(startRoot);\n writer.add(newLine);\n"
}
] | 2008/11/14 | [
"https://Stackoverflow.com/questions/290326",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/142/"
] |
290,330 | <p>How is the guest account in SQL Server (2000, 2005, 2008) supposed to be used? What is it good for? I've tried enabling the account but I still can't get certain users to be able to refresh Excel 2007 PivotTables attached to views which I have given SELECT rights to GUEST.</p>
<p>What am I missing? </p>
| [
{
"answer_id": 290507,
"author": "Josh",
"author_id": 2204759,
"author_profile": "https://Stackoverflow.com/users/2204759",
"pm_score": 4,
"selected": true,
"text": "transformer.setOutputProperty(OutputKeys.INDENT, \"yes\");"
},
{
"answer_id": 485126,
"author": "StaxMan",
"author_id": 59501,
"author_profile": "https://Stackoverflow.com/users/59501",
"pm_score": 2,
"selected": false,
"text": "SMOutputFactory sf = new SMOutputFactory(XMLOutputFactory.newInstance());\nSMOutputDocument doc = sf.createOutputDocument(new FileOutputStream(\"output.xml\"));\ndoc.setIndentation(\"\\n \", 1, 2); // for unix linefeed, 2 spaces per level \n// write doc like: \nSMOutputElement root = doc.addElement(\"element1\"); \nroot.addElement(\"element2\").addCharacters(\"someData\"); \ndoc.closeRoot(); // important, flushes, closes output\n"
},
{
"answer_id": 3625359,
"author": "Juha Syrjälä",
"author_id": 1431,
"author_profile": "https://Stackoverflow.com/users/1431",
"pm_score": 5,
"selected": false,
"text": "XMLOutputFactory xmlof = XMLOutputFactory.newInstance();\nXMLStreamWriter writer = new IndentingXMLStreamWriter(xmlof.createXMLStreamWriter(out));\n"
},
{
"answer_id": 18876209,
"author": "Sebastien Lorber",
"author_id": 82609,
"author_profile": "https://Stackoverflow.com/users/82609",
"pm_score": 0,
"selected": false,
"text": "public class IndentingStaxEventItemWriter<T> extends StaxEventItemWriter<T> {\n\n @Setter\n @Getter\n private boolean indenting = true;\n\n @Override\n protected XMLEventWriter createXmlEventWriter( XMLOutputFactory outputFactory, Writer writer) throws XMLStreamException {\n if ( isIndenting() ) {\n return new IndentingXMLEventWriter( super.createXmlEventWriter( outputFactory, writer ) );\n }\n else {\n return super.createXmlEventWriter( outputFactory, writer );\n }\n }\n\n}\n <dependency>\n <groupId>net.java.dev.stax-utils</groupId>\n <artifactId>stax-utils</artifactId>\n <version>20070216</version>\n</dependency>\n"
},
{
"answer_id": 38371920,
"author": "Roland",
"author_id": 480894,
"author_profile": "https://Stackoverflow.com/users/480894",
"pm_score": 3,
"selected": false,
"text": "public String transform(String xml) throws XMLStreamException, TransformerException\n{\n Transformer t = TransformerFactory.newInstance().newTransformer();\n t.setOutputProperty(OutputKeys.INDENT, \"yes\");\n t.setOutputProperty(\"{http://xml.apache.org/xslt}indent-amount\", \"2\");\n Writer out = new StringWriter();\n t.transform(new StreamSource(new StringReader(xml)), new StreamResult(out));\n return out.toString();\n}\n"
},
{
"answer_id": 51123218,
"author": "Nh Wh",
"author_id": 9924820,
"author_profile": "https://Stackoverflow.com/users/9924820",
"pm_score": 1,
"selected": false,
"text": "XMLOutputFactory outputFactory = XMLOutputFactory.newInstance();\n XMLEventWriter writer = outputFactory.createXMLEventWriter(w);\n XMLEventFactory eventFactory = XMLEventFactory.newInstance();\n Characters newLine = eventFactory.createCharacters(\"\\n\"); \n writer.add(startRoot);\n writer.add(newLine);\n"
}
] | 2008/11/14 | [
"https://Stackoverflow.com/questions/290330",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/36590/"
] |
290,335 | <p>I have a table cell, and I want a div within it to always be at the bottom left corner. The following works fine in IE and Safari, but Firefox is positioning the <code>div</code> absolutely on the page, not within the cell (code based on the solution solution <a href="https://stackoverflow.com/questions/104953/position-an-html-element-relative-to-its-container-using-css">here</a>). I have tested both with and without the DTD, which put Firefox in Quirks mode and Standards mode, and neither worked properly. I'm stuck - any ideas?</p>
<pre><code><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title>Test</title>
<style type="text/css">
table { width:500px; }
th, td { vertical-align: top; border:1px solid black; position:relative; }
th { width:100px; }
.manage { text-align:right; position:absolute; bottom:0; right:0; }
</style>
</head>
<body >
<table>
<tr>
<th>Some info about the following thing and this is actually going to span a few lines</th>
<td><p>A short blurb</p><div class="manage">Edit | Delete</div></td>
</tr>
<tr>
<th>Some info about the following thing and this is actually going to span a few lines</th>
<td><p>A short blurb</p><div class="manage">Edit | Delete</div></td>
</tr>
</table>
</body>
</html>
</code></pre>
| [
{
"answer_id": 290371,
"author": "Boris Smirnov",
"author_id": 35513,
"author_profile": "https://Stackoverflow.com/users/35513",
"pm_score": 1,
"selected": false,
"text": "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\"\n \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">\n<html xmlns=\"http://www.w3.org/1999/xhtml\" xml:lang=\"en\" lang=\"en\">\n <head>\n <title>Test</title>\n <style type=\"text/css\">\n table { width:500px; }\n th, td { vertical-align: top; border:1px solid black; }\n th { width:100px; }\n div.body {position:relative; width:500px;}\n .manage { text-align:right; position:absolute; bottom:0; right:0; display:block}\n </style>\n </head>\n <body >\n <div class=\"body\"><table>\n <tr>\n <th>Some info about the following thing and this is actually going to span a few lines</th>\n <td><p>A short blurb</p><div class=\"manage\">Edit | Delete</div></td>\n </tr>\n </table></div>\n </body>\n</html>\n"
},
{
"answer_id": 290384,
"author": "Lasar",
"author_id": 9438,
"author_profile": "https://Stackoverflow.com/users/9438",
"pm_score": 0,
"selected": false,
"text": "position: relative td div td position: relative"
},
{
"answer_id": 290389,
"author": "Powerlord",
"author_id": 15880,
"author_profile": "https://Stackoverflow.com/users/15880",
"pm_score": 0,
"selected": false,
"text": "vertical-align: bottom;"
},
{
"answer_id": 290395,
"author": "Aron Rotteveel",
"author_id": 11568,
"author_profile": "https://Stackoverflow.com/users/11568",
"pm_score": 3,
"selected": false,
"text": "height:100% position:relative; <table>\n <tr>\n <td>\n <div style=\"position:relative;height:100%;\">\n Normal inline content.\n <div class=\"manage\">your absolute-positioned content</div>\n </div>\n </td>\n </tr>\n</table>\n"
},
{
"answer_id": 3291529,
"author": "Wouter",
"author_id": 396966,
"author_profile": "https://Stackoverflow.com/users/396966",
"pm_score": 1,
"selected": false,
"text": "display:block"
}
] | 2008/11/14 | [
"https://Stackoverflow.com/questions/290335",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/96/"
] |
290,347 | <p>I need to use sendmail from Macs in an office. At the moment, I can get it to work on the two development Macs (which I think is due to MAMP being installed and working), but getting it to go on the others seems to be a problem...</p>
<p>I assume it's down to some config issue, and hope there's someway to fix it (without resorting to installing MAMP on each machine !).</p>
<p>I think it may be down to the 'local' nature of the from, but not sure. Here's a dump of /var/log/mail.log if that's any help: </p>
<pre><code>Nov 14 14:37:06 claire-g5 postfix/master[5339]: daemon started -- version 2.4.3, configuration /etc/postfix
Nov 14 14:37:06 claire-g5 postfix/qmgr[5341]: 2B625250BDB: from=<claire@claire-g5.local>, size=1131, nrcpt=1 (queue active)
Nov 14 14:37:06 claire-g5 postfix/qmgr[5341]: D5D19250D5A: from=<claire@claire-g5.local>, size=1191, nrcpt=1 (queue active)
Nov 14 14:37:06 claire-g5 postfix/smtp[5344]: 2B625250BDB: host mx01.xxx.uk[212.x.x.134] said: 451 cannot relay now to <xx@xx.com>, please try again later (in reply to RCPT TO command)
Nov 14 14:37:06 claire-g5 postfix/smtp[5346]: D5D19250D5A: host mx01.xxx.uk[212.x.x.186] said: 451 cannot relay now to <xx@xx.com>, please try again later (in reply to RCPT TO command)
Nov 14 14:37:07 claire-g5 postfix/smtp[5346]: D5D19250D5A: to=<xx@xx.com>, relay=mx01.xxx.uk[212.x.x.134]:25, delay=2350, delays=2349/0.08/0.7/0.12, dsn=4.0.0, status=deferred (host mx01.xxx.uk[212.x.x.134] said: 451 cannot
Nov 14 14:37:07 claire-g5 postfix/pickup[5340]: 1A2EC2511D1: uid=501 from=<claire
</code></pre>
| [
{
"answer_id": 290400,
"author": "Dycey",
"author_id": 35961,
"author_profile": "https://Stackoverflow.com/users/35961",
"pm_score": 0,
"selected": false,
"text": "### MAMP Postfix Configuration - Start ###\n\nmyorigin = example.com\nmyhostname = mailer.$myorigin\nsmtpd_sender_restrictions = permit_inet_interfaces\n\n# smart host\nrelayhost = auth.example.co.uk\nsmtp_sasl_auth_enable = yes\nsmtp_sasl_password_maps = hash:/etc/postfix/sasl_MAMP_passwd\nsmtp_sasl_security_options = noanonymous\n\n\n### MAMP Postfix Configuration - End ###\n# DONT REMOVE: MAMP PRO main.cf template compatibility version: 1\n"
}
] | 2008/11/14 | [
"https://Stackoverflow.com/questions/290347",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/35961/"
] |
290,368 | <p>How can I go through all external links in a div with javascript, adding (or appending) a class and alt-text?</p>
<p>I guess I need to fetch all objects inside the div element, then check if each object is a , and check if the href attributen starts with http(s):// (should then be an external link), then add content to the alt and class attribute (if they don't exist create them, if they do exists; append the wanted values).</p>
<p>But, how do I do this in code?</p>
| [
{
"answer_id": 290445,
"author": "Josh",
"author_id": 2204759,
"author_profile": "https://Stackoverflow.com/users/2204759",
"pm_score": 0,
"selected": false,
"text": "$(\"div a[href^='http']\").each(function() {\n $(this).attr(\"alt\",altText);\n var oldClassAttributeValue = $(this).attr(\"class\");\n if(!oldClassAttributeValue) {\n $(this).attr(\"class\",newClassAttributeValue);\n }\n});\n"
},
{
"answer_id": 290496,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "var links = document.getElementsByTagName(\"a\"); //use div object here instead of document\nfor (var i=0; i<links.length; i++)\n{\n if (links[i].href.substring(0, 5) == 'https')\n {\n links[i].setAttribute('title', 'abc');\n links[i].setAttribute('class', 'abc');\n links[i].setAttribute('className', 'abc');\n }\n}\n"
},
{
"answer_id": 290534,
"author": "mike nvck",
"author_id": 36531,
"author_profile": "https://Stackoverflow.com/users/36531",
"pm_score": 0,
"selected": false,
"text": "window.onload = function(){\n targetDiv = document.getElementById(\"divName\");\n linksArray = targetDiv.getElementsByTagName(\"a\");\n for(i=0;i=linksArray.length;i++){\n thisLink = linksArray[i].href;\n if(thisLink.substring(4,0) = \"http\"){\n linksArray[i].className += \"yourcontent\"; //you said append so +=\n linksArray[i].alt += \"yourcontent\";\n } \n }\n }\n"
},
{
"answer_id": 290837,
"author": "PhiLho",
"author_id": 15459,
"author_profile": "https://Stackoverflow.com/users/15459",
"pm_score": 3,
"selected": true,
"text": "<style type=\"text/css\">\n.AddedClass\n{\n background-color: #88FF99;\n}\n</style>\n<script type=\"text/javascript\">\nwindow.onload = function ()\n{\n var re = /^(https?:\\/\\/[^\\/]+).*$/;\n var currentHref = window.location.href.replace(re, '$1');\n var reLocal = new RegExp('^' + currentHref.replace(/\\./, '\\\\.'));\n\n var linksDiv = document.getElementById(\"Links\");\n if (linksDiv == null) return;\n var links = linksDiv.getElementsByTagName(\"a\");\n for (var i = 0; i < links.length; i++)\n {\n var href = links[i].href;\n if (href == '' || reLocal.test(href) || !/^http/.test(href))\n continue;\n if (links[i].className != undefined)\n {\n links[i].className += ' AddedClass';\n }\n else\n {\n links[i].className = 'AddedClass';\n }\n if (links[i].title != undefined && links[i].title != '')\n {\n links[i].title += ' (outside link)';\n }\n else\n {\n links[i].title = 'Outside link';\n }\n }\n}\n</script>\n\n<div id=\"Links\">\n<a name=\"_Links\"></a>\n<a href=\"/foo.asp\">FOO</a>\n<a href=\"ftp://FTP.org/FILE.zip\">FILE</a>\n<a href=\"http://example.com/somewhere.html\">SomeWhere</a>\n<a href=\"http://example.com/somewhere2.html\" class=\"Gah\">SomeWhere 2</a>\n<a href=\"http://example.com/somewhere3.html\" title=\"It goes somewhere\">SomeWhere 3</a>\n<a href=\"https://another-example.com/elsewhere.php?foo=bar\">ElseWhere 1</a>\n<a href=\"https://another-example.com/elsewhere.php?foo=boz\" class=\"Doh\">ElseWhere 2</a>\n<a href=\"https://another-example.com/elsewhere.php?foo=rad\" title=\"It goes elsewhere\">ElseWhere 3</a>\n<a href=\"deep/below/bar.asp\">BAR</a>\n<a href=\"javascript:ShowHideElement('me');\">Show/Hide</a>\n</div>\n"
}
] | 2008/11/14 | [
"https://Stackoverflow.com/questions/290368",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
290,382 | <p>I'm sure it's just simple html/css but I don't know what to call the bar (googling horizontal bar html always results in a horizontal rule).</p>
<p><a href="http://jquery.com/" rel="nofollow noreferrer">http://jquery.com/</a> has one - the grayish bar the runs across the top separating the menu from the content of the page. I'd love to make one of my own.</p>
| [
{
"answer_id": 290435,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "body {\n background: #2a3139 url(../images/bg_home_tile_sml.jpg) repeat-x 50% 0;\n}\n"
},
{
"answer_id": 290451,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<!-- content above bar goes here -->\n<div style=\"height:30px;background-color:lightgray;clear:both;\" ></div>\n<!-- content below bar goes here -->\n"
}
] | 2008/11/14 | [
"https://Stackoverflow.com/questions/290382",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
290,386 | <p>Has anyone seen this type of IE display problem?</p>
<p><a href="http://xs133.xs.to/xs133/08465/ie_problem910.jpg.xs.jpg" rel="nofollow noreferrer">Example http://xs133.xs.to/xs133/08465/ie_problem910.jpg.xs.jpg</a></p>
<p>Note that it is doing some sort of word-wrap/duplication when it renders.</p>
<p>The code for the brown box and the text that should be in it is:<br/></p>
<pre><code><div class='span-23'>
<div class='span-7'>
<div class='info_box' style='height: 30px; padding-top: 10px'>
<div class='span-4'><b>Vehicle Full Term Premium:</b></div>
<div class='span-2' id='veh_ft_prem' style='text-align: right;'></div>
<div class='span-4'><b>Vehicle Written Premium:</b></div>
<div class='span-2' id='veh_writ_prem' style='text-align: right;'></div>
</div>
</div>
</div>
</code></pre>
<p>I'm using BlueprintCSS and the info_box CSS class is:</p>
<pre><code>.info_box {
background: #fbe6a0;
color: #222222;
border-color: #222222;
padding:.8em;
padding-right: 0;
margin-bottom:1em;
border:2px solid #222222;}
</code></pre>
| [
{
"answer_id": 290435,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "body {\n background: #2a3139 url(../images/bg_home_tile_sml.jpg) repeat-x 50% 0;\n}\n"
},
{
"answer_id": 290451,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<!-- content above bar goes here -->\n<div style=\"height:30px;background-color:lightgray;clear:both;\" ></div>\n<!-- content below bar goes here -->\n"
}
] | 2008/11/14 | [
"https://Stackoverflow.com/questions/290386",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16437/"
] |
290,392 | <p>I've got a somewhat dated Java EE application running on Sun Application Server 8.1 (aka SJSAS, precursor to Glassfish). With 500+ simultaneous users the application becomes unacceptably slow and I'm trying to assist in identifying where most of the execution time is spent and what can be done to speed it up. So far, we've been experimenting and measuring with LoadRunner, the app server logs, Oracle statpack, snoop, adjusting the app server acceptor and session (worker) threads, adjusting Hibernate batch size and join fetch use, etc but after some initial gains we're struggling to improve matters more.</p>
<p>Ok, with that introduction to the problem, here's the real question: If you had a slow Java EE application running on a box whose CPU and memory use never went above 20% and while running with 500+ users you showed two things: 1) that requesting even static files within the same app server JVM process was exceedingly slow, and 2) that requesting a static file outside of the app server JVM process but on the same box was fast, what would you investigate?</p>
<p>My thoughts initially jumped to the application server threads, both acceptor and session threads, thinking that even requests for static files were being queued, waiting for an available thread, and if the CPU/memory weren't really taxed then more threads were in order. But then we upped both the acceptor and session threads substantially and there was no improvement. </p>
<p>Clarification Edits: </p>
<p>1) Static files should be served by a web server rather than an app server. I am using the fact that in our case this (unfortunately) is not the configuration so that I can see the app server performance for files that it doesn't execute -- therefore excluding any database performance costs, etc. </p>
<p>2) I don't think there is a proxy between the requesters and the app server but even if there was it doesn't seem to be overloaded because static files requested from the same application server machine but outside of the application's JVM instance return immediately.</p>
<p>3) The JVM heap size (Xmx) is set to 1GB.</p>
<p>Thanks for any help!</p>
| [
{
"answer_id": 290435,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "body {\n background: #2a3139 url(../images/bg_home_tile_sml.jpg) repeat-x 50% 0;\n}\n"
},
{
"answer_id": 290451,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<!-- content above bar goes here -->\n<div style=\"height:30px;background-color:lightgray;clear:both;\" ></div>\n<!-- content below bar goes here -->\n"
}
] | 2008/11/14 | [
"https://Stackoverflow.com/questions/290392",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/30642/"
] |
290,397 | <p>I have a list of articles, and each article belongs to a section.</p>
<pre><code>class Section(models.Model):
name = models.CharField(max_length=200)
def __unicode__(self):
return self.name
class Article(models.Model):
section = models.ForeignKey(Section)
headline = models.CharField(max_length=200)
# ...
</code></pre>
<p>I want to display the articles, grouped by section.</p>
<pre>
Sponsorships, Advertising & Marketing
1. Nike To Outfit All 18 Univ. Of Memphis Athletic Teams
2. Phil Jackson Questions Harrah's Signage At New Orleans Arena
3. Puma Hires N.Y.-Based Ad Agency Droga5 To Lead Global Account
4. Pizza Patrón To Replace Pizza Hut As AAC Exclusive Provider
5. Marketplace Roundup
Sports Media
6. Many Patriots Fans In New England Will Not See Tonight's Game
7. ESPN Ombudsman Says Net Should Have Clarified Holtz Situation
8. EA Sports To Debut Fitness Title For Nintendo Wii In Spring '09
9. Blog Hound: Rockets-Suns Scuffle Today's No.1 Topic
10. Media Notes
Leagues & Governing Bodies
11. DEI, Chip Ganassi Racing To Merge Into Four-Car Sprint Cup Team
12. NASCAR Roundtable Part II: New Strategies, Cutbacks Discussed
13. Average Ticket Price For NFL Playoff Games To Drop By 10%
</pre>
<p>I figured out how to do most of it with Django's template system.</p>
<pre><code>{% regroup articles by section as articles_by_section %}
{% for article in articles_by_section %}
<h4>{{ article.grouper }}</h4>
<ul>
{% for item in article.list %}
<li>{{ forloop.counter }}. {{ item.headline }}</li>
{% endfor %}
</ul>
{% endfor %}
</code></pre>
<p>I just can't figure out how to do the numbers. The code above numbers the articles in Sports Media 1-5 instead of 6-10. Any suggestions?</p>
| [
{
"answer_id": 291005,
"author": "Daniel Naab",
"author_id": 32638,
"author_profile": "https://Stackoverflow.com/users/32638",
"pm_score": -1,
"selected": false,
"text": "{% regroup articles by section as articles_by_section %}\n\n<ol>\n{% for article in articles_by_section %} \n <h4>{{ article.grouper }}</h4>\n {% for item in article.list %} \n <li>{{ item.headline }}</li>\n {% endfor %}\n{% endfor %}\n</ol>\n"
},
{
"answer_id": 309327,
"author": "Patrick McElhaney",
"author_id": 437,
"author_profile": "https://Stackoverflow.com/users/437",
"pm_score": 3,
"selected": true,
"text": "{{ forloop.counter }} {% counter %} class CounterNode(template.Node):\n\n def __init__(self):\n self.count = 0\n\n def render(self, context):\n self.count += 1\n return self.count\n\n@register.tag\ndef counter(parser, token):\n return CounterNode()\n"
},
{
"answer_id": 359197,
"author": "Tom",
"author_id": 3715,
"author_profile": "https://Stackoverflow.com/users/3715",
"pm_score": 1,
"selected": false,
"text": "{% for article in articles %} \n {% ifchanged article.section %}\n {% if not forloop.first %}</ul>{% endif %}\n <h4>{{article.section}}</h4>\n <ul>\n {% endifchanged %}\n <li>{{forloop.counter}}. {{ article.headline }}</li>\n {% if forloop.last %}</ul>{% endif %}\n{% endfor %}\n"
}
] | 2008/11/14 | [
"https://Stackoverflow.com/questions/290397",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/437/"
] |
290,402 | <p>Out of curiosity, anyone knows the particulars of the internal implementation of </p>
<pre><code>ListControl.SelectedIndex = (int) <new valueIndex>
</code></pre>
<p>VS </p>
<pre><code>ListControl.SelectedValue = <new value>.ToString()
</code></pre>
<p>I'm having difficulties with a custom validation object we've built here to process all validation in one sweep. I suspect using <code><SelectedValue = ></code> will raise a <code>SelectedIndexChanged</code> event, even though both the value and index remain the same, both before and after the operation.</p>
<p>(The ListControl's values are populated declaratively....)</p>
<p>As ever, thank you for your time!</p>
| [
{
"answer_id": 291005,
"author": "Daniel Naab",
"author_id": 32638,
"author_profile": "https://Stackoverflow.com/users/32638",
"pm_score": -1,
"selected": false,
"text": "{% regroup articles by section as articles_by_section %}\n\n<ol>\n{% for article in articles_by_section %} \n <h4>{{ article.grouper }}</h4>\n {% for item in article.list %} \n <li>{{ item.headline }}</li>\n {% endfor %}\n{% endfor %}\n</ol>\n"
},
{
"answer_id": 309327,
"author": "Patrick McElhaney",
"author_id": 437,
"author_profile": "https://Stackoverflow.com/users/437",
"pm_score": 3,
"selected": true,
"text": "{{ forloop.counter }} {% counter %} class CounterNode(template.Node):\n\n def __init__(self):\n self.count = 0\n\n def render(self, context):\n self.count += 1\n return self.count\n\n@register.tag\ndef counter(parser, token):\n return CounterNode()\n"
},
{
"answer_id": 359197,
"author": "Tom",
"author_id": 3715,
"author_profile": "https://Stackoverflow.com/users/3715",
"pm_score": 1,
"selected": false,
"text": "{% for article in articles %} \n {% ifchanged article.section %}\n {% if not forloop.first %}</ul>{% endif %}\n <h4>{{article.section}}</h4>\n <ul>\n {% endifchanged %}\n <li>{{forloop.counter}}. {{ article.headline }}</li>\n {% if forloop.last %}</ul>{% endif %}\n{% endfor %}\n"
}
] | 2008/11/14 | [
"https://Stackoverflow.com/questions/290402",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3403/"
] |
290,405 | <p>If you use a GUID as a password for a publicly facing application as a means to gain access to a service, is this security through obscurity?</p>
<p>I think the obvious answer is yes, but the level of security seems very high to me since the chances of guessing a GUID is very very low correct?</p>
<p><b>Update</b></p>
<p>The GUID will be stored in a device, when plugged in, will send over the GUID via SSL connection.</p>
<p>Maybe I could generate a GUID, then do a AES 128 bit encrption on the GUID and store that value on the device?</p>
| [
{
"answer_id": 290463,
"author": "Treb",
"author_id": 22114,
"author_profile": "https://Stackoverflow.com/users/22114",
"pm_score": 4,
"selected": false,
"text": "'{' '}' '-' {91626979-FB5C-439A-BBA3-7715ED647504} 91626979FB5C439ABBA37715ED647504"
}
] | 2008/11/14 | [
"https://Stackoverflow.com/questions/290405",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
290,424 | <p>I would want to do something like:</p>
<pre><code>>>> lst = [1, 2, 3, 4, 5]
>>> lst.find(lambda x: x % 2 == 0)
2
>>> lst.findall(lambda x: x % 2 == 0)
[2, 4]
</code></pre>
<p>Is there anything nearing such behavior in Python's standard libraries?</p>
<p>I know it's very easy to roll-your-own here, but I'm looking for a more standard way.</p>
| [
{
"answer_id": 290440,
"author": "John Montgomery",
"author_id": 5868,
"author_profile": "https://Stackoverflow.com/users/5868",
"pm_score": 8,
"selected": true,
"text": ">>> lst = [1, 2, 3, 4, 5]\n>>> filter(lambda x: x % 2 == 0, lst)\n[2, 4]\n >>> lst = [1, 2, 3, 4, 5]\n>>> [x for x in lst if x %2 == 0]\n[2, 4]\n >>> next(x for x in lst if x % 2 == 0)\n2\n filter(lambda x: x % 2 == 0, lst)[0]\n[x for x in lst if x %2 == 0][0]\n filter(lambda x: x % 2 == 0, lst)[:1]\n[x for x in lst if x %2 == 0][:1]\n"
},
{
"answer_id": 64464243,
"author": "lordkrandel",
"author_id": 483869,
"author_profile": "https://Stackoverflow.com/users/483869",
"pm_score": 3,
"selected": false,
"text": ">>> lst = [i for i in range(1, 6)]\n\n>>> lst\n[1, 2, 3, 4, 5]\n\n>>> gen = (x for x in lst if x % 10 == 0)\n\n>>> next(gen, 'not_found')\n'not_found'\n\n>>> [x for x in gen]\n[]\n >>> n = next((x for x in lst if x % 10 == 0), None)\n>>> if n is None:\n... print('Not found')\n... \nNot found\n >>> find = lambda fun, lst: next((x for x in lst if fun(x)), None)\n>>> find(lambda x: x % 10 == 0, lst)\n>>> find(lambda x: x % 5 == 0, lst)\n5\n\n>>> findall = lambda fun, lst: [x for x in lst if fun(x)]\n>>> findall(lambda x: x % 5 == 0, lst)\n[5]\n"
}
] | 2008/11/14 | [
"https://Stackoverflow.com/questions/290424",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8206/"
] |
290,436 | <p>Presently I have a some legacy code, which generates the op code. If the code has more number of macros then the code generation takes so much of time (In terms of hours!!).
I have gone through the logic, they are handling the macro by searching for it and doing a replace of each variable in it some thing like inlining.<br>
Is there a way that I can optimize it without manipulating the string?</p>
| [
{
"answer_id": 290512,
"author": "Vinay",
"author_id": 28641,
"author_profile": "https://Stackoverflow.com/users/28641",
"pm_score": 0,
"selected": false,
"text": "int c = a + b\n"
},
{
"answer_id": 318750,
"author": "Chris",
"author_id": 8415,
"author_profile": "https://Stackoverflow.com/users/8415",
"pm_score": 2,
"selected": true,
"text": "for(each line in the program)\n{\n for(each macro definition)\n {\n test if the macro appears;\n perform replacement if needed;\n }\n}\n for(each line in the program)\n{\n tokenize the line;\n for(each token in the line)\n {\n switch(based on the token type)\n {\n case(an identifier)\n lookup the identifier in the table of macro names;\n perform replacement as necessary;\n ....\n }\n }\n}\n"
}
] | 2008/11/14 | [
"https://Stackoverflow.com/questions/290436",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/28641/"
] |
290,449 | <p>Hello I was writing a Regular Expression (first time in my life I might add) but I just can't figure out how to do what I want. So far, so good since I already allow only Letters and spaces (as long as it's not the first character) now what I'm missing is that I don't want to allow any numbers in between the characters...could anybody help me please?</p>
<pre><code>/^[^\s][\sa-zA-Z]+[^\d\W]/
</code></pre>
| [
{
"answer_id": 290472,
"author": "Graeme Perrow",
"author_id": 1821,
"author_profile": "https://Stackoverflow.com/users/1821",
"pm_score": 1,
"selected": false,
"text": "/^[a-zA-Z][\\sa-zA-Z]*$/\n $"
},
{
"answer_id": 290479,
"author": "Alnitak",
"author_id": 6782,
"author_profile": "https://Stackoverflow.com/users/6782",
"pm_score": 4,
"selected": true,
"text": "/^[a-zA-Z][\\sa-zA-Z]*$/\n ^ - start of line\n[a-zA-Z] - any letter\n[\\sa-zA-Z]* - zero or more letters or spaces\n$ - the end of the line\n [a-zA-Z]\n $"
},
{
"answer_id": 291275,
"author": "Alan Moore",
"author_id": 20938,
"author_profile": "https://Stackoverflow.com/users/20938",
"pm_score": 1,
"selected": false,
"text": "/^[A-Za-z]+(?:\\s+[A-Za-z]+)*$/\n"
}
] | 2008/11/14 | [
"https://Stackoverflow.com/questions/290449",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/28586/"
] |
290,454 | <p>I am new to RESTful stuff. But, I want to use it in my rails app. When I add this to my routes.rb <code>map.resources :notes</code> I get routes to these methods created:</p>
<ul>
<li>index</li>
<li>create</li>
<li>new</li>
<li>edit</li>
<li>show</li>
<li>update</li>
<li>destroy</li>
</ul>
<p>What I am wondering is what is the difference between edit/update and create/new? Is there any standard definitions of how these method pairs vary and what each one does?</p>
| [
{
"answer_id": 290538,
"author": "Owen",
"author_id": 2109,
"author_profile": "https://Stackoverflow.com/users/2109",
"pm_score": 4,
"selected": true,
"text": "create new update edit create/new/edit/update"
}
] | 2008/11/14 | [
"https://Stackoverflow.com/questions/290454",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5004/"
] |
290,456 | <p>This is a follow-up to <a href="https://stackoverflow.com/questions/269417/which-language-should-i-use">two</a> <a href="https://stackoverflow.com/questions/271488/linking-languages">questions</a> I asked a week or so back. The upshot of those was that I was building a prototype of an AI-based application for the web, and I wondered what language(s) to use. The conclusion seemed to be that I should go for something like python and then convert any critical bits into something faster like Java or C/C++.</p>
<p>That sounds fine to me, but I'm wondering now whether python is really the right language to use for building a web application. Most web applications I've worked on in the past were C/C++ CGI and then php. The php I found much easier to work with as it made linking the user interface to the back-end so much easier, and also it made more logical sense to me. </p>
<p>I've not used python before, but what I'm basically wondering is how easy is CGI programming in python? Will I have to go back to the tedious way of doing it in C/C++ where you have to store HTML code in templates and have the CGI read them in and replace special codes with appropriate values or is it possible to have the templates <em>be</em> the code as with php?</p>
<p>I'm probably asking a deeply ignorant question here, for which I apologise, but hopefully someone will know what I'm getting at! My overall question is: is writing web applications in python a good idea, and is it as easy as it is with php?</p>
| [
{
"answer_id": 290650,
"author": "S.Lott",
"author_id": 10661,
"author_profile": "https://Stackoverflow.com/users/10661",
"pm_score": 4,
"selected": true,
"text": "django-admin.py startproject import"
}
] | 2008/11/14 | [
"https://Stackoverflow.com/questions/290456",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11522/"
] |
290,459 | <p>I am reworking some ui in an application written by freelance .Net developers from another country. </p>
<p>I am not going to go into how bad the code is and entangled the code with structure content and presentation are... </p>
<p>But one of the things I notice is that menu for accessing the parts of the app is made with Button controls that post to the server and return a different page. I would like to change the buttons to LinkControls are there any reasons that people might have done this ? </p>
<p>I notice that when I do change to to LinkButtons there is actually javascript that seems to trigger the post action. Any reasons or ways to avoid this ?</p>
| [
{
"answer_id": 290517,
"author": "Phil Jenkins",
"author_id": 35496,
"author_profile": "https://Stackoverflow.com/users/35496",
"pm_score": 3,
"selected": true,
"text": ".linkButton\n{\n background-color: transparent;\n border-style: none;\n color: /* Something nice */\n cursor: pointer;\n text-align: left;\n text-decoration: underline;\n display: table-cell;\n}\n"
}
] | 2008/11/14 | [
"https://Stackoverflow.com/questions/290459",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/35513/"
] |
290,465 | <p>Does anyone know of a way to paste over a visually selected area without having the selection placed in the default register?</p>
<p>I know I can solve the problem by always pasting from an explicit register. But it's a pain in the neck to type <kbd>"</kbd><kbd>x</kbd><kbd>p</kbd> instead of just <kbd>p</kbd></p>
| [
{
"answer_id": 290543,
"author": "Gowri",
"author_id": 3253,
"author_profile": "https://Stackoverflow.com/users/3253",
"pm_score": -1,
"selected": false,
"text": ":set guioptions-=a\n:set guioptions-=A\n"
},
{
"answer_id": 290723,
"author": "Luc Hermitte",
"author_id": 15934,
"author_profile": "https://Stackoverflow.com/users/15934",
"pm_score": 6,
"selected": true,
"text": "\"{register}p \" I haven't found how to hide this function (yet)\nfunction! RestoreRegister()\n let @\" = s:restore_reg\n return ''\nendfunction\n\nfunction! s:Repl()\n let s:restore_reg = @\"\n return \"p@=RestoreRegister()\\<cr>\"\nendfunction\n\n\" NB: this supports \"rp that replaces the selection by the contents of @r\nvnoremap <silent> <expr> p <sid>Repl()\n"
},
{
"answer_id": 812118,
"author": "Jeff Lake",
"author_id": 13300,
"author_profile": "https://Stackoverflow.com/users/13300",
"pm_score": 5,
"selected": false,
"text": "d D c C d \"_d c \"_c \"These are to cancel the default behavior of d, D, c, C\n\" to put the text they delete in the default register.\n\" Note that this means e.g. \"ad won't copy the text into\n\" register a anymore. You have to explicitly yank it.\nnnoremap d \"_d\nvnoremap d \"_d\nnnoremap D \"_D\nvnoremap D \"_D\nnnoremap c \"_c\nvnoremap c \"_c\nnnoremap C \"_C\nvnoremap C \"_C\n"
},
{
"answer_id": 1530518,
"author": "Joernsn",
"author_id": 168502,
"author_profile": "https://Stackoverflow.com/users/168502",
"pm_score": 2,
"selected": false,
"text": "let s:putSwap = 1 \nfunction TogglePutSwap()\n if s:putSwap\n vnoremap <silent> <expr> p <sid>Repl()\n let s:putSwap = 0 \n echo 'noreplace put'\n else\n vnoremap <silent> <expr> p p \n let s:putSwap = 1 \n echo 'replace put'\n endif\n return\nendfunction\nnoremap ,p :call TogglePutSwap()<cr>\n"
},
{
"answer_id": 4446608,
"author": "danprice",
"author_id": 539391,
"author_profile": "https://Stackoverflow.com/users/539391",
"pm_score": 3,
"selected": false,
"text": "function! RestoreRegister()\n let @\" = s:restore_reg\n if &clipboard == \"unnamed\"\n let @* = s:restore_reg\n endif\n return ''\nendfunction\n"
},
{
"answer_id": 5093286,
"author": "Benoit",
"author_id": 457352,
"author_profile": "https://Stackoverflow.com/users/457352",
"pm_score": 6,
"selected": false,
"text": "xnoremap p pgvy\n \"xp xnoremap p pgv\"@=v:register.'y'<cr>\n v:register"
},
{
"answer_id": 13492870,
"author": "Taine",
"author_id": 741722,
"author_profile": "https://Stackoverflow.com/users/741722",
"pm_score": 3,
"selected": false,
"text": "function! YRRunAfterMaps() \n \" From Steve Losh, Preserve the yank post selection/put. \n vnoremap p :<c-u>YRPaste 'p', 'v'<cr>gv:YRYankRange 'v'<cr> \nendfunction \n"
},
{
"answer_id": 15266864,
"author": "mrak",
"author_id": 1230227,
"author_profile": "https://Stackoverflow.com/users/1230227",
"pm_score": 3,
"selected": false,
"text": "~/.vimrc xnoremap <expr> p 'pgv\"'.v:register.'y'\n xnoremap Visual Visual + Select <expr> {rhs} xnoremap {lhs} {rhs} 'pgv\"'.v:register.'y' . v:register \"xp pgv\"xy x"
},
{
"answer_id": 31411902,
"author": "Jason Denney",
"author_id": 1373076,
"author_profile": "https://Stackoverflow.com/users/1373076",
"pm_score": 4,
"selected": false,
"text": ".vimrc xnoremap p \"_dP\n"
},
{
"answer_id": 60032747,
"author": "steven_noble",
"author_id": 145684,
"author_profile": "https://Stackoverflow.com/users/145684",
"pm_score": 0,
"selected": false,
"text": "nmap viwp viwpyiw\nnmap vi'p vi'pyi'\nnmap vi\"p vi\"pyi\"\nnmap vi(p vi(pyi(\nnmap vi[p vi[pyi[\nnmap vi<p vi<pyi<\n"
},
{
"answer_id": 73258457,
"author": "Cyrus Yip",
"author_id": 14399237,
"author_profile": "https://Stackoverflow.com/users/14399237",
"pm_score": 0,
"selected": false,
"text": "P viwP\n h: v_P"
},
{
"answer_id": 73711864,
"author": "Xin Wang",
"author_id": 2295167,
"author_profile": "https://Stackoverflow.com/users/2295167",
"pm_score": 0,
"selected": false,
"text": "vnoremap p p:let @+=@0<CR>\n\nvnoremap P P:let @+=@0<CR>\n :let @+=@0\n"
}
] | 2008/11/14 | [
"https://Stackoverflow.com/questions/290465",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/37708/"
] |
290,475 | <p>We have a major VB6 trading application which uses MS Access (Don't ask!) It is always blasting trades into an MS Access database.</p>
<p>The rest of the infrastructure here has moved on considerably and I want to read this Access database periodically and copy any new trades into a SQL server database.</p>
<p>The SQL and C# needed to do this is trivially easy.</p>
<p>BUT I want to make sure I do it in such a way that does not lock the Access database or cause problems for the VB6 app. In other words when populating my DataTable from Access I do NOT want to lock the database and prevent the VB6 app writing to it. I seem to remember from old ADO there were share modes you could use for this purpose.</p>
<p>What sort of connection string should I use from .NET to accomplish this?</p>
| [
{
"answer_id": 290561,
"author": "Mat Nadrofsky",
"author_id": 26853,
"author_profile": "https://Stackoverflow.com/users/26853",
"pm_score": 0,
"selected": false,
"text": "\"Data Source=C:\\IronSpeed\\TestAccessDB\\TestTypes.mdb;\nJet OLEDB:Database Locking Mode=1;\nMode=Read\"\n"
}
] | 2008/11/14 | [
"https://Stackoverflow.com/questions/290475",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/35055/"
] |
290,484 | <p>I am writing a silly little app in C++ to test one of my libraries. I would like the app to display a list of commands to the user, allow the user to type a command, and then execute the action associated with that command. Sounds simple enough.
In C# I would end up writing a list/map of commands like so:</p>
<pre><code> class MenuItem
{
public MenuItem(string cmd, string desc, Action action)
{
Command = cmd;
Description = desc;
Action = action;
}
public string Command { get; private set; }
public string Description { get; private set; }
public Action Action { get; private set; }
}
static void Main(string[] args)
{
var items = new List<MenuItem>();
items.Add(new MenuItem(
"add",
"Adds 1 and 2",
()=> Console.WriteLine(1+2)));
}
</code></pre>
<p>Any suggestions on how to achieve this in C++? I don't really want to define separate classes/functions for each command. I can use Boost, but not TR1.</p>
| [
{
"answer_id": 290516,
"author": "Johannes Schaub - litb",
"author_id": 34509,
"author_profile": "https://Stackoverflow.com/users/34509",
"pm_score": 4,
"selected": true,
"text": "void exit_me(); /* exits the program */\nvoid help(); /* displays help */\n\nstd::map< std::string, boost::function<void()> > menu;\nmenu[\"exit\"] = &exit_me;\nmenu[\"help\"] = &help;\n\nstd::string choice;\nfor(;;) {\n std::cout << \"Please choose: \\n\";\n std::map<std::string, boost::function<void()> >::iterator it = menu.begin();\n while(it != menu.end()) {\n std::cout << (it++)->first << std::endl;\n }\n\n std::cin >> choice;\n if(menu.find(choice) == menu.end()) {\n /* item isn't found */\n continue; /* next round */\n } \n\n menu[choice](); /* executes the function */\n}\n menu[\"help\"] = cout << constant(\"This is my little program, you can use it really nicely\");\n switch"
},
{
"answer_id": 290620,
"author": "Harper Shelby",
"author_id": 21196,
"author_profile": "https://Stackoverflow.com/users/21196",
"pm_score": 0,
"selected": false,
"text": "using std::string;\nclass MenuItem \n{ \n public:\n MenuItem(string cmd, string desc, boost::function<bool()> action):Command(cmd),\n Description(desc),\n Action(action) \n {}\n boost::function<bool()> GetAction() { return Action; }\n string GetDescription() { return Description; }\n string GetCommand() { return Command; }\n private:\n string Command;\n string Description;\n boost::function<bool()> Action;\n}\n"
}
] | 2008/11/14 | [
"https://Stackoverflow.com/questions/290484",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21704/"
] |
290,488 | <p>This isn't my code; I am trying to figure out what exactly this does. This is a part of a big, ancient system written in C (actually it was written 4 years ago, but most likely written by a late 80s programmer mentality). Part of the code:</p>
<pre><code>char DestFile[256];
char DestFile2[256];
//This part is just to show an example
strcpy(DestFile, "/foo/boo/goo.gz")
strcpy ( DestFile2, DestFile );
Ptr = strrchr ( DestFile2, '.' );
if ( Ptr != 0 ) {
if ( ( strcmp ( Ptr, ".gz" ) == 0 ) ||
( strcmp ( Ptr, ".Z" ) == 0 ) ) {
*Ptr = 0;
rename ( DestFile, DestFile2 );
}
}
</code></pre>
<p>DestFile2 is not set anywhere else in the function. I compiled the code above, and printing out the DestFile shows nothing has changed. The only thing i can think of that this does is removing the file extension (*Ptr=0) but my knowledge of C is very limited...</p>
<p>Any ideas? It looks like every time it gets a file with .gz or .z it renames the file to the same name.</p>
| [
{
"answer_id": 290521,
"author": "Soraz",
"author_id": 24610,
"author_profile": "https://Stackoverflow.com/users/24610",
"pm_score": 5,
"selected": true,
"text": " |- Ptr\n v \n M y f i l e . g z \\0\n rename(\"myfile.gz\", \"myfile\");\n"
}
] | 2008/11/14 | [
"https://Stackoverflow.com/questions/290488",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/34395/"
] |
290,503 | <p>Let's say you got a file containing texts (from 1 to N) separated by a $
How can a slit the file so the end result is N files? </p>
<blockquote>
<p>text1 with newlines $<br>
text2 $etc... $<br>
textN</p>
</blockquote>
<p>I'm thinking something with awk or sed but is there any available unix app that already perform that kind of task?</p>
| [
{
"answer_id": 290519,
"author": "Bill Karwin",
"author_id": 20860,
"author_profile": "https://Stackoverflow.com/users/20860",
"pm_score": 3,
"selected": true,
"text": "split -p awk 'BEGIN {RS = \"$\"} { ... }'\n { ... } csplit"
},
{
"answer_id": 290665,
"author": "Powerlord",
"author_id": 15880,
"author_profile": "https://Stackoverflow.com/users/15880",
"pm_score": 1,
"selected": false,
"text": "cut -d $ -f 1- filename\n"
},
{
"answer_id": 2011499,
"author": "ghostdog74",
"author_id": 131527,
"author_profile": "https://Stackoverflow.com/users/131527",
"pm_score": 1,
"selected": false,
"text": "awk -vRS=\"$\" '{ print $0 > \"text\"t++\".out\" }' ORS=\"\" file\n"
}
] | 2008/11/14 | [
"https://Stackoverflow.com/questions/290503",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23051/"
] |
290,513 | <p>I need an regular expression pattern to only accept positive whole numbers. It can also accept a single zero.</p>
<p>I do not want to accept decimals, negative number and numbers with leading zeros.</p>
<p>Any suggestions?</p>
| [
{
"answer_id": 290530,
"author": "3Doubloons",
"author_id": 25818,
"author_profile": "https://Stackoverflow.com/users/25818",
"pm_score": 3,
"selected": false,
"text": "/([1-9][0-9]*)|0/\n"
},
{
"answer_id": 290531,
"author": "Robert Gamble",
"author_id": 25222,
"author_profile": "https://Stackoverflow.com/users/25222",
"pm_score": 2,
"selected": false,
"text": "/^0|[1-9]\\d*$/\n"
},
{
"answer_id": 290532,
"author": "Cheery",
"author_id": 21711,
"author_profile": "https://Stackoverflow.com/users/21711",
"pm_score": 4,
"selected": false,
"text": "[1-9][0-9]*|0 [0-9]+"
},
{
"answer_id": 290539,
"author": "Federico A. Ramponi",
"author_id": 18770,
"author_profile": "https://Stackoverflow.com/users/18770",
"pm_score": 8,
"selected": true,
"text": "^(0|[1-9][0-9]*)$\n"
},
{
"answer_id": 8142099,
"author": "Scott",
"author_id": 1048332,
"author_profile": "https://Stackoverflow.com/users/1048332",
"pm_score": 4,
"selected": false,
"text": "^(([1-9]*)|(([1-9]*)\\.([0-9]*)))$\n ^(([0-9]*)|(([0-9]*)\\.([0-9]*)))$\n"
}
] | 2008/11/14 | [
"https://Stackoverflow.com/questions/290513",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/26327/"
] |
290,523 | <p>What im wondering how to do is when someone edits a list item and it goes through my event code that is fired when a change is made and save is hit, i dont want anyone to be able to edit that list item itself while its still processnig that request. So i was wondering if while in that event i can disable the individual item from being edited by someone else untill it is done doing what it is doing.</p>
| [
{
"answer_id": 293109,
"author": "Bjørn Furuknap",
"author_id": 28382,
"author_profile": "https://Stackoverflow.com/users/28382",
"pm_score": 3,
"selected": true,
"text": " public override void ItemAdding(SPItemEventProperties properties)\n {\n if (properties.ListItem[\"updating\"].ToString() == \"updating\")\n {\n properties.Cancel = true;\n properties.ErrorMessage = \"Item is currently updating, please try again later\";\n }\n else\n {\n properties.ListItem[\"updating\"] = \"updating\";\n this.DisableEventFiring();\n properties.ListItem.Update();\n this.EnableEventFiring();\n\n // do your stuff\n\n properties.ListItem[\"updating\"] = \"\";\n this.DisableEventFiring();\n properties.ListItem.Update();\n this.EnableEventFiring();\n }\n }\n"
}
] | 2008/11/14 | [
"https://Stackoverflow.com/questions/290523",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18431/"
] |
290,527 | <p>Similar to <a href="https://stackoverflow.com/questions/288794/does-c-optimize-the-concatenation-of-string-literals">this</a> question, but for VB.NET since I learned this is a language thing.</p>
<p>For instance, would the compiler know to translate</p>
<blockquote>
<p>Dim s As String = "test " + "this " +
"function"</p>
</blockquote>
<p>to</p>
<pre><code>Dim s As String = "test this function"
</code></pre>
<p>and thus avoid the performance hit with the string concatenation?</p>
| [
{
"answer_id": 297257,
"author": "Jason Hernandez",
"author_id": 34863,
"author_profile": "https://Stackoverflow.com/users/34863",
"pm_score": 5,
"selected": true,
"text": "Public Class Class1\n\n\n Dim s As String = \"test \" + \"this \" + \"function\"\n\n Public Function test() As String\n Return s\n End Function\n\nEnd Class\n {\n .maxstack 8\n L_0000: ldarg.0 \n L_0001: call instance void [mscorlib]System.Object::.ctor()\n L_0006: nop \n L_0007: ldarg.0 \n L_0008: ldstr \"test this function\"\n L_000d: stfld string ClassLibrary1.Class1::s\n L_0012: nop \n L_0013: ret \n}\n"
},
{
"answer_id": 3760576,
"author": "Paulius Paskevicius",
"author_id": 453940,
"author_profile": "https://Stackoverflow.com/users/453940",
"pm_score": 3,
"selected": false,
"text": "String String Dim s As String = \"A\" & \"B\" & \"C\" \n L_0008: ldstr \"ABC\"\n String Dim s As String = \"A\"\ns &= \"B\"\ns &= \"C\" \n String Dim s As String = \"A\" _\n& \"B\" _\n& \"C\" _\n vbCrLf Environment.NewLine"
}
] | 2008/11/14 | [
"https://Stackoverflow.com/questions/290527",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/337/"
] |
290,535 | <p>Using jQuery, what's the best way to find the next form element on the page, starting from an arbitrary element? When I say form element I mean <code><input></code>, <code><select></code>, <code><button></code> or <code><textarea></code>.</p>
<p>In the following examples, the element with the id "this" is the arbitrary starting point, and the element with the id "next" is the one I want to find. The same answer should work for all examples.</p>
<p>Example 1:</p>
<pre><code><ul>
<li><input type="text" /></li>
<li><input id="this" type="text" /></li>
</ul>
<ul>
<li><input id="next" type="text" /></li>
</ul>
<button></button>
</code></pre>
<p>Example 2:</p>
<pre><code><ul>
<li><input id="this" type="text" /></li>
</ul>
<button id="next"></button>
</code></pre>
<p>Example 3:</p>
<pre><code><input id="this" type="text" />
<input id="next" type="text" />
</code></pre>
<p>Example 4:</p>
<pre><code><div>
<input id="this" type="text" />
<input type="hidden" />
<div>
<table>
<tr><td></td><td><input id="next" type="text" /></td></tr>
</table>
</div>
<button></button>
</div>
</code></pre>
<p>EDIT: The two answers provided so far both require writing a sequence number to all input elements on the page. As I mentioned in the comments of one of them, this is kind of what I'm already doing and I would much prefer have a read-only solution since this will be happening inside a plugin.</p>
| [
{
"answer_id": 290604,
"author": "jckeyes",
"author_id": 17881,
"author_profile": "https://Stackoverflow.com/users/17881",
"pm_score": 2,
"selected": false,
"text": "<div>\n <input id=\"FormElement_0\" type=\"text\" />\n <input id=\"FormElement_1\" type=\"text\" />\n<div>\n //I'm assuming \"this\" is referring to the first input\n\n//grab the id\nvar id = $(this).attr('id');\n\n//get the index from the id and increment it\nvar index = parseInt(id.split('_')[0], 10);\nindex++;\n\n//grab the element witht that index\nvar next = $('#FormElement_' + index);\n"
},
{
"answer_id": 292005,
"author": "redsquare",
"author_id": 6440,
"author_profile": "https://Stackoverflow.com/users/6440",
"pm_score": 7,
"selected": true,
"text": "$(':input:eq(' + ($(':input').index(this) + 1) + ')');"
},
{
"answer_id": 292215,
"author": "enobrev",
"author_id": 14651,
"author_profile": "https://Stackoverflow.com/users/14651",
"pm_score": 1,
"selected": false,
"text": "function nextInput(form, id) {\n var aInputs = $('#' + form).find(':input[type!=hidden]');\n for (var i in aInputs) {\n if ($(aInputs[i]).attr('id') == id) {\n if (typeof(aInputs[parseInt(i) + 1]) != 'undefined') {\n return aInputs[parseInt(i) + 1];\n }\n }\n }\n}\n <html>\n <head>\n <script src=\"http://www.google.com/jsapi\"></script>\n <script>\n function nextInput(form, id) {\n var aInputs = $('#' + form).find(':input[type!=hidden]');\n for (var i in aInputs) {\n if ($(aInputs[i]).attr('id') == id) {\n if (typeof(aInputs[parseInt(i) + 1]) != 'undefined') {\n return aInputs[parseInt(i) + 1];\n }\n }\n }\n }\n\n google.load(\"jquery\", \"1.2.6\");\n google.setOnLoadCallback(function() {\n console.log(nextInput('myform1', 'this1'));\n console.log(nextInput('myform2', 'this2'));\n console.log(nextInput('myform3', 'this3'));\n console.log(nextInput('myform4', 'this4'));\n });\n </script>\n </head>\n <body>\n <form id=\"myform1\">\n <ul>\n <li><input type=\"text\" /></li>\n <li><input id=\"this1\" type=\"text\" /></li>\n </ul>\n <ul>\n <li><input id=\"next1\" type=\"text\" /></li>\n </ul>\n </form>\n\n <form id=\"myform2\">\n <ul>\n <li><input type=\"text\" /></li>\n <li><input id=\"this2\" type=\"text\" /></li>\n </ul>\n <ul>\n <li><input id=\"next2\" type=\"text\" /></li>\n </ul>\n </form>\n\n <form id=\"myform3\">\n <input id=\"this3\" type=\"text\" />\n <input id=\"next3\" type=\"text\" />\n </form>\n\n <form id=\"myform4\">\n <div>\n <input id=\"this4\" type=\"text\" />\n <input type=\"hidden\" />\n <div>\n <table>\n <tr><td></td><td><input id=\"next4\" type=\"text\" /></td></tr>\n </table>\n </div>\n <button></button>\n </div>\n </form>\n </body>\n</html>\n"
},
{
"answer_id": 292591,
"author": "alexmeia",
"author_id": 36587,
"author_profile": "https://Stackoverflow.com/users/36587",
"pm_score": 2,
"selected": false,
"text": "var yourFormFields = $(\"yourForm\").find('button,input,textarea,select');\n var index = yourFormFields.index( this ); // the index of your current element in the list. if the current element is not in the list, index = -1\n\nif ( index > -1 && ( index + 1 ) < yourFormFields.length ) { \n\n var nextElement = yourFormFields.eq( index + 1 );\n\n }\n"
},
{
"answer_id": 3280637,
"author": "reSPAWNed",
"author_id": 71793,
"author_profile": "https://Stackoverflow.com/users/71793",
"pm_score": 4,
"selected": false,
"text": "$(\":input:eq(\" + ($(\":input\").index(this) + 1) + \")\");\n"
},
{
"answer_id": 8498201,
"author": "Jai",
"author_id": 270836,
"author_profile": "https://Stackoverflow.com/users/270836",
"pm_score": 3,
"selected": false,
"text": "function nextOnTabIndex(element) {\n var fields = $($('form')\n .find('a[href], button, input, select, textarea')\n .filter(':visible').filter('a, :enabled')\n .toArray()\n .sort(function(a, b) {\n return ((a.tabIndex > 0) ? a.tabIndex : 1000) - ((b.tabIndex > 0) ? b.tabIndex : 1000);\n }));\n\n\n return fields.eq((fields.index(element) + 1) % fields.length);\n }\n <script>\n $(function() {\n $('a[href], button, input, select, textarea').click(function() {\n console.log(nextOnTabIndex($(this)).attr('name'));\n })\n });\n</script>\n\n<form>\n <input type='text' name='a'/>\n <input type='text' name='b' tabindex='1' />\n <a>Hello</a>\n <input type='text' name='c'/>\n <textarea name='d' tabindex='2'></textarea>\n <input id='submit' type='submit' name='e' tabindex='1' />\n</form>\n"
},
{
"answer_id": 13755181,
"author": "NicoJuicy",
"author_id": 209555,
"author_profile": "https://Stackoverflow.com/users/209555",
"pm_score": 0,
"selected": false,
"text": "var elementSelector = \"input:visible,textarea:visible\";\nvar nextSibling = $(elementSelector )[$(elementSelector ).index() + 1];\n//$(nextSibling).focus(); possible action\n var nextSibling = $(\"input:visible,textarea:visible\")[$(\"input:visible,textarea:visible\").index() + 1];\n"
},
{
"answer_id": 19034525,
"author": "Jeff Mathews",
"author_id": 2820521,
"author_profile": "https://Stackoverflow.com/users/2820521",
"pm_score": 3,
"selected": false,
"text": "$(document.body).keydown(function(event) {\n if(event.keyCode == 13 ) {\n $(\":input\")[$(\":input\").index(document.activeElement) + 1].focus();\n return false;\n }\n});\n"
},
{
"answer_id": 21914293,
"author": "Jay Haase",
"author_id": 287343,
"author_profile": "https://Stackoverflow.com/users/287343",
"pm_score": 0,
"selected": false,
"text": "input_el.nextAll( 'input:visible:first' ).focus();\n"
},
{
"answer_id": 24409436,
"author": "PiersB",
"author_id": 3468620,
"author_profile": "https://Stackoverflow.com/users/3468620",
"pm_score": 0,
"selected": false,
"text": "<div> ids = $(\":input:visible:not([readonly])\").map(function () { return this.id });\nnextId = ids[($.inArray($(this).attr(\"id\"), ids) + 1) % ids.length];\n$(\"#\" + nextId).focus();\n"
}
] | 2008/11/14 | [
"https://Stackoverflow.com/questions/290535",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
290,537 | <p>I have a solution with many projects. There is actually a Core project and a few plugins. I changed OutputPath for all plugins so all binaries end up in the Core bin\debug folder. (this is necessary as the Core do not have a reference on plugins, hence it does not "include" plugins binaries when it is compiled.)</p>
<p>So basically my folder structure is as follow:</p>
<pre>
Solution
MySolution.sln
Plugin1\
Plugin2\
Core\bin\debug
</pre>
<p>Each plugin OutputPath is "..\Core\bin\debug". When I open the solution Visual Studio creates a folder "Core\bin\debug" in Solution's folder parent as if the relative path starts from .sln file. However when I build the solution the binaries are output to the correct path ("Solution\Core\bin\debug"). </p>
Core\bin\debug
<p>It looks like a Visual Studio bug to me, but maybe I overlooked some option somewhere. Any ideas how to resolve this problem ?</p>
<p>PS: I know this not a critical issue as everything build and works fine, however I dislike the idea of meaningless folder hanging around</p>
| [
{
"answer_id": 290568,
"author": "Jeromy Irvine",
"author_id": 8223,
"author_profile": "https://Stackoverflow.com/users/8223",
"pm_score": 2,
"selected": false,
"text": "copy \"$(TargetPath)\" \"$(SolutionDir)Core\\$(OutDir)\"\n copy \"$(TargetPath).pdb\" \"$(SolutionDir)Core\\$(OutDir)\"\ncopy \"$(TargetPath).config\" \"$(SolutionDir)Core\\$(OutDir)\"\n copy \"$(TargetPath)*\" \"$(SolutionDir)Core\\$(OutDir)\"\n"
}
] | 2008/11/14 | [
"https://Stackoverflow.com/questions/290537",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/37706/"
] |
290,545 | <p>I am adapting a little rmi client-server application. I have written several things :</p>
<pre><code>HelloInterface -> A Hello World interface for RMI
Server -> The server app'
Client -> The client app'
</code></pre>
<p>Nothing special, but... I have put my hands in a new RMISecurityManager, which calls a JNI method and checks the permission for a separate user:</p>
<pre><code>package rmi;
import java.rmi.RMISecurityManager;
import java.io.*;
public class NativeRMISecurityManager extends RMISecurityManager
{
private boolean unix;
protected static ThreadLocal user = new ThreadLocal();
/*
* On interdit l'utilisation du constructeur par defaut
* pour obliger l'utilisation du constructeur avec user.
*/
private NativeRMISecurityManager()
{
super();
}
public NativeRMISecurityManager (final String user)
{
super();
String OS = System.getProperty("os.name").toLowerCase();
unix = (OS.compareTo("windows") != 0); /* Assume that if not
* windows, then "UNIX/POSIX"
*/
/*
* ThreadLocal's user : Each thread is considered
* to have different access rights to the machine
*/
NativeRMISecurityManager.user.set(user);
if (!unix)
{
System.out.println("Systeme : "+OS);
}
}
public void checkRead(String file)
{
super.checkRead(file);
/*
* If we are on a **IX platform we want to check that
* the _user_ has access rights.
*/
if (unix)
{
String str_user = (String)NativeRMISecurityManager.user.get();
if (file == null)
{
throw new SecurityException("file = NULL !!!");
}
if (str_user == null)
{
throw new SecurityException("user = NULL in the ThreadLocal!!!");
}
int ret = c_checkRead(
file,
str_user
);
if (ret != 0)
{
throw new SecurityException("Access error: " + file);
}
}
}
public native int c_checkRead(String file, String user);
}
</code></pre>
<p>In the Server class I'm doing that : </p>
<pre><code>String user = "my_user";
System.setSecurityManager(new NativeRMISecurityManager(user));
</code></pre>
<p>This class seems to work in the Server's main thread. Now the problem is when I try and connect to that Server class and lookup the Registry.
I get that exception : </p>
<pre><code>Exception in thread "RMI TCP Connection(1)-192.168.42.207" java.lang.ExceptionInInitializerError
at sun.rmi.transport.StreamRemoteCall.getInputStream(StreamRemoteCall.java:111)
at sun.rmi.transport.Transport.serviceCall(Transport.java:118)
at sun.rmi.transport.tcp.TCPTransport.handleMessages(TCPTransport.java:466)
at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.run(TCPTransport.java:707)
at java.lang.Thread.run(Thread.java:595)
Caused by: java.lang.SecurityException: user = NULL dans le ThreadLocal!!!
at rmi.NativeRMISecurityManager.checkRead(NativeRMISecurityManager.java:62)
at java.io.File.exists(File.java:700)
at java.lang.ClassLoader$3.run(ClassLoader.java:1689)
at java.security.AccessController.doPrivileged(Native Method)
at java.lang.ClassLoader.loadLibrary0(ClassLoader.java:1686)
at java.lang.ClassLoader.loadLibrary(ClassLoader.java:1668)
at java.lang.Runtime.loadLibrary0(Runtime.java:822)
at java.lang.System.loadLibrary(System.java:993)
at sun.security.action.LoadLibraryAction.run(LoadLibraryAction.java:50)
at java.security.AccessController.doPrivileged(Native Method)
at sun.rmi.server.MarshalInputStream.<clinit>(MarshalInputStream.java:97)
... 5 more
</code></pre>
<p>IMHO the meaning of this is that a thread is (implicitly) created and gets the NativeRMISecurityManager as its default SecurityManager.</p>
<p>Would somebody have any advice concerning that ?</p>
| [
{
"answer_id": 291993,
"author": "Greg Case",
"author_id": 462,
"author_profile": "https://Stackoverflow.com/users/462",
"pm_score": 3,
"selected": true,
"text": "public class NativeRMISecurityManager extends RMISecurityManager {\n\n private static final boolean UNIX;\n\n static {\n String OS = System.getProperty(\"os.name\").toLowerCase();\n UNIX = (OS.compareTo(\"windows\") != 0); /* Assume that if not \n * windows, then \"UNIX/POSIX\" \n */\n }\n\n protected static InheritableThreadLocal<String> user =\n new InheritableThreadLocal<String>();\n\n public static setThreadUser(String username) {\n user.set(username);\n }\n\n\n public NativeRMISecurityManager(String initialUser) {\n super();\n // Set the user for the thread that constructs the security manager\n // All threads created as a child of that thread will inherit the user\n // All threads not created as a child of that thread will have a 'null' user\n setThreadUser(initialUser);\n }\n\n\n public void checkRead(String file) {\n super.checkRead(file);\n /*\n * If we are on a **IX platform we want to check that \n * the _user_ has access rights.\n */\n if (UNIX)\n {\n if (file == null)\n {\n throw new SecurityException(\"file = NULL !!!\");\n }\n\n String str_user = NativeRMISecurityManager.user.get();\n\n if (str_user != null)\n {\n // Note: sanitize input to native method\n int ret = c_checkRead(file, str_user);\n\n if (ret != 0)\n {\n throw new SecurityException(\"Access error: \" + file);\n }\n }\n\n // Assume a system thread and allow access\n }\n }\n\n public native int c_checkRead(String file, String user);\n}\n"
},
{
"answer_id": 298148,
"author": "Creasixtine",
"author_id": 26465,
"author_profile": "https://Stackoverflow.com/users/26465",
"pm_score": 1,
"selected": false,
"text": "package rmi;\n\nimport java.rmi.RMISecurityManager;\n\n/**\n * <p> Ce SecurityManager, qui herite de RMISecurityManager,\n * implemente une verification supplementaire des droits\n * d'acces aux fichiers.\n * A la creation du SecurityManager et lors de la creation\n * de nouveaux threads, on renseigne ThreadLocal du nom du\n * _user_ du thread.\n * <p>Ainsi, lors des checkRead() et checkWrite()\n * notre SecurityManager appelle une methode native (JNI)\n * qui va verifier directement si le user a les droits \n * d'acces a la ressource. \n * <p><b>Warning : NE PAS OUBLIER DE FAIRE APPEL A \n * setCurrentUser() DANS CHAQUE THREAD CREE.</b>\n * <p> <b>Remarque :</b> Pour les informations sur la compilation \n * et l'execution de la lib ecrite en C, cf. le fichier README. \n * @author a_po\n */\npublic class NativeRMISecurityManager extends RMISecurityManager\n{\n private boolean unix;\n protected ThreadLocal user = new ThreadLocal();\n\n /**\n * Constructeur par defaut.\n * <p><b>ATTENTION :</b> Bien faire appel a la methode setCurrentUser(String) !\n * Sinon le SecurityManager se comportera comme un RMISecurityManager classique.\n * @see public void setCurrentUser(String userName)\n */\n public NativeRMISecurityManager()\n {\n super();\n String OS = System.getProperty(\"os.name\").toLowerCase();\n unix = (OS.compareTo(\"windows\") != 0); /* Si le systeme \n * n'EST PAS windows, \n * alors c'est UNIX...\n * \n * Pas tres rigoureux,\n * mais sinon il faut tester\n * Systeme V, Linux, *BSD,\n * Sun OS, ...\n */\n\n /*\n * User du ThreadLocal : Chaque thread est considere comme ayant des\n * droits d'acces au systeme potentiellement differents.\n */\n this.user.set(user);\n\n if (!unix)\n {\n System.out.println(\"Systeme : \"+OS);\n }\n }\n\n\n /**\n * Verification en lecture.\n * <p>\n * Dans le cas ou l'on est sur une plateforme POSIX,\n * on souhaite verifier que le _user_ du Thread a le droit\n * de lecture sur le fichier.\n * <p>\n * De plus, dans le cas ou user est null, cela signifie\n * OBLIGATOIREMENT que le thread a ete cree \"automatiquement\"\n * et que le thread courant n'est pas un thread de \"tache a executer\".\n * <p>\n * En effet, le user est recupere dans le ThreadLocal\n * et on force l'initialisation de cette variable a l'instanciation\n * du SecurityManager (en mettant le constructeur par defaut prive) ou\n * en faisant appel a setCurrentUser(String)\n * @see void rmi.NativeRMISecurityManager.setCurrentUser(String user)\n */\n public void checkRead(String file)\n {\n super.checkRead(file);\n\n String str_user = (String)this.user.get();\n\n if (unix && str_user != null)\n {\n if (file == null)\n {\n throw new SecurityException(\"file = NULL !!!\");\n }\n\n int ret = c_checkRead(file, str_user);\n if (ret != 0)\n {\n throw new SecurityException(\"Erreur d'acces au fichier : \" + file);\n }\n }\n }\n\n /**\n * Verification d'acces en ecriture sur un fichier.\n * @see void rmi.NativeRMISecurityManager.checkRead(String file)\n */\n public void checkWrite(String file)\n {\n super.checkWrite(file);\n String str_user = (String)this.user.get();\n\n if (unix && str_user != null)\n {\n if (file == null)\n {\n throw new SecurityException(\"file = NULL !!!\");\n }\n\n int ret = c_checkWrite(file, str_user);\n if (ret != 0)\n {\n throw new SecurityException(\"Erreur d'acces au fichier : \" + file);\n }\n }\n }\n\n /**\n * Configure le thread courant pour que le user soit pris en compte\n * dans les verifications d'acces aux fichiers.\n * @param user\n */\n public void setCurrentUser(String userName)\n {\n this.user = new ThreadLocal();\n this.user.set(userName);\n }\n\n public String getCurrentUser()\n {\n if (user!=null){\n return (String)user.get();\n }\n else return null;\n }\n\n /**\n * Methode native a implementer en C.\n * @param file\n * @param user\n * @return 0 si ok <p> -1 sinon\n */\n public native int c_checkRead(String file, String user);\n\n /**\n * Idem que pour c_checkRead\n * @param file\n * @param user\n * @return\n * @see int rmi.NativeRMISecurityManager.c_checkRead(String file, String user)\n */\n public native int c_checkWrite(String file, String user);\n\n /**\n * Chargement de la bibliotheque JNI.\n */\n static\n {\n System.loadLibrary(\"rmi_NativeRMISecurityManager\");\n }\n}\n #include <stdio.h>\n#include <jni.h>\n#include <sys/stat.h>\n#include <sys/types.h>\n#include <unistd.h>\n#include <pwd.h>\n#include <stdlib.h>\n#include <grp.h>\n#include <string.h>\n#include \"rmi_NativeRMISecurityManager.h\"\n\n/* Droits en lecture / ecriture / execution */\n\n#define R_RIGHT 4\n#define X_RIGHT 1\n#define W_RIGHT 2\n\nJNIEXPORT jint JNICALL Java_rmi_NativeRMISecurityManager_c_1checkRead\n (JNIEnv *env, jobject obj, jstring file, jstring user)\n{\n int ret = check_permission(env, obj, file, user);\n /**\n * La permission d'acces a un fichier vaut ceci :\n * 1 pour l'execution\n * 2 pour l'ecriture\n * 4 pour la lecture.\n * Donc :\n * * Droit en lecture : 4, 5, 6, 7\n * * Droit en ecriture : 2, 3, 6, 7\n * * Droit en execution : 1, 3, 5, 7.\n */\n if (ret == R_RIGHT || ret == R_RIGHT + W_RIGHT || \n ret == R_RIGHT + X_RIGHT || ret == R_RIGHT + W_RIGHT + X_RIGHT)\n {\n return 0;\n }\n else\n return -1;\n}\n\nJNIEXPORT jint JNICALL Java_rmi_NativeRMISecurityManager_c_1checkWrite\n (JNIEnv *env, jobject obj, jstring file, jstring user)\n{\n int ret = check_permission(env, obj, file, user);\n /**\n * La permission d'acces a un fichier vaut ceci :\n * 1 pour l'execution\n * 2 pour l'ecriture\n * 4 pour la lecture.\n * Donc :\n * * Droit en lecture : 4, 5, 6, 7\n * * Droit en ecriture : 2, 3, 6, 7\n * * Droit en execution : 1, 3, 5, 7.\n */\n if (ret == W_RIGHT || ret == W_RIGHT + R_RIGHT || \n ret == W_RIGHT + X_RIGHT || ret == W_RIGHT + R_RIGHT + X_RIGHT)\n {\n return 0;\n }\n else\n return -1;\n}\n\n\nint check_permission(JNIEnv *env, jobject obj, jstring file, jstring user)\n{\n struct stat pstat;\n const char* pzcfile = (*env)->GetStringUTFChars(env, file, 0);\n const char* pzcuser = (*env)->GetStringUTFChars(env, user, 0);\n struct passwd* puserInfo;\n int bisOwner = 0;\n int bisGroup = 0;\n struct group* pgroupInfo;\n int i;\n int droits = 0;\n\n /* recuperer les informations relatives au fichier */\n if(lstat(pzcfile, &pstat)<0)\n {\n fprintf(stderr,\"* Le fichier %s n'exite pas.\\n\", pzcfile);\n (*env)->ReleaseStringUTFChars(env, file, pzcfile);\n (*env)->ReleaseStringUTFChars(env, user, pzcuser);\n return -1;\n }\n\n /* recuperer l'identifiant du user */\n puserInfo = getpwnam(pzcuser);\n if(puserInfo == NULL)\n {\n fprintf(stderr,\"* L'utilisateur %s n'est pas connu du systeme.\\n\", pzcuser);\n (*env)->ReleaseStringUTFChars(env, file, pzcfile);\n (*env)->ReleaseStringUTFChars(env, user, pzcuser);\n return -2;\n }\n\n /* regarder si le user est proprietaire du fichier */\n if(puserInfo->pw_uid == pstat.st_uid)\n {\n bisOwner = 1;\n }\n /* si le user n'est pas proprietaire, verifier s'il est membre du groupe */\n if(!bisOwner)\n {\n /* recuperer les informations relatives au groupe */\n pgroupInfo = getgrgid(pstat.st_gid);\n /* parcourir la liste des membres du groupe a la recherche du user */\n for(i=0;;i++)\n {\n if(pgroupInfo->gr_mem[i] == NULL)\n {\n break;\n }\n if(strcmp(pgroupInfo->gr_mem[i],pzcuser) == 0)\n {\n bisGroup = 1;\n break;\n }\n }\n }\n\n /* recuperer les droits correspondants au user */\n if(bisOwner)\n {\n droits = (pstat.st_mode & S_IRWXU) >> 6;\n }\n else if(bisGroup)\n {\n droits = (pstat.st_mode & S_IRWXG) >> 3;\n }\n else\n {\n droits = pstat.st_mode & S_IRWXO;\n }\n\n /* liberer les espaces memoire alloues */\n (*env)->ReleaseStringUTFChars(env, file, pzcfile);\n (*env)->ReleaseStringUTFChars(env, user, pzcuser);\n return droits;\n}\n"
}
] | 2008/11/14 | [
"https://Stackoverflow.com/questions/290545",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/26465/"
] |
290,548 | <p>How can I validate a username and password against Active Directory? I simply want to check if a username and password are correct.</p>
| [
{
"answer_id": 290558,
"author": "stephbu",
"author_id": 12702,
"author_profile": "https://Stackoverflow.com/users/12702",
"pm_score": 5,
"selected": false,
"text": "LOGON32_LOGON_NETWORK (3)\n"
},
{
"answer_id": 290571,
"author": "Charles Bretana",
"author_id": 32632,
"author_profile": "https://Stackoverflow.com/users/32632",
"pm_score": 3,
"selected": false,
"text": "#region NTLogonUser\n#region Direct OS LogonUser Code\n[DllImport( \"advapi32.dll\")]\nprivate static extern bool LogonUser(String lpszUsername, \n String lpszDomain, String lpszPassword, int dwLogonType, \n int dwLogonProvider, out int phToken);\n\n[DllImport(\"Kernel32.dll\")]\nprivate static extern int GetLastError();\n\npublic static bool LogOnXP(String sDomain, String sUser, String sPassword)\n{\n int token1, ret;\n int attmpts = 0;\n\n bool LoggedOn = false;\n\n while (!LoggedOn && attmpts < 2)\n {\n LoggedOn= LogonUser(sUser, sDomain, sPassword, 3, 0, out token1);\n if (LoggedOn) return (true);\n else\n {\n switch (ret = GetLastError())\n {\n case (126): ; \n if (attmpts++ > 2)\n throw new LogonException(\n \"Specified module could not be found. error code: \" + \n ret.ToString());\n break;\n\n case (1314): \n throw new LogonException(\n \"Specified module could not be found. error code: \" + \n ret.ToString());\n\n case (1326): \n // edited out based on comment\n // throw new LogonException(\n // \"Unknown user name or bad password.\");\n return false;\n\n default: \n throw new LogonException(\n \"Unexpected Logon Failure. Contact Administrator\");\n }\n }\n }\n return(false);\n}\n#endregion Direct Logon Code\n#endregion NTLogonUser\n"
},
{
"answer_id": 290580,
"author": "DiningPhilanderer",
"author_id": 30934,
"author_profile": "https://Stackoverflow.com/users/30934",
"pm_score": 6,
"selected": false,
"text": "using (DirectoryEntry adsEntry = new DirectoryEntry(path, strAccountId, strPassword))\n{\n using (DirectorySearcher adsSearcher = new DirectorySearcher(adsEntry))\n {\n //adsSearcher.Filter = \"(&(objectClass=user)(objectCategory=person))\";\n adsSearcher.Filter = \"(sAMAccountName=\" + strAccountId + \")\";\n\n try\n {\n SearchResult adsSearchResult = adsSearcher.FindOne();\n bSucceeded = true;\n\n strAuthenticatedBy = \"Active Directory\";\n strError = \"User has been authenticated by Active Directory.\";\n }\n catch (Exception ex)\n {\n // Failed to authenticate. Most likely it is caused by unknown user\n // id or bad strPassword.\n strError = ex.Message;\n }\n finally\n {\n adsEntry.Close();\n }\n }\n}\n"
},
{
"answer_id": 290599,
"author": "Steven A. Lowe",
"author_id": 9345,
"author_profile": "https://Stackoverflow.com/users/9345",
"pm_score": 5,
"selected": false,
"text": "using System.DirectoryServices;\n\n//srvr = ldap server, e.g. LDAP://domain.com\n//usr = user name\n//pwd = user password\npublic bool IsAuthenticated(string srvr, string usr, string pwd)\n{\n bool authenticated = false;\n\n try\n {\n DirectoryEntry entry = new DirectoryEntry(srvr, usr, pwd);\n object nativeObject = entry.NativeObject;\n authenticated = true;\n }\n catch (DirectoryServicesCOMException cex)\n {\n //not authenticated; reason why is in cex\n }\n catch (Exception ex)\n {\n //not authenticated due to some other exception [this is optional]\n }\n\n return authenticated;\n}\n"
},
{
"answer_id": 290606,
"author": "Mathieu Garstecki",
"author_id": 22078,
"author_profile": "https://Stackoverflow.com/users/22078",
"pm_score": 4,
"selected": false,
"text": "using (DirectoryEntry entry = new DirectoryEntry())\n{\n entry.Username = \"here goes the username you want to validate\";\n entry.Password = \"here goes the password\";\n\n DirectorySearcher searcher = new DirectorySearcher(entry);\n\n searcher.Filter = \"(objectclass=user)\";\n\n try\n {\n searcher.FindOne();\n }\n catch (COMException ex)\n {\n if (ex.ErrorCode == -2147023570)\n {\n // Login or password is incorrect\n }\n }\n}\n\n// FindOne() didn't throw, the credentials are correct\n"
},
{
"answer_id": 499716,
"author": "marc_s",
"author_id": 13302,
"author_profile": "https://Stackoverflow.com/users/13302",
"pm_score": 9,
"selected": false,
"text": "System.DirectoryServices.AccountManagement // create a \"principal context\" - e.g. your domain (could be machine, too)\nusing(PrincipalContext pc = new PrincipalContext(ContextType.Domain, \"YOURDOMAIN\"))\n{\n // validate the credentials\n bool isValid = pc.ValidateCredentials(\"myuser\", \"mypassword\");\n}\n True"
},
{
"answer_id": 5580053,
"author": "chauwel",
"author_id": 696649,
"author_profile": "https://Stackoverflow.com/users/696649",
"pm_score": 3,
"selected": false,
"text": "using System;\nusing System.Collections.Generic;\nusing System.Text;\nusing System.Security;\nusing System.Diagnostics;\n\nstatic public bool Validate(string domain, string username, string password)\n{\n try\n {\n Process proc = new Process();\n proc.StartInfo = new ProcessStartInfo()\n {\n FileName = \"no_matter.xyz\",\n CreateNoWindow = true,\n WindowStyle = ProcessWindowStyle.Hidden,\n WorkingDirectory = Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData),\n UseShellExecute = false,\n RedirectStandardError = true,\n RedirectStandardOutput = true,\n RedirectStandardInput = true,\n LoadUserProfile = true,\n Domain = String.IsNullOrEmpty(domain) ? \"\" : domain,\n UserName = username,\n Password = Credentials.ToSecureString(password)\n };\n proc.Start();\n proc.WaitForExit();\n }\n catch (System.ComponentModel.Win32Exception ex)\n {\n switch (ex.NativeErrorCode)\n {\n case 1326: return false;\n case 2: return true;\n default: throw ex;\n }\n }\n catch (Exception ex)\n {\n throw ex;\n }\n\n return false;\n} \n"
},
{
"answer_id": 5588127,
"author": "palswim",
"author_id": 393280,
"author_profile": "https://Stackoverflow.com/users/393280",
"pm_score": 4,
"selected": false,
"text": "using System.DirectoryServices;\n\nusing(var DE = new DirectoryEntry(path, username, password)\n{\n try\n {\n DE.RefreshCache(); // This will force credentials validation\n }\n catch (COMException ex)\n {\n // Validation failed - handle how you want\n }\n}\n"
},
{
"answer_id": 11033489,
"author": "Søren Mors",
"author_id": 219295,
"author_profile": "https://Stackoverflow.com/users/219295",
"pm_score": 6,
"selected": false,
"text": "using System;\nusing System.DirectoryServices.Protocols;\nusing System.Net;\n\nnamespace ProtocolTest\n{\n class Program\n {\n static void Main(string[] args)\n {\n try\n {\n LdapConnection connection = new LdapConnection(\"ldap.fabrikam.com\");\n NetworkCredential credential = new NetworkCredential(\"user\", \"password\");\n connection.Credential = credential;\n connection.Bind();\n Console.WriteLine(\"logged in\");\n }\n catch (LdapException lexc)\n {\n String error = lexc.ServerErrorMessage;\n Console.WriteLine(lexc);\n }\n catch (Exception exc)\n {\n Console.WriteLine(exc);\n }\n }\n }\n}\n lexc.ServerErrorMessage 525 user not found (1317)\n52e invalid credentials (1326)\n530 not permitted to logon at this time (1328)\n531 not permitted to logon at this workstation (1329)\n532 password expired (1330)\n533 account disabled (1331) \n701 account expired (1793)\n773 user must reset password (1907)\n775 user account locked (1909)\n"
},
{
"answer_id": 34481264,
"author": "hossein andarkhora",
"author_id": 3643534,
"author_profile": "https://Stackoverflow.com/users/3643534",
"pm_score": 2,
"selected": false,
"text": " private bool IsValidActiveDirectoryUser(string activeDirectoryServerDomain, string username, string password)\n {\n try\n {\n DirectoryEntry de = new DirectoryEntry(\"LDAP://\" + activeDirectoryServerDomain, username + \"@\" + activeDirectoryServerDomain, password, AuthenticationTypes.Secure);\n DirectorySearcher ds = new DirectorySearcher(de);\n ds.FindOne();\n return true;\n }\n catch //(Exception ex)\n {\n return false;\n }\n }\n"
},
{
"answer_id": 41352220,
"author": "Michael Liu",
"author_id": 1127114,
"author_profile": "https://Stackoverflow.com/users/1127114",
"pm_score": 3,
"selected": false,
"text": "false using System;\nusing System.ComponentModel;\nusing System.Runtime.InteropServices;\n\nusing Microsoft.Win32.SafeHandles;\n\npublic static class Win32Authentication\n{\n private class SafeTokenHandle : SafeHandleZeroOrMinusOneIsInvalid\n {\n private SafeTokenHandle() // called by P/Invoke\n : base(true)\n {\n }\n\n protected override bool ReleaseHandle()\n {\n return CloseHandle(this.handle);\n }\n }\n\n private enum LogonType : uint\n {\n Network = 3, // LOGON32_LOGON_NETWORK\n }\n\n private enum LogonProvider : uint\n {\n WinNT50 = 3, // LOGON32_PROVIDER_WINNT50\n }\n\n [DllImport(\"kernel32.dll\", SetLastError = true)]\n private static extern bool CloseHandle(IntPtr handle);\n\n [DllImport(\"advapi32.dll\", SetLastError = true)]\n private static extern bool LogonUser(\n string userName, string domain, string password,\n LogonType logonType, LogonProvider logonProvider,\n out SafeTokenHandle token);\n\n public static void AuthenticateUser(string userName, string password)\n {\n string domain = null;\n string[] parts = userName.Split('\\\\');\n if (parts.Length == 2)\n {\n domain = parts[0];\n userName = parts[1];\n }\n\n SafeTokenHandle token;\n if (LogonUser(userName, domain, password, LogonType.Network, LogonProvider.WinNT50, out token))\n token.Dispose();\n else\n throw new Win32Exception(); // calls Marshal.GetLastWin32Error()\n }\n}\n try\n{\n Win32Authentication.AuthenticateUser(\"EXAMPLE\\\\user\", \"P@ssw0rd\");\n // Or: Win32Authentication.AuthenticateUser(\"user@example.com\", \"P@ssw0rd\");\n}\ncatch (Win32Exception ex)\n{\n switch (ex.NativeErrorCode)\n {\n case 1326: // ERROR_LOGON_FAILURE (incorrect user name or password)\n // ...\n case 1327: // ERROR_ACCOUNT_RESTRICTION\n // ...\n case 1330: // ERROR_PASSWORD_EXPIRED\n // ...\n case 1331: // ERROR_ACCOUNT_DISABLED\n // ...\n case 1907: // ERROR_PASSWORD_MUST_CHANGE\n // ...\n case 1909: // ERROR_ACCOUNT_LOCKED_OUT\n // ...\n default: // Other\n break;\n }\n}\n"
},
{
"answer_id": 60369789,
"author": "Gayan Chinthaka Dharmarathna",
"author_id": 6863414,
"author_profile": "https://Stackoverflow.com/users/6863414",
"pm_score": 0,
"selected": false,
"text": " using System.DirectoryServices;\n using System.DirectoryServices.Protocols;\n using System.DirectoryServices.AccountManagement;\n using System.Net; \n\nprivate void AuthUser() { \n\n\n try{\n string Uid = \"USER_NAME\";\n string Pass = \"PASSWORD\";\n if (Uid == \"\")\n {\n MessageBox.Show(\"Username cannot be null\");\n }\n else if (Pass == \"\")\n {\n MessageBox.Show(\"Password cannot be null\");\n }\n else\n {\n LdapConnection connection = new LdapConnection(\"YOUR DOMAIN\");\n NetworkCredential credential = new NetworkCredential(Uid, Pass);\n connection.Credential = credential;\n connection.Bind();\n\n // after authenticate Loading user details to data table\n PrincipalContext ctx = new PrincipalContext(ContextType.Domain);\n UserPrincipal user = UserPrincipal.FindByIdentity(ctx, Uid);\n DirectoryEntry up_User = (DirectoryEntry)user.GetUnderlyingObject();\n DirectorySearcher deSearch = new DirectorySearcher(up_User);\n SearchResultCollection results = deSearch.FindAll();\n ResultPropertyCollection rpc = results[0].Properties;\n DataTable dt = new DataTable();\n DataRow toInsert = dt.NewRow();\n dt.Rows.InsertAt(toInsert, 0);\n\n foreach (string rp in rpc.PropertyNames)\n {\n if (rpc[rp][0].ToString() != \"System.Byte[]\")\n {\n dt.Columns.Add(rp.ToString(), typeof(System.String));\n\n foreach (DataRow row in dt.Rows)\n {\n row[rp.ToString()] = rpc[rp][0].ToString();\n }\n\n } \n }\n //You can load data to grid view and see for reference only\n dataGridView1.DataSource = dt;\n\n\n }\n } //Error Handling part\n catch (LdapException lexc)\n {\n String error = lexc.ServerErrorMessage;\n string pp = error.Substring(76, 4);\n string ppp = pp.Trim();\n\n if (\"52e\" == ppp)\n {\n MessageBox.Show(\"Invalid Username or password, contact ADA Team\");\n }\n if (\"775\" == ppp)\n {\n MessageBox.Show(\"User account locked, contact ADA Team\");\n }\n if (\"525\" == ppp)\n {\n MessageBox.Show(\"User not found, contact ADA Team\");\n }\n if (\"530\" == ppp)\n {\n MessageBox.Show(\"Not permitted to logon at this time, contact ADA Team\");\n }\n if (\"531\" == ppp)\n {\n MessageBox.Show(\"Not permitted to logon at this workstation, contact ADA Team\");\n }\n if (\"532\" == ppp)\n {\n MessageBox.Show(\"Password expired, contact ADA Team\");\n }\n if (\"533\" == ppp)\n {\n MessageBox.Show(\"Account disabled, contact ADA Team\");\n }\n if (\"533\" == ppp)\n {\n MessageBox.Show(\"Account disabled, contact ADA Team\");\n }\n\n\n\n } //common error handling\n catch (Exception exc)\n {\n MessageBox.Show(\"Invalid Username or password, contact ADA Team\");\n\n }\n\n finally {\n tbUID.Text = \"\";\n tbPass.Text = \"\";\n\n }\n }\n"
},
{
"answer_id": 65323314,
"author": "dnxit",
"author_id": 1106625,
"author_profile": "https://Stackoverflow.com/users/1106625",
"pm_score": 1,
"selected": false,
"text": "//\"LDAP://\" + domainName\nprivate void btnValidate_Click(object sender, RoutedEventArgs e)\n{\n try\n {\n DirectoryEntry de = new DirectoryEntry(txtDomainName.Text, txtUsername.Text, txtPassword.Text);\n DirectorySearcher dsearch = new DirectorySearcher(de);\n SearchResult results = null;\n\n results = dsearch.FindOne();\n\n MessageBox.Show(\"Validation Success.\");\n }\n catch (LdapException ex)\n {\n MessageBox.Show($\"Validation Failure. {ex.GetBaseException().Message}\");\n }\n catch (Exception ex)\n {\n MessageBox.Show($\"Validation Failure. {ex.GetBaseException().Message}\");\n }\n}\n\nprivate void btnValidate2_Click(object sender, RoutedEventArgs e)\n{\n try\n {\n LdapConnection lcon = new LdapConnection(new LdapDirectoryIdentifier((string)null, false, false));\n NetworkCredential nc = new NetworkCredential(txtUsername.Text,\n txtPassword.Text, txtDomainName.Text);\n lcon.Credential = nc;\n lcon.AuthType = AuthType.Negotiate;\n lcon.Bind(nc);\n\n MessageBox.Show(\"Validation Success.\");\n }\n catch (LdapException ex)\n {\n MessageBox.Show($\"Validation Failure. {ex.GetBaseException().Message}\");\n }\n catch (Exception ex)\n {\n MessageBox.Show($\"Validation Failure. {ex.GetBaseException().Message}\");\n }\n}\n"
},
{
"answer_id": 73021921,
"author": "Raphael Frei",
"author_id": 16692176,
"author_profile": "https://Stackoverflow.com/users/16692176",
"pm_score": 0,
"selected": false,
"text": "public static string AzureLogin(string user, string password) {\n\n string status;\n\n try {\n new DirectorySearcher(new DirectoryEntry(\"LDAP://yourdomain.com\", user, password) {\n AuthenticationType = AuthenticationTypes.Secure,\n Username = user,\n Password = password\n }) {\n Filter = \"(objectclass=user)\"\n }.FindOne().Properties[\"displayname\"][0].ToString();\n\n status = $\"SUCCESS - User {user} has logged in.\";\n\n } catch(System.Exception e) {\n status = $\"ERROR - While logging in: {e}\";\n }\n\n return status;\n}\n"
}
] | 2008/11/14 | [
"https://Stackoverflow.com/questions/290548",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
290,559 | <p>I want to write a script that will stop a scheduled task on a remote computer, do some stuff, and then start the schedule task back up.</p>
<p>How can I do it?</p>
| [
{
"answer_id": 291347,
"author": "Ben Noland",
"author_id": 32899,
"author_profile": "https://Stackoverflow.com/users/32899",
"pm_score": 8,
"selected": true,
"text": "schtasks /end /s <machine name> /tn <task name>\n schtasks /run /s <machine name> /tn <task name>\n\n\nC:\\>schtasks /?\n\nSCHTASKS /parameter [arguments]\n\nDescription:\n Enables an administrator to create, delete, query, change, run and\n end scheduled tasks on a local or remote system. Replaces AT.exe.\n\nParameter List:\n /Create Creates a new scheduled task.\n\n /Delete Deletes the scheduled task(s).\n\n /Query Displays all scheduled tasks.\n\n /Change Changes the properties of scheduled task.\n\n /Run Runs the scheduled task immediately.\n\n /End Stops the currently running scheduled task.\n\n /? Displays this help message.\n\nExamples:\n SCHTASKS\n SCHTASKS /?\n SCHTASKS /Run /?\n SCHTASKS /End /?\n SCHTASKS /Create /?\n SCHTASKS /Delete /?\n SCHTASKS /Query /?\n SCHTASKS /Change /?\n"
},
{
"answer_id": 26151891,
"author": "Oleks",
"author_id": 102112,
"author_profile": "https://Stackoverflow.com/users/102112",
"pm_score": 2,
"selected": false,
"text": "/disable /enable /change schtasks.exe /change /s <machine name> /tn <task name> /disable\nschtasks.exe /change /s <machine name> /tn <task name> /enable\n"
},
{
"answer_id": 32695273,
"author": "Daniel Ray-Marks",
"author_id": 4105701,
"author_profile": "https://Stackoverflow.com/users/4105701",
"pm_score": 2,
"selected": false,
"text": "schtasks /change /disable /tn \"Name Of Task\" /s REMOTEMACHINENAME /u mydomain\\administrator /p adminpassword \n"
},
{
"answer_id": 54850031,
"author": "voip1811",
"author_id": 11108587,
"author_profile": "https://Stackoverflow.com/users/11108587",
"pm_score": 1,
"selected": false,
"text": "schtasks /change /ENABLE /tn \"Auto Restart\" /s mycomutername /u mycomputername\\username/p mypassowrd\n"
}
] | 2008/11/14 | [
"https://Stackoverflow.com/questions/290559",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/32899/"
] |
290,583 | <p>Vista SP1
Visual Studio 2008 SP1
.NET 3.5 SP1
C#</p>
<p>I have a winforms app I'm playing with that uses a SerialPort object as a private variable. When the application is compiled and executed, it works great. It also works running in debug mode wihtout any breakpoints. 90% of the time when I stop at a breakpoint and try to step through code I get an 'unhandled exception ocurred' dialog with these details:</p>
<p>System.ObjectDisposedException was unhandled
Message="Safe handle has been closed"
Source="mscorlib"
ObjectName=""
StackTrace:
at Microsoft.Win32.Win32Native.SetEvent(SafeWaitHandle handle)
at System.Threading.EventWaitHandle.Set()
at System.IO.Ports.SerialStream.AsyncFSCallback(UInt32 errorCode, UInt32 numBytes, NativeOverlapped* pOverlapped)
at System.Threading._IOCompletionCallback.PerformIOCompletionCallback(UInt32 errorCode, UInt32 numBytes, NativeOverlapped* pOVERLAP)
InnerException:</p>
<p>The frustrating thing is, I do not have to be stepping over serial-related code! I just have to have done <em>something</em> with the port. So I might read a string, manipulate the string, add two numbers together, whatever, and then BANG.</p>
<p>Again, this works just fine when NOT debugging, or when debugging wihtout any breakpoints. There seems to be something about stopping at a breakpoint that makes the CLR dispose the SerialStream on a different thread.</p>
<p>There is a lot of chatter online about problems with renoving USB devices causing this. But I'm using the build-in motherboard port on COM1.</p>
<p>I don't think I had this issue in .NET 2.0 so I may have to go back to that...</p>
<p>I need to simplify the application quite a bit before I can post code - but has anyone seen behavior like this in the debugger before?</p>
<p>Thanks so much!</p>
| [
{
"answer_id": 44070189,
"author": "Berend Visser",
"author_id": 8036699,
"author_profile": "https://Stackoverflow.com/users/8036699",
"pm_score": 0,
"selected": false,
"text": "serialPortLock = Monitor.TryEnter(serialPort, 3000);\nThread.Sleep(5);\nserialPort.Write(msg, 0, msg.Length);\n"
}
] | 2008/11/14 | [
"https://Stackoverflow.com/questions/290583",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/37710/"
] |
290,590 | <p>For both .NET Winforms and Windows Presentation Foundation, if I have a text box that the user has just entered text into, and a button, if the user clicks the button the "LostFocus" event fires before the button click event fires. However if the user uses a keyboard shortcut for the button (e.g. Button's text is "&Button" or "_Button" and user performs Alt+B), then the "LostFocus" event fires after the button click event, which is less useful.</p>
<p>Do you know of reasonable workarounds? We have various things that we want to occur in LostFocus before ButtonClick.</p>
| [
{
"answer_id": 290661,
"author": "Quibblesome",
"author_id": 1143,
"author_profile": "https://Stackoverflow.com/users/1143",
"pm_score": 1,
"selected": false,
"text": "Button b = (Button) sender;\nb.Focus();\n"
},
{
"answer_id": 290937,
"author": "Jason Down",
"author_id": 9732,
"author_profile": "https://Stackoverflow.com/users/9732",
"pm_score": 3,
"selected": true,
"text": "public partial class Form1 : Form\n {\n private Boolean _didLostFocusLogic;\n\n public Form1()\n {\n InitializeComponent();\n }\n\n private void textBox1_Leave(object sender, EventArgs e)\n {\n LostFocusLogic();\n }\n\n private void button1_Click(object sender, EventArgs e)\n {\n ButtonClickLogic();\n }\n\n private void LostFocusLogic()\n {\n /* Do stuff */\n _didLostFocusLogic = true;\n }\n\n private void ButtonClickLogic()\n {\n if (!_didLostFocusLogic)\n LostFocusLogic();\n\n _didLostFocusLogic = false; // Reset for next time.\n\n /* Do stuff */\n }\n }\n"
}
] | 2008/11/14 | [
"https://Stackoverflow.com/questions/290590",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
290,596 | <p>Sql server complaining about this IF NOT EXISTS statement, saying that there is 'incorrect syntax near the keyword 'OR'.</p>
<p>My query:</p>
<pre><code>IF NOT EXISTS (
(SELECT * FROM Users where userID = 1)
OR
(SELECT * FROM sales WHERE saleID = 1)
)
BEGIN
// blah blah blah
END
</code></pre>
| [
{
"answer_id": 290618,
"author": "Steven A. Lowe",
"author_id": 9345,
"author_profile": "https://Stackoverflow.com/users/9345",
"pm_score": 3,
"selected": false,
"text": "IF \n NOT EXISTS (SELECT 1 FROM Users where userID = 1) \nAND \n NOT EXISTS (SELECT 1 FROM sales WHERE saleID = 1)\nBEGIN \n -- blah blah blah\nEND\n IF NOT (\n EXISTS (SELECT 1 FROM Users where userID = 1) \n OR \n EXISTS (SELECT 1 FROM sales WHERE saleID = 1)\n)\nBEGIN \n -- blah blah blah\nEND\n"
},
{
"answer_id": 290622,
"author": "dragonjujo",
"author_id": 37344,
"author_profile": "https://Stackoverflow.com/users/37344",
"pm_score": 0,
"selected": false,
"text": "IF NOT EXISTS(SELECT * FROM Users WHERE userID = 1) OR (AND) NOT EXISTS(SELECT * FROM sales WHERE saleID = 1)\n"
}
] | 2008/11/14 | [
"https://Stackoverflow.com/questions/290596",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
290,598 | <p>I'm doing some text rendering in Cocoa using NSAttributedString, and setting the font and underline properties, etc. However, I can't figure out how I can change the text's tracking. Any suggestions?</p>
| [
{
"answer_id": 292563,
"author": "cms",
"author_id": 28532,
"author_profile": "https://Stackoverflow.com/users/28532",
"pm_score": 1,
"selected": false,
"text": "NSLayoutManager"
}
] | 2008/11/14 | [
"https://Stackoverflow.com/questions/290598",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3830/"
] |
290,610 | <p>I have a table which has a field <code>sort_id</code>. In this field there are numbers from 1 to n, that define the order of the data sets.
Now I want to delete some elements and afterwards I want to reorder the table. Therefore I need a query that "finds" the gaps and changes the <code>sort_id</code> field according to the modifications.</p>
<p>Sure, I could do something like this:</p>
<pre><code>SELECT sort_id FROM table WHERE id = 5
</code></pre>
<p>Then save the sort_id and afterwards:</p>
<pre><code>DELETE FROM table WHERE id = 5
UPDATE table SET sort_id = sort_id - 1 WHERE sort_id > {id from above}
</code></pre>
<p>But I'd like to do the reordering process in one step.</p>
| [
{
"answer_id": 290641,
"author": "Mladen Prajdic",
"author_id": 31345,
"author_profile": "https://Stackoverflow.com/users/31345",
"pm_score": 0,
"selected": false,
"text": "SELECT row_number() over(order by sort_id) as RN\nFROM table\n update t1\nset sort_id = t2.RN\nFROM table t1 \n join (SELECT row_number() over(order by sort_id) as RN FROM table) t2 \n on t1.UniqueId = t2.UniqueId\n"
},
{
"answer_id": 290856,
"author": "Arvo",
"author_id": 35777,
"author_profile": "https://Stackoverflow.com/users/35777",
"pm_score": 0,
"selected": false,
"text": "update table t1\nset sort_id = (select count * from table t2 where t2.sort_id <= t1.sort_id)\n"
},
{
"answer_id": 290956,
"author": "Bill Karwin",
"author_id": 20860,
"author_profile": "https://Stackoverflow.com/users/20860",
"pm_score": 2,
"selected": false,
"text": "SELECT UPDATE SET @i := 0;\nUPDATE mytable\nSET sort_id = (@i := @i + 1)\nORDER BY sort_id;\n sort_id id=6"
}
] | 2008/11/14 | [
"https://Stackoverflow.com/questions/290610",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/35903/"
] |
290,617 | <p>I feel like I'm re-inventing the wheel here, but I need to find a way of taking a URL from a catchall,and redirecting that to another route.</p>
<p>The reason for this is because I need to do some things like adding session cookies for certain urls, and then pass them on to their relevant action.</p>
<p>What's the best way of implementing this?</p>
<p>Thanks in advance for any help!</p>
| [
{
"answer_id": 292050,
"author": "anonymous",
"author_id": 36602,
"author_profile": "https://Stackoverflow.com/users/36602",
"pm_score": 0,
"selected": false,
"text": "routes.MapRoute(\n \"Partner\",\n \"partners/{partner}/{*wildcard}\",\n new { controller = \"Partners\", action = \"PartnerRedirect\" }\n);\n"
},
{
"answer_id": 294507,
"author": "anonymous",
"author_id": 36602,
"author_profile": "https://Stackoverflow.com/users/36602",
"pm_score": 0,
"selected": false,
"text": "routes.MapRoute(\n \"Partner\",\n \"partners/{partner}/{*wildcard}\",\n new { controller = \"Partners\", action = \"PartnerRedirect\" }\n);\n routes.MapRoute(\n \"Partner\",\n \"partners/{partner}/{controller}/{action}/{other stuff you need}\",\n new { /* whatever defaults you want */ }\n);\n"
}
] | 2008/11/14 | [
"https://Stackoverflow.com/questions/290617",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/31532/"
] |
290,632 | <p><strong>Original Question</strong></p>
<p>I am writting a logging class where the goal is to be able to do this:</p>
<pre><code>// thread one
Logger() << "Some string" << std::ios::hex << 45;
// thread two
Logger() << L"Some wide string" << std::endl;
</code></pre>
<p>Currently my Logger header looks something like this:</p>
<pre><code>#pragma once;
#include <ostream>
class Logger
{
public:
Logger();
~Logger();
std::ostream* out_stream;
};
template <typename T>
Logger& operator<< (Logger& logger, T thing) {
*logger.out_stream << thing;
return logger;
}
</code></pre>
<p>Some notes about this class:</p>
<ol>
<li>Cross platform compatibility is not an issue.</li>
<li>Inside of Logger.cpp there is a singleton class that takes care of creating the "real" ostream.</li>
<li>The Logger constructor and deconstructor perform the necessary locking of the singleton.</li>
</ol>
<p>I have three problems:</p>
<ul>
<li>How do I make the operator<< function a friend or member so I can set out_stream as private? </li>
<li>How do I make the operator<< function work for manipulators?</li>
<li>How can I add a specialization so that if T is a WCHAR* or std::wstring that it will convert it to char* or std::string before passing it to out_stream? (I can do the conversion. Losing high unicode characters isn't a problem in my case.)</li>
</ul>
<p><strong>Summary of things learned in answers:</strong></p>
<ul>
<li>Put template BEFORE friend instead of after.</li>
<li>std::ios::hex is not a manipulator. std::hex is a manipulator.</li>
</ul>
<p><strong>End Result</strong></p>
<pre><code>#pragma once
#include <ostream>
#include <string>
std::string ConvertWstringToString(std::wstring wstr);
class Logger
{
public:
Logger();
~Logger();
template <typename T>
Logger& operator<< (T data) {
*out << data;
return *this;
}
Logger& operator<< (std::wstring data) {
return *this << ConvertWstringToString(data);
}
Logger& operator<< (const wchar_t* data) {
std::wstring str(data);
return *this << str;
}
private:
std::ostream* out;
};
</code></pre>
| [
{
"answer_id": 290644,
"author": "Lodle",
"author_id": 23339,
"author_profile": "https://Stackoverflow.com/users/23339",
"pm_score": 0,
"selected": false,
"text": "Logger(\"This is my log msg %0X\", 45);\n void Logger(const char* format, ...)\n{\n char szMsg[3000];\n\n va_list args;\n va_start( args, format );\n vsnprintf( szMsg, sizeof(szMsg) - 1, format, args );\n va_end(args);\n\n // code to print szMsg to a file or whatever here\n}\n"
},
{
"answer_id": 290658,
"author": "Johannes Schaub - litb",
"author_id": 34509,
"author_profile": "https://Stackoverflow.com/users/34509",
"pm_score": 4,
"selected": true,
"text": "class Logger\n{\npublic:\n Logger();\n ~Logger();\n\n std::ostream* out_stream;\n\n template <typename T>\n friend Logger& operator<< (Logger& logger, T thing) {\n *logger.out_stream << thing;\n return logger;\n }\n\n /* special treatment for std::wstring. just overload the operator! No need\n * to specialize it. */\n friend Logger& operator<< (Logger& logger, const std::wstring & wstr) {\n /* do something here */\n }\n\n};\n template <typename T>\nfriend Logger& operator<< (Logger& logger, T thing);\n #include <iostream>\n#include <cstdlib>\nusing namespace std;\n\ntemplate<typename Char, typename Traits = char_traits<Char> >\nstruct logger{\n typedef std::basic_ostream<Char, Traits> ostream_type;\n typedef ostream_type& (*manip_type)(ostream_type&);\n logger(ostream_type& os):os(os){}\n logger &operator<<(manip_type pfn) {\n if(pfn == static_cast<manip_type>(std::endl)) {\n time_t t = time(0);\n os << \" --- \" << ctime(&t) << pfn; \n } else\n os << pfn;\n return *this; \n }\n template<typename T> \n logger &operator<<(T const& t) { \n os << t; \n return *this;\n }\nprivate: \n ostream_type & os;\n};\n\nnamespace { logger<char> clogged(cout); }\nint main() { clogged << \"something with log functionality\" << std::endl; }\n setf"
},
{
"answer_id": 290664,
"author": "Adam Rosenfield",
"author_id": 9530,
"author_profile": "https://Stackoverflow.com/users/9530",
"pm_score": 2,
"selected": false,
"text": "logger.h logger.cpp operator << std::ostream std::ostream operator << ostream operator << template <typename T> friend Logger& operator<< (Logger& logger, T thing);\n template <typename T>\nLogger& operator<< (Logger& logger, T thing) {\n *logger.out_stream << thing;\n return logger;\n}\n\n// Template specialization - the \"template <>\" part is necessary\ntemplate <>\nLogger& operator<< (Logger& logger, const wchar_t *wstr)\n{\n // convert wstr to an ANSI string and log it\n}\n\ntemplate <>\nLogger& operator<< (Logger& logger, const std::wstring & wstr)\n{\n // convert wstr to an ANSI string and log it\n}\n"
},
{
"answer_id": 290919,
"author": "James Curran",
"author_id": 12725,
"author_profile": "https://Stackoverflow.com/users/12725",
"pm_score": 2,
"selected": false,
"text": "class Logger\n{\npublic:\n Logger();\n ~Logger();\n\ntemplate <typename T>\ninline Logger& Display(T thing)\n{\n *out_stream << thing;\n return *this;\n}\nprivate:\n std::ostream* out_stream;\n};\n\ntemplate <typename T>\nLogger& operator<< (Logger& logger, T thing) \n{\n return logger.Display(thing);\n}\n"
}
] | 2008/11/14 | [
"https://Stackoverflow.com/questions/290632",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19476/"
] |
290,635 | <p>I'm trying to write a quick little java application to read the contents of a pcap file (from Wireshark) and play the data back on the network on a linux box. The file will only contain UDP broadcast packets, so my application only really needs the timestamp, port number, and data from the packet to do what I need. My problem is that the application that I'm trying to test with this code is listening for IPv4 UDP broadcasts on Windows. My test application keeps opening an IPv6 socket to send the data out.</p>
<p>I'm using <code>netstat -a -u -p</code> to determine that the socket is a udp6 socket. On windows I know it isn't.</p>
<p>What is the easiest or best way to force the test app on linux in java to open a udp or udp4 socket instead? I don't want to be forced in to providing the ipv4 network address each time. I want to be able to move this code to another machine without having to remember that their is some configuration that needs to be changed.</p>
| [
{
"answer_id": 4322157,
"author": "Urizev",
"author_id": 435855,
"author_profile": "https://Stackoverflow.com/users/435855",
"pm_score": 2,
"selected": false,
"text": " # echo 0 > /proc/sys/net/ipv6/bindv6only\n"
}
] | 2008/11/14 | [
"https://Stackoverflow.com/questions/290635",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5074/"
] |
290,636 | <p>I am working on modifying an existing spell check plugin for TinyMCE. </p>
<p>This is what is supposed to happen:
1. User hits "space" and the spell check runs.
2. If the word is spelled wrong the word gets wrapped with a span and gets a red underline</p>
<p>what I find happening is that when the user hits space bar the word does get spell checked but the cursor pops back to the end of the word just typed (instead of to where the space is) (you can see this in action at <a href="http://mail.solidhouse.com/webmail2/test.html" rel="nofollow noreferrer">http://mail.solidhouse.com/webmail2/test.html</a>)</p>
<p>here is my pseudcode:
var b = this.editor.selection.getBookmark();
//for each node
node.nodeValue.replace(r5, '$1$2');
this.editor.selection.moveToBookmark(b);</p>
<p>what I am suspecting is that moveToBookmark keeps the cursor within the element but I have no idea what to do to remedy this.</p>
<p>(I have tried incrementing b.start and b.end but that did not work)</p>
<p>I know this is hard to explain. Any thoughts on this are greatly appreciated. </p>
| [
{
"answer_id": 293465,
"author": "Jon Smock",
"author_id": 25538,
"author_profile": "https://Stackoverflow.com/users/25538",
"pm_score": 0,
"selected": false,
"text": "this.parentNode.moveToBookmark(b);\n"
}
] | 2008/11/14 | [
"https://Stackoverflow.com/questions/290636",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/37723/"
] |
290,652 | <p>My stored procedure has an output parameter:</p>
<pre><code>@ID INT OUT
</code></pre>
<p>How can I retrieve this using ado.net?</p>
<pre><code>using (SqlConnection conn = new SqlConnection(...))
{
SqlCommand cmd = new SqlCommand("sproc", conn);
cmd.CommandType = CommandType.StoredProcedure;
// add parameters
conn.Open();
// *** read output parameter here, how?
conn.Close();
}
</code></pre>
| [
{
"answer_id": 290676,
"author": "WACM161",
"author_id": 12255,
"author_profile": "https://Stackoverflow.com/users/12255",
"pm_score": 5,
"selected": false,
"text": "using System; \nusing System.Data; \nusing System.Data.SqlClient; \n\n\nclass OutputParams \n{ \n [STAThread] \n static void Main(string[] args) \n { \n\n using( SqlConnection cn = new SqlConnection(\"server=(local);Database=Northwind;user id=sa;password=;\")) \n { \n SqlCommand cmd = new SqlCommand(\"CustOrderOne\", cn); \n cmd.CommandType=CommandType.StoredProcedure ; \n\n SqlParameter parm= new SqlParameter(\"@CustomerID\",SqlDbType.NChar) ; \n parm.Value=\"ALFKI\"; \n parm.Direction =ParameterDirection.Input ; \n cmd.Parameters.Add(parm); \n\n SqlParameter parm2= new SqlParameter(\"@ProductName\",SqlDbType.VarChar); \n parm2.Size=50; \n parm2.Direction=ParameterDirection.Output; \n cmd.Parameters.Add(parm2); \n\n SqlParameter parm3=new SqlParameter(\"@Quantity\",SqlDbType.Int); \n parm3.Direction=ParameterDirection.Output; \n cmd.Parameters.Add(parm3);\n\n cn.Open(); \n cmd.ExecuteNonQuery(); \n cn.Close(); \n\n Console.WriteLine(cmd.Parameters[\"@ProductName\"].Value); \n Console.WriteLine(cmd.Parameters[\"@Quantity\"].Value.ToString());\n Console.ReadLine(); \n } \n} \n"
},
{
"answer_id": 290772,
"author": "BQ.",
"author_id": 4632,
"author_profile": "https://Stackoverflow.com/users/4632",
"pm_score": 7,
"selected": false,
"text": "SqlParameter Direction Output SqlCommand Parameters // SqlConnection and SqlCommand are IDisposable, so stack a couple using()'s\nusing (SqlConnection conn = new SqlConnection(connectionString))\nusing (SqlCommand cmd = new SqlCommand(\"sproc\", conn))\n{\n // Create parameter with Direction as Output (and correct name and type)\n SqlParameter outputIdParam = new SqlParameter(\"@ID\", SqlDbType.Int)\n { \n Direction = ParameterDirection.Output \n };\n\n cmd.CommandType = CommandType.StoredProcedure;\n cmd.Parameters.Add(outputIdParam);\n\n conn.Open();\n cmd.ExecuteNonQuery();\n\n // Some various ways to grab the output depending on how you would like to\n // handle a null value returned from the query (shown in comment for each).\n\n // Note: You can use either the SqlParameter variable declared\n // above or access it through the Parameters collection by name:\n // outputIdParam.Value == cmd.Parameters[\"@ID\"].Value\n\n // Throws FormatException\n int idFromString = int.Parse(outputIdParam.Value.ToString());\n\n // Throws InvalidCastException\n int idFromCast = (int)outputIdParam.Value; \n\n // idAsNullableInt remains null\n int? idAsNullableInt = outputIdParam.Value as int?; \n\n // idOrDefaultValue is 0 (or any other value specified to the ?? operator)\n int idOrDefaultValue = outputIdParam.Value as int? ?? default(int); \n\n conn.Close();\n}\n Parameters[].Value object SqlDbType SqlParameter Parameters[\"@Param\"].Value.ToString() Console.Write() String.Format()"
},
{
"answer_id": 9277121,
"author": "Nate Kindrew",
"author_id": 378293,
"author_profile": "https://Stackoverflow.com/users/378293",
"pm_score": 6,
"selected": false,
"text": "using (SqlConnection conn = new SqlConnection())\n{\n SqlCommand cmd = new SqlCommand(\"sproc\", conn);\n cmd.CommandType = CommandType.StoredProcedure;\n\n // add parameters\n SqlParameter outputParam = cmd.Parameters.Add(\"@ID\", SqlDbType.Int);\n outputParam.Direction = ParameterDirection.Output;\n\n conn.Open();\n\n using(IDataReader reader = cmd.ExecuteReader())\n {\n while(reader.Read())\n {\n //read in data\n }\n }\n // reader is closed/disposed after exiting the using statement\n int id = outputParam.Value;\n}\n"
},
{
"answer_id": 33009030,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "using (SqlConnection conn = new SqlConnection(...))\n{\n SqlCommand cmd = new SqlCommand(\"sproc\", conn);\n cmd.CommandType = CommandType.StoredProcedure;\n\n // add other parameters parameters\n\n //Add the output parameter to the command object\n SqlParameter outPutParameter = new SqlParameter();\n outPutParameter.ParameterName = \"@Id\";\n outPutParameter.SqlDbType = System.Data.SqlDbType.Int;\n outPutParameter.Direction = System.Data.ParameterDirection.Output;\n cmd.Parameters.Add(outPutParameter);\n\n conn.Open();\n cmd.ExecuteNonQuery();\n\n //Retrieve the value of the output parameter\n string Id = outPutParameter.Value.ToString();\n\n // *** read output parameter here, how?\n conn.Close();\n}\n"
},
{
"answer_id": 33650907,
"author": "Vinícius Todesco",
"author_id": 4953360,
"author_profile": "https://Stackoverflow.com/users/4953360",
"pm_score": 3,
"selected": false,
"text": "string ConnectionString = ConfigurationManager.ConnectionStrings[\"DBCS\"].ConnectionString;\nusing (SqlConnection con = new SqlConnection(ConnectionString))\n{\n//Create the SqlCommand object\nSqlCommand cmd = new SqlCommand(“spAddEmployee”, con);\n\n//Specify that the SqlCommand is a stored procedure\ncmd.CommandType = System.Data.CommandType.StoredProcedure;\n\n//Add the input parameters to the command object\ncmd.Parameters.AddWithValue(“@Name”, txtEmployeeName.Text);\ncmd.Parameters.AddWithValue(“@Gender”, ddlGender.SelectedValue);\ncmd.Parameters.AddWithValue(“@Salary”, txtSalary.Text);\n\n//Add the output parameter to the command object\nSqlParameter outPutParameter = new SqlParameter();\noutPutParameter.ParameterName = “@EmployeeId”;\noutPutParameter.SqlDbType = System.Data.SqlDbType.Int;\noutPutParameter.Direction = System.Data.ParameterDirection.Output;\ncmd.Parameters.Add(outPutParameter);\n\n//Open the connection and execute the query\ncon.Open();\ncmd.ExecuteNonQuery();\n\n//Retrieve the value of the output parameter\nstring EmployeeId = outPutParameter.Value.ToString();\n}\n"
},
{
"answer_id": 42311547,
"author": "Greg R Taylor",
"author_id": 4133948,
"author_profile": "https://Stackoverflow.com/users/4133948",
"pm_score": 3,
"selected": false,
"text": "public static class SqlParameterExtensions\n{\n public static T GetValueOrDefault<T>(this SqlParameter sqlParameter)\n {\n if (sqlParameter.Value == DBNull.Value \n || sqlParameter.Value == null)\n {\n if (typeof(T).IsValueType)\n return (T)Activator.CreateInstance(typeof(T));\n\n return (default(T));\n }\n\n return (T)sqlParameter.Value;\n }\n}\n\n\n// Usage\nusing (SqlConnection conn = new SqlConnection(connectionString))\nusing (SqlCommand cmd = new SqlCommand(\"storedProcedure\", conn))\n{\n SqlParameter outputIdParam = new SqlParameter(\"@ID\", SqlDbType.Int)\n { \n Direction = ParameterDirection.Output \n };\n\n cmd.CommandType = CommandType.StoredProcedure;\n cmd.Parameters.Add(outputIdParam);\n\n conn.Open();\n cmd.ExecuteNonQuery();\n\n int result = outputIdParam.GetValueOrDefault<int>();\n}\n"
},
{
"answer_id": 50324919,
"author": "Sandeep Pandey",
"author_id": 7404365,
"author_profile": "https://Stackoverflow.com/users/7404365",
"pm_score": 2,
"selected": false,
"text": "param.ParameterName = \"@yourParamterName\"; param.Value = 0; param.Direction = System.Data.ParameterDirection.Output;"
}
] | 2008/11/14 | [
"https://Stackoverflow.com/questions/290652",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
290,662 | <p>Where can I setup custom errors for directories in my application such as App_Code, App_Browsers, etc.? I already have customErrors configured in the web.config and that works as expected. For example,</p>
<p><a href="http://www.mysite.com/bla.aspx" rel="nofollow noreferrer">http://www.mysite.com/bla.aspx</a> > redirects to 404 page</p>
<p>but</p>
<p><a href="http://www.mysite.com/App_Code/" rel="nofollow noreferrer">http://www.mysite.com/App_Code/</a> > displays "The system cannot find the file specified."</p>
<p>There's no physical App_Code directory for my site. Is this something that I can change in IIS?</p>
| [
{
"answer_id": 291374,
"author": "flesh",
"author_id": 27805,
"author_profile": "https://Stackoverflow.com/users/27805",
"pm_score": 0,
"selected": false,
"text": " void Application_Error(object sender, EventArgs e) \n{\n //uncomment this to narrow down 'helpful' microsoft messages\n //HttpRequest request = ((HttpApplication)sender).Context.Request; \n\n\n Exception ex = Server.GetLastError();\n //ErrorManager is a custom error handling module\n ErrorManager.ProcessError(ex);\n Response.Redirect(\"~/error.aspx?error=\" + HttpUtility.UrlEncode(ex.Message), true);\n}\n"
}
] | 2008/11/14 | [
"https://Stackoverflow.com/questions/290662",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2034/"
] |
290,667 | <p>Are there limits or performance penalties on the amount of code inside of my <code>home.cs</code> form?</p>
<p>I am writing a database application front-end in C# in Visual Studio 2008. The way things are lining up, I am using a tab-page way of changing the info shown to the end users, instead of using new forms. </p>
<p>Coming from VBA/MS Access, I remember that if you go over a certain number of lines of code, it would produce an error and not compile. Will C# do this in Visual Studio 2008, or will I suffer a performance hit? I know code readability could be a problem because everything would be in one place, but I can also see that as an advantage in some situations.</p>
| [
{
"answer_id": 290724,
"author": "Chris Marasti-Georg",
"author_id": 96,
"author_profile": "https://Stackoverflow.com/users/96",
"pm_score": 2,
"selected": false,
"text": "Dock = DockStyle.Fill"
}
] | 2008/11/14 | [
"https://Stackoverflow.com/questions/290667",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19802/"
] |
290,668 | <p>If I simply wrap my query with:</p>
<pre><code>BEGIN TRANSACTION
COMMIT TRANSACTION
</code></pre>
<p>If anything fails inside of that, will it automatically rollback?</p>
<p>From looking at other code, they seem to check for an error, if there is an error then they do a GOTO statement which then calls ROLLBACK TRANSACTION</p>
<p>But that seems like allot of work, to have to check for IF( @@ERROR <> 0) after every insert/update.</p>
| [
{
"answer_id": 290696,
"author": "Mladen Prajdic",
"author_id": 31345,
"author_profile": "https://Stackoverflow.com/users/31345",
"pm_score": 2,
"selected": false,
"text": "SET XACT_ABORT ON\n\nBEGIN TRANSACTION\n-- CODE HERE\nCOMMIT TRANSACTION\n"
},
{
"answer_id": 290704,
"author": "GluedHands",
"author_id": 37726,
"author_profile": "https://Stackoverflow.com/users/37726",
"pm_score": 1,
"selected": false,
"text": "BEGIN TRANSACTION\n\nUPDATE table SET column = 'ABC' WHERE column = '123'\n\nCOMMIT TRANSACTION\n\n--//column now has a value of 'ABC'\n\nBEGIN TRANSACTION\n\nUPDATE table SET column = 'ABC' WHERE column = '123'\n\nROLLBACK TRANSACTION\n\n--//column still has it's previous value ('123') No changes were made.\n"
},
{
"answer_id": 290753,
"author": "Jeremiah Peschka",
"author_id": 11780,
"author_profile": "https://Stackoverflow.com/users/11780",
"pm_score": 5,
"selected": false,
"text": "SET XACT_ABORT ON;\n\nBEGIN TRY\n BEGIN TRANSACTION;\n\n -- Code goes here\n\n COMMIT TRANSACTION;\nEND TRY\nBEGIN CATCH\n IF @@TRANCOUNT > 0\n ROLLBACK TRANSACTION;\n\n DECLARE\n @ERROR_SEVERITY INT,\n @ERROR_STATE INT,\n @ERROR_NUMBER INT,\n @ERROR_LINE INT,\n @ERROR_MESSAGE NVARCHAR(4000);\n\n SELECT\n @ERROR_SEVERITY = ERROR_SEVERITY(),\n @ERROR_STATE = ERROR_STATE(),\n @ERROR_NUMBER = ERROR_NUMBER(),\n @ERROR_LINE = ERROR_LINE(),\n @ERROR_MESSAGE = ERROR_MESSAGE();\n\n RAISERROR('Msg %d, Line %d, :%s',\n @ERROR_SEVERITY,\n @ERROR_STATE,\n @ERROR_NUMBER,\n @ERROR_LINE,\n @ERROR_MESSAGE);\nEND CATCH\n"
}
] | 2008/11/14 | [
"https://Stackoverflow.com/questions/290668",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
290,679 | <p>Over the years, I think I have seen and tried every conceivable way of generating stub data structures (fake data) for complex object graphs. It always gets hairy in java.</p>
<pre><code> * * * *
A---B----C----D----E
</code></pre>
<p>(Pardon cheap UML) </p>
<p>The key issue is that there are certain relationships between the values, so a certain instance of C may imply given values for E. </p>
<p>Any attempt I have seen at applying a single pattern or group of pattens to solve this problem in java ultimately end up being messy.</p>
<p>I am considering if groovy or any of the dynamic vm languages can do a better job. It should be possible to do things significantly simpler with closures. </p>
<p>Anyone have any references/examples of this problem solved nicely with (preferably) groovy or scala ?</p>
<p>Edit:
I did not know "Object Mother" was the name of the pattern, but it's the one I'm having troubles with: When the object structure to be generated by the Object Mother is sufficiently complex, you'll always end up with a fairly complex internal structure inside the Object Mother itself (or by composing multiple Object Mothers). Given a sufficiently large target structure (Say 30 classes), finding structured ways to implement the object mother(s) is really hard. Now that I know the name of the pattern i can google it better though ;) </p>
| [
{
"answer_id": 2611252,
"author": "Javid Jamae",
"author_id": 254046,
"author_profile": "https://Stackoverflow.com/users/254046",
"pm_score": 1,
"selected": false,
"text": "public class ItineraryObjectMother\n{\n Status status;\n private long departureTime;\n\n public ItineraryObjectMother()\n {\n status = new Status(\"BLAH\");\n departureTime = 123456L;\n }\n public Itinerary build()\n {\n Itinerary itinerary = new Itinerary(status);\n itinerary.setDepartureTime(departureTime);\n return itinerary;\n }\n public ItineraryObjectMother status(Status status)\n {\n this.status = status;\n return this;\n }\n public ItineraryObjectMother departs(long departureTime)\n {\n this.departureTime = departureTime;\n return this;\n }\n\n}\n Itinerary i1 = new ItineraryObjectMother().departs(1234L).status(someStatus).build();\nItinerary i2 = new ItineraryObjectMother().departs(1234L).build();\n"
}
] | 2008/11/14 | [
"https://Stackoverflow.com/questions/290679",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23691/"
] |
290,697 | <p>how do i insert items into an html listbox from a database?
im using asp c#. i cant make the listbox run at server because the application wont work if i do that. so i have to insert values from a database into an html listbox. I just need to display 1 column of data. cheers..</p>
| [
{
"answer_id": 290732,
"author": "Adam Lassek",
"author_id": 1249,
"author_profile": "https://Stackoverflow.com/users/1249",
"pm_score": 0,
"selected": false,
"text": "<asp:Placeholder /> var select = new HtmlSelect() { Size = 5 };\n\n//assuming the data has been placed in an IEnumarble\nforeach (var item in items)\n{\n select.Items.Add(new ListItem() { Value = item });\n}\nselectPlaceholder.Controls.Add(select);\n"
}
] | 2008/11/14 | [
"https://Stackoverflow.com/questions/290697",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23491/"
] |
290,699 | <p>I need to have a set of overloaded functions in my code but I get convertion wanrings.
Here is a test code:</p>
<pre><code>#include windows.h
void f(DWORD arg){...}
//void f(SIZE_T arg){}
void main(void)
{
DWORD dword=0;
SIZE_T size_t=dword;
f(size_t);
}
</code></pre>
<p>The compiler gives warning:</p>
<pre><code>test.cpp(11) : warning C4244: 'argument' : conversion from 'SIZE_T' to 'DWORD', possible loss of data
</code></pre>
<p>If I uncomment void f(SIZE_T arg) I get</p>
<pre><code>test.cpp(5) : error C2084: function 'void f(DWORD)' already has a body
</code></pre>
<p>How can I avoid having this warning or error? </p>
| [
{
"answer_id": 290712,
"author": "Adam Rosenfield",
"author_id": 9530,
"author_profile": "https://Stackoverflow.com/users/9530",
"pm_score": 4,
"selected": false,
"text": "size_t DWORD DWORD SIZE_T sz = dword;\nf((DWORD)sz); // no warning here\n size_t f void f_DWORD(DWORD arg) { ... }\nvoid f_size_t(size_t arg) { ... }\n size_t SIZE_T size_t size_t SIZE_T size_t"
},
{
"answer_id": 291912,
"author": "Max Lybbert",
"author_id": 10593,
"author_profile": "https://Stackoverflow.com/users/10593",
"pm_score": 0,
"selected": false,
"text": "f(DWORD) f(size_t) f() size_t"
},
{
"answer_id": 37050087,
"author": "KunMing Xie",
"author_id": 5235611,
"author_profile": "https://Stackoverflow.com/users/5235611",
"pm_score": -1,
"selected": false,
"text": "typedef ULONG_PTR SIZE_T;\n\n#if defined(_WIN64)\n typedef unsigned __int64 ULONG_PTR;\n#else\n typedef unsigned long ULONG_PTR;\n#endif\n"
}
] | 2008/11/14 | [
"https://Stackoverflow.com/questions/290699",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
290,700 | <p>Suppose that you have two huge files (several GB) that you want to concatenate together, but that you have very little spare disk space (let's say a couple hundred MB). That is, given <code>file1</code> and <code>file2</code>, you want to end up with a single file which is the result of concatenating <code>file1</code> and <code>file2</code> together byte-for-byte, and delete the original files.</p>
<p>You can't do the obvious <code>cat file2 >> file1; rm file2</code>, since in between the two operations, you'd run out of disk space.</p>
<p>Solutions on any and all platforms with free or non-free tools are welcome; this is a hypothetical problem I thought up while I was downloading a Linux ISO the other day, and the download got interrupted partway through due to a wireless hiccup.</p>
| [
{
"answer_id": 290721,
"author": "Douglas Leeder",
"author_id": 3978,
"author_profile": "https://Stackoverflow.com/users/3978",
"pm_score": 4,
"selected": true,
"text": "dd"
},
{
"answer_id": 291479,
"author": "luke",
"author_id": 25920,
"author_profile": "https://Stackoverflow.com/users/25920",
"pm_score": 0,
"selected": false,
"text": "head file2 --bytes=1024 >> file1 && tail --bytes=+1024 file2 >file2 \n"
},
{
"answer_id": 1180597,
"author": "Marcin",
"author_id": 113344,
"author_profile": "https://Stackoverflow.com/users/113344",
"pm_score": 2,
"selected": false,
"text": "gzip file1\n\ngzip file2\n\nzcat file1 file2 | gzip > file3\n\nrm file1\n\nrm file2\n\ngunzip file3\n"
}
] | 2008/11/14 | [
"https://Stackoverflow.com/questions/290700",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9530/"
] |
290,709 | <p>Is there a way to do this almost out-of-the-box?</p>
<p>I could go and write a big method that would use the collected tokens to figure out which leaves should be put in which branches and in the end populate a TreeNode object, but since gppg already handled everything by using supplied regular expressions, I was wondering if there's an easier way? Even if not, any pointers as to how best to approach the problem of creating an AST would be appreciated.</p>
<p>Apologies if I said anything silly, I'm only just beginning to play the compiler game. :)</p>
| [
{
"answer_id": 2777685,
"author": "Vadym Chekan",
"author_id": 158913,
"author_profile": "https://Stackoverflow.com/users/158913",
"pm_score": 1,
"selected": false,
"text": "{%\npublic BatchNode Batch;\npublic ErrorHandler yyhldr;\nprivate TransformationContext _txContext = TransformationContext.Instance;\n%}\n Batch\n : StatementList {Batch = new BatchNode($1.Statements);}\n ;\n\nStatementList\n : Statement {$$.Statements = new List<StatementNode>(); $$.Statements.Add($1.Statement); }\n | StatementList Statement {$$.Statements = $1.Statements; $$.Statements.Add($2.Statement);}\n ;\n var parser = new Parser.Parser();\nvar scanner = new Scanner();\nparser.scanner = scanner;\nscanner.SetSource(sourceString, 0);\nbool result = parser.Parse();\nif (result)\n HandleMyAst(parser.Batch)\n"
}
] | 2008/11/14 | [
"https://Stackoverflow.com/questions/290709",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
290,734 | <p>I have a repository which contains some unversioned directories and files. The server running svn was recently changed and since the checkout was done using the url svn://OLD-IP, I relocated my svn working copy, this time to the url svn://NEW-DOMAIN-NAME. </p>
<p>Now since there are some unversioned resources, the switch did not happen properly and the working copy got locked. A cleanup operation did not work either because of these unversioned resources. </p>
<p>I looked up in the net and found about svn ignore and tried that but to no use. I am unable to release all locks. Any ideas on solving the problem? Once I release the locks, I believe I can use svn ignore and carry on the relocate operation.</p>
| [
{
"answer_id": 290793,
"author": "CesarB",
"author_id": 28258,
"author_profile": "https://Stackoverflow.com/users/28258",
"pm_score": 3,
"selected": false,
"text": "svn status svn help status C svn update svn revert svn cleanup svn update svn switch update switch"
},
{
"answer_id": 11985707,
"author": "KT..",
"author_id": 1603020,
"author_profile": "https://Stackoverflow.com/users/1603020",
"pm_score": 2,
"selected": false,
"text": "cleanup update"
}
] | 2008/11/14 | [
"https://Stackoverflow.com/questions/290734",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/27474/"
] |
290,739 | <p>I have a form that sits behind ASP.NET forms authentication. So far, the implementation follows a typical "out of the box" type configuration.</p>
<p>One page allows users to post messages. If the user sits on that page for a long time to compose the message, it may run past the auth session expiration. In that case, the post does not get recorded... they are just redirected to the login page.</p>
<p>What approach should I take to prevent the frustrating event of a long message being lost? </p>
<p>Obviously I could just make the auth session really long, but there are other factors in the system which discourage that approach. <strong>Is there a way I could make an exception for this particular page so that it will never redirect to the Login so long as its a postback?</strong></p>
| [
{
"answer_id": 291038,
"author": "Mark Brackett",
"author_id": 2199,
"author_profile": "https://Stackoverflow.com/users/2199",
"pm_score": 1,
"selected": false,
"text": "// Global.asax\nvoid FormsAuthentication_OnAuthenticate(object sender, FormsAuthenticationEventArgs e) {\n // check for postback somehow\n if (Request.Url == \"MyPage.aspx\" && Request.Form[\"MySuperSecret\"] == \"123\") {\n e.User = new GenericPrincipal(new GenericIdentity(), new string[] { });\n }\n}\n"
},
{
"answer_id": 293945,
"author": "marclar",
"author_id": 28118,
"author_profile": "https://Stackoverflow.com/users/28118",
"pm_score": 0,
"selected": false,
"text": "( HttpContext.Request.UserHostAddress )\n"
}
] | 2008/11/14 | [
"https://Stackoverflow.com/questions/290739",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/337/"
] |
290,743 | <p>I am invoking a C library via JNI that prints to stdout. How can I redirect this output to System.out?</p>
| [
{
"answer_id": 290749,
"author": "Alnitak",
"author_id": 6782,
"author_profile": "https://Stackoverflow.com/users/6782",
"pm_score": 3,
"selected": false,
"text": "System.out stdout System.out stdout OutputStream stdio write printf System.out.flush() stdio write fflush(stdout)"
}
] | 2008/11/14 | [
"https://Stackoverflow.com/questions/290743",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
290,774 | <p>How can I get rid of: </p>
<pre><code><input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE" value="..."/>
</code></pre>
<p>Completely !</p>
| [
{
"answer_id": 290811,
"author": "Julio César",
"author_id": 2148,
"author_profile": "https://Stackoverflow.com/users/2148",
"pm_score": 5,
"selected": true,
"text": "<%@ Page Language=\"C#\" AutoEventWireup=\"true\"\nCodebehind=\"Default.aspx.cs\" Inherits=\"Sample._Default\"\nEnableViewState=\"false\" %>\n #region Disable ViewState\n protected override void SavePageStateToPersistenceMedium(object state)\n {\n }\n protected override object LoadPageStateFromPersistenceMedium()\n {\n return null;\n }\n #endregion\n"
},
{
"answer_id": 786128,
"author": "ronaldwidha",
"author_id": 83960,
"author_profile": "https://Stackoverflow.com/users/83960",
"pm_score": 1,
"selected": false,
"text": "#region Disable ViewState\nprotected override void SavePageStateToPersistenceMedium(object state)\n{\n}\nprotected override object LoadPageStateFromPersistenceMedium()\n{\n return null;\n}\n#endregion\n <input type=\"hidden\" name=\"__VIEWSTATE\" id=\"__VIEWSTATE\" value=\"\" />\n"
}
] | 2008/11/14 | [
"https://Stackoverflow.com/questions/290774",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/35513/"
] |
290,778 | <p>I'm having a problem with a administrative app I'm working on. I'm build an interface for stopping, starting and querying various services across 40 or so servers. </p>
<p>I'm looking at service.controller and have been successful in stopping and starting various services with button events but now I'm trying to figure out a way to return the service status to a text box and query for service status every 10 seconds or so and I feel like I'm hitting a brick wall. </p>
<p>Does anyone have any tips or insight?</p>
<p>Thanks!!</p>
| [
{
"answer_id": 290907,
"author": "Dan R",
"author_id": 24222,
"author_profile": "https://Stackoverflow.com/users/24222",
"pm_score": 3,
"selected": true,
"text": " private void t_Elapsed(object sender, ElapsedEventArgs e)\n {\n // Check service statuses\n }\n private delegate void TextUpdateHandler(string updatedText);\n\n private void UpdateServerStatuses(string statuses)\n {\n if (this.InvokeRequired)\n {\n TextUpdateHandler update = new TextUpdateHandler(this.UpdateServerStatuses);\n this.BeginInvoke(update, statuses);\n }\n else\n {\n // load textbox here\n }\n }\n"
},
{
"answer_id": 6982746,
"author": "Evolved",
"author_id": 766028,
"author_profile": "https://Stackoverflow.com/users/766028",
"pm_score": 2,
"selected": false,
"text": "Private serviceController As ServiceController = Nothing \nPrivate serviceControllerStatusRunning = False\n\nPrivate Sub Form1_Load(sender As Object, e As System.EventArgs) Handles Me.Load\n Try\n serviceController = New ServiceController(\"NameOfTheTheServiceYouWant\")\n If serviceController.Status = ServiceControllerStatus.Stopped Then\n ' put code for stopped status here\n Else\n ' put code for running status here\n End If\n BackgroundWorker1.RunWorkerAsync()\n Catch ex As Exception\n MessageBox.Show(\"error:\" + ex.Message)\n serviceController = Nothing\n Me.Close()\n Exit Sub\n End Try\nEnd Sub\n\nPrivate Sub BackgroundWorker1_DoWork(sender As System.Object, e As System.ComponentModel.DoWorkEventArgs) Handles BackgroundWorker1.DoWork\n If serviceControllerStatusRunning Then\n serviceController.WaitForStatus(ServiceControllerStatus.Stopped)\n serviceControllerStatusRunning = False\n Else\n serviceController.WaitForStatus(ServiceControllerStatus.Running)\n serviceControllerStatusRunning = True\n End If\nEnd Sub\n\nPrivate Sub BackgroundWorker1_RunWorkerCompleted(sender As System.Object, e As System.ComponentModel.RunWorkerCompletedEventArgs) Handles BackgroundWorker1.RunWorkerCompleted\n if serviceControllerStatusRunning then\n ' put code for running status here\n else\n ' put code for stopped status here\n end if\n BackgroundWorker1.RunWorkerAsync() ' start worker thread again\nEnd Sub\n"
}
] | 2008/11/14 | [
"https://Stackoverflow.com/questions/290778",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/35760/"
] |
290,779 | <p>My teams evolution of TDD includes what appear to be departures from traditional oop.</p>
<ol>
<li><p>Moving away from classes that are self sufficient
We still encapsulate data where appropriate. But in order to mock any helper classes, we usually create some way to externally set them via constructor or mutator.</p></li>
<li><p>We don't use private methods, ever.
In order to take advantage of our mocking framework (RhinoMocks) the methods can't be private. This has been the biggest one to "sell" to our traditional devs. And to some degree I see their point. I just value testing more.</p></li>
</ol>
<p>What are your thoughts?</p>
| [
{
"answer_id": 290872,
"author": "labilbe",
"author_id": 1195872,
"author_profile": "https://Stackoverflow.com/users/1195872",
"pm_score": 1,
"selected": false,
"text": "[assembly: InternalsVisibleTo(\"MyAssembly.Tests\")]"
},
{
"answer_id": 291091,
"author": "Brian",
"author_id": 18192,
"author_profile": "https://Stackoverflow.com/users/18192",
"pm_score": 0,
"selected": false,
"text": "CauseBSOD"
}
] | 2008/11/14 | [
"https://Stackoverflow.com/questions/290779",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/34895/"
] |
290,786 | <p>Do you know what's the format of the DepartureWindow parameter for sabre web-services' OTA_AirLowFareSearch call? Whatever I pass, it shows me an error.</p>
<p>This is the entire documentation for those parameters (I kid you not):</p>
<pre><code><!--"DepartureDateTime" represents the date and time of departure.-->
<DepartureDateTime>2004-11-22T15:00:00</DepartureDateTime>
<!--"DepartureWindow" represents a window of time to search prior and post departure.-->
<!--Example: JR.DFW/S-OYLAS22NOV1500‡ZRD09001700-->
<DepartureWindow>09001700</DepartureWindow>
</code></pre>
<p>I've already tryied passing the number of seconds since DepartureDateTime and a unix timestamp without success. The error message it's:</p>
<pre><code>Error response received. The error was: INVALID TIME WINDOW IN Z FIELDS
</code></pre>
<p>Thanks</p>
| [
{
"answer_id": 347440,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": " <ns1:DepartureDateTime>2009-01-03T15:00:00</ns1:DepartureDateTime>\n <ns1:DepartureWindow>11001559</ns1:DepartureWindow>\n"
}
] | 2008/11/14 | [
"https://Stackoverflow.com/questions/290786",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
290,799 | <p>I'm programming in FORTRAN and C on an SGI running Irix 6.5, but this should be applicable to all Unix-like systems. How do I find which library I need to link to my program when I get an "unresolved text symbol" link error? Here's an example of what I'm seeing from the linker:</p>
<pre><code>ld32: ERROR 33 Unresolved text symbol "ortho2_" -- first referenced by ./libfoo.a
</code></pre>
<p>Do I just have to know which libraries are required, or is there some tool or command that can help me figure this out?</p>
| [
{
"answer_id": 290815,
"author": "Robert Gamble",
"author_id": 25222,
"author_profile": "https://Stackoverflow.com/users/25222",
"pm_score": 4,
"selected": true,
"text": "nm nm -D /lib/libc.so.6\n grep"
},
{
"answer_id": 290873,
"author": "Tim Whitcomb",
"author_id": 24895,
"author_profile": "https://Stackoverflow.com/users/24895",
"pm_score": 2,
"selected": false,
"text": "nm libfgl.a"
},
{
"answer_id": 292759,
"author": "Jonathan Leffler",
"author_id": 15168,
"author_profile": "https://Stackoverflow.com/users/15168",
"pm_score": 2,
"selected": false,
"text": "getch() getch() curses curses getch() nm -r -R ortho2"
},
{
"answer_id": 295961,
"author": "SumoRunner",
"author_id": 18975,
"author_profile": "https://Stackoverflow.com/users/18975",
"pm_score": 2,
"selected": false,
"text": "#!/bin/csh\nforeach i (*.o *.a *.so)\n echo $i\n nm $i | grep -i $1\nend\n"
}
] | 2008/11/14 | [
"https://Stackoverflow.com/questions/290799",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6688/"
] |
290,806 | <p>I might be one anal programmer, but I like code that looks good from a distance. I just found myself lining up a CSS style so that instead of this:</p>
<pre><code>#divPreview {
text-align: center;
vertical-align: middle;
border: #779 1px solid;
overflow: auto;
width: 210px;
height: 128px;
background-color: #fff"
}
</code></pre>
<p>it now looks like:</p>
<pre><code>#divPreview {
width: 210px;
height: 128px;
overflow: auto;
text-align: center;
vertical-align: middle;
border: #779 1px solid;
background-color: #fff";
}
</code></pre>
<p>I will almost always write numerical comparisons in order of size like</p>
<pre><code>if (0 < n && n < 10)
</code></pre>
<p>instead of</p>
<pre><code>if (0 < n && 10 > n)
</code></pre>
<p>and finally I will tend to arrange if-then-else code so that the THEN part is smaller than the ELSE part (cause the heavier stuff goes to the bottom, right?)</p>
<pre><code>if (afflicted == true) {
GetSome();
HelpRight();
}
else {
NowPlease();
}
</code></pre>
<p>ugh!</p>
<pre><code>if (afflicted == false) {
HowMuchTrouble();
}
else {
IsItToDo();
ThisReally();
}
</code></pre>
<p>aahhh</p>
<p>I could go on and on with more examples, but you get the idea...</p>
<p>Question: Am I alone in my neurosis here? What's your coding kink?</p>
| [
{
"answer_id": 290812,
"author": "Steve",
"author_id": 22712,
"author_profile": "https://Stackoverflow.com/users/22712",
"pm_score": 3,
"selected": false,
"text": "#divPreview {\n width : 210px;\n height : 128px;\n overflow : auto;\n text-align : center;\n vertical-align : middle;\n border : #779 1px solid;\n background-color : #fff\";\n }\n"
},
{
"answer_id": 290813,
"author": "Steven A. Lowe",
"author_id": 9345,
"author_profile": "https://Stackoverflow.com/users/9345",
"pm_score": 3,
"selected": false,
"text": "if (!afflicted)\n{\n HowMuchTrouble();\n}\nelse \n{\n IsItToDo();\n ThisReally();\n}\n"
},
{
"answer_id": 290824,
"author": "krosenvold",
"author_id": 23691,
"author_profile": "https://Stackoverflow.com/users/23691",
"pm_score": 4,
"selected": false,
"text": "if (afflicted) {\n GetSome();\n HelpRight();\n} else {\n NowPlease();\n}\n"
},
{
"answer_id": 290828,
"author": "Pyrolistical",
"author_id": 21838,
"author_profile": "https://Stackoverflow.com/users/21838",
"pm_score": 7,
"selected": true,
"text": "int foo = 42;\nint fooBar = 1024;\n int foo = 42;\nint fooBar = 1024;\n int foo = 42;\nint fooBar = 1024;\nString nowLetsBeEvil = 6400;\n sqrt(x + y, x - z);\nsqrt(x , x );\n"
},
{
"answer_id": 290834,
"author": "g .",
"author_id": 6944,
"author_profile": "https://Stackoverflow.com/users/6944",
"pm_score": 4,
"selected": false,
"text": "#divPreview {\n width: 210px;\n height: 128px;\n overflow: auto;\n text-align: center;\n vertical-align: middle;\n border: #779 1px solid;\n background-color: #fff\";\n}\n if (0 < n && n < 10)\n if (afflicted) {\n GetSome();\n HelpRight();\n}\nelse {\n NowPlease();\n}\n"
},
{
"answer_id": 290847,
"author": "Federico A. Ramponi",
"author_id": 18770,
"author_profile": "https://Stackoverflow.com/users/18770",
"pm_score": 2,
"selected": false,
"text": "foo = egg + spam\nfoobar = sausage + spam\n if (a<b && c<d) ...\nx = a*b + c*d\n if (a < b && c < d) ...\nx = a*b+c*d\n"
},
{
"answer_id": 290848,
"author": "Bill K",
"author_id": 12943,
"author_profile": "https://Stackoverflow.com/users/12943",
"pm_score": 3,
"selected": false,
"text": "if(x != null)\n y=x.getParam();\nelse\n y=0;\n y = x == null ? 0 : x.getParam();\n y = x.getParam() if x\n y = x?getParam();\n"
},
{
"answer_id": 290857,
"author": "jckeyes",
"author_id": 17881,
"author_profile": "https://Stackoverflow.com/users/17881",
"pm_score": 0,
"selected": false,
"text": "var myObj = {\n anInt: 3993,\n aFunction: function() {alert('woot');},\n aString: \"Random\",\n aBool: false\n}\n var myObj = {\n anInt: 3993,\n aBool: false,\n aString: \"Random\",\n\n aFunction: function() {\n alert('woot');\n }\n}\n"
},
{
"answer_id": 290858,
"author": "BoltBait",
"author_id": 20848,
"author_profile": "https://Stackoverflow.com/users/20848",
"pm_score": 1,
"selected": false,
"text": "#divPreview {\n width: 210px;\n height: 128px;\n border: #779 1px solid;\n overflow: auto;\n text-align: center;\n vertical-align: middle;\n background-color: #fff\";\n}\n"
},
{
"answer_id": 290920,
"author": "rpattabi",
"author_id": 15139,
"author_profile": "https://Stackoverflow.com/users/15139",
"pm_score": 2,
"selected": false,
"text": " puts \"ragu\"+\"pattabi\" \n puts \"ragu \" +\"pattabi\"\n puts \"ragu \" + \" pattabi\"\n hr = my_intf->do_the_thing_with( i_1,\n i_2,\n i_3 );\n\nhr = my_intf->do_the_thing_with( \"enter_the_dragon\", 1965,\n \"return_of_the_dragon\", 1972 );\n\nhr = my_intf->do_the_thing_with( \"enter_the_dragon\", \"bruce lee\", \"chinese\" );\n"
},
{
"answer_id": 291077,
"author": "Steve T",
"author_id": 415,
"author_profile": "https://Stackoverflow.com/users/415",
"pm_score": 0,
"selected": false,
"text": "#header {}\n #header h1 {}\n #header h2 {}\n\n#nav {}\n #nav ul {}\n #nav li {}\n #nav li a {}\n #nav li a:hover {}\n\n#content {}\n #content p {}\n\n#footer {}\n class A {\n\n private int b = 3;\n private int c = 2;\n\n public void method(string str) {\n\n if(str != null && str.length > 5) \n DoStuffWithString();\n else \n ShowInvalidError();\n\n }\n}\n"
},
{
"answer_id": 291248,
"author": "Omniwombat",
"author_id": 31351,
"author_profile": "https://Stackoverflow.com/users/31351",
"pm_score": -1,
"selected": false,
"text": "if (3.14159 == foo) {\n//Do stuff\n}\n if (3.14159 = foo) { //No good.\n//Do stuff\n}\n"
},
{
"answer_id": 291746,
"author": "Nivas",
"author_id": 25949,
"author_profile": "https://Stackoverflow.com/users/25949",
"pm_score": 0,
"selected": false,
"text": " int anInt = 10;\n float aFloat = 1.2155;\nMyOwnClass myObject = null;\n int anInteger = 10;\nfloat aFloat = 1.2155;\nMyOwnClass myObject = null;\n"
},
{
"answer_id": 291787,
"author": "Peter C.",
"author_id": 31389,
"author_profile": "https://Stackoverflow.com/users/31389",
"pm_score": -1,
"selected": false,
"text": "int num = 5, num2 = 7, num3;\n int num3, num = 5, num2 = 7;\n function()\n{\n // Code here.\n}\n"
},
{
"answer_id": 292335,
"author": "Ande Turner",
"author_id": 4857,
"author_profile": "https://Stackoverflow.com/users/4857",
"pm_score": 0,
"selected": false,
"text": "public static String intArrayToString( final int[] array ) {\n\n if ( array.length == 0 ) {\n\n return \"[]\" ;\n }\n\n StringBuffer sb = new StringBuffer() ;\n\n sb.append( \"[ \" ).append( array[ 0 ] ) ;\n\n if ( array.length > 1 ) {\n\n for ( int i = 1 ; i < array.length ; i++ ) {\n\n sb.append( \", \" ).append( array[ i ] ) ;\n }\n }\n return sb.append( \" ]\" ).toString() ;\n}\n if ( 0 < n && n < 10 ) {\n\n doSomething() ;\n}\n if ( afflicted ) {\n\n doSomething() ;\n\n} else {\n\n doSomethingElse() ;\n}\n"
},
{
"answer_id": 292930,
"author": "Todd Smith",
"author_id": 31624,
"author_profile": "https://Stackoverflow.com/users/31624",
"pm_score": -1,
"selected": false,
"text": "#divPreview \n{\n background-color : #fff\";\n border : #779 1px solid;\n height : 128px;\n overflow : auto;\n text-align : center;\n vertical-align : middle;\n width : 210px;\n}\n If (a)\n{\n}\n if (a) {\n}\n public class Employee\n{\n public string FirstName { get; set; }\n public string LastName { get; set; }\n\n}\n"
},
{
"answer_id": 293074,
"author": "orcmid",
"author_id": 33810,
"author_profile": "https://Stackoverflow.com/users/33810",
"pm_score": -1,
"selected": false,
"text": "#divPreview { \n text-align: center; \n vertical-align: middle; \n border: #779 1px solid; \n overflow: auto; \n width: 210px; \n height: 128px; \n background-color: #fff\" }\n"
}
] | 2008/11/14 | [
"https://Stackoverflow.com/questions/290806",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11397/"
] |
290,819 | <p>Are delegates the same thing as callbacks? Or are they related somehow?</p>
| [
{
"answer_id": 290854,
"author": "Wolf5",
"author_id": 37643,
"author_profile": "https://Stackoverflow.com/users/37643",
"pm_score": 3,
"selected": false,
"text": "delegate void MyDelegate(string Text);\n //This will result in a MessageBox with \"Lalalala\"\nMyFunctionThatGetsTheCallbackFunctionRef(MyCallBackFunc); \n\nvoid MyFunctionThatGetsTheCallbackFunctionRef(MyDelegate TheFunction){\n TheFunction(\"Lalalala\");\n}\n\nvoid MyCallBackFunc(string Text){\n //my callback\n MessageBox.Show(Text);\n}\n"
}
] | 2008/11/14 | [
"https://Stackoverflow.com/questions/290819",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
290,840 | <p>Let's say I have a table:</p>
<pre>
i j
---
a 1
a 2
a 3
a 4
b 5
b 6
b 7
b 8
b 9
</pre>
<p>Obvoiusly <code>SELECT a, GROUP_CONCAT(b SEPARATOR ',') GROUP BY a</code> would give me</p>
<pre>
a 1,2,3,4
b 5,6,7,8,9
</pre>
<p>But what if I want to get only a LIMITED number of results, like 2, for example:</p>
<pre>
a 1,2
b 5,6
</pre>
<p>Any ideas?</p>
| [
{
"answer_id": 293327,
"author": "Bill Karwin",
"author_id": 20860,
"author_profile": "https://Stackoverflow.com/users/20860",
"pm_score": 0,
"selected": false,
"text": "SELECT t.i, GROUP_CONCAT(t.j)\nFROM\n (SELECT t1.i, t1.j\n FROM mytable AS t1\n LEFT JOIN mytable AS t2\n ON (t1.i = t2.i AND t1.j >= t2.j) \n GROUP BY t1.i, t1.j\n HAVING COUNT(*) <= 2) AS t\nGROUP BY t.i;\n j SUBSTRING() SELECT i, SUBSTRING( GROUP_CONCAT(j), 1, 3 )\nFROM mytable\nGROUP BY i;\n"
},
{
"answer_id": 17527243,
"author": "Jakub Matczak",
"author_id": 1003915,
"author_profile": "https://Stackoverflow.com/users/1003915",
"pm_score": 2,
"selected": true,
"text": "SUBSTRING_INDEX() GROUP_CONCAT() SELECT i, SUBSTRING_INDEX( GROUP_CONCAT(j), ',', 2)\nFROM mytable\nGROUP BY i;\n j"
}
] | 2008/11/14 | [
"https://Stackoverflow.com/questions/290840",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/37141/"
] |
290,851 | <p>The basics have already been answered <a href="https://stackoverflow.com/questions/257125/human-language-of-a-document">here</a>. But is there a pre-built PHP lib doing the same as Lingua::Identify from CPAN?</p>
| [
{
"answer_id": 290864,
"author": "chroder",
"author_id": 18802,
"author_profile": "https://Stackoverflow.com/users/18802",
"pm_score": 3,
"selected": true,
"text": "Text_LanguageDetect"
}
] | 2008/11/14 | [
"https://Stackoverflow.com/questions/290851",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/35189/"
] |
290,860 | <p>I'm attempting to get my first ASP.NET web page working on windows using <a href="http://www.mono-project.com/Main_Page" rel="nofollow noreferrer">Mono</a> and the XSP web server.</p>
<p>I'm following this chaps <a href="http://www.codeproject.com/KB/cross-platform/introtomono2.aspx" rel="nofollow noreferrer">example</a>. The <a href="http://www.codeproject.com/KB/cross-platform/introtomono1.aspx" rel="nofollow noreferrer">first part</a> of his example works very well with the latest version of mono. however the web part seems to fall over with the following error</p>
<blockquote>
<p>'{Path Name}\Index.aspx.cs' is not a
valid virtual path.</p>
</blockquote>
<p>Here's the full Stack Trace:</p>
<pre><code>System.Web.HttpException: 'C:\Projects\Mono\ASPExample\simpleapp\index.aspx.cs' is not a valid virtual path.
at System.Web.HttpRequest.MapPath (System.String virtualPath, System.String baseVirtualDir, Boolean allowCrossAppMapping) [0x00000]
at System.Web.HttpRequest.MapPath (System.String virtualPath) [0x00000]
at System.Web.Compilation.BuildManager.AddToCache (System.String virtualPath, System.Web.Compilation.BuildProvider bp) [0x00000]
at System.Web.Compilation.BuildManager.BuildAssembly (System.Web.VirtualPath virtualPath) [0x00000]
at System.Web.Compilation.BuildManager.GetCompiledType (System.String virtualPath) [0x00000]
at System.Web.Compilation.BuildManager.CreateInstanceFromVirtualPath (System.String virtualPath, System.Type requiredBaseType) [0x00000]
at System.Web.UI.PageParser.GetCompiledPageInstance (System.String virtualPath, System.String inputFile, System.Web.HttpContext context) [0x00000]
at System.Web.UI.PageHandlerFactory.GetHandler (System.Web.HttpContext context, System.String requestType, System.String url, System.String path) [0x00000]
at System.Web.HttpApplication.GetHandler (System.Web.HttpContext context, System.String url, Boolean ignoreContextHandler) [0x00000]
at System.Web.HttpApplication.GetHandler (System.Web.HttpContext context, System.String url) [0x00000]
at System.Web.HttpApplication+<Pipeline>c__Iterator5.MoveNext () [0x00000]
</code></pre>
<p>I was wondering if anyone knew what this error meant. I guess i'm looking for a mono expert, who's tried out the windows version.</p>
| [
{
"answer_id": 295310,
"author": "CraftyFella",
"author_id": 30317,
"author_profile": "https://Stackoverflow.com/users/30317",
"pm_score": 0,
"selected": false,
"text": "@echo off\ncall C:\\PROGRA~1\\MONO-2~1.1\\bin\\setmonopath.bat\nxsp --root . --port 8088 --applications /:.\n"
},
{
"answer_id": 295474,
"author": "CraftyFella",
"author_id": 30317,
"author_profile": "https://Stackoverflow.com/users/30317",
"pm_score": 1,
"selected": true,
"text": "<%@ Page Language=\"C#\" %>\n<%@ Import Namespace=\"System.Data\" %>\n<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">\n<html xmlns=\"http://www.w3.org/1999/xhtml\" xml:lang=\"en\" lang=\"en\">\n <head>\n <title>Code behind Arrrrrrrrrrgh</title>\n <meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" />\n\n <script runat=\"server\">\n private void Page_Load(Object sender, EventArgs e)\n {\n DisplayServerDetails();\n DisplayRequestDetails();\n\n }\n\n private void DisplayServerDetails()\n {\n serverName.Text = Environment.MachineName;\n operatingSystem.Text = Environment.OSVersion.Platform.ToString();\n operatingSystemVersion.Text = Environment.OSVersion.Version.ToString();\n }\n\n private void DisplayRequestDetails()\n {\n requestedPage.Text = Request.Url.AbsolutePath;\n requestIP.Text = Request.UserHostAddress;\n requestUA.Text = Request.UserAgent;\n }\n\n </script>\n\n </head>\n\n <body>\n <form method=\"post\" runat=\"server\">\n <table width=\"450px\" border=\"1px\">\n <tr>\n <td colspan=\"2\"><strong>Server Details</strong></td>\n </tr>\n <tr>\n <td>Server Name:</td>\n <td>\n <asp:Label id=\"serverName\" runat=\"server\"></asp:Label></td>\n </tr>\n <tr>\n <td>Operating System:</td>\n <td>\n <asp:Label id=\"operatingSystem\" runat=\"server\"></asp:Label>\n </td>\n </tr>\n <tr>\n <td>Operating System Version:</td>\n <td>\n <asp:Label id=\"operatingSystemVersion\" runat=\"server\">\n </asp:Label>\n </td>\n </tr>\n </table>\n <br>\n <table width=\"450px\" border=\"1px\">\n <tr>\n <td colspan=\"2\"><strong>Request Details</strong></td>\n </tr>\n <tr>\n <td>Page Requested:</td>\n <td>\n <asp:Label id=\"requestedPage\" runat=\"server\"></asp:Label>\n </td>\n </tr>\n <tr>\n <td>Request From:</td>\n <td>\n <asp:Label id=\"requestIP\" runat=\"server\"></asp:Label>\n </td>\n </tr>\n <tr>\n <td>User Agent:</td>\n <td>\n <asp:Label id=\"requestUA\" runat=\"server\"></asp:Label>\n </td>\n </tr>\n </table>\n </form>\n </body>\n"
}
] | 2008/11/14 | [
"https://Stackoverflow.com/questions/290860",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/30317/"
] |
290,867 | <p>How do I serialize a 'Type'?</p>
<p>I want to serialize to XML an object that has a property that is a type of an object. The idea is that when it is deserialized I can create an object of that type.</p>
<pre><code>public class NewObject
{
}
[XmlRoot]
public class XmlData
{
private Type t;
public Type T
{
get { return t; }
set { t = value; }
}
}
static void Main(string[] args)
{
XmlData data = new XmlData();
data.T = typeof(NewObject);
try
{
XmlSerializer serializer = new XmlSerializer(typeof(XmlData));
try
{
using (FileStream fs = new FileStream("test.xml", FileMode.Create))
{
serializer.Serialize(fs, data);
}
}
catch (Exception ex)
{
}
}
catch (Exception ex)
{
}
}
</code></pre>
<p>I get this exception:
"The type ConsoleApplication1.NewObject was not expected. Use the XmlInclude or SoapInclude attribute to specify types that are not known statically."</p>
<p>Where do I put the [XmlInclude]? Is this even possible?</p>
| [
{
"answer_id": 290916,
"author": "Filip Frącz",
"author_id": 21704,
"author_profile": "https://Stackoverflow.com/users/21704",
"pm_score": 2,
"selected": false,
"text": "IXmlSerializable Type.FullName Type.AssemblyQualifiedName Assembly.GetType(string)"
},
{
"answer_id": 4780020,
"author": "Mikael",
"author_id": 587222,
"author_profile": "https://Stackoverflow.com/users/587222",
"pm_score": 1,
"selected": false,
"text": "Class dummie\n{\n Type objType;\n string xml;\n}\n"
},
{
"answer_id": 6601500,
"author": "TheSean",
"author_id": 94995,
"author_profile": "https://Stackoverflow.com/users/94995",
"pm_score": 4,
"selected": false,
"text": "Type System.RuntimeType public class c \n{ \n [XmlIgnore]\n private Type t;\n [XmlIgnore]\n public Type T {\n get { return t; }\n set { \n t = value;\n tName = value.AssemblyQualifiedName;\n }\n }\n\n public string tName{\n get { return t.AssemblyQualifiedName; }\n set { t = Type.GetType(value);}\n }\n}\n"
}
] | 2008/11/14 | [
"https://Stackoverflow.com/questions/290867",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9516/"
] |
290,875 | <p><rant-mode>
Have you ever seen a programming language that does not allow to add comments to the code? Welcome to the world of RTML (may it burn in hell)!
</rant-mode></p>
<h2>Question</h2>
<blockquote>
<p>What is the best technique (if any) you've adopted to comment your RTML code?</p>
</blockquote>
<p>Thank you!</p>
| [
{
"answer_id": 4424981,
"author": "bmarti44",
"author_id": 451238,
"author_profile": "https://Stackoverflow.com/users/451238",
"pm_score": 3,
"selected": true,
"text": "New \"**************** My comment and stuff ******************\"\n MULTI WHEN nil WHEN nil WHEN nil\n MULTI\n TEXT @a-random-variable\n"
},
{
"answer_id": 5464816,
"author": "Scherbius.com",
"author_id": 675937,
"author_profile": "https://Stackoverflow.com/users/675937",
"pm_score": 0,
"selected": false,
"text": " COMMENT \"nosearch\"\n HEAD\n TITLE \"untitled\"\n BODY\n TEXT \"This\n"
}
] | 2008/11/14 | [
"https://Stackoverflow.com/questions/290875",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/31415/"
] |
290,884 | <p>The very common beginner mistake is when you try to use a class property "statically" without making an instance of that class. It leaves you with the mentioned error message:</p>
<blockquote>
<p>You can either make the non static method static or make an instance of that class to use its properties.</p>
</blockquote>
<p><strong>What the reason behind this? Am not concern with the solution, rather the reason.</strong></p>
<pre><code>private java.util.List<String> someMethod(){
/* Some Code */
return someList;
}
public static void main(String[] strArgs){
// The following statement causes the error.
java.util.List<String> someList = someMethod();
}
</code></pre>
| [
{
"answer_id": 290895,
"author": "Steven A. Lowe",
"author_id": 9345,
"author_profile": "https://Stackoverflow.com/users/9345",
"pm_score": 7,
"selected": false,
"text": "static static"
},
{
"answer_id": 292263,
"author": "Ande Turner",
"author_id": 4857,
"author_profile": "https://Stackoverflow.com/users/4857",
"pm_score": 3,
"selected": false,
"text": "Object instance = new Constuctor().methodCall();\n primitive name = new Constuctor().methodCall();\n"
},
{
"answer_id": 725928,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "this pointer/reference. This is also the reason why a static method can not use this"
},
{
"answer_id": 1140431,
"author": "Michael Borgwardt",
"author_id": 16883,
"author_profile": "https://Stackoverflow.com/users/16883",
"pm_score": 5,
"selected": false,
"text": "public class Foo\n{\n private String foo;\n public Foo(String foo){ this.foo = foo; }\n public getFoo(){ return this.foo; }\n\n public static void main(String[] args){\n System.out.println( getFoo() );\n }\n}\n"
},
{
"answer_id": 11494870,
"author": "Erik Eidt",
"author_id": 471129,
"author_profile": "https://Stackoverflow.com/users/471129",
"pm_score": 4,
"selected": false,
"text": "instanceMethod();\nthis.instanceMethod();\n ... = instanceField;\n... = this.instanceField;\n"
}
] | 2008/11/14 | [
"https://Stackoverflow.com/questions/290884",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/37740/"
] |
290,896 | <p>Say I have this simple form:</p>
<pre><code>class ContactForm(forms.Form):
first_name = forms.CharField(required=True)
last_name = forms.CharField(required=True)
</code></pre>
<p>And I have a default value for one field but not the other. So I set it up like this:</p>
<pre><code>default_data = {'first_name','greg'}
form1=ContactForm(default_data)
</code></pre>
<p>However now when I go to display it, Django shows a validation error saying last_name is required:</p>
<pre><code>print form1.as_table()
</code></pre>
<p>What is the correct way to do this? Since this isn't data the user has submitted, just data I want to prefill.</p>
<p><strong>Note:</strong> required=False will not work because I do want it required when the user submits the data. Just when I'm first showing the form on the page, I won't have a default value.</p>
| [
{
"answer_id": 290910,
"author": "Jack M.",
"author_id": 3421,
"author_profile": "https://Stackoverflow.com/users/3421",
"pm_score": 1,
"selected": false,
"text": "from django import forms\nclass ContactForm(forms.Form):\n subject = forms.CharField(max_length=100)\n message = forms.CharField()\n sender = forms.EmailField()\n cc_myself = forms.BooleanField(required=False)\n"
},
{
"answer_id": 290962,
"author": "Alex Koshelev",
"author_id": 19772,
"author_profile": "https://Stackoverflow.com/users/19772",
"pm_score": 5,
"selected": true,
"text": "initial"
},
{
"answer_id": 39913942,
"author": "sorrat",
"author_id": 853876,
"author_profile": "https://Stackoverflow.com/users/853876",
"pm_score": 1,
"selected": false,
"text": "form.errors.clear()"
}
] | 2008/11/14 | [
"https://Stackoverflow.com/questions/290896",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13009/"
] |
290,898 | <p>Without getting into the details of <em>why</em>, I'm looking for a clean (as possible) way to replace kernel functions and system calls from a loadable module. My initial idea was to write some code to override some functions, which would take the original function (perhaps, if possible, <em>call</em> the function), and then add some of my own code. The key is that the function that I write has to have the name of the original function, so other code, upon trying to access it, will access mine instead.</p>
<p>I can easily (comparatively) do this directly in the kernel by just throwing my code into the appropriate functions, but I was wondering if anyone knew a little C magic that isn't <em>necessarily</em> horrible kernel (or C) coding practice that could achieve the same result.</p>
<p>Thoughts of #defines and typedefs come to mind, but I can't quite hack it out in my head.</p>
<p>In short: does anyone know a way to effectively override functions in the Linux kernel (from a module)?</p>
<p>EDIT: Since it's been asked, I essentially want to log certain functions (creating/deleting directories, etc.) <em>from within the kernel</em>, but for sanity's sake, a loadable module seems to make sense, rather than having to write a big patch to the kernel code and recompile on every change. A minimal amount of added code to the kernel is okay, but I want to offload most of the work to a module.</p>
| [
{
"answer_id": 296704,
"author": "Phillip Whelan",
"author_id": 25305,
"author_profile": "https://Stackoverflow.com/users/25305",
"pm_score": 1,
"selected": false,
"text": "* IN_ACCESS - read of the file\n* IN_MODIFY - last modification\n* IN_ATTRIB - attributes of file change\n* IN_OPEN and IN_CLOSE - open or close of file\n* IN_MOVED_FROM and IN_MOVED_TO - when the file is moved or renamed\n* IN_DELETE - a file/directory deleted\n* IN_CREATE - a file/directory created\n* IN_DELETE_SELF - file monitored is deleted\n"
},
{
"answer_id": 1679294,
"author": "Robert S. Barnes",
"author_id": 71074,
"author_profile": "https://Stackoverflow.com/users/71074",
"pm_score": 0,
"selected": false,
"text": "// add the following in the file arch/i386/kernel/i386_ksyms.c\nextern void* sys_call_table[];\nEXPORT_SYMBOL(sys_call_table);\n printk() our_sys_open printk() open() init_module sys_call_table cleanup_module open A_open B_open A_open sys_open B_open A_open"
}
] | 2008/11/14 | [
"https://Stackoverflow.com/questions/290898",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/34426/"
] |
290,899 | <p>How exactly using VB6 can I can call any Windows shell command as you would from the command-line?</p>
<p>For example, something as trivial as:</p>
<pre><code>echo foo
</code></pre>
| [
{
"answer_id": 290906,
"author": "Ed Guiness",
"author_id": 4200,
"author_profile": "https://Stackoverflow.com/users/4200",
"pm_score": 3,
"selected": false,
"text": "Dim RetVal\nRetVal = Shell(\"C:\\WINDOWS\\CALC.EXE\", 1) ' Run Calculator.\n"
},
{
"answer_id": 290912,
"author": "dub",
"author_id": 30022,
"author_profile": "https://Stackoverflow.com/users/30022",
"pm_score": 5,
"selected": true,
"text": "Shell \"cmd echo foo\", vbNormalFocus \n"
},
{
"answer_id": 318442,
"author": "JeffK",
"author_id": 5420,
"author_profile": "https://Stackoverflow.com/users/5420",
"pm_score": 3,
"selected": false,
"text": "Dim shell As wshShell\nDim lngReturnCode As Long\nDim strShellCommand As String\n\nSet shell = New wshShell\n\nstrShellCommand = \"C:\\Program Files\\My Company\\MyProg.exe \" & _\n \"-Ffoption -Ggoption\"\n\nlngReturnCode = shell.Run(strShellCommand, vbNormalFocus, vbTrue)\n"
},
{
"answer_id": 322964,
"author": "Eugenio Miró",
"author_id": 41236,
"author_profile": "https://Stackoverflow.com/users/41236",
"pm_score": 3,
"selected": false,
"text": "Shell Environ(\"COMSPEC\") & \" /c echo foo\", vbNormalFocus\n pid = Shell(Environ(\"COMSPEC\") & \" /c echo foo\", vbNormalFocus)\n"
},
{
"answer_id": 596354,
"author": "raven",
"author_id": 4228,
"author_profile": "https://Stackoverflow.com/users/4228",
"pm_score": 3,
"selected": false,
"text": "Shell \"cmd /c echo foo\"\n"
},
{
"answer_id": 30793160,
"author": "CerFyxz",
"author_id": 5001249,
"author_profile": "https://Stackoverflow.com/users/5001249",
"pm_score": -1,
"selected": false,
"text": "\"\"...\"\" shell (\"\"echo pass|schtasks /create /TR \"C:\\folder\\...\\program.exe\" /more_parameters\"\")\n \" \"C:\\..."
}
] | 2008/11/14 | [
"https://Stackoverflow.com/questions/290899",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4872/"
] |
290,913 | <p>In C++, is it possible to have a base plus derived class implement a single interface?</p>
<p>For example:</p>
<pre><code>class Interface
{
public:
virtual void BaseFunction() = 0;
virtual void DerivedFunction() = 0;
};
class Base
{
public:
virtual void BaseFunction(){}
};
class Derived : public Base, public Interface
{
public:
void DerivedFunction(){}
};
void main()
{
Derived derived;
}
</code></pre>
<p>This fails because Derived can not be instantiated. As far as the compiler is concerned Interface::BaseFunction is never defined.</p>
<p>So far the only solution I've found would be to declare a pass through function in Derived</p>
<pre><code>class Derived : public Base, public Interface
{
public:
void DerivedFunction(){}
void BaseFunction(){ Base::BaseFunction(); }
};
</code></pre>
<p>Is there any better solution?</p>
<hr>
<p><strong>EDIT:</strong> If it matters, here is a real world problem I had using MFC dialogs. </p>
<p>I have a dialog class (MyDialog lets say) that derives from CDialog. Due to dependency issues, I need to create an abstract interface (MyDialogInterface). The class that uses MyDialogInterface needs to use the methods specific to MyDialog, but also needs to call CDialog::SetParent. I just solved it by creating MyDialog::SetParent and having it pass through to CDialog::SetParent, but was wondering if there was a better way.</p>
| [
{
"answer_id": 290921,
"author": "Johannes Schaub - litb",
"author_id": 34509,
"author_profile": "https://Stackoverflow.com/users/34509",
"pm_score": 5,
"selected": true,
"text": "BaseFunction Interface class Interface\n{\n public:\n virtual void BaseFunction() = 0;\n virtual void DerivedFunction() = 0;\n};\n\nclass Base : public Interface\n{\n public:\n virtual void BaseFunction(){}\n};\n\nclass Derived : public Base\n{\n public: \n virtual void DerivedFunction(){}\n};\n\nint main()\n{\n Derived derived;\n}\n Interface class DerivedInterface\n{\n public:\n virtual void DerivedFunction() = 0;\n};\n\nclass BaseInterface\n{\n public:\n virtual void BaseFunction() = 0;\n};\n\nclass Base : public BaseInterface\n{\n public:\n virtual void BaseFunction(){}\n};\n\nclass Derived : public DerivedInterface\n{\n public: \n virtual void DerivedFunction(){}\n}; \n\nclass Both : public DerivedInterface, public Base {\n public: \n virtual void DerivedFunction(){}\n};\n\nint main()\n{\n Derived derived;\n Base base;\n Both both;\n}\n virtual"
},
{
"answer_id": 290926,
"author": "Torlack",
"author_id": 5243,
"author_profile": "https://Stackoverflow.com/users/5243",
"pm_score": 1,
"selected": false,
"text": "Interface Base Derived Interface Derived"
},
{
"answer_id": 290976,
"author": "JohnMcG",
"author_id": 1674,
"author_profile": "https://Stackoverflow.com/users/1674",
"pm_score": 2,
"selected": false,
"text": "class Contained\n{\n public:\n void containedFunction() {}\n};\n\nclass Derived\n{\n public:\n virtual void derivedFunction() {}\n virtual void containedFunction() {return contained.containedFunction();}\n private:\n Containted contained;\n};\n"
},
{
"answer_id": 291367,
"author": "Kennet Belenky",
"author_id": 37788,
"author_profile": "https://Stackoverflow.com/users/37788",
"pm_score": 1,
"selected": false,
"text": "Derived Derived\n vtable: Interface\n BaseFunction*\n DerivedFunction*\n vtable: Base\n BaseFunction*\n Base Base::BaseFunction Derived Derived\n vtable: Interface\n BaseFunction* = 0\n DerivedFunction* = Derived::DerivedFunction\n vtable: Base\n BaseFunction* = Base::BaseFunction\n"
},
{
"answer_id": 291995,
"author": "Joe",
"author_id": 12567,
"author_profile": "https://Stackoverflow.com/users/12567",
"pm_score": 0,
"selected": false,
"text": "Derived DerivedInterface BaseInterface DerivedInterface BaseInterface DerivedInterface BaseInterface DerivedInterface class DerivedInterface\n{\n public:\n virtual void DerivedFunction() = 0;\n BaseInterface* GetBaseInterface()\n {return dynamic_cast<BaseInterface*>(this);}\n};\n\nvoid main()\n{\n Derived derived;\n\n DerivedInterface* derivedInterface = &derived;\n derivedInterface->GetBaseInterface()->BaseFunction();\n}\n"
}
] | 2008/11/14 | [
"https://Stackoverflow.com/questions/290913",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12567/"
] |
290,923 | <p>I have a file in cvs that has Sticky Options set to <code>-kk</code>. This replaces all cvs keywords with just the keyword name to facilitate diffs. For example, <code>$Author: Alex B$</code> becomes <code>$Author$</code>. </p>
<p>How do I disable the <code>-kk</code> behavior and get back to "normal" cvs where keywords are substituted in? I've tried <code>rm</code>'ing the file and updating, I've tried <code>cvs update -A</code> and neither changes the flag.</p>
| [
{
"answer_id": 290945,
"author": "Ken Gentle",
"author_id": 8709,
"author_profile": "https://Stackoverflow.com/users/8709",
"pm_score": 3,
"selected": true,
"text": "cvs update -kkv <filename>\n keyword value checkout update"
},
{
"answer_id": 3710512,
"author": "Iain",
"author_id": 447523,
"author_profile": "https://Stackoverflow.com/users/447523",
"pm_score": 2,
"selected": false,
"text": "Sticky options: -kk"
},
{
"answer_id": 7980376,
"author": "JochenJung",
"author_id": 351893,
"author_profile": "https://Stackoverflow.com/users/351893",
"pm_score": 2,
"selected": false,
"text": "cvs admin -kkv <filename>\n cvs update -kkv <filename>\n"
}
] | 2008/11/14 | [
"https://Stackoverflow.com/questions/290923",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6180/"
] |
290,927 | <p>Is it expensive?</p>
<p>I am developing an HtmlHelper that renders directly to Response.Output in order to save unnecesary string creation and I need to choose between: </p>
<pre><code><% Validator.RenderClient(Response.Output); %>
</code></pre>
<p>and</p>
<pre><code><% Validator.RenderClient(); %>
</code></pre>
<p>and get the textWriter from HttpContext.Current.Response</p>
| [
{
"answer_id": 290949,
"author": "oglester",
"author_id": 2017,
"author_profile": "https://Stackoverflow.com/users/2017",
"pm_score": 2,
"selected": false,
"text": "public static HttpContext get_Current()\n{\n return (ContextBase.Current as HttpContext);\n}\n public static object HostContext\n{\n get\n {\n object hostContext = \n Thread.CurrentThread.GetIllogicalCallContext().HostContext;\n if (hostContext == null)\n {\n hostContext = GetLogicalCallContext().HostContext;\n }\n return hostContext;\n }\n"
},
{
"answer_id": 293810,
"author": "Santiago Corredoira",
"author_id": 4264,
"author_profile": "https://Stackoverflow.com/users/4264",
"pm_score": 2,
"selected": false,
"text": " System.Diagnostics.Stopwatch sp = new System.Diagnostics.Stopwatch();\n\n // With HttpContext.Current:\n sp.Start();\n for (int i = 0; i < 100; i++)\n {\n HttpContext.Current.Response.Output.Write(i.ToString());\n }\n sp.Stop();\n long result1 = sp.ElapsedTicks;\n\n // Without:\n TextWriter output2 = HttpContext.Current.Response.Output;\n sp.Reset();\n sp.Start();\n for (int i = 0; i < 100; i++)\n {\n output2.Write(i.ToString());\n }\n sp.Stop();\n long result2 = sp.ElapsedTicks; \n"
},
{
"answer_id": 2027865,
"author": "John Leidegren",
"author_id": 58961,
"author_profile": "https://Stackoverflow.com/users/58961",
"pm_score": 3,
"selected": true,
"text": "var results1 = new List<long>();\nvar results2 = new List<long>();\n\nfor (int j = 0; j < 100; j++)\n{\n var sp = new System.Diagnostics.Stopwatch();\n\n // With HttpContext.Current: \n sp.Start();\n for (int i = 0; i < 10000; i++)\n {\n HttpContext.Current.Response.Output.Write(i);\n }\n sp.Stop();\n\n results1.Add(sp.ElapsedTicks);\n\n // Without: \n TextWriter output2 = HttpContext.Current.Response.Output;\n sp.Reset();\n\n sp.Start();\n for (int i = 0; i < 10000; i++)\n {\n output2.Write(i);\n }\n sp.Stop();\n\n HttpContext.Current.Response.Clear();\n\n results2.Add(sp.ElapsedTicks);\n}\n\nresults1.Sort();\nresults2.Sort();\n\nHttpContext.Current.Response.Write(string.Format(\"HttpContext.Current={0:0.000}ms, Local variable={1:0.000}ms, R={2:0.0%}<br/>\", results1[results1.Count / 2] / (double)TimeSpan.TicksPerMillisecond, results2[results2.Count / 2] / (double)TimeSpan.TicksPerMillisecond, (double)results1[results1.Count / 2] / (double)results2[results2.Count / 2]));\n HttpContext.Current=0,536ms, Local variable=0,486ms, R=110,2% \n"
}
] | 2008/11/14 | [
"https://Stackoverflow.com/questions/290927",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4264/"
] |
290,952 | <p>Suppose I have #define foo in various header files. It may expand to some different things. I would like to know (when compiling a .cc file) when a #define is encountered, to what it will expand, it which file it is and where it got included from.</p>
<p>Is it possible? If not, are there any partial solutions that may help?</p>
<p>Feel free to add comments with clarification requests.</p>
<p><strong>Edit: current answers seem to concentrate on the case when there is one #define and I just want to jump to definition or know what the definition is. That's the simple case and yes, your solutions work. But when I have the same #define in different files, and want to know which one kicks in first, none of these techniques is useful. Okay, I actually used #warning carefully to find the right place. But this requires much work.</strong></p>
| [
{
"answer_id": 291001,
"author": "Johannes Schaub - litb",
"author_id": 34509,
"author_profile": "https://Stackoverflow.com/users/34509",
"pm_score": 5,
"selected": true,
"text": "# shows preprocessed source with cpp internals removed\ng++ -E -P file.cc\n# shows preprocessed source kept with macros and include directives \ng++ -E -dD -dI -P file.cc \n -P"
},
{
"answer_id": 291008,
"author": "Martin York",
"author_id": 14065,
"author_profile": "https://Stackoverflow.com/users/14065",
"pm_score": 2,
"selected": false,
"text": "g++ -E -dM file.cpp | grep MACRO\n"
},
{
"answer_id": 291899,
"author": "Max Lybbert",
"author_id": 10593,
"author_profile": "https://Stackoverflow.com/users/10593",
"pm_score": 3,
"selected": false,
"text": "gcc my_file.c -Dfoo=@\n"
}
] | 2008/11/14 | [
"https://Stackoverflow.com/questions/290952",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9403/"
] |
290,980 | <p>I have a Windows forms project (VS 2005, .net 2.0). The solution has references to 9 projects. Everything works and compiles fine on one of my computers. When I move it to a second computer, 8 out of the 9 project compile with no problem. When I try to compile the 9th project (the main project for the application - produces the .exe file to execute the application), I get the following error: </p>
<pre><code>'Error 3: A strongly-named assembly is required. (Exception from HRESULT: 0x80131044)'
</code></pre>
<p>The file location for the error is is listed as "C:\PATH-TO-APP\LC". </p>
<p>I have checked in the project properties and all of the projects are set to build in Debug mode, none of them are supposed to be signed. In the project that is failing, the only assembly that it references that is not in any of the other projects is Microsoft.VisualBasic (a .net 2.0 assembly). So I am at a loss to find what ids causing this error (the file referenced above in the error message - "LC" - does not exist. </p>
<p>Anyone know how I can force the project to accept all unsigned assemblies, or to determine which assembly is the culprit?</p>
<p>The only meaningful difference between the dev environments between the dev environment where this worked and the current one is that the first was XP and this is Vista64. However, a colleague of mine who is using XP is getting the same error.</p>
<p><strong>Third-party assemblies being used:</strong></p>
<ul>
<li>ComponentFactory.Krypton.Toolkit</li>
<li>ComponentFactory.Krypton.Navigator</li>
<li>VistaDB.NET20</li>
</ul>
<p>All of these are referenced in other projects in the solution which build with no problems, so it doesn't look like these are the problem.</p>
<p>So far I have tried deleting the suo file, Rebuild All, unloading and reloading projects from the solution, removing and readding referenced assemblies. Nothing has worked.<code></code></p>
| [
{
"answer_id": 291204,
"author": "Charles Bretana",
"author_id": 32632,
"author_profile": "https://Stackoverflow.com/users/32632",
"pm_score": 2,
"selected": false,
"text": "Public Key or Token: ab 1a 81 37 f9 79 0c 88 \n .assembly extern Reflex\n{\n.publickey = (2F 5A 20 3A 86 D3 5F 71 ) // /Z :.._q\n.ver 1:0:0:0\n}\n .publickey .publickeytoken"
},
{
"answer_id": 64827702,
"author": "user160357",
"author_id": 8019611,
"author_profile": "https://Stackoverflow.com/users/8019611",
"pm_score": 4,
"selected": false,
"text": "Strong Name true"
}
] | 2008/11/14 | [
"https://Stackoverflow.com/questions/290980",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/51/"
] |
290,982 | <p>I have a block of code that works and I wanted to ask what exactly is happening here?</p>
<pre><code>Class<?> normalFormClass = null;
</code></pre>
<p>---added---</p>
<p>The wildcard "<code><?></code>" is the part that is confusing for me. Why would this be used rather than not using it (generics)?</p>
| [
{
"answer_id": 290995,
"author": "Vinko Vrsalovic",
"author_id": 5190,
"author_profile": "https://Stackoverflow.com/users/5190",
"pm_score": 5,
"selected": true,
"text": "Integer normalForm = new Integer();\nnormalFormClass = normalForm.getClass();\n String normalForm = new String();\nnormalFormClass = normalForm.getClass();\n Class foo \n Class<?> foo \n"
},
{
"answer_id": 291260,
"author": "John in MD",
"author_id": 4476,
"author_profile": "https://Stackoverflow.com/users/4476",
"pm_score": 3,
"selected": false,
"text": "Class<?> normalClass = null;\n Class normalClass = null;\n"
}
] | 2008/11/14 | [
"https://Stackoverflow.com/questions/290982",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/34475/"
] |
290,996 | <p>How do I get the HTTP status code (eg 200 or 500) after calling curl_easy_perform? </p>
| [
{
"answer_id": 291006,
"author": "Vinko Vrsalovic",
"author_id": 5190,
"author_profile": "https://Stackoverflow.com/users/5190",
"pm_score": 8,
"selected": true,
"text": "curl_code = curl_easy_perform (session);\nlong http_code = 0;\ncurl_easy_getinfo (session, CURLINFO_RESPONSE_CODE, &http_code);\nif (http_code == 200 && curl_code != CURLE_ABORTED_BY_CALLBACK)\n{\n //Succeeded\n}\nelse\n{\n //Failed\n}\n"
},
{
"answer_id": 48748025,
"author": "kralyk",
"author_id": 786102,
"author_profile": "https://Stackoverflow.com/users/786102",
"pm_score": 4,
"selected": false,
"text": "200 400 500 CURLE_OK"
}
] | 2008/11/14 | [
"https://Stackoverflow.com/questions/290996",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23524/"
] |
290,997 | <p>We have the TAncestor class which has a virtual method GetFile.<br>
We will have some TDescendant = class(TAncestor) which may override GetFile.<br>
We want to insure that in such a case those overriden methods do not call inherited in their implementation.<br>
But if they don't implement GetFile and just use the one from TAncestor, it's fine.<br>
Is there a (simple) way to do this? </p>
<p>to make it clearer:<br>
- yes, doc clearly says 'do not use inherited in your descendant class'<br>
- I have no control of what others will code when overriding and don't rely on them reading the doc<br>
- I cannot restrict the execution to the exact class TAncestor as it is legit for descendant to use it if they don't provide their own implementation<br>
- I cannot make it abstract because it needs to have a default implementation<br>
- I want to enforce this with a way of detecting in the base class that the code is called through a descendant overridden implementation<br>
- Looking at the stack seems overkill but is my 1st idea so far</p>
| [
{
"answer_id": 291046,
"author": "Steve",
"author_id": 22712,
"author_profile": "https://Stackoverflow.com/users/22712",
"pm_score": 1,
"selected": false,
"text": "procedure TDescentdent.GetFile;\nbegin\n //do not call inherited\n //Do something new\nend;\n"
},
{
"answer_id": 291048,
"author": "Jamie",
"author_id": 922,
"author_profile": "https://Stackoverflow.com/users/922",
"pm_score": 1,
"selected": false,
"text": "procedure TDescentdent.GetFile;\nbegin\n FileUtils.GetFile \nend;\n"
},
{
"answer_id": 291112,
"author": "Rob Kennedy",
"author_id": 33732,
"author_profile": "https://Stackoverflow.com/users/33732",
"pm_score": 2,
"selected": false,
"text": "type\n TGetFileImpl = procedure of object;\n\n TAncestor = class\n private\n FGetFile: TGetFileImpl;\n protected\n property GetFileImpl: TGetFileImpl write FGetFile write FGetFile;\n public\n procedure GetFile; // not virtual.\n end;\n\n TDescendant = class(TAncestor)\n private\n procedure SpecializedGetFile;\n public\n constructor Create;\n end;\n\nprocedure TAncestor.GetFile;\nbegin\n if Assigned(GetFileImpl) then\n GetFileImpl\n else begin\n // Do default implementation instead\n end;\nend;\n\nconstructor TDescendant.Create;\nbegin\n GetFileImpl := SpecializedGetFile;\nend;\n GetFile TGetFileImpl GetFile"
},
{
"answer_id": 291576,
"author": "Francesca",
"author_id": 9842,
"author_profile": "https://Stackoverflow.com/users/9842",
"pm_score": 0,
"selected": false,
"text": "type\n TForm1 = class(TForm)\n btnGoodDescendant: TButton;\n btnBadDescendant: TButton;\n btnSimpleDescendant: TButton;\n procedure btnGoodDescendantClick(Sender: TObject);\n procedure btnBadDescendantClick(Sender: TObject);\n procedure btnSimpleDescendantClick(Sender: TObject);\n private\n { Private declarations }\n public\n { Public declarations }\n end;\n\n TAncestor = class\n public\n procedure GetFile; virtual;\n end;\n\n TBadDescendant = class(TAncestor)\n public\n procedure GetFile; override;\n end;\n\n TGoodDescendant = class(TAncestor)\n public\n procedure GetFile; override;\n end;\n\n TDescendant = class(TAncestor)\n public\n end;\n\nvar\n Form1: TForm1;\n\nimplementation\n\n{$R *.dfm}\n\nprocedure TAncestor.GetFile;\ntype\n TGetFileImpl = procedure of object;\nvar\n BaseGetFile, GetFileImpl: TGetFileImpl;\n ClassAncestor: TClass;\nbegin\n // detecting call through inherited...\n GetFileImpl := GetFile; // method actually called\n ClassAncestor := ClassType;\n while (ClassAncestor <> nil) and (ClassAncestor <> TAncestor) do\n ClassAncestor := ClassAncestor.ClassParent;\n if ClassAncestor = nil then\n raise Exception.Create('no ancestor???');\n BaseGetFile := TAncestor(@ClassAncestor).GetFile; // TAncestor code\n // if we are here, we should be directly using TAncestor code, not\n // not calling inherited from a derived class\n // thus the actual code should be exactly TAncestor code.\n if TMethod(GetFileImpl).Code <> TMethod(BaseGetFile).Code then\n raise Exception.Create('You must not call inherited!');\n\n // this is the Ancestor work code here\n ShowMessage('Ancestor code for GetFile');\nend;\n\n{ TBadDescendant }\n\nprocedure TBadDescendant.GetFile;\nbegin\n inherited;\n ShowMessage('TBadDescendant code for GetFile');\nend;\n\n{ TGoodDescendant }\n\nprocedure TGoodDescendant.GetFile;\nbegin\n ShowMessage('TGoodDescendant code for GetFile');\nend;\n\nprocedure TForm1.btnGoodDescendantClick(Sender: TObject);\nbegin\n with TGoodDescendant.Create do\n GetFile;\nend;\n\nprocedure TForm1.btnBadDescendantClick(Sender: TObject);\nbegin\n with TBadDescendant.Create do\n GetFile;\nend;\n\nprocedure TForm1.btnSimpleDescendantClick(Sender: TObject);\nbegin\n with TDescendant.Create do\n GetFile;\nend;\n"
},
{
"answer_id": 308563,
"author": "Kcats",
"author_id": 22602,
"author_profile": "https://Stackoverflow.com/users/22602",
"pm_score": 0,
"selected": false,
"text": "procedure TBadDescendant.GetFile;\nvar\n AncestorImpl : procedure(This : TObject);\n ThisClass : TClass;\nbegin\n AncestorImpl := @TAncestor.GetFile;\n ThisClass := ClassType;\n PPointer(Self)^ := TAncestor;\n AncestorImpl(Self);\n PPointer(Self)^ := ThisClass;\n ShowMessage('TBadDescendant code for GetFile');\nend;\n"
}
] | 2008/11/14 | [
"https://Stackoverflow.com/questions/290997",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9842/"
] |
291,000 | <p>I'm looking for a library in PHP that can create a tree structure from a database (or array of values) with left and right ids. For the result when getting values I am only looking for an array so I can create any type of view. For adding and removing, it would be nice if the library did it all. Even if the library is within another library, I don't mind as I'll probably pull it out and integrate it with my own libraries.</p>
<p>Anyone know of anything?</p>
<p>I'm using PHP & MySQL, so it'd be helpful if it used atleast PHP. If it's a different database I can probably convert it, although maybe the same with PHP if it doesn't use too much language specific functionality.</p>
| [
{
"answer_id": 4358306,
"author": "sirin k",
"author_id": 447880,
"author_profile": "https://Stackoverflow.com/users/447880",
"pm_score": 0,
"selected": false,
"text": " <?php\nclass Node\n{\n public $data;\n public $leftChild;\n public $rightChild;\n\n public function __construct($data)\n {\n $this->data=$data;\n $this->leftChild=null;\n $this->rightChild=null;\n }\n public function disp_data()\n {\n echo $this->data;\n }\n\n\n}//end class Node\nclass BinaryTree\n{\n public $root;\n //public $s;\n public function __construct()\n {\n $this->root=null;\n //$this->s=file_get_contents('store');\n\n }\n//function to display the tree\n public function display()\n {\n $this->display_tree($this->root);\n\n }\n public function display_tree($local_root)\n {\n\n if($local_root==null) \n return;\n $this->display_tree($local_root->leftChild);\n echo $local_root->data.\"<br/>\";\n $this->display_tree($local_root->rightChild);\n\n } \n// function to insert a new node\n public function insert($key)\n {\n $newnode=new Node($key);\n if($this->root==null)\n {\n $this->root=$newnode;\n return;\n }\n else\n {\n $parent=$this->root;\n $current=$this->root;\n while(true)\n {\n $parent=$current;\n //$this->find_order($key,$current->data);\n if($key==($this->find_order($key,$current->data)))\n {\n $current=$current->leftChild;\n if($current==null)\n {\n $parent->leftChild=$newnode;\n return;\n }//end if2\n }//end if1 \n else\n {\n $current=$current->rightChild;\n if($current==null)\n {\n $parent->rightChild=$newnode;\n return; \n } //end if1 \n } //end else\n }//end while loop \n }//end else\n\n } //end insert function\n\n//function to search a particular Node\n public function find($key)\n {\n $current=$this->root;\n while($current->data!=$key)\n {\n if($key==$this->find_order($key,$current->data))\n {\n $current=$current->leftChild;\n }\n else\n {\n $current=$current->rightChild;\n }\n if($current==null)\n return(null);\n\n }\n return($current->data); \n }// end the function to search\n public function delete1($key)\n {\n $current=$this->root;\n $parent=$this->root;\n\n $isLeftChild=true;\n while($current->data!=$key)\n {\n $parent=$current;\n if($key==($this->find_order($key,$current->data)))\n {\n $current=$current->leftChild;\n $isLeftChild=true;\n } \n else\n {\n $current=$current->rightChild;\n $isLeftChild=false; \n } \n if($current==null)\n return(null);\n }//end while loop \n\n echo \"<br/><br/>Node to delete:\".$current->data;\n //to delete a leaf node \n if($current->leftChild==null&&$current->rightChild==null)\n {\n if($current==$this->root)\n $this->root=null; \n else if($isLeftChild==true)\n {\n $parent->leftChild=null;\n } \n else\n {\n $parent->rightChild=null;\n }\n return($current); \n }//end if1\n //to delete a node having a leftChild \n else if($current->rightChild==null)\n {\n if($current==$this->root)\n $this->root=$current->leftChild;\n else if($isLeftChild==true)\n {\n $parent->leftChild=$current->leftChild;\n }\n else\n {\n $parent->rightChild=$current->leftChild;\n } \n return($current);\n }//end else if1\n //to delete a node having a rightChild\n else if($current->leftChild==null)\n {\n if($current==$this->root)\n $this->root=$current->rightChild;\n else if($isLeftChild==true)\n {\n $parent->leftChild=$current->rightChild;\n } \n else\n {\n $parent->rightChild=$current->rightChild; \n } \n return($current);\n } \n //to delete a node having both childs\n else\n {\n $successor=$this->get_successor($current);\n if($current==$this->root)\n {\n $this->root=$successor; \n\n }\n else if($isLeftChild==true)\n {\n $parent->leftChild=$successor;\n }\n else\n {\n $parent->rightChild=$successor;\n } \n $successor->leftChild=$current->leftChild;\n return($current);\n } \n\n\n }//end the function to delete a node\n//Function to find the successor node\n public function get_successor($delNode)\n {\n $succParent=$delNode;\n $successor=$delNode;\n $temp=$delNode->rightChild;\n while($temp!=null)\n {\n $succParent=$successor;\n $successor=$temp;\n $temp=$temp->leftChild;\n }\n if($successor!=$delNode->rightChild)\n {\n $succParent->leftChild=$successor->rightChild;\n $successor->rightChild=$delNode->rightChild;\n }\n return($successor);\n }\n//function to find the order of two strings\n public function find_order($str1,$str2)\n {\n $str1=strtolower($str1);\n $str2=strtolower($str2);\n $i=0;\n $j=0;\n\n $p1=$str1[i];\n $p2=$str2[j]; \n while(true)\n { \n if(ord($p1)<ord($p2)||($p1==''&&$p2==''))\n {\n\n return($str1);\n }\n else\n {\n if(ord($p1)==ord($p2))\n {\n $p1=$str1[++$i];\n $p2=$str2[++$j];\n continue;\n }\n return($str2); \n }\n }//end while\n\n } //end function find string order\n\n public function is_empty()\n {\n if($this->root==null)\n return(true);\n else\n return(false);\n }\n}//end class BinaryTree\n?>\n"
}
] | 2008/11/14 | [
"https://Stackoverflow.com/questions/291000",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5441/"
] |
291,003 | <p>The JUnit framework contains 2 <code>Assert</code> classes (in different packages, obviously) and the methods on each appear to be very similar. Can anybody explain why this is?</p>
<p>The classes I'm referring to are: <a href="http://junit.org/junit/javadoc/4.5/junit/framework/Assert.html" rel="noreferrer"><code>junit.framework.Assert</code></a> and <a href="http://junit.org/junit/javadoc/4.5/org/junit/Assert.html" rel="noreferrer"><code>org.junit.Assert</code></a>.</p>
| [
{
"answer_id": 291032,
"author": "sblundy",
"author_id": 4893,
"author_profile": "https://Stackoverflow.com/users/4893",
"pm_score": 3,
"selected": false,
"text": "junit.framework org.junit junit.framework.Assert"
},
{
"answer_id": 291045,
"author": "Mnementh",
"author_id": 21005,
"author_profile": "https://Stackoverflow.com/users/21005",
"pm_score": 9,
"selected": true,
"text": "junit.framework.TestCase junit.framework.Assert Annotations TestCase Assert import static org.junit.Assert.*;\n org.junit"
},
{
"answer_id": 291074,
"author": "ReneS",
"author_id": 33229,
"author_profile": "https://Stackoverflow.com/users/33229",
"pm_score": 6,
"selected": false,
"text": "junit.framework.Assert org.junit.Assert"
},
{
"answer_id": 919873,
"author": "guerda",
"author_id": 32043,
"author_profile": "https://Stackoverflow.com/users/32043",
"pm_score": 2,
"selected": false,
"text": "org.junit.Assert Arrays"
},
{
"answer_id": 1211408,
"author": "David Moles",
"author_id": 27358,
"author_profile": "https://Stackoverflow.com/users/27358",
"pm_score": 4,
"selected": false,
"text": "org.junit.Assert assertEquals() float double junit.framework.Assert"
},
{
"answer_id": 54808547,
"author": "MatPag",
"author_id": 2910520,
"author_profile": "https://Stackoverflow.com/users/2910520",
"pm_score": 2,
"selected": false,
"text": "junit.framework IDE Project"
}
] | 2008/11/14 | [
"https://Stackoverflow.com/questions/291003",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2648/"
] |
291,012 | <p>I need to connect to Outlook through ASP.NET web application using user credentials. What are my options? </p>
<p>FYI: User logs into the web site by using Windows Authentication. I'm working with Outlook 2003. </p>
| [
{
"answer_id": 291282,
"author": "FlySwat",
"author_id": 1965,
"author_profile": "https://Stackoverflow.com/users/1965",
"pm_score": 0,
"selected": false,
"text": "outlook.Application outlookApp = new outlook.ApplicationClass();\noutlook.NameSpace olNameSpace = outlookApp.GetNamespace(\"MAPI\");\nolNameSpace.Logon (Credentials); \n\noutlook.ContactItem contact = (outlook.ContactItem)\n outlookApp.CreateItem(OlItemType.olContactItem);\n\ncontact.FirstName = \"Joe\";\ncontact.LastName = \"Smith\";\n\ncontact.Save();\n"
}
] | 2008/11/14 | [
"https://Stackoverflow.com/questions/291012",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/37759/"
] |
291,019 | <p>I ask this because at work I am supposed to develop a web-application that is used in an intranet, by two people. It's an application that should keep some states in a workflow. So I have to keep data in a session and have to care about concurrency. It would be so much easier to develop a normal desktop-application. But the client was clear on this (I wished everything in the spec would be so clear): he wants a web application.</p>
<p>I know that many people don't want to install applications, but here are two users, and I'm able to install it on the computers of them.</p>
<p>So I want to know: What are the reasons, why webapps are so popular these days? Is it a hype and in two years the clients will demand more desktop-applications? Or is there something about webapps that makes them especially sexy/appealing?</p>
| [
{
"answer_id": 291056,
"author": "Charles Bretana",
"author_id": 32632,
"author_profile": "https://Stackoverflow.com/users/32632",
"pm_score": 1,
"selected": false,
"text": " 1. They required no installation or deployment on client machines\n 2. They could not break other apps on the client machine. \n 3. They could be made to function on just about any computer in the world that had a browser and could connect to the application's web server.\n"
}
] | 2008/11/14 | [
"https://Stackoverflow.com/questions/291019",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21005/"
] |
291,031 | <p>Writing a JSP page, what exactly does the <code><c:out></code> do? I've noticed that the following both has the same result:</p>
<pre><code><p>The person's name is <c:out value="${person.name}" /></p>
<p>The person's name is ${person.name}</p>
</code></pre>
| [
{
"answer_id": 291047,
"author": "krosenvold",
"author_id": 23691,
"author_profile": "https://Stackoverflow.com/users/23691",
"pm_score": 8,
"selected": true,
"text": "c:out person.name = <script>alert(\"Yo\")</script> c:out"
},
{
"answer_id": 291081,
"author": "Chris Serra",
"author_id": 13435,
"author_profile": "https://Stackoverflow.com/users/13435",
"pm_score": 3,
"selected": false,
"text": "c:out person.name"
},
{
"answer_id": 291118,
"author": "alexmeia",
"author_id": 36587,
"author_profile": "https://Stackoverflow.com/users/36587",
"pm_score": 7,
"selected": false,
"text": "c:out <c:out value=\"${person.name}\">No name</c:out>\n"
}
] | 2008/11/14 | [
"https://Stackoverflow.com/questions/291031",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/24396/"
] |
291,033 | <p>I have just started to study computer sciences at my university where they teach us programming in Scheme.</p>
<p>Since I have learned C++ for the last 6 years, Scheme appears a little odd to me. My instructors tell me you can write any program you can write in C or Java with it. </p>
<p>Is anybody really using this language?</p>
| [
{
"answer_id": 291246,
"author": "Max Lybbert",
"author_id": 10593,
"author_profile": "https://Stackoverflow.com/users/10593",
"pm_score": 1,
"selected": false,
"text": "call/cc dynamic-wind dynamic-unwind"
}
] | 2008/11/14 | [
"https://Stackoverflow.com/questions/291033",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/37758/"
] |
291,037 | <p>What is the easiest way to set the contents of an <code><asp:ContentPlaceHolder></code> programmatically? I imagine ill have to do a <code>Master.FindControl</code> call?</p>
| [
{
"answer_id": 292133,
"author": "tvanfosson",
"author_id": 12950,
"author_profile": "https://Stackoverflow.com/users/12950",
"pm_score": 2,
"selected": false,
"text": "<asp:Content runat=\"server\" ID=\"myContent\" ContentPlaceHolderID=\"masterContent\">\n</asp:Content>\n public void Page_Load( object sender, EventArgs e )\n{\n HtmlContainerControl div = new HtmlGenericControl( \"DIV\" );\n div.innerHTML = \"....whatever...\";\n myContent.Controls.Clear();\n myContent.Controls.Add(div);\n}\n"
},
{
"answer_id": 292330,
"author": "flesh",
"author_id": 27805,
"author_profile": "https://Stackoverflow.com/users/27805",
"pm_score": 0,
"selected": false,
"text": "public static class ControlExtensions\n{\n /// <summary>\n /// recursive control search (extension method)\n /// </summary>\n public static Control FindControl(this Control control, string Id, ref Control found)\n {\n if (control.ID == Id)\n {\n found = control;\n }\n else\n {\n if (control.FindControl(Id) != null)\n {\n found = control.FindControl(Id);\n return found;\n }\n else\n {\n foreach (Control c in control.Controls)\n {\n if (found == null)\n c.FindControl(Id, ref found);\n else\n break;\n }\n\n }\n }\n return found;\n }\n}\n"
}
] | 2008/11/14 | [
"https://Stackoverflow.com/questions/291037",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/25515/"
] |
291,057 | <p>I am new to C#. I wanted to do a simple program with some type of loops.
I wanted my program to loop through the numbers that the user enters and if it is less than a number then write keep guessing,but once they enter the number 25 i wanted it to say Merry Christmas.. Please Help</p>
<pre><code>int number;
do
{
Console.WriteLine("Guess a number between 20 through 25");
number = int.Parse(Console.ReadLine());
} while (number < 25);
</code></pre>
<p>C# Beginner</p>
| [
{
"answer_id": 291072,
"author": "Gavin Miller",
"author_id": 33226,
"author_profile": "https://Stackoverflow.com/users/33226",
"pm_score": 1,
"selected": false,
"text": "int number;\n\ndo\n{\n Console.WriteLine(\"Guess a number between 20 through 25\");\n number = int.Parse(Console.ReadLine());\n} while (number < 25);\n\nif (number == 25)\n Console.WriteLine(\"Merry Christmas\");\n"
},
{
"answer_id": 291076,
"author": "Erick B",
"author_id": 1373,
"author_profile": "https://Stackoverflow.com/users/1373",
"pm_score": 3,
"selected": false,
"text": "int number = 0;\nwhile (number != 25)\n{\n Console.WriteLine(\"Guess a number between 20 through 25\");\n number = int.Parse(Console.ReadLine());\n if (number != 25)\n Console.WriteLine(\"Keep guessing\");\n else\n Console.WriteLine(\"Merry Christmas\");\n}\n"
},
{
"answer_id": 291084,
"author": "mannu",
"author_id": 15858,
"author_profile": "https://Stackoverflow.com/users/15858",
"pm_score": 0,
"selected": false,
"text": "int number;\n\ndo\n{\n Console.WriteLine(\"Guess a number between 20 through 25\");\n number = int.Parse(Console.ReadLine());\n} while (number != 25);\n\nConsole.WriteLine(\"Merry Christmas\");\n"
},
{
"answer_id": 291085,
"author": "k...m",
"author_id": 35090,
"author_profile": "https://Stackoverflow.com/users/35090",
"pm_score": 2,
"selected": false,
"text": "int number;\ndo\n{\n Console.WriteLine(\"Guess a number between 20 through 25\");\n int.TryParse(Console.ReadLine(), out number);\n} while (number != 25);\n"
},
{
"answer_id": 291184,
"author": "CodingWithSpike",
"author_id": 28278,
"author_profile": "https://Stackoverflow.com/users/28278",
"pm_score": 2,
"selected": false,
"text": " static void x()\n {\n Console.WriteLine(\"Guess a number between 20 through 25\");\n string input = null;\n while(true)\n {\n input = Console.ReadLine();\n if (input == null || input.Length == 0)\n break; // will exit the loop\n if (input != \"25\")\n Console.WriteLine(\"Keep guessing\");\n else\n {\n Console.WriteLine(\"Merry Christmas\");\n break;\n }\n }\n }\n"
},
{
"answer_id": 26922638,
"author": "Islam",
"author_id": 4250902,
"author_profile": "https://Stackoverflow.com/users/4250902",
"pm_score": 0,
"selected": false,
"text": " int myNumber;\n\n Guess: Console.Write(\"Guess a number between 20 through 25: \");\n myNumber = int.Parse(Console.ReadLine());\n\n while(myNumber != 25)\n {\n Console.WriteLine(\"Keep Guessing\");\n goto Guess;\n }\n Console.Write(\"Merry Christmas\");\n\n Console.ReadKey();\n"
}
] | 2008/11/14 | [
"https://Stackoverflow.com/questions/291057",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
291,059 | <p>I'm creating an asp.net app with just some lite data access from xml files. However, I need to be able to authenticate administrative users (via forms) to manage that data. I don't want to stand up a sql db just for authentication purposes. I'd like to use xml, but not sure about security with that. Any suggestions? Custom role provider? MyOpenID?</p>
| [
{
"answer_id": 291072,
"author": "Gavin Miller",
"author_id": 33226,
"author_profile": "https://Stackoverflow.com/users/33226",
"pm_score": 1,
"selected": false,
"text": "int number;\n\ndo\n{\n Console.WriteLine(\"Guess a number between 20 through 25\");\n number = int.Parse(Console.ReadLine());\n} while (number < 25);\n\nif (number == 25)\n Console.WriteLine(\"Merry Christmas\");\n"
},
{
"answer_id": 291076,
"author": "Erick B",
"author_id": 1373,
"author_profile": "https://Stackoverflow.com/users/1373",
"pm_score": 3,
"selected": false,
"text": "int number = 0;\nwhile (number != 25)\n{\n Console.WriteLine(\"Guess a number between 20 through 25\");\n number = int.Parse(Console.ReadLine());\n if (number != 25)\n Console.WriteLine(\"Keep guessing\");\n else\n Console.WriteLine(\"Merry Christmas\");\n}\n"
},
{
"answer_id": 291084,
"author": "mannu",
"author_id": 15858,
"author_profile": "https://Stackoverflow.com/users/15858",
"pm_score": 0,
"selected": false,
"text": "int number;\n\ndo\n{\n Console.WriteLine(\"Guess a number between 20 through 25\");\n number = int.Parse(Console.ReadLine());\n} while (number != 25);\n\nConsole.WriteLine(\"Merry Christmas\");\n"
},
{
"answer_id": 291085,
"author": "k...m",
"author_id": 35090,
"author_profile": "https://Stackoverflow.com/users/35090",
"pm_score": 2,
"selected": false,
"text": "int number;\ndo\n{\n Console.WriteLine(\"Guess a number between 20 through 25\");\n int.TryParse(Console.ReadLine(), out number);\n} while (number != 25);\n"
},
{
"answer_id": 291184,
"author": "CodingWithSpike",
"author_id": 28278,
"author_profile": "https://Stackoverflow.com/users/28278",
"pm_score": 2,
"selected": false,
"text": " static void x()\n {\n Console.WriteLine(\"Guess a number between 20 through 25\");\n string input = null;\n while(true)\n {\n input = Console.ReadLine();\n if (input == null || input.Length == 0)\n break; // will exit the loop\n if (input != \"25\")\n Console.WriteLine(\"Keep guessing\");\n else\n {\n Console.WriteLine(\"Merry Christmas\");\n break;\n }\n }\n }\n"
},
{
"answer_id": 26922638,
"author": "Islam",
"author_id": 4250902,
"author_profile": "https://Stackoverflow.com/users/4250902",
"pm_score": 0,
"selected": false,
"text": " int myNumber;\n\n Guess: Console.Write(\"Guess a number between 20 through 25: \");\n myNumber = int.Parse(Console.ReadLine());\n\n while(myNumber != 25)\n {\n Console.WriteLine(\"Keep Guessing\");\n goto Guess;\n }\n Console.Write(\"Merry Christmas\");\n\n Console.ReadKey();\n"
}
] | 2008/11/14 | [
"https://Stackoverflow.com/questions/291059",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10693/"
] |
291,102 | <p>I've decided to attempt using the <a href="https://blog.codinghorror.com/preventing-csrf-and-xsrf-attacks/" rel="nofollow noreferrer">double submitted cookies</a> technique to attempt to prevent XSRF attacks on the site I'm working on. So the way I have it written down here is, all actions that actually DO something other than GET information, will be posts. Gets will be...uh...GETs. Secondly, every form that posts will have the key/cookie combo.</p>
<p>My question is, what would be the easiest way to implement this in an ASP.NET MVC web application?</p>
<p>Not to answer my own question, but here are my initial thoughts:</p>
<p>Right now my controllers all inherit from a base controller, so my first thought was to override the OnActionExecuted method to check for the existence of the required form field, and from there if it finds it, verify it against the cookie and either allow the post to continue or kick it to some error page.</p>
<p>For the form portion I was thinking of generating my own html extension methods like... Html.BeginSecureForm() that overloads all of the same methods as BeginForm (In case I need them) but auto generates the Pseudorandom key and cookie and places the cookie and the form field inside the form (IF ITS A POST!) automagically.</p>
<p>Sorry, if this is kind of jumbled up, I have notes scattered throughout these pages and I'm trying to organize them. Part of that is to figure out my design for this XSRF security thing.</p>
| [
{
"answer_id": 819384,
"author": "Jeff Atwood",
"author_id": 1,
"author_profile": "https://Stackoverflow.com/users/1",
"pm_score": 0,
"selected": false,
"text": "Html.AntiForgeryToken()"
}
] | 2008/11/14 | [
"https://Stackoverflow.com/questions/291102",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/33910/"
] |
291,115 | <p>I'm using JScrollPane to allow scrolling in a JFrame that has a text component that's serving as a text editor. What I want to do, after setting the text in this editor, is have it scroll back up to the top, so you can see what's at the beginning of the file.</p>
<p>Does anyone know how to do this?</p>
| [
{
"answer_id": 291748,
"author": "Vincent Ramdhanie",
"author_id": 27439,
"author_profile": "https://Stackoverflow.com/users/27439",
"pm_score": 3,
"selected": false,
"text": " scrollPane.getViewport().setViewPosition(new Point(0,0));\n"
},
{
"answer_id": 3548638,
"author": "Eric Warriner",
"author_id": 236895,
"author_profile": "https://Stackoverflow.com/users/236895",
"pm_score": 5,
"selected": false,
"text": "final JScrollPane scroll = new JScrollPane(text);\njavax.swing.SwingUtilities.invokeLater(new Runnable() {\n public void run() { \n scroll.getVerticalScrollBar().setValue(0);\n }\n});\n"
},
{
"answer_id": 14469969,
"author": "Pb600",
"author_id": 1798878,
"author_profile": "https://Stackoverflow.com/users/1798878",
"pm_score": 3,
"selected": false,
"text": "DefaultCaret caret = (DefaultCaret) textArea.getCaret();\ncaret.setUpdatePolicy(DefaultCaret.NEVER_UPDATE);\n"
},
{
"answer_id": 32283824,
"author": "aosphyma",
"author_id": 5279331,
"author_profile": "https://Stackoverflow.com/users/5279331",
"pm_score": 3,
"selected": false,
"text": "setCaretPosition(0) setText(String t)"
},
{
"answer_id": 49819017,
"author": "Richard T",
"author_id": 26976,
"author_profile": "https://Stackoverflow.com/users/26976",
"pm_score": 2,
"selected": false,
"text": "textArea.setSelectionStart(0);\ntextArea.setSelectionEnd(0); \n"
}
] | 2008/11/14 | [
"https://Stackoverflow.com/questions/291115",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
291,117 | <p>So I've got a program that needs to be multilingual. The only difference between what I'm needing and what I've found on the web is that all the computers my program will run on are set to the localization of EN.</p>
<p>We have spanish speaking employees that will use the program just like the english speaking employees. So I won't be able to set something up based on the localization of the computer, it'll all have to be done in code.</p>
<p>I was thinking of trying to create an XML file (really just a dataset) for every form that I have and having each data table be a selectable language. In each table, it would have the information (control name, property, and text) to set the labels/checkboxes/etc that it needs to. I'll have to create a new form control so that I can have a generic function to go through and rename all of these controls if possible.</p>
<pre><code><DataSet>
<English>
<ControlName>labelHello</ControlName>
<ControlProperty>Text</ControlProperty>
<Text>Hello</Text>
</English>
<English>
<ControlName>labelBye</ControlName>
<ControlProperty>Text</ControlProperty>
<Text>Bye</Text>
</English>
<Spanish>
<ControlName>labelHello</ControlName>
<ControlProperty>Text</ControlProperty>
<Text>Hola</Text>
</Spanish>
</DataSet>
</code></pre>
<p>Also I didn't know much about the strings in the resources file for each form. Could I do it from there and use .Net functions to achieve this?</p>
<p>So I'm up for lots of suggestions because I really don't want to go back into the program I just wrote and put this in, I hate going back and adding more functionality once I've already spent so much time with this sucker...</p>
<p>Thanks</p>
| [
{
"answer_id": 291133,
"author": "Joe",
"author_id": 13087,
"author_profile": "https://Stackoverflow.com/users/13087",
"pm_score": 3,
"selected": true,
"text": "Thread.CurrentThread.CurrentUICulture = new CultureInfo(\"es-ES\");\n"
},
{
"answer_id": 294801,
"author": "GregUzelac",
"author_id": 27068,
"author_profile": "https://Stackoverflow.com/users/27068",
"pm_score": 1,
"selected": false,
"text": " resources.ApplyResources(this, \"$this\")\n"
}
] | 2008/11/14 | [
"https://Stackoverflow.com/questions/291117",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21828/"
] |
291,132 | <p>Are there any things to be careful about when defining the <code>method_missing</code> method in Ruby? I'm wondering whether there are some not-so-obvious interactions from inheritance, exception throwing, performance, or anything else.</p>
| [
{
"answer_id": 291718,
"author": "James A. Rosen",
"author_id": 1190,
"author_profile": "https://Stackoverflow.com/users/1190",
"pm_score": 7,
"selected": true,
"text": "respond_to? method_missing method_missing(:sym) respond_to?(:sym) # Wrap a Foo; don't expose the internal guts.\n# Pass any method that starts with 'a' on to the\n# Foo.\nclass FooWrapper\n def initialize(foo)\n @foo = foo\n end\n def some_method_that_doesnt_start_with_a\n 'bar'\n end\n def a_method_that_does_start_with_a\n 'baz'\n end\n def respond_to?(sym, include_private = false)\n pass_sym_to_foo?(sym) || super(sym, include_private)\n end\n def method_missing(sym, *args, &block)\n return foo.call(sym, *args, &block) if pass_sym_to_foo?(sym)\n super(sym, *args, &block)\n end\n private\n def pass_sym_to_foo?(sym)\n sym.to_s =~ /^a/ && @foo.respond_to?(sym)\n end\nend\n\nclass Foo\n def argh\n 'argh'\n end\n def blech\n 'blech'\n end\nend\n\nw = FooWrapper.new(Foo.new)\n\nw.respond_to?(:some_method_that_doesnt_start_with_a)\n# => true\nw.some_method_that_doesnt_start_with_a\n# => 'bar'\n\nw.respond_to?(:a_method_that_does_start_with_a)\n# => true\nw.a_method_that_does_start_with_a\n# => 'baz'\n\nw.respond_to?(:argh)\n# => true\nw.argh\n# => 'argh'\n\nw.respond_to?(:blech)\n# => false\nw.blech\n# NoMethodError\n\nw.respond_to?(:glem!)\n# => false\nw.glem!\n# NoMethodError\n\nw.respond_to?(:apples?)\nw.apples?\n# NoMethodError\n"
},
{
"answer_id": 292838,
"author": "Pistos",
"author_id": 28558,
"author_profile": "https://Stackoverflow.com/users/28558",
"pm_score": 4,
"selected": false,
"text": "selected_view_rows = @dbh.viewname( :column => value, ... )\n"
},
{
"answer_id": 297393,
"author": "James A. Rosen",
"author_id": 1190,
"author_profile": "https://Stackoverflow.com/users/1190",
"pm_score": 3,
"selected": false,
"text": "method_missing method_missing"
},
{
"answer_id": 42757631,
"author": "jack2684",
"author_id": 745170,
"author_profile": "https://Stackoverflow.com/users/745170",
"pm_score": 1,
"selected": false,
"text": "method_missing obj.call_method obj.send(:call_method) method_missing send"
},
{
"answer_id": 49017214,
"author": "Capripot",
"author_id": 1003472,
"author_profile": "https://Stackoverflow.com/users/1003472",
"pm_score": 2,
"selected": false,
"text": "respond_to_missing? respond_to? method(:method_name) class UserWrapper\n def initialize\n @json_user = { first_name: 'Jean', last_name: 'Dupont' }\n end\n\n def method_missing(sym, *args, &block)\n return @json_user[sym] if @json_user.keys.include?(sym)\n super\n end\n\n def respond_to_missing?(sym, include_private = false)\n @json_user.keys.include?(sym) || super\n end\nend\n irb(main):015:0> u = UserWrapper.new\n=> #<UserWrapper:0x00007fac7b0d3c28 @json_user={:first_name=>\"Jean\", :last_name=>\"Dupont\"}>\nirb(main):016:0> u.first_name\n=> \"Jean\"\nirb(main):017:0> u.respond_to?(:first_name)\n=> true\nirb(main):018:0> u.method(:first_name)\n=> #<Method: UserWrapper#first_name>\nirb(main):019:0> u.foo\nNoMethodError (undefined method `foo' for #<UserWrapper:0x00007fac7b0d3c28>)\n respond_to_missing? method_missing"
}
] | 2008/11/14 | [
"https://Stackoverflow.com/questions/291132",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4883/"
] |
291,135 | <pre><code> ArrayList filters = new ArrayList();
filters.Add(new string[] { "Name", "Equals", "John" });
ObjectDataSource1.SelectParameters.Add("AppliedFilters",
string.Join(",",(string[])filters.ToArray(typeof(string))));
</code></pre>
<p>Am trying to add a parameter to my object data source which is bound to my select method which should accept a string[]. But as the SelectParameters.Add takes in (string,string) or the other 3 overloads which do not seem to function for me correctly. </p>
<p>The select method accepts a string param though i prefer it accept a string[] or arraylist, but for now I can live with accepting a string which i should convert back to string[]</p>
<p>Resolution:
followed this article <a href="https://stackoverflow.com/questions/235166/how-do-i-set-up-objectdatasource-select-parameters-at-runtime">link text</a></p>
<p><strong>Closed</strong> as duplicate of the question referenced above.</p>
| [
{
"answer_id": 291718,
"author": "James A. Rosen",
"author_id": 1190,
"author_profile": "https://Stackoverflow.com/users/1190",
"pm_score": 7,
"selected": true,
"text": "respond_to? method_missing method_missing(:sym) respond_to?(:sym) # Wrap a Foo; don't expose the internal guts.\n# Pass any method that starts with 'a' on to the\n# Foo.\nclass FooWrapper\n def initialize(foo)\n @foo = foo\n end\n def some_method_that_doesnt_start_with_a\n 'bar'\n end\n def a_method_that_does_start_with_a\n 'baz'\n end\n def respond_to?(sym, include_private = false)\n pass_sym_to_foo?(sym) || super(sym, include_private)\n end\n def method_missing(sym, *args, &block)\n return foo.call(sym, *args, &block) if pass_sym_to_foo?(sym)\n super(sym, *args, &block)\n end\n private\n def pass_sym_to_foo?(sym)\n sym.to_s =~ /^a/ && @foo.respond_to?(sym)\n end\nend\n\nclass Foo\n def argh\n 'argh'\n end\n def blech\n 'blech'\n end\nend\n\nw = FooWrapper.new(Foo.new)\n\nw.respond_to?(:some_method_that_doesnt_start_with_a)\n# => true\nw.some_method_that_doesnt_start_with_a\n# => 'bar'\n\nw.respond_to?(:a_method_that_does_start_with_a)\n# => true\nw.a_method_that_does_start_with_a\n# => 'baz'\n\nw.respond_to?(:argh)\n# => true\nw.argh\n# => 'argh'\n\nw.respond_to?(:blech)\n# => false\nw.blech\n# NoMethodError\n\nw.respond_to?(:glem!)\n# => false\nw.glem!\n# NoMethodError\n\nw.respond_to?(:apples?)\nw.apples?\n# NoMethodError\n"
},
{
"answer_id": 292838,
"author": "Pistos",
"author_id": 28558,
"author_profile": "https://Stackoverflow.com/users/28558",
"pm_score": 4,
"selected": false,
"text": "selected_view_rows = @dbh.viewname( :column => value, ... )\n"
},
{
"answer_id": 297393,
"author": "James A. Rosen",
"author_id": 1190,
"author_profile": "https://Stackoverflow.com/users/1190",
"pm_score": 3,
"selected": false,
"text": "method_missing method_missing"
},
{
"answer_id": 42757631,
"author": "jack2684",
"author_id": 745170,
"author_profile": "https://Stackoverflow.com/users/745170",
"pm_score": 1,
"selected": false,
"text": "method_missing obj.call_method obj.send(:call_method) method_missing send"
},
{
"answer_id": 49017214,
"author": "Capripot",
"author_id": 1003472,
"author_profile": "https://Stackoverflow.com/users/1003472",
"pm_score": 2,
"selected": false,
"text": "respond_to_missing? respond_to? method(:method_name) class UserWrapper\n def initialize\n @json_user = { first_name: 'Jean', last_name: 'Dupont' }\n end\n\n def method_missing(sym, *args, &block)\n return @json_user[sym] if @json_user.keys.include?(sym)\n super\n end\n\n def respond_to_missing?(sym, include_private = false)\n @json_user.keys.include?(sym) || super\n end\nend\n irb(main):015:0> u = UserWrapper.new\n=> #<UserWrapper:0x00007fac7b0d3c28 @json_user={:first_name=>\"Jean\", :last_name=>\"Dupont\"}>\nirb(main):016:0> u.first_name\n=> \"Jean\"\nirb(main):017:0> u.respond_to?(:first_name)\n=> true\nirb(main):018:0> u.method(:first_name)\n=> #<Method: UserWrapper#first_name>\nirb(main):019:0> u.foo\nNoMethodError (undefined method `foo' for #<UserWrapper:0x00007fac7b0d3c28>)\n respond_to_missing? method_missing"
}
] | 2008/11/14 | [
"https://Stackoverflow.com/questions/291135",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.