qid int64 4 19.1M | question stringlengths 18 48.3k | answers list | date stringlengths 10 10 | metadata list |
|---|---|---|---|---|
345,025 | <p>I have an XML document looking similar to this:</p>
<pre><code><items>
<item cat="1" owner="14">bla</item>
<item cat="1" owner="9">bla</item>
<item cat="1" owner="14">bla</item>
<item cat="2" owner="12">bla</item>
<item cat="2" owner="12">bla</item>
</items>
</code></pre>
<p>Now I'd like to get all unique owners (I actually only need the attribute value of the owner) belonging to a specified category using a linq query. In my example, the query for cat 1 would return a list containing 9 and 14. How can I do that? Linq syntax would be preferred over Lambdas. Thanks in advance ;)</p>
| [
{
"answer_id": 345109,
"author": "Jennifer",
"author_id": 22360,
"author_profile": "https://Stackoverflow.com/users/22360",
"pm_score": 5,
"selected": true,
"text": "var distinctOwners = (from item in itemsElement.Element(\"item\") \n where itemElements.Attribute(\"cat\") == 1 \nselect item.Attribute(\"owner\")).Distinct();\n"
},
{
"answer_id": 345115,
"author": "AnthonyWJones",
"author_id": 17516,
"author_profile": "https://Stackoverflow.com/users/17516",
"pm_score": 2,
"selected": false,
"text": "static IEnumerable<int> GetOwners(XDocument doc, string cat)\n{\n return from item in doc.Descendants(\"item\")\n where item.Attribute(\"cat\").Value == cat\n select (int)item.Attribute(\"owner\")).Distinct();\n\n}\n"
},
{
"answer_id": 345121,
"author": "Theo",
"author_id": 43402,
"author_profile": "https://Stackoverflow.com/users/43402",
"pm_score": 0,
"selected": false,
"text": " XElement ele = XElement.Parse(@\"<items><item cat=\"\"1\"\" owner=\"\"14\"\">bla</item><item cat=\"\"1\"\" owner=\"\"9\"\">bla</item>\" +\n @\"<item cat=\"\"1\"\" owner=\"\"14\"\">bla</item><item cat=\"\"2\"\" owner=\"\"12\"\">bla</item>\" +\n @\"<item cat=\"\"2\"\" owner=\"\"12\"\">bla</item></items>\");\n\n int cat = 1;\n\n\n List<int> owners = ele.Elements(\"item\")\n .Where(x=>x.Attribute(\"cat\").Value==cat.ToString()).Select(x=>Convert.ToInt32(x.Attribute(\"owner\").Value)).Distinct().ToList();\n"
}
] | 2008/12/05 | [
"https://Stackoverflow.com/questions/345025",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16440/"
] |
345,041 | <p>say p.products_price equals 1</p>
<p>why does:</p>
<blockquote>
<pre><code>UPDATE products p
SET p.products_price = (1 + p.products_price)
WHERE p.products_id = 8
</code></pre>
</blockquote>
<p>make p.products_price equals 3?</p>
<p>It is adding 1 to the price and then doing it all over again? I am trying to do something a little more complicated but when it didn't work I broke it down to the simplest thing ever. Can I make some kind of temporary value here and calculate the new price and then set it to that?</p>
<p>Please help I am raging,
Thanks.</p>
<p>MySQL client version: 4.1.22</p>
<p>edit: the column is decimal type, i tried the same update on an int column with the same result.</p>
<p>edit: this is not running in code so there is no chance of the code calling the same update twice</p>
| [
{
"answer_id": 345208,
"author": "Matthew Rapati",
"author_id": 15000,
"author_profile": "https://Stackoverflow.com/users/15000",
"pm_score": 3,
"selected": false,
"text": "UPDATE products \nSET products_price = (1 + products_price) \nWHERE products_id = 8\n"
}
] | 2008/12/05 | [
"https://Stackoverflow.com/questions/345041",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15000/"
] |
345,042 | <p>I would like to shorten very long descriptions to the available table column width. I have the column width information in pixels. Now I would like to convert this measure to the number of characters, so I can shorten the text to the specified number.</p>
<p>I doesn't have to be 100% correct, a near assumption will also work.</p>
| [
{
"answer_id": 345099,
"author": "Diodeus - James MacFarlane",
"author_id": 12579,
"author_profile": "https://Stackoverflow.com/users/12579",
"pm_score": 2,
"selected": false,
"text": "<div id='test' style='width:200px;height:100px;overflow:hidden'>\n<p>Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Suspendisse at felis. Etiam ullamcorper. Aenean fringilla, eros eu dapibus tristique, erat lacus vestibulum metus, nec pharetra leo ante et quam. Nunc ac mi molestie justo placerat laoreet. Morbi eget dolor. Curabitur pretium, mi quis iaculis molestie, dolor ligula sagittis orci, at sodales quam dolor quis sem. Suspendisse vitae risus. Maecenas vestibulum dolor vel augue. Sed purus. Ut nisi massa, vestibulum id, lobortis eget, aliquet eu, enim. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos hymenaeos.</p>\n</div>\n<script type=\"text/javascript\">\nalert($('test').scrollHeight)\n</script>\n <div id='test' style='width:300px;height:100px;overflow:hidden'>\nLorem ipsum dolor sit amet, consectetuer adipiscing elit. Suspendisse at felis. Etiam ullamcorper. Aenean fringilla, eros eu dapibus tristique, erat lacus vestibulum metus, nec pharetra leo ante et quam. Nunc ac mi molestie justo placerat laoreet. Morbi eget dolor. Curabitur pretium, mi quis iaculis molestie, dolor ligula sagittis orci, at sodales quam dolor quis sem. Suspendisse vitae risus. Maecenas vestibulum dolor vel augue. Sed purus. Ut nisi massa, vestibulum id, lobortis eget, aliquet eu, enim. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos hymenaeos.\n</div>\n<script type=\"text/javascript\">\nfunction shorten(element) { \n if($(element).scrollHeight>$(element).getHeight()) {\n var myText = $(element).innerHTML.split(\" \")\n myText.length=myText.length-2\n $(element).update(myText.join(\" \")+\" ...\")\n window.setTimeout('shorten(\"'+element+'\")',1)\n }\n\n}\nshorten('test')\n</script>\n"
},
{
"answer_id": 4325910,
"author": "Edd",
"author_id": 221238,
"author_profile": "https://Stackoverflow.com/users/221238",
"pm_score": 1,
"selected": false,
"text": "p#descr1 { height:46px; overflow:hidden; }\n\n<script type=\"text/javascript\">\n\n function shorten(element) {\n if ($(element).attr('scrollHeight') > $(element).height()) {\n var myText = $(element).text().split(\" \")\n myText.length = myText.length - 2\n $(element).html(myText.join(\" \") + \" ...\")\n window.setTimeout('shorten(\"' + element + '\")', 1)\n }\n }\n\n $(document).ready(function () {\n shorten('#descr1'); // the id of the container\n\n });\n\n</script>\n"
},
{
"answer_id": 8856636,
"author": "Pat",
"author_id": 1148432,
"author_profile": "https://Stackoverflow.com/users/1148432",
"pm_score": 2,
"selected": false,
"text": "overflow: hidden;\ntext-overflow: ellipsis;\nwhite-space: nowrap;\n"
}
] | 2008/12/05 | [
"https://Stackoverflow.com/questions/345042",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6482/"
] |
345,045 | <p>I have a C++ DLL including bitmap resources created by Visual Studio.</p>
<p>Though I can load the DLL in VB6 using LoadLibrary, I cannot load the image resources either by using LoadImage or by using LoadBitmap. When I try to get the error using GetLastError(), it doesnot return any errors.</p>
<p>I have tried using LoadImage and LoadBitmap in another C++ program with the same DLL and they work without any problems.</p>
<p>Is there any other way of accessing the resource bitmaps in C++ DLLs using VB6?</p>
| [
{
"answer_id": 345123,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "Private Declare Function LoadLibrary Lib \"kernel32\" Alias \"LoadLibraryA\" (ByVal lpLibFileName As String) As Long\n\nPrivate Declare Function LoadBitmap Lib \"user32\" Alias \"LoadBitmapA\" (ByVal hInstance As Long, ByVal lpBitmapName As String) As Long\n\nDLLHandle = LoadLibrary(\"Mydll.dll\")\n\nmyimage = LoadBitmap(DLLHandle, \"101\")\n myimage 0 DLLHandle imagehandle = LoadBitmap(DLLHandle,LPCSTR(101));\n"
},
{
"answer_id": 345213,
"author": "efotinis",
"author_id": 12320,
"author_profile": "https://Stackoverflow.com/users/12320",
"pm_score": 2,
"selected": true,
"text": "DLLHandle = LoadLibrary(\"Mydll.dll\")\nmyimage = LoadBitmap(DLLHandle, \"#101\") ' note the \"#\"\n imagehandle = LoadBitmap(DLLHandle, MAKEINTRESOURCE(101));\n"
}
] | 2008/12/05 | [
"https://Stackoverflow.com/questions/345045",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
345,047 | <p>A weird bug was occurring in production which I was asked to look into.<br/> The issue was tracked down to a couple of variables being declared within a For loop and not being initialized on each iteration. An assumption had been made that due to the scope of their declaration they would be "reset" on each iteration. <br/>Could someone explain why they would not be)?<br />
(My first question, really looking forward to the responses.)<br/>
The example below is obviously not the code in question but reflects the scenario: <br/>
Please excuse the code example, it looks fine in the editor preview??</p>
<pre><code>for (int i =0; i< 10; i++)
{
decimal? testDecimal;
string testString;
switch( i % 2 )
{
case 0:
testDecimal = i / ( decimal ).32;
testString = i.ToString();
break;
default:
testDecimal = null;
testString = null;
break;
}
Console.WriteLine( "Loop {0}: testDecimal={1} - testString={2}", i, testDecimal , testString );
}
</code></pre>
<hr />
<h3>EDIT:</h3>
<p>Sorry, had to rush out for child care issue. The issue was that the prod code had was that the switch statement was huge and in some "case"'s a check on a class' property was being made, like if (myObject.Prop != null) then testString = myObject.Stringval... At the end of the switch, (outside) a check on testString == null was being made but it was holding the value from the last iteration,hence not being null as the coder assumed with the variable being declared within the loop.<br/> Sorry if my question and example was a bit off, I got the phone call about the day care as I was banging it together. I should have mentioned I compared IL from both variables in and out the loop. So, is the common opinion that "obviously the variables would not be reinitialized on each loop"?<br>
A little more info, the variables WHERE being initialized on each iteration until someone got over enthusiastic with ReSharper pointing out "the value is never used" and removed them.</p>
<hr />
<h3>EDIT:</h3>
<p>Folks, I thank you all. As my first post I see how much clearer I should be in the future. The cause of our unexpected variable assignment can me placed on an inexperienced developer doing everything ReSharper told him and not running any unit tests after he ran a "Code Cleanup" on an entire solution. Looking at the history of this module in VSS I see variables Where declared outside of the loop and where initialized on each iteration. The person in question wanted his ReSharper to show "all green" so "moved his variables closer to assignment" then "Removed redundant assignment"! I don't think he will be doing it again...now to spend the weekend running all the unit tests he missed!<br/> How to do mark a question as answered?</p>
| [
{
"answer_id": 345173,
"author": "Grant Wagner",
"author_id": 9254,
"author_profile": "https://Stackoverflow.com/users/9254",
"pm_score": 2,
"selected": false,
"text": "Loop 0: testDecimal=0 - testString=0\nLoop 1: testDecimal= - testString=\nLoop 2: testDecimal=6.25 - testString=2\nLoop 3: testDecimal= - testString=\nLoop 4: testDecimal=12.5 - testString=4\nLoop 5: testDecimal= - testString=\nLoop 6: testDecimal=18.75 - testString=6\nLoop 7: testDecimal= - testString=\nLoop 8: testDecimal=25 - testString=8\nLoop 9: testDecimal= - testString=\n"
},
{
"answer_id": 345267,
"author": "Ron Todosichuk",
"author_id": 43294,
"author_profile": "https://Stackoverflow.com/users/43294",
"pm_score": -1,
"selected": false,
"text": "private void LoopTest()\n{\n for (int i =0; i< 10; i++)\n {\n DoWork(i);\n }\n}\n\nprivate void Work(int i)\n{\n decimal? testDecimal;\n string testString;\n\n switch (i % 2)\n {\n case 0:\n testDecimal = i / (decimal).32;\n testString = i.ToString();\n break;\n default:\n testDecimal = null;\n testString = null;\n break;\n }\n Console.WriteLine( \"Loop {0}: testDecimal={1} - testString={2}\", i, testDecimal , testString );\n}\n"
},
{
"answer_id": 345274,
"author": "Grant Wagner",
"author_id": 9254,
"author_profile": "https://Stackoverflow.com/users/9254",
"pm_score": 4,
"selected": false,
"text": "using System;\n\nclass A\n{\n public static void Main()\n {\n for (int i =0; i< 10; i++)\n {\n decimal? testDecimal;\n string testString;\n switch( i % 2 )\n {\n case 0:\n testDecimal = i / ( decimal ).32;\n testString = i.ToString();\n break;\n default:\n testDecimal = null;\n testString = null;\n break;\n }\n\n Console.WriteLine( \"Loop {0}: testDecimal={1} - testString={2}\", i, testDecimal , testString );\n }\n }\n}\n .method public hidebysig static void Main() cil managed\n{\n .entrypoint\n .maxstack 8\n .locals init (\n [0] int32 num,\n [1] valuetype [mscorlib]System.Nullable`1<valuetype [mscorlib]System.Decimal> nullable,\n [2] string str,\n [3] int32 num2,\n [4] bool flag)\n L_0000: nop \n L_0001: ldc.i4.0 \n L_0002: stloc.0 \n L_0003: br.s L_0061\n L_0005: nop \n L_0006: ldloc.0 \n L_0007: ldc.i4.2 \n L_0008: rem \n L_0009: stloc.3 \n L_000a: ldloc.3 \n L_000b: ldc.i4.0 \n L_000c: beq.s L_0010\n L_000e: br.s L_0038\n L_0010: ldloca.s nullable\n L_0012: ldloc.0 \n L_0013: call valuetype [mscorlib]System.Decimal [mscorlib]System.Decimal::op_Implicit(int32)\n L_0018: ldc.i4.s 0x20\n L_001a: ldc.i4.0 \n L_001b: ldc.i4.0 \n L_001c: ldc.i4.0 \n L_001d: ldc.i4.2 \n L_001e: newobj instance void [mscorlib]System.Decimal::.ctor(int32, int32, int32, bool, uint8)\n L_0023: call valuetype [mscorlib]System.Decimal [mscorlib]System.Decimal::op_Division(valuetype [mscorlib]System.Decimal, valuetype [mscorlib]System.Decimal)\n L_0028: call instance void [mscorlib]System.Nullable`1<valuetype [mscorlib]System.Decimal>::.ctor(!0)\n L_002d: nop \n L_002e: ldloca.s num\n L_0030: call instance string [mscorlib]System.Int32::ToString()\n L_0035: stloc.2 \n L_0036: br.s L_0044\n L_0038: ldloca.s nullable\n L_003a: initobj [mscorlib]System.Nullable`1<valuetype [mscorlib]System.Decimal>\n L_0040: ldnull \n L_0041: stloc.2 \n L_0042: br.s L_0044\n L_0044: ldstr \"Loop {0}: testDecimal={1} - testString={2}\"\n L_0049: ldloc.0 \n L_004a: box int32\n L_004f: ldloc.1 \n L_0050: box [mscorlib]System.Nullable`1<valuetype [mscorlib]System.Decimal>\n L_0055: ldloc.2 \n L_0056: call void [mscorlib]System.Console::WriteLine(string, object, object, object)\n L_005b: nop \n L_005c: nop \n L_005d: ldloc.0 \n L_005e: ldc.i4.1 \n L_005f: add \n L_0060: stloc.0 \n L_0061: ldloc.0 \n L_0062: ldc.i4.s 10\n L_0064: clt \n L_0066: stloc.s flag\n L_0068: ldloc.s flag\n L_006a: brtrue.s L_0005\n L_006c: ret \n}\n using System;\n\nclass A\n{\n public static void Main()\n {\n decimal? testDecimal;\n string testString;\n\n for (int i =0; i< 10; i++)\n {\n switch( i % 2 )\n {\n case 0:\n testDecimal = i / ( decimal ).32;\n testString = i.ToString();\n break;\n default:\n testDecimal = null;\n testString = null;\n break;\n }\n\n Console.WriteLine( \"Loop {0}: testDecimal={1} - testString={2}\", i, testDecimal , testString );\n }\n }\n}\n .method public hidebysig static void Main() cil managed\n{\n .entrypoint\n .maxstack 8\n .locals init (\n [0] valuetype [mscorlib]System.Nullable`1<valuetype [mscorlib]System.Decimal> nullable,\n [1] string str,\n [2] int32 num,\n [3] int32 num2,\n [4] bool flag)\n L_0000: nop \n L_0001: ldc.i4.0 \n L_0002: stloc.2 \n L_0003: br.s L_0061\n L_0005: nop \n L_0006: ldloc.2 \n L_0007: ldc.i4.2 \n L_0008: rem \n L_0009: stloc.3 \n L_000a: ldloc.3 \n L_000b: ldc.i4.0 \n L_000c: beq.s L_0010\n L_000e: br.s L_0038\n L_0010: ldloca.s nullable\n L_0012: ldloc.2 \n L_0013: call valuetype [mscorlib]System.Decimal [mscorlib]System.Decimal::op_Implicit(int32)\n L_0018: ldc.i4.s 0x20\n L_001a: ldc.i4.0 \n L_001b: ldc.i4.0 \n L_001c: ldc.i4.0 \n L_001d: ldc.i4.2 \n L_001e: newobj instance void [mscorlib]System.Decimal::.ctor(int32, int32, int32, bool, uint8)\n L_0023: call valuetype [mscorlib]System.Decimal [mscorlib]System.Decimal::op_Division(valuetype [mscorlib]System.Decimal, valuetype [mscorlib]System.Decimal)\n L_0028: call instance void [mscorlib]System.Nullable`1<valuetype [mscorlib]System.Decimal>::.ctor(!0)\n L_002d: nop \n L_002e: ldloca.s num\n L_0030: call instance string [mscorlib]System.Int32::ToString()\n L_0035: stloc.1 \n L_0036: br.s L_0044\n L_0038: ldloca.s nullable\n L_003a: initobj [mscorlib]System.Nullable`1<valuetype [mscorlib]System.Decimal>\n L_0040: ldnull \n L_0041: stloc.1 \n L_0042: br.s L_0044\n L_0044: ldstr \"Loop {0}: testDecimal={1} - testString={2}\"\n L_0049: ldloc.2 \n L_004a: box int32\n L_004f: ldloc.0 \n L_0050: box [mscorlib]System.Nullable`1<valuetype [mscorlib]System.Decimal>\n L_0055: ldloc.1 \n L_0056: call void [mscorlib]System.Console::WriteLine(string, object, object, object)\n L_005b: nop \n L_005c: nop \n L_005d: ldloc.2 \n L_005e: ldc.i4.1 \n L_005f: add \n L_0060: stloc.2 \n L_0061: ldloc.2 \n L_0062: ldc.i4.s 10\n L_0064: clt \n L_0066: stloc.s flag\n L_0068: ldloc.s flag\n L_006a: brtrue.s L_0005\n L_006c: ret \n}\n .locals init ( ... )"
},
{
"answer_id": 345523,
"author": "Marc Gravell",
"author_id": 23354,
"author_profile": "https://Stackoverflow.com/users/23354",
"pm_score": 5,
"selected": true,
"text": " int value;\n for (int i = 0; i < 5; i++)\n {\n value = i;\n ThreadPool.QueueUserWorkItem(delegate { Console.WriteLine(value); });\n }\n Console.ReadLine();\n for (int i = 0; i < 5; i++)\n {\n int value = i;\n ThreadPool.QueueUserWorkItem(delegate { Console.WriteLine(value); });\n }\n Console.ReadLine();\n"
}
] | 2008/12/05 | [
"https://Stackoverflow.com/questions/345047",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12875/"
] |
345,068 | <p>I would like to have a single DatagramSocket to listen for both unicast and broadcast messages. Is this possible?</p>
| [
{
"answer_id": 346241,
"author": "Alnitak",
"author_id": 6782,
"author_profile": "https://Stackoverflow.com/users/6782",
"pm_score": 4,
"selected": true,
"text": "INADDR_ANY"
}
] | 2008/12/05 | [
"https://Stackoverflow.com/questions/345068",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/420/"
] |
345,091 | <p>I'm reviewing some code for a friend and say that he was using a return statement inside of a try-finally block. Does the code in the Finally section still fire even though the rest of the try block doesn't?</p>
<p>Example:</p>
<pre><code>public bool someMethod()
{
try
{
return true;
throw new Exception("test"); // doesn't seem to get executed
}
finally
{
//code in question
}
}
</code></pre>
| [
{
"answer_id": 345103,
"author": "mmx",
"author_id": 33708,
"author_profile": "https://Stackoverflow.com/users/33708",
"pm_score": 8,
"selected": false,
"text": "OutOfMemoryException StackOverflowException"
},
{
"answer_id": 345270,
"author": "Jon B",
"author_id": 27414,
"author_profile": "https://Stackoverflow.com/users/27414",
"pm_score": 7,
"selected": false,
"text": "class Class1\n{\n [STAThread]\n static void Main(string[] args)\n {\n Console.WriteLine(\"before\");\n Console.WriteLine(test());\n Console.WriteLine(\"after\");\n }\n\n static string test()\n {\n try\n {\n return \"return\";\n }\n finally\n {\n Console.WriteLine(\"finally\");\n }\n }\n}\n before\nfinally\nreturn\nafter\n"
},
{
"answer_id": 6456319,
"author": "markn",
"author_id": 812228,
"author_profile": "https://Stackoverflow.com/users/812228",
"pm_score": 4,
"selected": false,
"text": "// No code can appear after this line, before the try\nRuntimeHelpers.PrepareConstrainedRegions();\ntry\n{ \n // This is *NOT* a CER\n}\nfinally\n{\n // This is a CER; guaranteed to run, if the try was entered, \n // even if a StackOverflowException occurs.\n}\n"
},
{
"answer_id": 24546267,
"author": "Hakuna Matata",
"author_id": 2928237,
"author_profile": "https://Stackoverflow.com/users/2928237",
"pm_score": 2,
"selected": false,
"text": "try\n{\n System.out.println(\"try\");\n System.exit(0);\n}\nfinally\n{\n System.out.println(\"finally\");\n}\n"
},
{
"answer_id": 34312499,
"author": "Jonathan Perry",
"author_id": 273549,
"author_profile": "https://Stackoverflow.com/users/273549",
"pm_score": 0,
"selected": false,
"text": "finally try finally catch finally"
},
{
"answer_id": 48503709,
"author": "Ken Smith",
"author_id": 68231,
"author_profile": "https://Stackoverflow.com/users/68231",
"pm_score": 4,
"selected": false,
"text": "catch StackOverflowExceptions try/catch/finally try/catch finally finally static void Main(string[] args)\n{\n Console.WriteLine(\"Beginning demo of how finally clause doesn't get executed\");\n try\n {\n Console.WriteLine(\"Inside try but before exception.\");\n throw new Exception(\"Exception #1\");\n }\n catch (Exception ex)\n {\n Console.WriteLine($\"Inside catch for the exception '{ex.Message}' (before throwing another exception).\");\n throw;\n }\n finally\n {\n Console.WriteLine(\"This never gets executed, and that seems very, very wrong.\");\n }\n\n Console.WriteLine(\"This never gets executed, but I wasn't expecting it to.\"); \n Console.ReadLine();\n}\n"
}
] | 2008/12/05 | [
"https://Stackoverflow.com/questions/345091",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/28540/"
] |
345,111 | <p>I want to put my dependent files in the app directory.</p>
<p>I seem to remember that you can force VB6 to use the files in the local directory only.</p>
<p>Any hints?</p>
| [
{
"answer_id": 346077,
"author": "Joel Spolsky",
"author_id": 4,
"author_profile": "https://Stackoverflow.com/users/4",
"pm_score": 3,
"selected": false,
"text": "A.EXE A.EXE.local"
}
] | 2008/12/05 | [
"https://Stackoverflow.com/questions/345111",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4906/"
] |
345,147 | <p>i'm trying to send fake keyboard input to an application that's running in a Remote Desktop session. i'm using:</p>
<pre><code>Byte key = Ord("A");
keybd_event(key, 0, 0, 0); // key goes down
keybd_event(key, 0, KEYEVENTF_KEYUP, 0); // key goes up
</code></pre>
<p>Now this code does send the character "a" to any local window, but it will not send to the remote desktop window. </p>
<p>What that means is i use Remote Desktop to connect to a server, and i then open Notepad on that server. If i manually punch keys on the keyboard: they appear in Notepad's editor window. But keybd_event's fake keyboard input not causing "a"'s to appear in Notepad.</p>
<p>How can i programtically send fake keyboard input to an application running inside a remote desktop connection, from an application running on the local machine?</p>
<hr>
<p><strong>Nitpickers Corner</strong></p>
<p>In this particular case i want to do this becase i'm trying to defeat an idle-timeout. But i could just as well be trying to </p>
<ul>
<li>perform UI automation tests</li>
<li>UI stress tests</li>
<li>UI fault finding tests</li>
<li>UI unit tests</li>
<li>UI data input tests</li>
<li>UI paint tests</li>
<li>or UI resiliance tests. </li>
</ul>
<p>In other words, my reasons for wanting it aren't important</p>
<p><strong>Note:</strong> The timeout may be from remote desktop inactivity, or perhaps not. i don't know, and it doesn't affect my question.</p>
| [
{
"answer_id": 345302,
"author": "Ian Boyd",
"author_id": 12597,
"author_profile": "https://Stackoverflow.com/users/12597",
"pm_score": 4,
"selected": true,
"text": "Byte key = Ord(\"A\");\n\nkeybd_event(key, 0x1E, 0, 0); // key goes down\nkeybd_event(key, 0x9E, KEYEVENTF_KEYUP, 0); // key goes up\n"
},
{
"answer_id": 2332193,
"author": "selwyn",
"author_id": 16314,
"author_profile": "https://Stackoverflow.com/users/16314",
"pm_score": 2,
"selected": false,
"text": "int scan;\nscan = MapVirtualKey(key & 0xff, 0);\nkeybd_event(key, scan, 0, 0); // key goes down\nkeybd_event(key, scan | 0x80, KEYEVENTF_KEYUP, 0); // key goes up\n"
}
] | 2008/12/05 | [
"https://Stackoverflow.com/questions/345147",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12597/"
] |
345,157 | <p>I redirect the user to the login page when user click log out however I don't think it clears any application or session because all the data persisted when the user logs back in.</p>
<p>Currently the login page has a login control and the code behind on the page is only wired up the login Authenticate.</p>
<p>Can someone direct me to a good tutorial or article about handling log in and out of ASP.NET web sites?</p>
| [
{
"answer_id": 345164,
"author": "Ryan Cook",
"author_id": 43029,
"author_profile": "https://Stackoverflow.com/users/43029",
"pm_score": 7,
"selected": true,
"text": "Session.Abandon()\n HttpSessionState"
},
{
"answer_id": 345175,
"author": "AnthonyWJones",
"author_id": 17516,
"author_profile": "https://Stackoverflow.com/users/17516",
"pm_score": 4,
"selected": false,
"text": "Session.Abandon() Session.Clear()"
},
{
"answer_id": 6124495,
"author": "Lucky",
"author_id": 769555,
"author_profile": "https://Stackoverflow.com/users/769555",
"pm_score": 1,
"selected": false,
"text": "<script runat=\"server\"> \n protected void Page_Load(object sender, System.EventArgs e) { \n Session[\"FavoriteSoftware\"] = \"Adobe ColdFusion\"; \n Label1.Text = \"Session read...<br />\"; \n Label1.Text += \"Favorite Software : \" + Session[\"FavoriteSoftware\"]; \n Label1.Text += \"<br />SessionID : \" + Session.SessionID; \n Label1.Text += \"<br> Now clear the current session data.\"; \n Session.Clear(); \n Label1.Text += \"<br /><br />SessionID : \" + Session.SessionID; \n Label1.Text += \"<br />Favorite Software[after clear]: \" + Session[\"FavoriteSoftware\"]; \n } \n</script> \n\n\n\n<html xmlns=\"http://www.w3.org/1999/xhtml\"> \n<head id=\"Head1\" runat=\"server\"> \n <title>asp.net session Clear example: how to clear the current session data (remove all the session items)</title> \n</head> \n<body> \n <form id=\"form1\" runat=\"server\"> \n <div> \n <h2 style=\"color:Teal\">asp.net session example: Session Clear</h2> \n <asp:Label \n ID=\"Label1\" \n runat=\"server\" \n Font-Size=\"Large\" \n ForeColor=\"DarkMagenta\" \n > \n </asp:Label> \n </div> \n </form> \n</body> \n</html> \n"
},
{
"answer_id": 12017502,
"author": "BrainCoder",
"author_id": 1245631,
"author_profile": "https://Stackoverflow.com/users/1245631",
"pm_score": 4,
"selected": false,
"text": "Session.Abandon() Session_OnEnd Session.Clear() session with the same key alive Session.Abandon() new session key logs out Session.Clear()"
},
{
"answer_id": 26936348,
"author": "kat1330",
"author_id": 3380837,
"author_profile": "https://Stackoverflow.com/users/3380837",
"pm_score": 5,
"selected": false,
"text": "aspnet_sessionID HttpContext.Current.Session.Clear();\nHttpContext.Current.Session.Abandon();\nHttpContext.Current.Response.Cookies.Add(new HttpCookie(\"ASP.NET_SessionId\", \"\"));\n"
},
{
"answer_id": 34626605,
"author": "Darshan",
"author_id": 5733838,
"author_profile": "https://Stackoverflow.com/users/5733838",
"pm_score": -1,
"selected": false,
"text": " protected void Application_BeginRequest()\n {\n Response.Cache.SetCacheability(HttpCacheability.NoCache);\n Response.Cache.SetExpires(DateTime.Now.AddHours(-1));\n Response.Cache.SetNoStore();\n }\n"
},
{
"answer_id": 48334650,
"author": "Padhraic",
"author_id": 4476246,
"author_profile": "https://Stackoverflow.com/users/4476246",
"pm_score": 2,
"selected": false,
"text": "Abandon() //Removes all entries from the current session, if any. The session cookie is not removed.\nHttpContext.Session.Clear()\n //Removes all keys and values from the session-state collection.\nHttpContext.Current.Session.Clear(); \n\n//Cancels the current session.\nHttpContext.Current.Session.Abandon();\n"
},
{
"answer_id": 72898552,
"author": "Vishal Yelve",
"author_id": 4879197,
"author_profile": "https://Stackoverflow.com/users/4879197",
"pm_score": 0,
"selected": false,
"text": "[HttpPost]\n public IActionResult Logout()\n {\n try\n {\n CookieOptions option = new CookieOptions();\n if (Request.Cookies[AllSessionKeys.AuthenticationToken] != null)\n {\n option.Expires = DateTime.Now.AddDays(-1);\n Response.Cookies.Append(AllSessionKeys.AuthenticationToken, \"\", option);\n }\n\n HttpContext.Session.Clear();\n return RedirectToAction(\"Login\", \"Portal\");\n }\n catch (Exception)\n {\n throw;\n }\n }\n"
}
] | 2008/12/05 | [
"https://Stackoverflow.com/questions/345157",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/28647/"
] |
345,174 | <p>I need to be able to determine when <code>ContainsFocus</code> changes on a <code>Control</code> (specifically a windows form). Overriding <code>OnGotFocus</code> is not the answer. When I bring the form to the foreground, <code>ContainsFocus</code> is true and <code>Focused</code> is false. So is there an <code>OnGotFocus</code> equivalent for <code>ContainsFocus</code>? Or any other way?</p>
| [
{
"answer_id": 345177,
"author": "Mike Hall",
"author_id": 18202,
"author_profile": "https://Stackoverflow.com/users/18202",
"pm_score": 1,
"selected": false,
"text": "private Timer m_checkContainsFocusTimer = new Timer();\nprivate bool m_containsFocus = true;\n\nm_checkContainsFocusTimer.Interval = 1000; // every second is good enough\nm_checkContainsFocusTimer.Tick += new EventHandler(CheckContainsFocusTimer_Tick);\nm_checkContainsFocusTimer.Start();\n\nprivate void CheckContainsFocusTimer_Tick(object sender, EventArgs e)\n{\n if (!m_containsFocus && ContainsFocus)\n OnAppGotFocus();\n\n m_containsFocus = ContainsFocus;\n}\n"
},
{
"answer_id": 345365,
"author": "Eren Aygunes",
"author_id": 27980,
"author_profile": "https://Stackoverflow.com/users/27980",
"pm_score": 3,
"selected": true,
"text": " bool lastNotificationWasGotFocus = false;\n\n protected override void OnControlAdded(ControlEventArgs e)\n {\n SubscribeEvents(e.Control);\n base.OnControlAdded(e);\n }\n\n protected override void OnControlRemoved(ControlEventArgs e)\n {\n UnsubscribeEvents(e.Control);\n base.OnControlRemoved(e);\n }\n\n private void SubscribeEvents(Control control)\n {\n control.GotFocus += new EventHandler(control_GotFocus);\n control.LostFocus += new EventHandler(control_LostFocus);\n control.ControlAdded += new ControlEventHandler(control_ControlAdded);\n control.ControlRemoved += new ControlEventHandler(control_ControlRemoved);\n\n foreach (Control innerControl in control.Controls)\n {\n SubscribeEvents(innerControl);\n }\n }\n\n private void UnsubscribeEvents(Control control)\n {\n control.GotFocus -= new EventHandler(control_GotFocus);\n control.LostFocus -= new EventHandler(control_LostFocus);\n control.ControlAdded -= new ControlEventHandler(control_ControlAdded);\n control.ControlRemoved -= new ControlEventHandler(control_ControlRemoved);\n\n foreach (Control innerControl in control.Controls)\n {\n UnsubscribeEvents(innerControl);\n }\n }\n\n private void control_ControlAdded(object sender, ControlEventArgs e)\n {\n SubscribeEvents(e.Control);\n }\n\n private void control_ControlRemoved(object sender, ControlEventArgs e)\n {\n UnsubscribeEvents(e.Control);\n }\n\n protected override void OnGotFocus(EventArgs e)\n {\n CheckContainsFocus();\n base.OnGotFocus(e);\n }\n\n protected override void OnLostFocus(EventArgs e)\n {\n CheckLostFocus();\n base.OnLostFocus(e);\n }\n\n private void control_GotFocus(object sender, EventArgs e)\n {\n CheckContainsFocus();\n }\n\n private void control_LostFocus(object sender, EventArgs e)\n {\n CheckLostFocus();\n }\n\n private void CheckContainsFocus()\n {\n if (lastNotificationWasGotFocus == false)\n {\n lastNotificationWasGotFocus = true;\n OnContainsFocus();\n }\n }\n\n private void CheckLostFocus()\n {\n if (ContainsFocus == false)\n {\n lastNotificationWasGotFocus = false;\n OnLostFocus();\n }\n }\n\n private void OnContainsFocus()\n {\n Console.WriteLine(\"I have the power of focus!\");\n }\n\n private void OnLostFocus()\n {\n Console.WriteLine(\"I lost my power...\");\n }\n"
}
] | 2008/12/05 | [
"https://Stackoverflow.com/questions/345174",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18202/"
] |
345,178 | <p>I can do this:</p>
<pre><code>Dim fso As New FileSystemObject
</code></pre>
<p>or I can do this:</p>
<pre><code>Dim fso As Object
Set fso = CreateObject("Scripting.FileSystemObject")
</code></pre>
<p>How do I know what string to use for CreateObject? For example, how would I know to use the "Scripting." part of "Scripting.FileSystemObject"? Where do you go to look that up?</p>
| [
{
"answer_id": 345184,
"author": "huseyint",
"author_id": 39,
"author_profile": "https://Stackoverflow.com/users/39",
"pm_score": 6,
"selected": true,
"text": "HKEY_CLASSES_ROOT\\Scripting.FileSystemObject\n HKEY_CLASSES_ROOT\\CLSID\\{0D43FE01-F093-11CF-8940-00A0C9054228}\n"
}
] | 2008/12/05 | [
"https://Stackoverflow.com/questions/345178",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16415/"
] |
345,179 | <p>I am writing a deployment script using MSBuild. I want to clean my web directories prior to copying all the new files in. My current "Clean" target looks like this:</p>
<pre><code> <Target Name="Clean">
<Exec Command="del %(DeploymentSet.LocalWebRoot)\* /Q /F /S" IgnoreExitCode="true" />
</Target>
</code></pre>
<p>This takes an considerable amount of time as each file is deleted from each subfolder individually.</p>
<p>Is there a nice way to remove everything from a given folder with out deleting that folder? I want to maintain my permissions and vdir setup info.</p>
| [
{
"answer_id": 345202,
"author": "Patrick Cuff",
"author_id": 7903,
"author_profile": "https://Stackoverflow.com/users/7903",
"pm_score": 2,
"selected": true,
"text": "rmdir /s /q del %(DeploymentSet.LocalWebRoot)\\* /Q /F <Target Name=\"Clean\">\n <Exec Command=\"rmdir %(DeploymentSet.LocalWebRoot)\\subdir1 /Q /S\" IgnoreExitCode=\"true\" />\n <Exec Command=\"rmdir %(DeploymentSet.LocalWebRoot)\\subdir2 /Q /S\" IgnoreExitCode=\"true\" />\n ...\n <Exec Command=\"rmdir %(DeploymentSet.LocalWebRoot)\\subdirN /Q /S\" IgnoreExitCode=\"true\" />\n <Exec Command=\"del %(DeploymentSet.LocalWebRoot)\\* /Q /F\" IgnoreExitCode=\"true\" />\n </Target>\n"
},
{
"answer_id": 10119970,
"author": "grenade",
"author_id": 68115,
"author_profile": "https://Stackoverflow.com/users/68115",
"pm_score": 0,
"selected": false,
"text": "<Target Name=\"Clean\">\n <Exec Command=\"del /F /Q %(DeploymentSet.LocalWebRoot)\\*.*\" />\n <Exec Command=\"for /d /r "%(DeploymentSet.LocalWebRoot)" %v IN (*) DO rd /S /Q "%v"\" />\n</Target>\n"
}
] | 2008/12/05 | [
"https://Stackoverflow.com/questions/345179",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/303/"
] |
345,180 | <p>I wrote a DLL in .NET and I want to access it in VBScript. I don't want to add it to the assembly directory. </p>
<p>Is there a way to point too the DLL and create an instance of it?</p>
| [
{
"answer_id": 345248,
"author": "huseyint",
"author_id": 39,
"author_profile": "https://Stackoverflow.com/users/39",
"pm_score": 4,
"selected": true,
"text": "/codebase regasm your.dll /codebase\n"
},
{
"answer_id": 524082,
"author": "Dscoduc",
"author_id": 51949,
"author_profile": "https://Stackoverflow.com/users/51949",
"pm_score": 3,
"selected": false,
"text": "// bind a variabe to WScript.Shell\nSet WshShell = CreateObject(\"WScript.Shell\")\n\n// define the path to the regasm.exe file\nRegAsmPath = \"c:\\Windows\\Microsoft.NET\\Framework\\v2.0.50727\\RegAsm.exe\"\n\n// register the dll\nWshShell.run \"cmd /c \" & RegAsmPath & \" c:\\temp\\cbsecurity.dll /codebase /nologo /s\", 0, True\n\n// bind a variable to the dll\nSet cbUtil = CreateObject(\"CBSecurity.Utilities\")\n Public Function IsAlive() As Boolean\n Return True\nEnd Function\n //check if dll is available to your code\nmsgbox \"cbUtil is alive: \" & cbUtil.IsAlive\n"
},
{
"answer_id": 882137,
"author": "foolshat",
"author_id": 108773,
"author_profile": "https://Stackoverflow.com/users/108773",
"pm_score": 4,
"selected": false,
"text": "[assembly: ComVisible(true)]\n regasm yourdll.dll\n ComVisible $a = New-Object -comobject Your.Utils.Logging\n$a.WriteError2(\"Application\", \"hello\",1,1)\n Set logger = CreateObject(\"Your.Utils.Logging\")\nlogger.WriteError2 \"Application\", \"hello from vbs\",1,1 \n"
}
] | 2008/12/05 | [
"https://Stackoverflow.com/questions/345180",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1231/"
] |
345,185 | <p>Check out this test:</p>
<pre><code>[TestFixture]
public class Quick_test
{
[Test]
public void Test()
{
Assert.AreEqual(0, GetByYield().Count());
Assert.AreEqual(0, GetByEnumerable().Count());
}
private IEnumerable<string> GetByYield()
{
yield break;
}
private IEnumerable<string> GetByEnumerable()
{
return Enumerable.Empty<string>();
}
}
</code></pre>
<p>When I write stub methods I generally use the Enumerable.Empty way of doing it. I stumbled across some old code I wrote where I did it the yield way.</p>
<p>This got me to wondering:</p>
<ul>
<li>Which is more visually appealing to other developers?</li>
<li>Are there any hidden gotchas that would cause us to prefer one over the other?</li>
</ul>
<p>Thanks!</p>
| [
{
"answer_id": 345200,
"author": "leppie",
"author_id": 15541,
"author_profile": "https://Stackoverflow.com/users/15541",
"pm_score": 1,
"selected": false,
"text": "T[] e = {};\nreturn e;\n"
}
] | 2008/12/05 | [
"https://Stackoverflow.com/questions/345185",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2595/"
] |
345,187 | <p>How do I map numbers, linearly, between a and b to go between c and d.</p>
<p>That is, I want numbers between 2 and 6 to map to numbers between 10 and 20... but I need the generalized case.</p>
<p>My brain is fried.</p>
| [
{
"answer_id": 345203,
"author": "Konrad Rudolph",
"author_id": 1968,
"author_profile": "https://Stackoverflow.com/users/1968",
"pm_score": 5,
"selected": false,
"text": "R = (20 - 10) / (6 - 2)\ny = (x - 2) * R + 10\n"
},
{
"answer_id": 345204,
"author": "PeterAllenWebb",
"author_id": 21365,
"author_profile": "https://Stackoverflow.com/users/21365",
"pm_score": 8,
"selected": false,
"text": "Y = (X-A)/(B-A) * (D-C) + C\n"
},
{
"answer_id": 345222,
"author": "Chris Cudmore",
"author_id": 18907,
"author_profile": "https://Stackoverflow.com/users/18907",
"pm_score": 1,
"selected": false,
"text": "var interval = (d-c)/(b-a)\nfor n = 0 to (b - a)\n print c + n*interval\n"
},
{
"answer_id": 345500,
"author": "PhiLho",
"author_id": 15459,
"author_profile": "https://Stackoverflow.com/users/15459",
"pm_score": 0,
"selected": false,
"text": "int srcMin = 2, srcMax = 6;\nint tgtMin = 10, tgtMax = 20;\n\nint nb = srcMax - srcMin;\nint range = tgtMax - tgtMin;\nfloat rate = (float) range / (float) nb;\n\nprintln(srcMin + \" > \" + tgtMin);\nfloat stepF = tgtMin;\nfor (int i = 1; i < nb; i++)\n{\n stepF += rate;\n println((srcMin + i) + \" > \" + (int) (stepF + 0.5) + \" (\" + stepF + \")\");\n}\nprintln(srcMax + \" > \" + tgtMax);\n"
},
{
"answer_id": 14955731,
"author": "Dejell",
"author_id": 264419,
"author_profile": "https://Stackoverflow.com/users/264419",
"pm_score": 2,
"selected": false,
"text": "reverseX = (B-A)*(Y-C)/(D-C) + A\n"
},
{
"answer_id": 41088063,
"author": "Sourabh Bhat",
"author_id": 3368518,
"author_profile": "https://Stackoverflow.com/users/3368518",
"pm_score": 3,
"selected": false,
"text": "java.lang.Math final static double EPSILON = 1e-12;\n\npublic static double map(double valueCoord1,\n double startCoord1, double endCoord1,\n double startCoord2, double endCoord2) {\n\n if (Math.abs(endCoord1 - startCoord1) < EPSILON) {\n throw new ArithmeticException(\"/ 0\");\n }\n\n double offset = startCoord2;\n double ratio = (endCoord2 - startCoord2) / (endCoord1 - startCoord1);\n return ratio * (valueCoord1 - startCoord1) + offset;\n}\n"
},
{
"answer_id": 54105404,
"author": "Mohamed Ashraf",
"author_id": 10888397,
"author_profile": "https://Stackoverflow.com/users/10888397",
"pm_score": 1,
"selected": false,
"text": "double R = (d-c)/(b-a)\ndouble y = c+(x*R)+R\nreturn(y)\n"
},
{
"answer_id": 60731065,
"author": "Amerrnath",
"author_id": 1475089,
"author_profile": "https://Stackoverflow.com/users/1475089",
"pm_score": 2,
"selected": false,
"text": "[a1, a2] => [b1, b2]\n\nif s in range of [a1, a2]\n\nthen t which will be in range of [b1, b2]\n\nt= b1 + ((s- a1) * (b2-b1))/ (a2-a1)\n"
}
] | 2008/12/05 | [
"https://Stackoverflow.com/questions/345187",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/43005/"
] |
345,194 | <p>In jQuery, is there a function/plugin which I can use to match a given regular expression in a string?</p>
<p>For example, in an email input box, I get an email address, and want to see if it is in the correct format. What jQuery function should I use to see if my validating regular expression matches the input?</p>
<p>I've googled for a solution, but I haven't been able to find anything.</p>
| [
{
"answer_id": 345259,
"author": "hugoware",
"author_id": 17091,
"author_profile": "https://Stackoverflow.com/users/17091",
"pm_score": 5,
"selected": false,
"text": "var phrase = \"This is a phrase\";\nphrase = phrase.replace(/is/i, \"is not\");\nalert(phrase);\n"
},
{
"answer_id": 345806,
"author": "nickf",
"author_id": 9021,
"author_profile": "https://Stackoverflow.com/users/9021",
"pm_score": 6,
"selected": false,
"text": "filter $(\"input:text\")\n .filter(function() {\n return this.value.match(/[^\\d]/);\n })\n .addClass(\"inputError\")\n;\n id /[a-z]+_\\d+/ $(\"[id]\").filter(function() {\n return this.id.match(/[a-z]+_\\d+/);\n});\n"
},
{
"answer_id": 2951744,
"author": "Klatys",
"author_id": 350234,
"author_profile": "https://Stackoverflow.com/users/350234",
"pm_score": 5,
"selected": false,
"text": "var rege = /^([A-Za-z0-9_\\-\\.])+\\@([A-Za-z0-9_\\-\\.])+\\.([A-Za-z]{2,4})$/;\nif(rege.test($('#uemail').val())){ //do something }\n"
},
{
"answer_id": 3449350,
"author": "bilelz",
"author_id": 414903,
"author_profile": "https://Stackoverflow.com/users/414903",
"pm_score": 2,
"selected": false,
"text": "$(\"input.numeric\").keypress(function(e) { /* pour les champs qui ne prennent que du numeric en entrée */ \n var key = e.charCode || e.keyCode || 0; \n var keychar = String.fromCharCode(key);\n /*alert(\"keychar:\"+keychar + \" \\n charCode:\" + e.charCode + \" \\n key:\" +key);*/\n if ( ((key == 8 || key == 9 || key == 46 || key == 35 || key == 36 || (key >= 37 && key <= 40)) && e.charCode==0) /* backspace, end, begin, top, bottom, right, left, del, tab */\n || (key >= 48 && key <= 57) ) { /* 0-9 */\n return;\n } else {\n e.preventDefault();\n }\n });\n"
},
{
"answer_id": 11142098,
"author": "Har",
"author_id": 1071527,
"author_profile": "https://Stackoverflow.com/users/1071527",
"pm_score": -1,
"selected": false,
"text": "/^((([a-z]|\\d|[!#\\$%&'\\*\\+\\-\\/=\\?\\^_`{\\|}~]|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])+(\\.([a-z]|\\d|[!#\\$%&'\\*\\+\\-\\/=\\?\\^_`{\\|}~]|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])+)*)|((\\x22)((((\\x20|\\x09)*(\\x0d\\x0a))?(\\x20|\\x09)+)?(([\\x01-\\x08\\x0b\\x0c\\x0e-\\x1f\\x7f]|\\x21|[\\x23-\\x5b]|[\\x5d-\\x7e]|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])|(\\\\([\\x01-\\x09\\x0b\\x0c\\x0d-\\x7f]|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF]))))*(((\\x20|\\x09)*(\\x0d\\x0a))?(\\x20|\\x09)+)?(\\x22)))@((([a-z]|\\d|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])|(([a-z]|\\d|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])([a-z]|\\d|-|\\.|_|~|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])*([a-z]|\\d|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])))\\.)+(([a-z]|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])|(([a-z]|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])([a-z]|\\d|-|\\.|_|~|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])*([a-z]|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])))\\.?$/i\n /^((([a-z]|\\d|[!#\\$%&'\\*\\+\\-\\/=\\?\\^_`{\\|}~]|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])+(\\.([a-z]|\\d|[!#\\$%&'\\*\\+\\-\\/=\\?\\^_`{\\|}~]|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])+)*)|((\\x22)((((\\x20|\\x09)*(\\x0d\\x0a))?(\\x20|\\x09)+)?(([\\x01-\\x08\\x0b\\x0c\\x0e-\\x1f\\x7f]|\\x21|[\\x23-\\x5b]|[\\x5d-\\x7e]|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])|(\\\\([\\x01-\\x09\\x0b\\x0c\\x0d-\\x7f]|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF]))))*(((\\x20|\\x09)*(\\x0d\\x0a))?(\\x20|\\x09)+)?(\\x22)))@@((([a-z]|\\d|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])|(([a-z]|\\d|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])([a-z]|\\d|-|\\.|_|~|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])*([a-z]|\\d|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])))\\.)+(([a-z]|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])|(([a-z]|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])([a-z]|\\d|-|\\.|_|~|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])*([a-z]|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])))\\.?$/i\n"
},
{
"answer_id": 63315143,
"author": "CodeToLife",
"author_id": 1018154,
"author_profile": "https://Stackoverflow.com/users/1018154",
"pm_score": 0,
"selected": false,
"text": "$('#some_input_id').attr('oninput',\n\"this.value=this.value.replace(/[^0-9A-Za-z\\s_-]/g,'');\")\n ''"
}
] | 2008/12/05 | [
"https://Stackoverflow.com/questions/345194",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12649/"
] |
345,198 | <p>I want to set the backgroun color for a GridViewColumn that is databound inside of a listview in WPF. I'm not sure how to ask this question being fairly new to WPF, otherwise I wouldn't have bothered all of you.</p>
<p>I want to change the background color of the whole row, based on a bool flag in my databound object.</p>
<p>In this case, I have, well, a "CaseDetail" object, that when there are internal notes "IsInternalNote" I want the color of the row to change.</p>
<p>How can I pull this off in WPF?</p>
<p>What I have now, ( very simple ), which does NOT change the color.</p>
<pre><code><ListView ItemsSource="{Binding}" IsSynchronizedWithCurrentItem="True" >
<ListView.View>
<GridView>
<GridViewColumn DisplayMemberBinding="{Binding Date, StringFormat=MMM dd\, yyyy h:mm tt}" Header="Date" Width="Auto" />
<GridViewColumn DisplayMemberBinding="{Binding SubmittedBy}" Header="Submitted By" Width="Auto" />
<GridViewColumn Width="Auto" Header="Description" x:Name="colDesc">
<GridViewColumn.CellTemplate>
<DataTemplate>
<ScrollViewer MaxHeight="80" Width="300">
<StackPanel Orientation="Vertical">
<TextBlock Text="{Binding Description}" TextWrapping="Wrap" />
<TextBlock Text="{Binding File.FileName}" TextWrapping="Wrap" />
</StackPanel>
</ScrollViewer>
</DataTemplate>
</GridViewColumn.CellTemplate>
</GridViewColumn>
</GridView>
</ListView.View>
</ListView>
</code></pre>
| [
{
"answer_id": 345260,
"author": "Bryan Anderson",
"author_id": 21186,
"author_profile": "https://Stackoverflow.com/users/21186",
"pm_score": 2,
"selected": false,
"text": "<DataTemplate.Triggers>\n <Trigger Property=\"IsInternalNote\" Value=\"True\">\n <Setter Property=\"Background\" Value=\"Red\" />\n </Trigger>\n</DataTemplate.Triggers>\n"
},
{
"answer_id": 345423,
"author": "Thomas",
"author_id": 9970,
"author_profile": "https://Stackoverflow.com/users/9970",
"pm_score": 6,
"selected": true,
"text": "<ListBox ...>\n <ListBox.ItemTemplate>\n <DataTemplate>\n <Border x:Name=\"BGBorder\">\n <!-- --> \n </Border>\n <DataTemplate.Triggers>\n <DataTrigger \n Binding=\"{Binding Path=DataContext.IsAborted, RelativeSource={RelativeSource TemplatedParent}}\" \n Value=\"True\">\n <Setter Property=\"Background\" TargetName=\"BGBorder\" Value=\"Red\">\n </Setter>\n </DataTrigger>\n </DataTemplate.Triggers>\n </DataTemplate>\n </ListBox.ItemTemplate>\n</ListBox>\n"
}
] | 2008/12/05 | [
"https://Stackoverflow.com/questions/345198",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/32772/"
] |
345,199 | <p>I need to watch when certain processes are started or stopped on a Windows machine. I'm currently tapped into the WMI system and querying it every 5 seconds, but this causes a CPU spike every 5 seconds because WMI is WMI. Is there a better way of doing this? I could just make a list of running processes and attach an Exited event to them through the System.Diagnostics Namespace, but there is no Event Handler for creation.</p>
| [
{
"answer_id": 345836,
"author": "denis phillips",
"author_id": 748,
"author_profile": "https://Stackoverflow.com/users/748",
"pm_score": 2,
"selected": true,
"text": " static void Main(string[] args)\n {\n // Getting all instances of notepad\n // (this is only done once here so start up some notepad instances first)\n // you may want use GetProcessByPid or GetProcesses and filter them as required\n Process[] processesToWatch = Process.GetProcessesByName(\"notepad\");\n\n foreach (var process in processesToWatch)\n {\n process.EnableRaisingEvents = true;\n process.Exited +=\n (s, e) => Console.WriteLine(\"An instance of notepad exited\");\n }\n\n Thread watchThread = new Thread(() =>\n {\n while (true)\n {\n Process[] processes = Process.GetProcesses();\n foreach (var process in processes)\n {\n Console.WriteLine(\"{0}:{1}\", process.Id, process.ProcessName);\n }\n // Don't dedicate a thread to this like I'm doing here\n // setup a timer or something similiar\n Thread.Sleep(2000);\n }\n });\n watchThread.IsBackground = true;\n watchThread.Start();\n\n Console.WriteLine(\"Polling processes and waiting for notepad process exit events\");\n Console.ReadLine();\n }\n"
},
{
"answer_id": 345846,
"author": "Hristo Deshev",
"author_id": 17977,
"author_profile": "https://Stackoverflow.com/users/17977",
"pm_score": 2,
"selected": false,
"text": "\n foreach {"
},
{
"answer_id": 50315962,
"author": "Red John",
"author_id": 3721646,
"author_profile": "https://Stackoverflow.com/users/3721646",
"pm_score": 1,
"selected": false,
"text": "<QueryList>\n <Query Id=\"0\" Path=\"Security\">\n <Select Path=\"Security\">\n *[EventData[Data[@Name='NewProcessName'] ='C:\\Windows\\explorer.exe']]\n and\n *[System[(EventID=4688)]]\n </Select>\n </Query>\n</QueryList>\n"
}
] | 2008/12/05 | [
"https://Stackoverflow.com/questions/345199",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
345,225 | <p>I have a (varchar) field Foo which can only be specified if (bit) Bar is <em>not</em> true. I would like the textbox in which Foo is displayed to be <em>disabled</em> when Bar is true -- essentially, <code>FooBox.Enabled = !isBar</code>. I'm trying to do something like</p>
<pre><code>FooBox.DataBindings.Add(new Binding("Enabled", source, "!isBar"));
</code></pre>
<p>but of course the bang in there throws an exception. I've also tried constructs like "isBar != true" or "isBar <> true", but none work. Am I barking up the wrong tree here?</p>
| [
{
"answer_id": 345245,
"author": "gcores",
"author_id": 40256,
"author_profile": "https://Stackoverflow.com/users/40256",
"pm_score": -1,
"selected": false,
"text": "FooBox.DataBindings.Add(\"Enabled\", source, \"isBar\");\n"
}
] | 2008/12/05 | [
"https://Stackoverflow.com/questions/345225",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/26286/"
] |
345,227 | <p>I have been using LINQ to SQL for a while, and there is one thing that has always bothered me. Whenever I modify the schema of a table, in order to refresh it in the designer, I have to delete it and then add it back. That's fine, but this means I have to actually <em>find</em> the table in the designer. I have about 100+ tables in my database, and every time I do this, it's like finding a needle in a haystack. Well, maybe it's not that bad, but seriously, it takes way longer than it should.</p>
<p>Is there another option for refreshing tables that I am unaware of?</p>
| [
{
"answer_id": 345362,
"author": "Daniel Schaffer",
"author_id": 2596,
"author_profile": "https://Stackoverflow.com/users/2596",
"pm_score": -1,
"selected": false,
"text": "[Table(\"dbo.my_table\")]\npublic class MyTable\n{\n[Column(\"id\", AutoSync = AutoSync.OnInsert, IsDbGenerated = true, IsPrimaryKey = true)]\npublic Int32 Id { get; set; }\n\n[Column(\"name\", DbType=\"NVarChar(50) NOT NULL\")]\npublic String Name { get; set; }\n}\n"
}
] | 2008/12/05 | [
"https://Stackoverflow.com/questions/345227",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1436/"
] |
345,281 | <p>Is there a command-line argument that would force firefox.exe to launch a new process for a particular URL regardless of whether another instance of firefox is already running?</p>
| [
{
"answer_id": 345300,
"author": "Greg",
"author_id": 24181,
"author_profile": "https://Stackoverflow.com/users/24181",
"pm_score": 1,
"selected": false,
"text": "firefox -new-window"
},
{
"answer_id": 345320,
"author": "VonC",
"author_id": 6309,
"author_profile": "https://Stackoverflow.com/users/6309",
"pm_score": 6,
"selected": true,
"text": "firefox.exe -no-remote -p sidekick\n firefox.exe -P\n about:profiles"
},
{
"answer_id": 26039811,
"author": "RuntimeException",
"author_id": 15789,
"author_profile": "https://Stackoverflow.com/users/15789",
"pm_score": 2,
"selected": false,
"text": "REM ==============\n\nsetlocal\n\nset URL=%1\n\nREM FirefoxPortable installation folder\nset FIREFOX_PORTABLE_HOME=C:\\portables\\FirstFirefoxPortable\n\nREM Name of the FirefoxPortable executable file\nset FIREFOX_FILENAME_NOEXT=FirstFirefoxPortable\n\nREM Name of the Firefox executable file within App/firefox\nset FIREFOX_EXEC_NOEXT=firstfirefox\n\nset FIREFOX_PORTABLE_EXEC=%FIREFOX_PORTABLE_HOME%\\%FIREFOX_FILENAME_NOEXT%.exe\n\nREM Name of the other profile folder.\nset FIREFOX_PROFILE=firstprofile\n\nset CLEAR_HISTORY=true\nset CLEAR_CACHE=true\nset CLEAR_SAVED_PASSWORDS=true\nset CLEAR_SESSION=true\n\nset WAIT_DURATION=4\nset ADDITIONAL_WAIT_DURATION=2\n\nif not exist %FIREFOX_PORTABLE_HOME%\\%FIREFOX_PROFILE%.ini (\n\n@echo off\necho.\necho.\necho Setting up Firefox Profile\necho.\necho.\npause\n@echo on\n\necho [FirefoxPortable]>%FIREFOX_PORTABLE_HOME%\\%FIREFOX_PROFILE%.ini\necho FirefoxDirectory=App\\firefox>>%FIREFOX_PORTABLE_HOME%\\%FIREFOX_PROFILE%.ini\necho ProfileDirectory=%FIREFOX_PROFILE%\\profile>>%FIREFOX_PORTABLE_HOME%\\%FIREFOX_PROFILE%.ini\necho SettingsDirectory=%FIREFOX_PROFILE%\\settings>>%FIREFOX_PORTABLE_HOME%\\%FIREFOX_PROFILE%.ini\necho PluginsDirectory=%FIREFOX_PROFILE%\\plugins>>%FIREFOX_PORTABLE_HOME%\\%FIREFOX_PROFILE%.ini\necho FirefoxExecutable=%FIREFOX_EXEC_NOEXT%.exe>>%FIREFOX_PORTABLE_HOME%\\%FIREFOX_PROFILE%.ini\necho AdditionalParameters=>>%FIREFOX_PORTABLE_HOME%\\%FIREFOX_PROFILE%.ini\necho LocalHomepage=>>%FIREFOX_PORTABLE_HOME%\\%FIREFOX_PROFILE%.ini\necho DisableSplashScreen=false>>%FIREFOX_PORTABLE_HOME%\\%FIREFOX_PROFILE%.ini\necho AllowMultipleInstances=false>>%FIREFOX_PORTABLE_HOME%\\%FIREFOX_PROFILE%.ini\necho DisableIntelligentStart=false>>%FIREFOX_PORTABLE_HOME%\\%FIREFOX_PROFILE%.ini\necho SkipCompregFix=false>>%FIREFOX_PORTABLE_HOME%\\%FIREFOX_PROFILE%.ini\necho RunLocally=false>>%FIREFOX_PORTABLE_HOME%\\%FIREFOX_PROFILE%.ini\n\nrem create dirs\npushd %FIREFOX_PORTABLE_HOME%\nmkdir %FIREFOX_PORTABLE_HOME%\\%FIREFOX_PROFILE%\nmkdir %FIREFOX_PORTABLE_HOME%\\%FIREFOX_PROFILE%\\profile\nmkdir %FIREFOX_PORTABLE_HOME%\\%FIREFOX_PROFILE%\\settings\nmkdir %FIREFOX_PORTABLE_HOME%\\%FIREFOX_PROFILE%\\plugins\npopd\n\nrem copy profile\nxcopy /e %FIREFOX_PORTABLE_HOME%\\App\\DefaultData\\profile %FIREFOX_PORTABLE_HOME%\\%FIREFOX_PROFILE%\\profile\n\ncopy /y %FIREFOX_PORTABLE_HOME%\\%FIREFOX_PROFILE%.ini %FIREFOX_PORTABLE_HOME%\\FirefoxPortable.ini\nrename %FIREFOX_PORTABLE_HOME%\\FirefoxPortable.exe %FIREFOX_FILENAME_NOEXT%.exe\nrename %FIREFOX_PORTABLE_HOME%\\App\\Firefox\\firefox.exe %FIREFOX_EXEC_NOEXT%.exe\n)\n\nrem check if firefox is running\nREM tasklist /FI \"IMAGENAME eq %FIREFOX_FILENAME_NOEXT%.exe\" 2>NUL | find /I /N \"%FIREFOX_FILENAME_NOEXT%.exe\">NUL\nREM if \"%ERRORLEVEL%\"==\"0\" (\nREM echo Firefox running\nREM taskkill /t /FI \"IMAGENAME eq %FIREFOX_FILENAME_NOEXT%.exe\"\nREM ping -n 4 127.0.0.1 > NUL\nREM tasklist /FI \"IMAGENAME eq %FIREFOX_FILENAME_NOEXT%.exe\"\nREM echo retrying killing Firefox\nREM taskkill /f /t /FI \"IMAGENAME eq %FIREFOX_FILENAME_NOEXT%.exe\"\nREM ping -n 2 127.0.0.1 > NUL\nREM taskkill /f /t /FI \"IMAGENAME eq %FIREFOX_EXEC_NOEXT%.exe\"\nREM ) else (\nREM echo Firefox not running.. starting..\nREM )\n\n\ntaskkill /t /FI \"IMAGENAME eq %FIREFOX_FILENAME_NOEXT%.exe\"\n\nping -n %WAIT_DURATION% 127.0.0.1 > NUL\necho ==== try killing\ntasklist /FI \"IMAGENAME eq %FIREFOX_FILENAME_NOEXT%.exe\"\ntasklist /FI \"IMAGENAME eq %FIREFOX_EXEC_NOEXT%.exe\"\ntaskkill /t /FI \"IMAGENAME eq %FIREFOX_FILENAME_NOEXT%.exe\"\ntaskkill /t /FI \"IMAGENAME eq %FIREFOX_EXEC_NOEXT%.exe\"\n\nping -n %ADDITIONAL_WAIT_DURATION% 127.0.0.1 > NUL\necho ==== retry killing forcefully \ntasklist /FI \"IMAGENAME eq %FIREFOX_FILENAME_NOEXT%.exe\"\ntasklist /FI \"IMAGENAME eq %FIREFOX_EXEC_NOEXT%.exe\"\ntaskkill /f /t /FI \"IMAGENAME eq %FIREFOX_FILENAME_NOEXT%.exe\"\ntaskkill /f /t /FI \"IMAGENAME eq %FIREFOX_EXEC_NOEXT%.exe\"\n\n\nREM clear everything - delete profile\nREM del /f /s /q %FIREFOX_PORTABLE_HOME%\\%FIREFOX_PROFILE%\\profile\\*\nREM rmdir %FIREFOX_PORTABLE_HOME%\\%FIREFOX_PROFILE%\\profile\\\nREM mkdir %FIREFOX_PORTABLE_HOME%\\%FIREFOX_PROFILE%\\profile\\\n\nREM clear all sqlite files\nrem for /d %%x in (%FIREFOX_PORTABLE_HOME%\\%FIREFOX_PROFILE%\\*) do del /q /s /f %%x\\*sqlite\n\nif \"%CLEAR_HISTORY%\"==\"true\" (\necho.\necho Clearing History\necho.\nrem clear history (Bookmarks, browsing and download history)\ndel /q /s /f %FIREFOX_PORTABLE_HOME%\\%FIREFOX_PROFILE%\\profile\\places.sqlite*\n\nrem clear form history (Saved form data)\ndel /q /s /f %FIREFOX_PORTABLE_HOME%\\%FIREFOX_PROFILE%\\profile\\formhistory.sqlite*\n)\n\nif \"%CLEAR_SESSION%\"==\"true\" (\necho.\necho Clearing browsing session\necho.\nrem clear previous browsing session\ndel /q /s /f %FIREFOX_PORTABLE_HOME%\\%FIREFOX_PROFILE%\\profile\\sessionstore.js\n)\n\nif \"%CLEAR_SAVED_PASSWORDS%\"==\"true\" (\necho.\necho Clearing saved passwords\necho.\nrem clear saved passwords\ndel /q /s /f %FIREFOX_PORTABLE_HOME%\\%FIREFOX_PROFILE%\\profile\\logins.json\n)\n\nif \"%CLEAR_CACHE%\"==\"true\" (\necho.\necho Clearing cache\necho.\nrem clear permissions (Permission database for cookies, pop-up blocking, image loading and add-ons installation.)\ndel /q /s /f %FIREFOX_PORTABLE_HOME%\\%FIREFOX_PROFILE%\\profile\\permissions.sqlite*\n\nrem clear content preferences (Individual settings for pages.)\ndel /q /s /f %FIREFOX_PORTABLE_HOME%\\%FIREFOX_PROFILE%\\profile\\content-prefs.sqlite*\n\nrem clear cookies\ndel /q /s /f %FIREFOX_PORTABLE_HOME%\\%FIREFOX_PROFILE%\\profile\\cookies.sqlite*\n\nrem clear cache\ndel /q /s /f %FIREFOX_PORTABLE_HOME%\\%FIREFOX_PROFILE%\\profile\\cache2\\*\n\nrem clear offline cache\ndel /q /s /f %FIREFOX_PORTABLE_HOME%\\%FIREFOX_PROFILE%\\profile\\OfflineCache\\*\n\nrem clear DOM Storage\ndel /q /s /f %FIREFOX_PORTABLE_HOME%\\%FIREFOX_PROFILE%\\profile\\webappsstore.sqlite*\n)\n\nif \"%URL%\"==\"\" (\nset URL=www.google.com?q=DidYouPassTheURLArgument\n)\n@echo on\nstart /MAX \"%FIREFOX_FILENAME_NOEXT%.exe\" %FIREFOX_PORTABLE_EXEC% -P \"%FIREFOX_PROFILE%\" -no-remote -new-tab %URL%\nendlocal\n\nREM ==================\n setlocal\n\nset URL=%1\n\nREM FirefoxPortable installation folder\nset FIREFOX_PORTABLE_HOME=C:\\portables\\SecondFirefoxPortable\n\nREM Name of the FirefoxPortable executable file\nset FIREFOX_FILENAME_NOEXT=SecondFirefoxPortable\n\nREM Name of the Firefox executable file within App/firefox\nset FIREFOX_EXEC_NOEXT=secondfirefox\n\nset FIREFOX_PORTABLE_EXEC=%FIREFOX_PORTABLE_HOME%\\%FIREFOX_FILENAME_NOEXT%.exe\n\nREM Name of the other profile folder.\nset FIREFOX_PROFILE=secondprofile\n\nREM --- snip ---\n"
},
{
"answer_id": 59029435,
"author": "Olaf Dietsche",
"author_id": 1741542,
"author_profile": "https://Stackoverflow.com/users/1741542",
"pm_score": 0,
"selected": false,
"text": "firefox -new-instance -P \"Another Profile\"\n"
},
{
"answer_id": 66225679,
"author": "Pierz",
"author_id": 436794,
"author_profile": "https://Stackoverflow.com/users/436794",
"pm_score": 0,
"selected": false,
"text": "open -n -a Firefox.app --args -profile `mktemp -d /tmp/fx-profile.XXXX` -no-remote -new-instance\n"
}
] | 2008/12/05 | [
"https://Stackoverflow.com/questions/345281",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10026/"
] |
345,315 | <p>A listbox is passed, the data placed in an array, the array is sort and then the data is placed back in the listbox. The part that does work is putting the data back in the listbox. Its like the listbox is being passed by value instead of by ref.</p>
<p>Here's the sub that does the sort and the line of code that calls the sort sub.</p>
<pre><code>Private Sub SortListBox(ByRef LB As MSForms.ListBox)
Dim First As Integer
Dim Last As Integer
Dim NumItems As Integer
Dim i As Integer
Dim j As Integer
Dim Temp As String
Dim TempArray() As Variant
ReDim TempArray(LB.ListCount)
First = LBound(TempArray) ' this works correctly
Last = UBound(TempArray) - 1 ' this works correctly
For i = First To Last
TempArray(i) = LB.List(i) ' this works correctly
Next i
For i = First To Last
For j = i + 1 To Last
If TempArray(i) > TempArray(j) Then
Temp = TempArray(j)
TempArray(j) = TempArray(i)
TempArray(i) = Temp
End If
Next j
Next i ! data is now sorted
LB.Clear ! this doesn't clear the items in the listbox
For i = First To Last
LB.AddItem TempArray(i) ! this doesn't work either
Next i
End Sub
Private Sub InitializeForm()
' There's code here to put data in the list box
Call SortListBox(FieldSelect.CompleteList)
End Sub
</code></pre>
<p>Thanks for your help.</p>
| [
{
"answer_id": 456437,
"author": "barrowc",
"author_id": 2127508,
"author_profile": "https://Stackoverflow.com/users/2127508",
"pm_score": 1,
"selected": false,
"text": "Private Sub UserForm_Initialize()\n\nListBox1.AddItem \"john\"\nListBox1.AddItem \"paul\"\nListBox1.AddItem \"george\"\nListBox1.AddItem \"ringo\"\n\nSortListBox ListBox1\n\nEnd Sub\n UserForm_Initialize InitializeForm"
},
{
"answer_id": 69168100,
"author": "FreeSoftwareServers",
"author_id": 5079799,
"author_profile": "https://Stackoverflow.com/users/5079799",
"pm_score": 0,
"selected": false,
"text": "Private Sub UserForm_Initialize()\n\n Call HideTitleBar(Me)\n\n Set ExtraFiltersDic = CreateObject(\"scripting.dictionary\")\n ExtraFiltersDic.CompareMode = 1\n Set ExtraFiltersDic = GetExtraFiltersDic()\n\n Dim k\n For Each k In ExtraFiltersDic.Keys\n ListBox1.AddItem k\n Next\n \n Call SortListBox(ListBox1, ListBox2, ExtraFiltersDic)\n \nEnd Sub\n\nPublic Sub SortListBox(ByRef ListBox As MSForms.ListBox, Optional ByRef ListBox2 As MSForms.ListBox, Optional ByRef RelationalDic As Object)\n\n Dim First As Integer, Last As Integer, NumItems As Integer\n Dim i As Integer, j As Integer\n Dim TempArray() As Variant, Temp As String\n\n ReDim TempArray(ListBox.ListCount)\n\n First = LBound(TempArray)\n Last = UBound(TempArray) - 1\n For i = First To Last\n TempArray(i) = ListBox.List(i)\n Next i\n \n For i = First To Last\n For j = i + 1 To Last\n If TempArray(i) > TempArray(j) Then\n Temp = TempArray(j)\n TempArray(j) = TempArray(i)\n TempArray(i) = Temp\n End If\n Next j\n Next i\n\n ListBox.Clear\n\n If Not ListBox2 Is Nothing And Not RelationalDic Is Nothing Then\n Set KeyValDic = CreateObject(\"scripting.dictionary\")\n Set KeyValDic = RelationalDic\n End If\n\n For i = First To Last\n ListBox.AddItem TempArray(i)\n If Not ListBox2 Is Nothing And Not RelationalDic Is Nothing Then\n ListBox2.AddItem KeyValDic(TempArray(i))\n End If\n Next i\n\nEnd Sub\n"
}
] | 2008/12/05 | [
"https://Stackoverflow.com/questions/345315",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
345,318 | <p>What is the best design decision for a 'top-level' class to attach to an event to a class that may be '5+ layers down in the callstack?</p>
<p>For example, perhaps the MainForm has spawned an object, and that object has spawned a callstack of several other object calls. The most obvious way would be to chain the event up the object hierarchy, but this seems messy and requires a lot of work.</p>
<p>One other solution ive seen is to use the observer pattern by creating a publically accessible static object which exposes the event, and acts as a proxy between the bottom-level object, and the top-level 'form'.</p>
<p>Any recommendations?</p>
<p>Here's a pseudo-code example. In this example, the MainForm instantiates 'SomeObject', and attaches to an event. 'SomeObject' attaches to an object it instantiates, in an effort to carry the event up to the MainForm listener.</p>
<pre><code>class Mainform
{
public void OnLoad()
{
SomeObject someObject = new SomeObject();
someObject.OnSomeEvent += MyHandler;
someObject.DoStuff();
}
public void MyHandler()
{
}
}
class SomeObject
{
public void DoStuff()
{
SomeOtherObject otherObject = new SomeOtherObject();
otherObject.OnSomeEvent += MyHandler;
otherObject.DoStuff();
}
public void MyHandler()
{
if( OnSomeEvent != null )
OnSomeEvent();
}
public event Action OnSomeEvent;
}
</code></pre>
| [
{
"answer_id": 346511,
"author": "Nicholas Piasecki",
"author_id": 32187,
"author_profile": "https://Stackoverflow.com/users/32187",
"pm_score": 0,
"selected": false,
"text": "[EventPublication(\"StatusChanged\")] [EventSubscription(\"StatusChanged\")] \npublic void DoSomethingInTheBackground()\n{\n using (StatusNotification sn = new StatusNotification(this.WorkItem))\n {\n sn.Message(\"Loading customer data...\", 33);\n // Block while loading the customer data....\n sn.Message(\"Loading order history...\", 66);\n // Block while loading the order history...\n sn.Message(\"Done!\", 100);\n }\n}\n StatusNotification event \n[EventPublication(\"StatusChanged\")]\npublic event EventHandler<StatusEventArgs> StatusChanged;\n Message() Dispose() \n[EventSubscription(\"StatusChanged\", ThreadOption=ThreadOption.UserInterface)]\npublic void OnStatusChanged(object sender, StatusEventArgs e)\n{\n this.statusLabel.Text = e.Text;\n if (e.ProgressPercentage != -1)\n {\n this.progressBar.Visible = true;\n this.progressBar.Value = e.ProgressPercentage;\n }\n}\n MessageNotificationService"
},
{
"answer_id": 346686,
"author": "Juliet",
"author_id": 40516,
"author_profile": "https://Stackoverflow.com/users/40516",
"pm_score": 3,
"selected": true,
"text": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\n\nnamespace ConsoleApplication1\n{\n class Program\n {\n static void Main(string[] args)\n {\n FakeMainForm form = new FakeMainForm();\n form.CreateComponentAndListenForMessage();\n Console.ReadKey(true);\n }\n }\n\n class FakeMainForm\n {\n public FakeMainForm()\n {\n Listener.AddListener(MessageRecieved);\n }\n\n void MessageRecieved(string msg)\n {\n Console.WriteLine(\"FakeMainForm.MessageRecieved: {0}\", msg);\n }\n\n public void CreateComponentAndListenForMessage()\n {\n ComponentClass component = new ComponentClass();\n component.PretendToProcessData();\n }\n }\n\n class Listener\n {\n private static event Action<string> Notify;\n\n public static void AddListener(Action<string> handler)\n {\n Notify += handler;\n }\n\n public static void InvokeListener(string msg)\n {\n if (Notify != null) { Notify(msg); }\n }\n }\n\n class ComponentClass\n {\n public void PretendToProcessData()\n {\n Listener.InvokeListener(\"ComponentClass.PretendToProcessData() was called\");\n }\n }\n}\n"
}
] | 2008/12/05 | [
"https://Stackoverflow.com/questions/345318",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/43823/"
] |
345,323 | <p>I've been using cmd.Parameters.AddWithValue, and not specifying a DBType (int, varchar,...) to run queries. After looking at SQL Profiler, it seems that queries run with this method run a lot slower than when you specify the data type. </p>
<p>To give you an idea of how much slower it is, here's an example. The query is a simple lookup on a single table, and the column in the where statement is indexed. When specifying the data type, a certain query runs in about 0 MS (too small for sql server to measure), and requires 41 reads. When I remove the DBType, it can take around 200 ms, and 10000 reads for the query to complete. </p>
<p>I'm not sure if it's just SQL Profiler misreporting values, or if these values are actually correct, but it is reproducible, in that I can add and remove the DBType, and it will produce the values given in SQL Profiler.</p>
<p>Has anybody else come across this problem, and a simple way to fix it. I realize that I could go in adding the data type in all over my code, but that seems like a lot of stuff to add in, and if there is an easier way to fix it, that would be much appreciated.</p>
<p>[EDIT]</p>
<p>After some initial testing (running both scenarios in a loop) it seems like the values that profiler gives are accurate. </p>
<p>Just as added information I'm running .Net 2.0 on Windows XP Pro, and SQL Server 2000 on Windows 2000 for the DB.</p>
<p>[UPDATE]</p>
<p>After some digging around, I was able to find this <a href="http://www.u2u.info/Blogs/U2U/Lists/Posts/Post.aspx?ID=11" rel="nofollow noreferrer">blog post</a>, which may be related. Seems that string values in .Net (since they are unicode) are automatically created as nvarchar parameters. I'll have to wait until monday when I get into work to see if I can do something around this which fixes the problem. Still it seems as though I would have to set the data type, which was what I was trying to avoid. </p>
<p>This problem doesn't show up with every query I did, just a select few, so I still may just resort to setting the DBType in the queries with problems, but I'm looking for a more generalized solution to the problem.</p>
| [
{
"answer_id": 345408,
"author": "shahkalpesh",
"author_id": 23574,
"author_profile": "https://Stackoverflow.com/users/23574",
"pm_score": 0,
"selected": false,
"text": "SELECT OrderId FROM Orders WHERE OrderId = 1001 SELECT OrderId FROM Orders WHERE OrderId = '1001'"
},
{
"answer_id": 1002108,
"author": "Will Shaver",
"author_id": 68567,
"author_profile": "https://Stackoverflow.com/users/68567",
"pm_score": 2,
"selected": false,
"text": "cmd.Parameters.AddWithValue(\"charcolumn\", \"stringvalue\");\ncmd.Parameters[0].SqlDbType = SqlDbType.Char;\n cmd.CommandText = \"SELECT * FROM dbo.adonetdemo WHERE trackingstring = @tstring\";\ncmd.Parameters.AddWithValue(\"tstring\",\"4E0A-4F89-AE\");\ncmd.Parameters[0].DbType = System.Data.DbType.AnsiString;\n cmd.Parameters.AddWithValue(colName, val);\nif(val is string)\n cmd.Parameters[i].DbType = DbType.AnsiString;\n"
}
] | 2008/12/05 | [
"https://Stackoverflow.com/questions/345323",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1862/"
] |
345,324 | <p>I have an application that has multiple states, with each state responding to input differently.</p>
<p>The initial implementation was done with a big switch statement, which I refactored using the state pattern (at least, I think it's the state pattern. I'm kind of new to using design patterns, so I tend to get them confused) -</p>
<pre><code>class App {
public:
static App * getInstance();
void addState(int state_id, AppState * state) { _states[state_id] = state; }
void setCurrentState(int state_id) { _current_state = _states[state_id]; }
private:
App()
~App();
std::map<int, AppState *> _states;
AppState * _current_state;
static App * _instance;
}
class AppState {
public:
virtual void handleInput() = 0;
virtual ~AppState();
protected:
AppState();
}
</code></pre>
<p>Currently, each state is polling the OS for input, and acting accordingly. This means each concrete state has a huge switch statement with a case for each valid keypress. Some cases call functions, and other cases issue state changes by using App::setCurrentState(newstate). The catch is that a key that does something in one state may not do anything (or in rare circumstances, may do something different) in another state.</p>
<p>Okay, I think that's the pertinent background. Here's the actual question(s) -</p>
<p>First, what's the best way to eliminate the huge switch statements in the concrete states? <a href="https://stackoverflow.com/questions/126409/ways-to-eliminate-switch-in-code#126475">This question</a> suggests the command pattern, but I don't understand how I would use it here. Can someone help explain it, or suggest another solution?</p>
<p>As a side note, I've considered (and am not opposed to) the idea of letting the App class do the polling of the OS, and then pass inputs to _current_state->handleInput. In fact, something tells me that I'll want to do this as part of the refactoring. I just haven't done it yet.</p>
<p>Second, state changes are made by calling App::setCurrentState(newstate). I realize that this is akin to using globals, but I'm not sure of a better way to do it. My main goal is to be able to add states without modifying the App class. Suggestions would be welcome here as well.</p>
| [
{
"answer_id": 345654,
"author": "jyoung",
"author_id": 14841,
"author_profile": "https://Stackoverflow.com/users/14841",
"pm_score": 0,
"selected": false,
"text": "class StateMachine {\npublic:\n void handleInput() { //there is now only one dispatcher\n if( world.doingInput1() )\n _current_state->handleInput1( *this );\n\n else if( world.doingInput2() )\n _current_state->handleInput2( *this, world.get_Input2Argument() );\n\n //...\n }\n\n //the states, just a set of event handlers\n static const State& state1;\n static const State& state2;\n //...\n\n StateMachine( OutsideWorld& world )\n :world( world ) \n {\n setCurrentState( StateMachine::state1 );\n }\n\n void setCurrentState( const State& state ) { _current_state = &state; }\n\n OutsidWorld& world;\nprivate:\n State* _current_state;\n};\n\nclass State {\npublic:\n //virtual ~State(); //no resources so no cleanup\n virtual void handleInput1( StateMachine& sm ) const {};\n virtual void handleInput2( StateMachine& sm, int myParam ) const {};\n //...\n};\n\nclass State1 {\npublic:\n //define the ones that actually do stuff\n virtual void handleInput1( StateMachine& sm ) const { \n sm.world.DoSomething();\n sm.setCurrentState( StateMachine::state27 );\n }\n virtual void handleInput27( StateMachine& sm, int myParam ) const { \n sm.world.DoSomethingElse( myParam );\n };\n};\nconst State& StateMachine::state1 = *new State1();\n\n//... more states\n"
},
{
"answer_id": 345956,
"author": "Bill B",
"author_id": 27088,
"author_profile": "https://Stackoverflow.com/users/27088",
"pm_score": 1,
"selected": false,
"text": "class App {\n\n public:\n static App * getInstance();\n void addState(int state_id, AppState * state) { _states[state_id] = state; }\n void setCurrentState(int state_id) { _current_state = _states[state_id]; }\n\n private:\n App()\n ~App();\n std::map<int, AppState *> _states;\n AppState * _current_state;\n static App * _instance;\n}\n\nclass AppState {\n\n public:\n virtual void handleInput(int keycode) = 0;\n virtual ~AppState();\n\n protected:\n AppState(App * app);\n AppState * _app;\n\n}\n"
}
] | 2008/12/05 | [
"https://Stackoverflow.com/questions/345324",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/27088/"
] |
345,329 | <p>I have just started playing with the ASP.Net MVC framework, and today I created a simple UserControl that uses some CSS. Since the CSS was declared in a separate file and included in the View that called the UserControl, and not in the UserControl itself, Visual Studio could not find any of the CSS classes used in the UserControl. This got me thinking about what would be the most appropriate way of dealing with CSS in UserControls.</p>
<p>Declaring the CSS in the View that is using the UserControl gives more flexibility if the same control is used in different contexts and needs to be able to adapt to the style of the calling View.</p>
<p>Having the UserControl supply its own CSS would lead to a more clear separation, and the Views would not need to know anything about the HTML/CSS generated by the UserControl, but at the cost of a fixed look of the control.</p>
<p>Since I am totally new to the framework, I'm guessing people have already come to some good conclusions about this.</p>
<p>So, would you have the UserControl handle its own CSS, should it depend on the CSS declared in the calling View, or is there another, better solution?</p>
| [
{
"answer_id": 345405,
"author": "Timothy Khouri",
"author_id": 11917,
"author_profile": "https://Stackoverflow.com/users/11917",
"pm_score": 0,
"selected": false,
"text": "<%= MyHelperClass.Marquee(\"This text will scroll!!!\", \"important-text\") %>\n"
}
] | 2008/12/05 | [
"https://Stackoverflow.com/questions/345329",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/276/"
] |
345,343 | <p>What is the simplest way to count # of visits by a user in an ASP.NET web app?</p>
<p>Our app services anonymous users, registered users and an intermediate user, called a "prospect". Prospects are users that request information but do not create an account.</p>
<p>We leave an ID cookie for every type of user, and that's the key into our database for visit information.</p>
<p>Prospects never "sign in" per se, but we still want to count those visits. We also want to count member visits, even when they don't sign in.</p>
<p>I am thinking of storing the ASP.NET Session cookie and then incrementing our counter every time the session cookie changes.</p>
<p>Anyone out there already solve this, or have any suggestions?</p>
<p>PS: We are ASP.NET 1.1</p>
<p>Refinement: We want this data in our app's database, so Google Analytics is not a reasonable solutions for this...and we are using Google Analytics.</p>
| [
{
"answer_id": 345390,
"author": "FlySwat",
"author_id": 1965,
"author_profile": "https://Stackoverflow.com/users/1965",
"pm_score": 0,
"selected": false,
"text": "SELECT COUNT(1) FROM TblUsers WHERE UserType = 'Prospect' AND DateRange Between....\n"
}
] | 2008/12/05 | [
"https://Stackoverflow.com/questions/345343",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/32700/"
] |
345,352 | <p>I want to build a LineChart component where the color of the line is indicative on how high the value is. I should be able to do this buy just using a gradient stroke (see below) but for some reason the gradient only goes from left to right and the "angle" property is being ignored. How could i do this?</p>
<pre><code> <mx:PlotChart id="bpChart" width="514" height="144" dataProvider="{measurementsXLC}" >
<mx:series>
<mx:LineSeries id="bpSeries" displayName="Series 1" yField="value" xField="date" showDataEffect="fade" stroke="{lstroke}">
<mx:lineStroke>
<mx:LinearGradientStroke angle="270.0" weight="3" scaleMode="vertical" >
<mx:entries>
<mx:GradientEntry color="#ff0000" ratio="0.0"/>
<mx:GradientEntry color="#00ff00" ratio="1.0"/>
</mx:entries>
</mx:LinearGradientStroke>
</mx:lineStroke>
<mx:itemRenderer>
<mx:Component>
<mx:CircleItemRenderer >
</mx:CircleItemRenderer>
</mx:Component>
</mx:itemRenderer>
</mx:LineSeries>
<mx:LineSeries id="bpSeries2" displayName="Series 1" yField="value2" xField="date" showDataEffect="fade" />
</mx:series>
<mx:horizontalAxis>
<mx:DateTimeAxis id="dateAxis" dataUnits="milliseconds" labelUnits="days" />
</mx:horizontalAxis>
<mx:verticalAxis>
<mx:LinearAxis baseAtZero="false" autoAdjust="true" interval="5" />
</mx:verticalAxis>
</mx:PlotChart>
</code></pre>
| [
{
"answer_id": 460600,
"author": "James Hay",
"author_id": 47339,
"author_profile": "https://Stackoverflow.com/users/47339",
"pm_score": 1,
"selected": false,
"text": "override protected function updateDisplayList(unscaledWidth:Number,\n unscaledHeight:Number):void\n {\n super.updateDisplayList(unscaledWidth, unscaledHeight);\n\n var fill:IFill = GraphicsUtilities.fillFromStyle(getStyle(\"areaFill\"));\n var stroke:IStroke = getStyle(\"areaStroke\");\n var form:String = getStyle(\"form\");\n\n var g:Graphics = graphics;\n g.clear();\n\n if (!_area)\n return;\n\n var boundary:Array /* of Object */ = _area.filteredCache;\n var n:int = boundary.length;\n if (n <= 1)\n return;\n\n var xMin:Number;\n var xMax:Number = xMin = boundary[0].x;\n var yMin:Number;\n var yMax:Number = yMin = boundary[0].y;\n\n var i:int;\n var v:Object;\n\n for (i = 0; i < n; i++)\n {\n v = boundary[i];\n\n xMin = Math.min(xMin, v.x);\n yMin = Math.min(yMin, v.y);\n xMax = Math.max(xMax, v.x);\n yMax = Math.max(yMax, v.y);\n\n if (!isNaN(v.min))\n {\n yMin = Math.min(yMin, v.min);\n yMax = Math.max(yMax, v.min);\n }\n }\n\n if (fill)\n fill.begin(g, new Rectangle(0, 0, unscaledWidth, unscaledHeight));\n\n GraphicsUtilities.drawPolyLine(g, boundary, 0, n,\n \"x\", \"y\", stroke, form);\n\n g.lineStyle(0,0,0); \n\n if(boundary[0].element.minField != null && boundary[0].element.minField != \"\")\n {\n g.lineTo(boundary[n - 1].x, boundary[n - 1].min); \n\n GraphicsUtilities.drawPolyLine(g, boundary, n - 1, -1,\n \"x\", \"min\", noStroke, form, false);\n }\n else\n {\n g.lineTo(boundary[n - 1].x, _area.renderedBase); \n g.lineTo(boundary[0].x, _area.renderedBase);\n }\n\n g.lineStyle(0, 0, 0);\n g.lineTo(boundary[0].x, boundary[0].y);\n\n g.endFill();\n }\n"
},
{
"answer_id": 11755485,
"author": "Ad Pijnenburg",
"author_id": 1187072,
"author_profile": "https://Stackoverflow.com/users/1187072",
"pm_score": 2,
"selected": false,
"text": " override protected function updateDisplayList(unscaledWidth:Number,\n unscaledHeight:Number):void\n {\n super.updateDisplayList(unscaledWidth, unscaledHeight);\n\n var stroke:LinearGradientStroke = getStyle(\"lineStroke\");\n var form:String = getStyle(\"form\");\n var gradientBoxMatrix:Matrix = new Matrix();\n gradientBoxMatrix.createGradientBox(unscaledWidth,0.9*(unscaledHeight),Math.PI/2,0,-0.05*(unscaledHeight));\n graphics.clear();\n graphics.lineStyle(stroke.weight,0);\n\n graphics.lineGradientStyle(GradientType.LINEAR,[stroke.entries[0].color,stroke.entries[1].color],[1,1],[0,255],gradientBoxMatrix);\n\n graphics.moveTo(_lineSegment.items[_lineSegment.start].x,_lineSegment.items[_lineSegment.start].y);\n graphics.lineTo(_lineSegment.items[_lineSegment.end].x,_lineSegment.items[_lineSegment.end].y);\n }\n"
}
] | 2008/12/05 | [
"https://Stackoverflow.com/questions/345352",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
345,354 | <p>I have a control that is created like so:</p>
<pre><code>public partial class MYControl : MyControlBase
{
public string InnerText {
get { return textBox1.Text; }
set { textBox1.Text = value; }
}
public MYControl()
{
InitializeComponent();
}
}
partial class MYControl
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Component Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.textBox1 = new System.Windows.Forms.TextBox();
this.listBox1 = new System.Windows.Forms.ListBox();
this.label1 = new System.Windows.Forms.Label();
this.SuspendLayout();
//
// textBox1
//
this.textBox1.Location = new System.Drawing.Point(28, 61);
this.textBox1.Name = "textBox1";
this.textBox1.Size = new System.Drawing.Size(100, 20);
this.textBox1.TabIndex = 0;
//
// listBox1
//
this.listBox1.FormattingEnabled = true;
this.listBox1.Location = new System.Drawing.Point(7, 106);
this.listBox1.Name = "listBox1";
this.listBox1.Size = new System.Drawing.Size(120, 95);
this.listBox1.TabIndex = 1;
//
// label1
//
this.label1.AutoSize = true;
this.label1.Location = new System.Drawing.Point(91, 42);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(35, 13);
this.label1.TabIndex = 2;
this.label1.Text = "label1";
//
// MYControl
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.Controls.Add(this.label1);
this.Controls.Add(this.listBox1);
this.Controls.Add(this.textBox1);
this.Name = "MYControl";
this.Size = new System.Drawing.Size(135, 214);
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.Label label1;
}
</code></pre>
<p>MyControlBase contains the definition for the ListBox and TextBox. Now when I try to view this control in the Form Designer it gives me these errors:</p>
<blockquote>
<p>The variable 'listBox1' is either
undeclared or was never assigned.</p>
<p>The variable 'textBox1' is either
undeclared or was never assigned.</p>
</blockquote>
<p>This is obviously wrong as they are defined in MyControlBase with public access. Is there any way to massage Form Designer into allowing me to visually edit my control?</p>
| [
{
"answer_id": 345457,
"author": "Esteban Brenes",
"author_id": 14177,
"author_profile": "https://Stackoverflow.com/users/14177",
"pm_score": 0,
"selected": false,
"text": "protected System.Windows.Forms.TextBox textbox1; \nprotected System.Windows.Forms.ListBox listbox1;\n"
}
] | 2008/12/05 | [
"https://Stackoverflow.com/questions/345354",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/26166/"
] |
345,356 | <p>Python 2.6 was basically a stepping stone to make converting to Python 3 easier. A lot of the features destined for Python 3 were implemented in 2.6 if they didn't break backward compatibility with syntax and the class libs.</p>
<p>Why weren't set literals (<code>{1, 2, 3}</code>), set comprehensions (<code>{v for v in l}</code>), or dict comprehensions (<code>{k: v for k, v in d}</code>) among them? In particular dict comprehensions would have been a great boon... I find myself using the considerably uglier <code>dict([(k, v) for k, v in d])</code> an awful lot lately.</p>
<p>Is there something obvious I'm missing, or was this just a feature that didn't make the cut?</p>
| [
{
"answer_id": 345502,
"author": "tzot",
"author_id": 6899,
"author_profile": "https://Stackoverflow.com/users/6899",
"pm_score": 3,
"selected": false,
"text": "from __future__ import … dict([(k,v) for k,v in d]) dict((k,v) for k,v in d)"
}
] | 2008/12/05 | [
"https://Stackoverflow.com/questions/345356",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/156/"
] |
345,385 | <p>does anyone know if there is a simple way to bind a textblock to a List.
What I've done so far is create a listview and bind it to the List and then I have a template within the listview that uses a single textblock.</p>
<p>what I'd really like to do is just bind the List to a textblock and have it display all the lines.</p>
<p>In Winforms there was a "Lines" property that I could just throw the List into, but I'm not seeing it on the WPF textblock, or TextBox.</p>
<p>Any ideas?</p>
<p>did I miss something simple?</p>
<p>Here's the code</p>
<pre><code><UserControl x:Class="QSTClient.Infrastructure.Library.Views.WorkItemLogView"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Width="500" Height="400">
<StackPanel>
<ListView ItemsSource="{Binding Path=Logs}" >
<ListView.View>
<GridView>
<GridViewColumn Header="Log Message">
<GridViewColumn.CellTemplate>
<DataTemplate>
<TextBlock Text="{Binding}"/>
</DataTemplate>
</GridViewColumn.CellTemplate>
</GridViewColumn>
</GridView>
</ListView.View>
</ListView>
</StackPanel>
</code></pre>
<p></p>
<p>and the WorkItem Class</p>
<pre><code>public class WorkItem
{
public string Name { get; set; }
public string Description { get; set; }
public string CurrentLog { get; private set; }
public string CurrentStatus { get; private set; }
public WorkItemStatus Status { get; set; }
public ThreadSafeObservableCollection<string> Logs{get;private set;}
</code></pre>
<p>I'm using Prism to create the control and put it into a WindowRegion</p>
<pre><code> WorkItemLogView newView = container.Resolve<WorkItemLogView>();
newView.DataContext = workItem;
regionManager.Regions["ShellWindowRegion"].Add(newView);
</code></pre>
<p>thanks</p>
| [
{
"answer_id": 345515,
"author": "Jobi Joy",
"author_id": 8091,
"author_profile": "https://Stackoverflow.com/users/8091",
"pm_score": 6,
"selected": true,
"text": "<TextBlock Text=\"{Binding Path=Logs,Converter={StaticResource ListToStringConverter}}\"/>\n [ValueConversion(typeof(List<string>), typeof(string))]\npublic class ListToStringConverter : IValueConverter\n{\n\n public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)\n {\n if (targetType != typeof(string))\n throw new InvalidOperationException(\"The target must be a String\");\n\n return String.Join(\", \", ((List<string>)value).ToArray());\n }\n\n public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)\n {\n throw new NotImplementedException();\n }\n}\n"
},
{
"answer_id": 8062060,
"author": "punker76",
"author_id": 920384,
"author_profile": "https://Stackoverflow.com/users/920384",
"pm_score": 3,
"selected": false,
"text": "using System;\nusing System.Collections.ObjectModel;\nusing System.Windows;\n\nnamespace BindListToTextBlock\n{\n /// <summary>\n /// Interaction logic for MainWindow.xaml\n /// </summary>\n public partial class MainWindow : Window\n {\n private WorkItem workItem;\n\n public MainWindow() {\n this.WorkItems = new ObservableCollection<WorkItem>();\n this.DataContext = this;\n this.InitializeComponent();\n }\n\n public class WorkItem\n {\n public WorkItem() {\n this.Logs = new ObservableCollection<string>();\n }\n\n public string Name { get; set; }\n public ObservableCollection<string> Logs { get; private set; }\n }\n\n public ObservableCollection<WorkItem> WorkItems { get; set; }\n\n private void Button_Click(object sender, RoutedEventArgs e) {\n this.workItem = new WorkItem() {Name = string.Format(\"new item at {0}\", DateTime.Now)};\n this.workItem.Logs.Add(\"first log\");\n this.WorkItems.Add(this.workItem);\n }\n\n private void Button_Click_1(object sender, RoutedEventArgs e) {\n if (this.workItem != null) {\n this.workItem.Logs.Add(string.Format(\"more log {0}\", DateTime.Now));\n }\n }\n }\n}\n <Window x:Class=\"BindListToTextBlock.MainWindow\"\n xmlns=\"http://schemas.microsoft.com/winfx/2006/xaml/presentation\"\n xmlns:x=\"http://schemas.microsoft.com/winfx/2006/xaml\"\n xmlns:BindListToTextBlock=\"clr-namespace:BindListToTextBlock\"\n Title=\"MainWindow\"\n Height=\"350\"\n Width=\"525\">\n <Grid>\n <Grid.Resources>\n <BindListToTextBlock:ListToStringConverter x:Key=\"ListToStringConverter\" />\n </Grid.Resources>\n <Grid.RowDefinitions>\n <RowDefinition Height=\"Auto\" />\n <RowDefinition Height=\"Auto\" />\n <RowDefinition />\n </Grid.RowDefinitions>\n <Button Grid.Row=\"0\"\n Content=\"Add item...\"\n Click=\"Button_Click\" />\n <Button Grid.Row=\"1\"\n Content=\"Add some log to last item\"\n Click=\"Button_Click_1\" />\n <ListView Grid.Row=\"2\"\n ItemsSource=\"{Binding Path=WorkItems}\">\n <ListView.View>\n <GridView>\n <GridViewColumn Header=\"Name\">\n <GridViewColumn.CellTemplate>\n <DataTemplate>\n <TextBlock Text=\"{Binding Path=Name}\" />\n </DataTemplate>\n </GridViewColumn.CellTemplate>\n </GridViewColumn>\n <GridViewColumn Header=\"Log Message\">\n <GridViewColumn.CellTemplate>\n <DataTemplate>\n <TextBlock Text=\"{Binding Path=Logs, Converter={StaticResource ListToStringConverter}}\" />\n </DataTemplate>\n </GridViewColumn.CellTemplate>\n </GridViewColumn>\n </GridView>\n </ListView.View>\n </ListView>\n </Grid>\n</Window>\n using System;\nusing System.Collections;\nusing System.Globalization;\nusing System.Linq;\nusing System.Windows;\nusing System.Windows.Data;\n\nnamespace BindListToTextBlock\n{\n public class ListToStringConverter : IValueConverter\n {\n public object Convert(object value, Type targetType, object parameter, CultureInfo culture) {\n if (value is IEnumerable) {\n return string.Join(Environment.NewLine, ((IEnumerable)value).OfType<string>().ToArray());\n }\n return \"no messages yet\";\n }\n\n public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) {\n return DependencyProperty.UnsetValue;\n }\n }\n}\n public class CustomTextBlock : TextBlock, INotifyPropertyChanged\n{\n public static readonly DependencyProperty ListToBindProperty =\n DependencyProperty.Register(\"ListToBind\", typeof(IBindingList), typeof(CustomTextBlock), new PropertyMetadata(null, ListToBindPropertyChangedCallback));\n\n private static void ListToBindPropertyChangedCallback(DependencyObject o, DependencyPropertyChangedEventArgs e)\n {\n var customTextBlock = o as CustomTextBlock;\n if (customTextBlock != null && e.NewValue != e.OldValue) {\n var oldList = e.OldValue as IBindingList;\n if (oldList != null) {\n oldList.ListChanged -= customTextBlock.BindingListChanged;\n }\n var newList = e.NewValue as IBindingList;\n if (newList != null) {\n newList.ListChanged += customTextBlock.BindingListChanged;\n }\n }\n }\n\n private void BindingListChanged(object sender, ListChangedEventArgs e)\n {\n this.RaisePropertyChanged(\"ListToBind\");\n }\n\n public IBindingList ListToBind\n {\n get { return (IBindingList)this.GetValue(ListToBindProperty); }\n set { this.SetValue(ListToBindProperty, value); }\n }\n\n private void RaisePropertyChanged(string propName)\n {\n var eh = this.PropertyChanged;\n if (eh != null) {\n eh(this, new PropertyChangedEventArgs(propName));\n }\n }\n\n public event PropertyChangedEventHandler PropertyChanged;\n}\n CustomTextBlock <TextBlock Text=\"{Binding Path=ListToBind, RelativeSource=Self, Converter={StaticResource ListToStringConverter}}\"\n ListToBind={Binding Path=Logs} />\n"
},
{
"answer_id": 34543867,
"author": "david",
"author_id": 5126416,
"author_profile": "https://Stackoverflow.com/users/5126416",
"pm_score": 0,
"selected": false,
"text": " /// <summary>Convertisseur pour concaténer des objets.</summary>\n[ValueConversion(typeof(IEnumerable<object>), typeof(object))]\npublic class ConvListToString : IValueConverter {\n /// <summary>Convertisseur pour le Get.</summary>\n public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) {\n return String.Join(\", \", ((IEnumerable<object>)value).ToArray());\n }\n /// <summary>Convertisseur inverse, pour le Set (Binding).</summary>\n public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) {\n throw new NotImplementedException();\n }\n}\n"
}
] | 2008/12/05 | [
"https://Stackoverflow.com/questions/345385",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/29849/"
] |
345,396 | <p>I tried doing this but this only display the radiobutton without text beside it..</p>
<pre><code><% foreach (string s in Html.RadioButtonList("rbl")) {%>
<% =s %>
<% } %>
</code></pre>
| [
{
"answer_id": 410296,
"author": "ccook",
"author_id": 51275,
"author_profile": "https://Stackoverflow.com/users/51275",
"pm_score": 3,
"selected": false,
"text": "<% foreach (Model model in Models))\n {\n%><%= String.Format(\"<input type=\\\"radio\\\" value=\\\"{0}\\\" name=\\\"{1}\\\" id=\\\"{2}\\\"><label for=\\\"{2}\\\">{3}</label>\",\n model.ID, \"fieldName\", model.modelID, model.Name) %><br />\n<% } %>\n"
},
{
"answer_id": 711442,
"author": "Zack Peterson",
"author_id": 83,
"author_profile": "https://Stackoverflow.com/users/83",
"pm_score": 4,
"selected": false,
"text": "<!-- After using and looking at the code for the Html.RadioButtonList in the ASP.NET MVC 1.0 RTM codebase, I'm not sure how it is supposed to be useful. It only outputs the actual input radio button and doesn't render any corresponding labels. To get around this I ended up writing a foreach creating individual Html.RadioButton and labels -->\n<%\nvar radioButtonList = new SelectList(new List<ListItem> {\n new ListItem { Text = \"Current\", Value=\"false\", Selected=true },\n new ListItem { Text = \"Other\", Value=\"true\"}}, \"Value\", \"Text\", \"false\");\nvar htmlAttributes = new Dictionary<string, object> {\n { \"class\", \"radioButtonList\" },\n { \"onclick\", \"if(eval(this.value)) { $('#tblDate').show('slow'); } else { $('#tblDate').hide('slow'); }\" }\n};\nforeach (var radiobutton in radioButtonList) { %>\n <%=Html.RadioButton(\"rblDate\", radiobutton.Value, radiobutton.Selected, htmlAttributes)%>\n <label><%=radiobutton.Text%></label>\n<% } %>\n"
},
{
"answer_id": 12190476,
"author": "charith",
"author_id": 1635045,
"author_profile": "https://Stackoverflow.com/users/1635045",
"pm_score": 3,
"selected": false,
"text": "@{\n var radioButtonList = new SelectList(new List<ListItem> {\n new ListItem { Text = \"1\", Value=\"true\", Selected=true },\n new ListItem { Text = \"2\", Value=\"false\"},\n new ListItem { Text = \"3\", Value=\"false\"},\n new ListItem { Text = \"4\", Value=\"false\"},\n\n }, \"Value\", \"Text\", \"false\");\n\n var htmlAttributes = new Dictionary<string, object> {\n { \"class\", \"radioButtonList\" },\n { \"onclick\", \"if(eval(this.value)) { $('#tblDate').show('slow'); } else { $('#tblDate').hide('slow'); }\" }\n}; \n }\n\n@foreach (var radiobutton in radioButtonList) { \n\n @Html.RadioButtonFor(m => m.ContactDepartment, @radiobutton.Text) @radiobutton.Text\n\n <br/>\n}\n"
}
] | 2008/12/05 | [
"https://Stackoverflow.com/questions/345396",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/43838/"
] |
345,401 | <p>I've got a couple django models that look like this:</p>
<pre><code>from django.contrib.sites.models import Site
class Photo(models.Model):
title = models.CharField(max_length=100)
site = models.ForeignKey(Site)
file = models.ImageField(upload_to=get_site_profile_path)
def __unicode__(self):
return self.title
class Gallery(models.Model):
name = models.CharField(max_length=40)
site = models.ForeignKey(Site)
photos = models.ManyToManyField(Photo, limit_choices_to = {'site':name} )
def __unicode__(self):
return self.name
</code></pre>
<p>I'm having all kinds of <em>fun</em> trying to get the <code>limit_choices_to</code> working on the Gallery model. I only want the Admin to show choices for photos that belong to the same site as this gallery. Is this possible?</p>
| [
{
"answer_id": 345419,
"author": "Tom",
"author_id": 3715,
"author_profile": "https://Stackoverflow.com/users/3715",
"pm_score": -1,
"selected": false,
"text": "form.fields[\"photos\"].queryset = request.user.photo_set.all()\n"
},
{
"answer_id": 345529,
"author": "muhuk",
"author_id": 42188,
"author_profile": "https://Stackoverflow.com/users/42188",
"pm_score": 3,
"selected": true,
"text": "site Photo ForeignKey Gallery limit_choices_to photos Gallery ForeignKey Site class Photo(models.Model):\n title = models.CharField(max_length=100)\n gallery = models.ForeignKey(Gallery, related_name='photos')\n file = models.ImageField(upload_to=get_site_profile_path) \n\n def __unicode__(self):\n return self.title\n\n\nclass Gallery(models.Model): \n name = models.CharField(max_length=40)\n site = models.ForeignKey(Site)\n\n def __unicode__(self):\n return self.name\n site photo_instance.gallery.site @property\ndef site(self):\n return self.gallery.site\n site"
},
{
"answer_id": 1881187,
"author": "Vebjorn Ljosa",
"author_id": 17498,
"author_profile": "https://Stackoverflow.com/users/17498",
"pm_score": 3,
"selected": false,
"text": "Gallery photos class GalleryAdminForm(django.forms.ModelForm):\n\n class Meta:\n model = Gallery\n\n def __init__(self, *args, **kwargs):\n super(GalleryAdminForm, self).__init__(*args, **kwargs)\n self.fields['segments'].queryset = Photo.objects.filter(site=self.instance.site)\n\n\nclass GalleryAdmin(django.contrib.admin.ModelAdmin):\n form = GalleryAdminForm\n\ndjango.contrib.admin.site.register(Gallery, GalleryAdmin)\n"
}
] | 2008/12/05 | [
"https://Stackoverflow.com/questions/345401",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3912/"
] |
345,406 | <p>I am trying to convert this test code to C# and having a problem with the Trim command. Has anyone done anything similiar like this in C# going to use this with a text box for searching the aspx page. </p>
<pre><code>Dim q = From b In db.Blogs _
Where b.BlogContents.Contains(txtSearch.Text.Trim()) Or _
b.BlogTitle.Contains(txtSearch.Text.Trim()) _
Select b
</code></pre>
| [
{
"answer_id": 345503,
"author": "Marc Gravell",
"author_id": 23354,
"author_profile": "https://Stackoverflow.com/users/23354",
"pm_score": 3,
"selected": true,
"text": "string s = txtSearch.Text.Trim();\nvar q = from b in db.Blogs\n where b.BlogContents.Contains(s) || b.BlogTitle.Contains(s)\n select b;\n txtSearch Trim s .Text .Trim txtSearch.Text.Trim()"
},
{
"answer_id": 346989,
"author": "Shawn",
"author_id": 26,
"author_profile": "https://Stackoverflow.com/users/26",
"pm_score": 0,
"selected": false,
"text": "()"
}
] | 2008/12/05 | [
"https://Stackoverflow.com/questions/345406",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/37126/"
] |
345,411 | <p>I'm using Fedex's web services and getting an annoying error right up front before I can actually get anywhere.</p>
<p>There was an error in serializing body of message addressValidationRequest1: 'Unable to generate a temporary class (result=1).
error CS0030: Cannot convert type 'FedEx.InterOp.AddressValidationServiceReference.ParsedElement[]' to 'FedEx.InterOp.AddressValidationServiceReference.ParsedElement'
error CS0029: Cannot implicitly convert type 'FedEx.InterOp.AddressValidationServiceReference.ParsedElement' to 'FedEx.InterOp.AddressValidationServiceReference.ParsedElement[]'
'. Please see InnerException for more details.</p>
<p>I'm using .NET 3.5 and get a horrible named class generated for me (I'm not sure why it isn't just AddressValidationService):</p>
<p><code>AddressValidationPortTypeClient addressValidationService = new ...;</code></p>
<p>on this class I make my web service call:</p>
<p><code>addressValidationService.addressValidation(request);</code></p>
<p>This is when I get this error.</p>
<p>The only references I can find to this error come from ancient 1.1 projects. In my case my DLL has references to System.Web and System.Web.Services which seemed to be an issue back then.</p>
| [
{
"answer_id": 429712,
"author": "Simon_Weaver",
"author_id": 16940,
"author_profile": "https://Stackoverflow.com/users/16940",
"pm_score": 6,
"selected": true,
"text": "private ParsedElement[][] parsedStreetLineField;\nto\nprivate ParsedElement[] parsedStreetLineField;\nand\npublic ParsedElement[][] ParsedStreetLine {\nto\npublic ParsedElement[] ParsedStreetLine {\n"
}
] | 2008/12/05 | [
"https://Stackoverflow.com/questions/345411",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16940/"
] |
345,413 | <p>I am working on a plugin system that loads .dll's contained in a specified folder. I am then using reflection to load the assemblies, iterate through the types they contain and identify any that implement my <code>IPlugin</code> interface. </p>
<p>I am checking this with code similar to the following: </p>
<pre><code>foreach(Type t in myTypes )
{
if( typeof(IPlugin).IsAssignableFrom(t) )
{
...
}
}
</code></pre>
<p>For some reason IsAssignableFrom() keeps returning false when it should be returning true. I have tried replacing the <code>t</code> by explicitly giving it a type that should pass, and it works fine, but for some reason it isn't working with the types that are returned from the loaded assembly. To make things stranger, the code works fine on my co-worker's machine but not on mine.</p>
<p>Does anyone know of anything that might cause this sort of behavior?</p>
<p>Thanks</p>
| [
{
"answer_id": 345464,
"author": "Jb Evain",
"author_id": 36702,
"author_profile": "https://Stackoverflow.com/users/36702",
"pm_score": 6,
"selected": true,
"text": "typeof (IPlugin).Module.FullyQualifiedName\n foreach (var type in t.GetInterfaces ()) \n{ \n Console.WriteLine (type.Module.FullyQualifiedName)\n}\n"
},
{
"answer_id": 7907026,
"author": "Mark Jones",
"author_id": 703178,
"author_profile": "https://Stackoverflow.com/users/703178",
"pm_score": -1,
"selected": false,
"text": " public static bool CanBeTreatedAsType(this Type CurrentType, Type TypeToCompareWith)\n {\n // Always return false if either Type is null\n if (CurrentType == null || TypeToCompareWith == null)\n return false;\n\n // Return the result of the assignability test\n return TypeToCompareWith.IsAssignableFrom(CurrentType);\n }\n bool CanBeTreatedAs = typeof(SimpleChildClass).CanBeTreatedAsType(typeof(SimpleClass));\n CanBeTreatedAs = typeof(SimpleClass).CanBeTreatedAsType(typeof(IDisposable));\n"
},
{
"answer_id": 12427298,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": " AppDomain.CurrentDomain.AssemblyResolve += new ResolveEventHandler([Resolve Function]);\n"
},
{
"answer_id": 32858174,
"author": "kad81",
"author_id": 1084886,
"author_profile": "https://Stackoverflow.com/users/1084886",
"pm_score": 3,
"selected": false,
"text": "IsAssignableFrom if (typeof(IPlugin).IsAssignableFrom(t))\n if (t.IsAssignableFrom(typeof(IPlugin)))\n"
},
{
"answer_id": 37184535,
"author": "elm",
"author_id": 2674727,
"author_profile": "https://Stackoverflow.com/users/2674727",
"pm_score": 4,
"selected": false,
"text": "LoadFrom() LoadFile() LoadFrom CopyLocal = False Assembly.LoadFrom"
},
{
"answer_id": 65114687,
"author": "Bryida",
"author_id": 2454214,
"author_profile": "https://Stackoverflow.com/users/2454214",
"pm_score": 1,
"selected": false,
"text": "<ItemGroup>\n <ProjectReference Include=\"..\\PluginBase\\PluginBase.csproj\">\n <Private>false</Private>\n <ExcludeAssets>runtime</ExcludeAssets>\n </ProjectReference>\n</ItemGroup>\n"
},
{
"answer_id": 70796554,
"author": "yuval tirosh",
"author_id": 10804461,
"author_profile": "https://Stackoverflow.com/users/10804461",
"pm_score": 0,
"selected": false,
"text": " using Microsoft.Extensions.DependencyInjection;\n\n private IEnumerable<ISomeInterface> CreatePlugins(Assembly assembly)\n {\n ServiceCollection serviceCollestion = new ServiceCollection();\n serviceCollestion.AddSingleton(dependency1);\n serviceCollestion.AddSingleton(dependency2);\n serviceCollestion.AddSingleton(dependency3);\n var serviceProvider = serviceCollestion.BuildServiceProvider();\n\n foreach (Type type in assembly.GetTypes())\n {\n if (typeof(My.Namespace.ISomeInterface).IsAssignableFrom(type))\n {\n ISomeInterface result = ActivatorUtilities.CreateInstance(serviceProvider, type) as ISomeInterface;\n }\n }\n }\n"
}
] | 2008/12/05 | [
"https://Stackoverflow.com/questions/345413",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20489/"
] |
345,414 | <p>Let's say that I'm considering designing a WCF service whose primary purpose is to provide broad services that can be used by three disparate applications: a public-facing Web site, an internal Windows Forms application, and a wireless mobile device. The purpose of the service is twofold: (1) to consolidate code related to business processes in a central location and (2) to lock down access to the legacy database, finally and once and for all hiding it behind one suite of services. </p>
<p>Currently, each of the three applications has its own persistence and domain layers with slightly different views of the same database. Instead of all three applications talking to the database, they would talk to the WCF service, enabling new features from some clients (the mobile picker can't currently trigger processes to send e-mail, obviously) and centralizing notification systems (instead of a scheduled task polling the database every five minutes for new orders, just ping the overhead paging system when the <code>AcceptNewOrder()</code> service method is invoked by one of these clients). All in all, this sounds pretty sane so far.</p>
<p>In terms of overall design, however, I'm stumped when it comes to security. The Windows Forms application currently just uses Windows principals; employees are stored in Active Directory, and upon application startup, they can login as the current Windows user (in which case no password is required) or they can supply their domain name and password. The mobile client doesn't have any concept of a user; its connection to the database is a hardcoded string. And the Web site has thousands of users stored in the legacy database. So how do I implement the identity model and configure the WCF endpoints to deal with this?</p>
<p>In terms of the Windows Forms application, this is no great issue: the WCF proxy can be initiated once and can hang around in memory, so I only need the client credentials once (and can prompt for them again if the proxy ever faults). The mobile client can just be special cased and use an X509 certificate for authentication against the WCF service. But what do I do about the Web site?</p>
<p>In the Web site's case, anonymous access to some services is allowed. And for the services that require authentication in the hypothetical "Customer" role, I obviously don't want to have to authenticate them on each and every request for two reasons:</p>
<ul>
<li>I need their username and password each time. Storing this pair of information pretty much anywhere--the session, an encrypted cookie, the moon--seems like a bad idea.</li>
<li>I would have to hit the users table in the database for each request. Ouch.</li>
</ul>
<p>The only solution that I can come up with is to treat the Web site as a trusted subsystem. The WCF service expects a particular X509 certificate from the Web site. The Web site, using Forms Authentication internally (which invokes an <code>AuthenticateCustomer()</code> method on the service that returns a boolean result), can add an additional claim to the list of credentials, something like "joe@example.com is logged in as a customer." Then somehow a custom IIdentity object and IPrincipal could be constructed on the service with that claim, the WCF service being confident that the Web site has properly authenticated the customer (it will know that the claim hasn't been tampered with, at least, because it'll know the Web site's certificate ahead of time).</p>
<p>With all of that in place, the WCF service code would be able to say things like <code>[PrincipalPermission.Demand(Role=MyRoles.Customer)]</code> or <code>[PrincipalPermission.Demand(Role=MyRoles.Manager)]</code>, and the <code>Thread.CurrentPrincipal</code> would have something that represented a user (an e-mail address for a customer or a distinguished name for an employee, both of them useful for logging and auditing).</p>
<p>In other words, two different endpoints would exist for each service: one that accepted well-known client X509 certificates (for the mobile devices and the Web site), and one that accept Windows users (for the employees).</p>
<p>Sorry this is so long. So the question is: Does any of this make sense? Does the proposed solution make sense? And am I making this too complicated?</p>
| [
{
"answer_id": 351560,
"author": "Nicholas Piasecki",
"author_id": 32187,
"author_profile": "https://Stackoverflow.com/users/32187",
"pm_score": 5,
"selected": true,
"text": "makecert Personal Trusted People Trusted Root Certification Authorities HttpContext.Current.User.Identity.Name UserNameSecurityToken X509CertificateSecurityToken MyCustomPrincipal MyCustomPrincipal TrustedSubsystemAuthorizationPolicy MyCustomPrincipal TrustedSubsystemImpersonationAuthorizationPolicy MyCustomPrincipal UserNameAuthorizationPolicy UserName ClientCredentials ClientBase<T> ChannelFactory Endpoint MyCustomPrincipal Endpoint ClientCredentials \n // Scenario 1: X509Cert + custom UserName header yields for a Web site customer ...\n Console.WriteLine(\"{0}\", Thread.CurrentPrincipal.Identity.Name); // prints out, say, \"joe@example.com\"\n Console.WriteLine(\"{0}\", Thread.CurrentPrincipal.IsInRole(MyRoles.Customer)); // prints out \"True\"\n\n // Scenario 2: My custom UserNameSecurityToken authentication yields for an employee ...\n Console.WriteLine(\"{0}\", Thread.CurrentPrincipal.Identity.Name); // prints out, say, CN=Nick,DC=example, DC=com\n Console.WriteLine(\"{0}\", Thread.CurrentPrincipal.IsInRole(MyRoles.Employee)); // prints out \"True\"\n\n // Scenario 3: Web site doesn't pass in a UserName header ...\n Console.WriteLine(\"{0}\", Thread.CurrentPrincipal.Identity.Name); // prints out nothing\n Console.WriteLine(\"{0}\", Thread.CurrentPrincipal.IsInRole(MyRoles.Guest)); // prints out \"True\"\n Console.WriteLine(\"{0}\", Thread.CurrentPrincipal.IsInRole(MyRoles.Customer)); // prints out \"False\"\n PrincipalPermission.Demand"
}
] | 2008/12/05 | [
"https://Stackoverflow.com/questions/345414",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/32187/"
] |
345,427 | <p>How do I inner join multiple columns from the same tables via Linq? </p>
<p>For example:
I already have this...</p>
<pre><code>join c in db.table2 on table2.ID equals table1.ID
</code></pre>
<p>I need to add this...</p>
<pre><code>join d in db.table2 on table2.Country equals table1.Country
</code></pre>
| [
{
"answer_id": 345459,
"author": "TGnat",
"author_id": 25121,
"author_profile": "https://Stackoverflow.com/users/25121",
"pm_score": 1,
"selected": false,
"text": " dim qry = FROM t1 in table1 _\n JOIN t2 in table2 on t2.ID equals t1.ID _\n AND t2.Country equals t1.Country \n"
},
{
"answer_id": 345665,
"author": "Pete Haas",
"author_id": 43841,
"author_profile": "https://Stackoverflow.com/users/43841",
"pm_score": 5,
"selected": false,
"text": "var qry = from t1 in table1\n join t2 in table2\n on new {t1.ID,t1.Country} equals new {t2.ID,t2.Country}\n ...\n"
},
{
"answer_id": 806883,
"author": "Rik Hemsley",
"author_id": 329888,
"author_profile": "https://Stackoverflow.com/users/329888",
"pm_score": 5,
"selected": true,
"text": "from t1 in table1\nfrom t2 in table1\nwhere t1.x == t2.x\n&& t1.y == t2.y\n"
},
{
"answer_id": 1139119,
"author": "oglester",
"author_id": 2017,
"author_profile": "https://Stackoverflow.com/users/2017",
"pm_score": 4,
"selected": false,
"text": "var query = from s in context.ShoppingMalls\n join h in context.Houses\n on\n new { s.CouncilCode, s.PostCode }\n equals\n new { h.CouncilCode, h.PostCode }\n select s;\n"
},
{
"answer_id": 11077840,
"author": "Raj Kumar Dey",
"author_id": 1462890,
"author_profile": "https://Stackoverflow.com/users/1462890",
"pm_score": 3,
"selected": false,
"text": "var query = from s in context.ShoppingMalls\njoin h in context.Houses\non\nnew {CouncilCode=s.CouncilCode, PostCode=s.PostCode }\nequals\nnew {CouncilCode=h.District, PostCode=h.ZipCode }\nselect s;\n"
}
] | 2008/12/05 | [
"https://Stackoverflow.com/questions/345427",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/43841/"
] |
345,428 | <p>I want to use libgadu (library of instant messaging protocol) under Visual Studio 2008.
I have downloaded libgadu <a href="http://toxygen.net/libgadu/files/libgadu-1.8.2.tar.gz" rel="nofollow noreferrer">http://toxygen.net/libgadu/files/libgadu-1.8.2.tar.gz</a> and under cygwin I've compiled it - ./configure , make , make install.
File libgadu.h which appeard in include folder I copied to another folder which is marked in VS as Including files directory.</p>
<p>I wanted to compile code from documentation </p>
<pre><code>#include <cstdio>
#include <cstdlib>
#include <iostream>
#include <libgadu.h>
using namespace std;
int main(void)
{
char password[]= "haslo";
struct gg_session *sesja;
struct gg_login_params parametry;
struct gg_event *zdarzenie;
memset(&parametry, 0, sizeof(parametry));
parametry.uin = 12345;
parametry.password = password;
parametry.async = 1;
parametry.status = GG_STATUS_INVISIBLE;
sesja = gg_login(&parametry);
if (!sesja) {
cout << "Can't connect" << endl;
exit(1);
}
system("PAUSE");
}
</code></pre>
<p>During compiling i receive two errors:</p>
<pre><code>Error 1 error LNK2019: unresolved external symbol _gg_login referenced in function _main 1.obj
Error 2 fatal error LNK1120: 1 unresolved externals
</code></pre>
<p>What should I do with it?</p>
| [
{
"answer_id": 345437,
"author": "Frank Krueger",
"author_id": 338,
"author_profile": "https://Stackoverflow.com/users/338",
"pm_score": 3,
"selected": true,
"text": "libgadu"
}
] | 2008/12/05 | [
"https://Stackoverflow.com/questions/345428",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/43842/"
] |
345,432 | <p>I have a simple app loading a site optimized for the iPhone in a <code>UIWebView</code>.</p>
<p>Problem is, caching does not seem to work:</p>
<pre><code>[webView loadRequest: [NSURLRequest requestWithURL: [NSURL URLWithString: url]
cachePolicy: NSURLRequestUseProtocolCachePolicy
timeoutInterval: 60.0]];
</code></pre>
<p>Any things referenced in this remote page (css, images, external javascript files) never get cached (the requests never send a If-Modified-Since header or anything else in the way of cache control.)</p>
<p>Is it possible? It seems with a regular Cocoa WebView there a delegate methods that get called for each resource request and post load (<code>-didFinishLoadingFromDataSource:</code>) which you could use to roll your own caching.. but that does not seem applicable here.</p>
<p>My entire page (page and its referenced resources) is around 89K compressed.. which is slow over 3G in some spots and even worse over EDGE. Incoming requests are at least indicating that it accepts compression (<code>accept-encoding=gzip, deflate</code>), so that's good I suppose.</p>
<p>I read <a href="http://yuiblog.com/blog/2008/02/06/iphone-cacheability/" rel="nofollow noreferrer">this yui study</a>, which seems to indicate that the iPhone will cache 25k per item. The only thing referenced that is over 25k uncompressed is jquery (packed but uncompressed - it is 30k). Everything else should be cacheable. No request for anything referenced in the page fetched is triggering a 304 on the server side.</p>
<p>That yui study was from almost a year ago, and I am guessing with mobile safari only. </p>
<p>This is using a <code>UIWebView</code> in a native iPhone app.</p>
| [
{
"answer_id": 386352,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "UIWebViewDelegate webView:shouldStartLoadWithRequest:navigationType: loadHTMLString:baseURL:"
},
{
"answer_id": 1195847,
"author": "Denis",
"author_id": 146593,
"author_profile": "https://Stackoverflow.com/users/146593",
"pm_score": 3,
"selected": false,
"text": "<img src=\"img.gif\" width=\"...\" height=\"...\" />\n <img src=\"data:image/gif;base64,R0lGODlhUAAPA...JADs= \" width=\"...\" height=\"...\" />\n"
},
{
"answer_id": 3422982,
"author": "rage",
"author_id": 195096,
"author_profile": "https://Stackoverflow.com/users/195096",
"pm_score": 2,
"selected": false,
"text": "ASIWebPageRequest"
},
{
"answer_id": 6643847,
"author": "RandyMcMillan",
"author_id": 837137,
"author_profile": "https://Stackoverflow.com/users/837137",
"pm_score": 3,
"selected": false,
"text": "NSURLCache* cache = [NSURLCache sharedURLCache];\n[cache setMemoryCapacity:4 * 1024 * 1024];\n[cache setDiskCapacity:512*1024];\n\n[NSURLRequest requestWithURL:appURL\n cachePolicy:NSURLRequestReturnCacheDataElseLoad\n timeoutInterval:10.0];\n"
},
{
"answer_id": 12933516,
"author": "Palimondo",
"author_id": 41307,
"author_profile": "https://Stackoverflow.com/users/41307",
"pm_score": 0,
"selected": false,
"text": "NSURLCache UIWebView"
}
] | 2008/12/05 | [
"https://Stackoverflow.com/questions/345432",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/43843/"
] |
345,454 | <p>How can I programmatically generate keypress events from Javascript code running in Safari? It looks like WebKit is using the DOM level 3 model for creating keyboard events from Javascript, and the DOM level 3 keyboard event model does not support the keypress event. Is there another way that I can use?</p>
<p>I'm looking for as pure a Safari/WebKit DOM solution as possible. I'd really prefer not to modify the web page, and I'd also rather not add dependencies on external libraries. I need to activate any existing keypress handlers, so it won't work to add a new handler and directly call it.</p>
<p>It looks like WebKit has the keyCode and charCode properties of the keypress event defined in its UIEvent class, but they are read-only. Is there any way to set those properties? The following does not work:</p>
<pre><code>var evt = document.createEvent('UIEvents');
evt.initUIEvent('keypress', true, true, window, 0);
evt.keyCode = 114; // 'r'
evt.charCode = 114;
alert("keyCode = " + evt.keyCode + ", charCode = " + evt.charCode); // both 0
</code></pre>
<p>Setting the detail property in the call to initUIEvent also seems to have no effect.</p>
| [
{
"answer_id": 345460,
"author": "Matt",
"author_id": 32881,
"author_profile": "https://Stackoverflow.com/users/32881",
"pm_score": -1,
"selected": false,
"text": "<script language=\"text/javascript\" src=\"jquery.js\"></script>\n<script language=\"text/javascript\">\n$(function() {\n // add a keypress handler\n $(\"#someid\").keypress(function(e){\n alert('you just pressed ' + e.which);\n });\n // imitate the keypress\n $(\"#someid\").keypress();\n});\n</script>\n"
},
{
"answer_id": 434863,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 3,
"selected": false,
"text": "var eventObject = document.createEvent('TextEvent');\neventObject.initTextEvent('textInput',\n true,\n true,\n null,\n textToInsert);\n\ntextarea.dispatchEvent(eventObject);\n"
},
{
"answer_id": 571947,
"author": "todd",
"author_id": 69194,
"author_profile": "https://Stackoverflow.com/users/69194",
"pm_score": 0,
"selected": false,
"text": "describe 'I need to be able to edit items in a list', {\n\n... [setup code and other tests]\n\n'should create a new item if I press enter': function(){\n value_of($('#todo').items().size()).should_be(7)\n // be on the last item in the list\n task = $('#todo').items().filter(':last').focus()\n // press enter\n task.__keypress(13)\n // check that an item was added \n value_of($('#todo').tasks().size()).should_be(8)\n },\n}\n which $().items().bind('keypress', function(event){$().__keypress(event.which)}) \n __keypress: function(which){\n switch(which)\n {\n ...\n\n case 13: // enter\n [my code that creates a new item] \n break;\n default:\n } \n },\n\n"
}
] | 2008/12/05 | [
"https://Stackoverflow.com/questions/345454",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/42484/"
] |
345,489 | <p>I read somewhere that one should never use error conditions as normal program flow. Makes excellent sense to me... But</p>
<p>C# application sitting on top of a MySQL db. I need to parse a string value into two parts, an ID, and a value. (The original data come from a Devonian database), then validate the value against a lookup table. So, a couple of original strings might look like this: </p>
<p>"6776 Purple People Eater"</p>
<p>"BIK Yellow Polka-Dot Bikini (currently in use)"</p>
<p>"DCP Deuce Coup"</p>
<p>So, my little utility parses each string into the ID and the description based on the index of the first space (fortunately, consistent). I then pass the ID to the lookup, get the new value and away we go.</p>
<p>Unfortunately, TPTB also decided that we no longer need no stinkin' Yellow Polka-Dot Bikinis (currently in use). So, BIK does not return a row. Here's a code snippet: </p>
<pre><code> foreach (string product in productTokens) {
tempProduct = product.Trim();
if (tempProduct.Length > 0) {
if (tempProduct.Length < 10) {
product_id = tempProduct;
}
else {
int charPosition = tempProduct.IndexOf(" ");
product_id = tempProduct.Substring(0, charPosition);
}
try {
s_product = productAdapter.GetProductName(product_id).ToString();
}
catch (Exception e) {
if (e.Message.ToString() == "Object reference not set to an instance of an object.") {
s_product = "";
}
else {
errLog.WriteLine("Invalid product ID " + e.Message.ToString());
Console.WriteLine("Invalid product ID " + e.Message.ToString());
throw;
} //else
} //catch
if (s_product.Length > 0) {
sTemp = sTemp + s_product + "; ";
}
} //if product.length > 0
} //foreach product in productTokens
</code></pre>
<p>Really, really ugly! Particularly the part where I test for an invalid IDin the catch block. There simply must be a better way to handle this. </p>
<p>If anyone can help me out, I'd really appreciate it. </p>
<p>Thanks. </p>
| [
{
"answer_id": 345493,
"author": "Rob Prouse",
"author_id": 30827,
"author_profile": "https://Stackoverflow.com/users/30827",
"pm_score": 3,
"selected": true,
"text": "object productName = productAdapter.GetProductName(product_id);\nif ( productName != null )\n{\n s_product = productName.ToString();\n}\nelse\n{\n s_product = String.Empty;\n}\n"
},
{
"answer_id": 345496,
"author": "Marc Gravell",
"author_id": 23354,
"author_profile": "https://Stackoverflow.com/users/23354",
"pm_score": 0,
"selected": false,
"text": "var productName = s_product = productAdapter.GetProductName(product_id);\nif(productName == null) { ... do something }\nelse {\n string name = productName.ToString();\n}\n"
},
{
"answer_id": 345592,
"author": "Matt Campbell",
"author_id": 41110,
"author_profile": "https://Stackoverflow.com/users/41110",
"pm_score": 1,
"selected": false,
"text": "productAdapter.GetProductName() String String s_product = productAdapter.GetProductName(product_id) ?? string.Empty;\n String Exception.Message String.Split() IndexOf SubString product_id = tempProduct.Split(\" \", 2)[1];\n Exception Message NullReferenceException catch (NullReferenceException) {\n s_product = \"\";\n}\ncatch (Exception e) {\n // Log your invalid ID error condition here\n}\n"
}
] | 2008/12/05 | [
"https://Stackoverflow.com/questions/345489",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16851/"
] |
345,498 | <p>Because of a space-issue I have to make 'single-character-links' for crud actions:</p>
<p>In characters I would symbolise:<br>
'delete' with character <strong>x</strong><br>
'add' with <strong>+</strong><br>
…<br>
How would you symbolise 'change' ?</p>
| [
{
"answer_id": 345514,
"author": "VonC",
"author_id": 6309,
"author_profile": "https://Stackoverflow.com/users/6309",
"pm_score": 3,
"selected": false,
"text": "*"
}
] | 2008/12/05 | [
"https://Stackoverflow.com/questions/345498",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
345,505 | <p>How can you <a href="http://en.wikipedia.org/wiki/Diff" rel="noreferrer">diff</a> two pipelines without using temporary files in Bash? Say you have two command pipelines:</p>
<pre><code>foo | bar
baz | quux
</code></pre>
<p>And you want to find the <code>diff</code> in their outputs. One solution would obviously be to:</p>
<pre><code>foo | bar > /tmp/a
baz | quux > /tmp/b
diff /tmp/a /tmp/b
</code></pre>
<p>Is it possible to do so without the use of temporary files in Bash? You can get rid of one temporary file by piping in one of the pipelines to diff:</p>
<pre><code>foo | bar > /tmp/a
baz | quux | diff /tmp/a -
</code></pre>
<p>But you can't pipe both pipelines into diff simultaneously (not in any obvious manner, at least). Is there some clever trick involving <code>/dev/fd</code> to do this without using temporary files?</p>
| [
{
"answer_id": 345526,
"author": "VonC",
"author_id": 6309,
"author_profile": "https://Stackoverflow.com/users/6309",
"pm_score": 8,
"selected": true,
"text": " foo | bar > file1.txt && baz | quux > file2.txt && diff file1.txt file2.txt\n diff <(foo | bar) <(baz | quux)\n\n foo | bar | diff - <(baz | quux) # or only use process substitution once\n -- /dev/stdin ++ /dev/fd/63 /dev/fd/63 pipe(2) dup2 quux diff /dev/fd /proc/self/fd echo <(true) /dev/fd/63 strace -f -efile,desc,clone,execve bash -c '/bin/true | diff -u - <(/bin/true)'\n - diff mkfifo file1_pipe.txt\nfoo|bar > file1_pipe.txt && baz | quux | diff file1_pipe.txt - && rm file1_pipe.txt\n ls *.txt | tee /dev/tty txtlist.txt \n tee cat *.txt | tee >(foo | bar > result1.txt) >(baz | quux > result2.txt) | foobar\n"
},
{
"answer_id": 345536,
"author": "BenM",
"author_id": 43850,
"author_profile": "https://Stackoverflow.com/users/43850",
"pm_score": 7,
"selected": false,
"text": "diff <(foo | bar) <(baz | quux)\n"
},
{
"answer_id": 38694413,
"author": "mlg",
"author_id": 965724,
"author_profile": "https://Stackoverflow.com/users/965724",
"pm_score": 3,
"selected": false,
"text": "comm grep -f comm -23 <(seq 100 | sort) <(seq 10 20 && sleep 5 && seq 20 30 | sort)\n comm grep -f sd seq 100 | sd 'seq 10 20 && sleep 5 && seq 20 30'\n seq 100 seq 10 tail -f sd"
}
] | 2008/12/05 | [
"https://Stackoverflow.com/questions/345505",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9530/"
] |
345,506 | <p>suppose I have an enum</p>
<pre><code>[Flags]
public enum E {
zero = 0,
one = 1
}
</code></pre>
<p>then I can write</p>
<pre><code>E e;
object o = 1;
e = (E) o;
</code></pre>
<p>and it will work.</p>
<p>BUT if I try to do that at runtime, like</p>
<pre><code>(o as IConvertible).ToType(typeof(E), null)
</code></pre>
<p>it will throw InvalidCastException.</p>
<p>So, is there something that I can invoke at runtime, and it will convert from int32 to enum, in the same way as if I wrote a cast as above?</p>
| [
{
"answer_id": 345509,
"author": "Konrad Rudolph",
"author_id": 1968,
"author_profile": "https://Stackoverflow.com/users/1968",
"pm_score": 0,
"selected": false,
"text": "null Activator.CreateInstance object o = Activator.CreateInstance(typeof(E));\n"
},
{
"answer_id": 345607,
"author": "shahkalpesh",
"author_id": 23574,
"author_profile": "https://Stackoverflow.com/users/23574",
"pm_score": 3,
"selected": true,
"text": "\nobject o = 1;\nobject z = Enum.ToObject(typeof(E), o); \n"
},
{
"answer_id": 347275,
"author": "Ben Childs",
"author_id": 2925,
"author_profile": "https://Stackoverflow.com/users/2925",
"pm_score": 0,
"selected": false,
"text": "Enum.Parse(typeof(E), (int)o)\n"
}
] | 2008/12/05 | [
"https://Stackoverflow.com/questions/345506",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/43848/"
] |
345,513 | <p>Can someone give some hints of how to delete the last n lines from a file in Perl? I have a very large file of around 400 MB, and I want to delete some 125,000 last lines from it.</p>
| [
{
"answer_id": 345521,
"author": "Svante",
"author_id": 31615,
"author_profile": "https://Stackoverflow.com/users/31615",
"pm_score": 5,
"selected": true,
"text": "head wc -l -n head wc"
},
{
"answer_id": 345533,
"author": "brian d foy",
"author_id": 2766176,
"author_profile": "https://Stackoverflow.com/users/2766176",
"pm_score": 2,
"selected": false,
"text": ":1234567,$d\n"
},
{
"answer_id": 345706,
"author": "Norman Ramsey",
"author_id": 41661,
"author_profile": "https://Stackoverflow.com/users/41661",
"pm_score": 2,
"selected": false,
"text": "tac file | sed '1,125000d' | tac\n"
},
{
"answer_id": 347309,
"author": "Schwern",
"author_id": 14660,
"author_profile": "https://Stackoverflow.com/users/14660",
"pm_score": 3,
"selected": false,
"text": "truncate() read() truncate() #!/usr/bin/perl\n\nuse strict;\nuse warnings;\n\nuse File::ReadBackwards;\n\nmy $LINES = 10; # Change to 125_000 or whatever\nmy $File = shift; # file passed in as argument\n\nmy $rbw = File::ReadBackwards->new($File) or die $!;\n\n# Count backwards $LINES or the beginning of the file is hit\nmy $line_count = 0;\nuntil( $rbw->eof || $line_count == $LINES ) {\n $rbw->readline;\n $line_count++;\n}\n\n# Chop off everything from that point on.\ntruncate($File, $rbw->tell) or die \"Could not truncate! $!\";\n"
},
{
"answer_id": 348451,
"author": "douglashunter",
"author_id": 13838,
"author_profile": "https://Stackoverflow.com/users/13838",
"pm_score": 0,
"selected": false,
"text": "use Fnctl $rbw->get_handle truncate"
},
{
"answer_id": 1587598,
"author": "nighteblis",
"author_id": 192306,
"author_profile": "https://Stackoverflow.com/users/192306",
"pm_score": 0,
"selected": false,
"text": ":|dd of=urfile seek=1 bs=$(($(stat -c%s urfile)-$(tail -1 urfile|wc -c)))\n"
},
{
"answer_id": 1587630,
"author": "mouviciel",
"author_id": 45249,
"author_profile": "https://Stackoverflow.com/users/45249",
"pm_score": 0,
"selected": false,
"text": "ed printf '$-125000,$d\\nw\\nq\\n' | ed -s myHugeFile\n"
},
{
"answer_id": 1592801,
"author": "Brad Gilbert",
"author_id": 1337,
"author_profile": "https://Stackoverflow.com/users/1337",
"pm_score": 0,
"selected": false,
"text": "#! /usr/bin/env perl\nuse strict;\nuse warnings;\nuse autodie;\n\nopen my $file, '+<', 'test.in'; # rw\nmy @list;\nwhile(<$file>){\n if( @list <= 10 ){\n push @list, tell $file;\n }else{\n (undef,@list) = (@list,tell $file);\n }\n}\n\nseek $file, 0, 0;\ntruncate $file, $list[0] if @list;\nclose $file;\n"
}
] | 2008/12/05 | [
"https://Stackoverflow.com/questions/345513",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/33411/"
] |
345,518 | <p>I have a file that has one entry per line. Each line has the following format:</p>
<pre><code> "group:permissions:users"
</code></pre>
<p>Permissions and users could have more than one value separated by comas like this:</p>
<pre><code> "grp1:create,delete:yo,el,ella"
</code></pre>
<p>I want is to return the following:</p>
<pre><code>yo
el
ella
</code></pre>
<p>This is what I have so far:</p>
<pre><code>cat file | grep grp1 -w | cut -f3 -d: | cut -d "," -f 2
</code></pre>
<p>This returns <code>yo,el.ella</code>, How can I make it return one value per line?</p>
| [
{
"answer_id": 345528,
"author": "Jay",
"author_id": 20840,
"author_profile": "https://Stackoverflow.com/users/20840",
"pm_score": 5,
"selected": true,
"text": "[user@host]$ echo \"grp1:create,delete:yo,el,ella\" | awk -F ':' '{print $3}'\nyo,el,ella\n [user@host]$ echo \"grp1:create,delete:yo,el,ella\" | awk -F ':' '{print $3}' | tr ',' '\\n'\nyo\nel\nella\n"
},
{
"answer_id": 349976,
"author": "user43983",
"author_id": 43983,
"author_profile": "https://Stackoverflow.com/users/43983",
"pm_score": 2,
"selected": false,
"text": "cat file | name-of-script\n #!/bin/bash\nwhile IFS=: read group permissions users; do\n if [ \"$group\" = \"grp1\" ]; then\n IFS=,\n set -- $users\n while [ $# -ne 0 ]; do\n echo $1\n shift\n done\n fi\ndone\n"
}
] | 2008/12/05 | [
"https://Stackoverflow.com/questions/345518",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16316/"
] |
345,540 | <p>I can't seem to be able to disable a select box when the select tag is not nested inside a form tag. Some things I tried are (using Firefox 3):
(via Jquery)</p>
<pre><code>$("#mySelect").attr("disabled", true);
$("#mySelect").attr("disabled", "disabled");
</code></pre>
<p>(also)</p>
<pre><code>document.getElementById('mySelect').disabled = true;
document.getElementById('mySelect').disabled = true;
</code></pre>
<p>Here is the HTML:</p>
<pre><code><select id="mySelect" onchange="updateChoice();">
<option value="1">First</option>
<option value="2" selected="">Second</option>
</select>
</code></pre>
<p>Must I have this select box inside a form element?</p>
| [
{
"answer_id": 345554,
"author": "Tom",
"author_id": 20,
"author_profile": "https://Stackoverflow.com/users/20",
"pm_score": 3,
"selected": true,
"text": "body <html>\n <head>\n <title>JavaScript Select Demo</title>\n </head>\n <body>\n <select id=\"mySelect\" onchange=\"updateChoice();\">\n <option value=\"1\">First</option>\n <option value=\"2\" selected=\"\">Second</option>\n </select>\n </body>\n <script type=\"text/javascript\">\n document.getElementById('mySelect').disabled = true;\n </script>\n</html>\n <head>\n <title>JavaScript Select Demo</title>\n <script type=\"text/javascript\">\n window.onload = function() {\n document.getElementById('mySelect').disabled = true; ;\n }\n </script>\n </head>\n onchange"
},
{
"answer_id": 348145,
"author": "Andreas Grech",
"author_id": 44084,
"author_profile": "https://Stackoverflow.com/users/44084",
"pm_score": 2,
"selected": false,
"text": "$.ready $(function () {\n //Type in your code here\n});\n"
}
] | 2008/12/05 | [
"https://Stackoverflow.com/questions/345540",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4352/"
] |
345,546 | <p>In Windows for ASP, you can get it perfmon, but...</p>
<p>How to get <strong>"requests per second"</strong> for Apache in Linux?</p>
| [
{
"answer_id": 1891155,
"author": "Adam Franco",
"author_id": 15872,
"author_profile": "https://Stackoverflow.com/users/15872",
"pm_score": 5,
"selected": false,
"text": "wc -l #!/bin/sh\n\n##############################################################################\n# This script will monitor the number of lines in a log file to determine the\n# number of requests per second.\n#\n# Example usage:\n# reqs-per-sec -f 15 -i /var/www/http/access.log\n#\n# Author: Adam Franco\n# Date: 2009-12-11\n# License: http://www.gnu.org/copyleft/gpl.html GNU General Public License (GPL)\n##############################################################################\n\nusage=\"Usage: `basename $0` -f <frequency in seconds, min 1, default 60> -l <log file>\"\n\n# Set up options\nwhile getopts \":l:f:\" options; do\n case $options in\n l ) logFile=$OPTARG;;\n f ) frequency=$OPTARG;;\n \\? ) echo -e $usage\n exit 1;;\n * ) echo -e $usage\n exit 1;;\n\n esac\ndone\n\n# Test for logFile\nif [ ! -n \"$logFile\" ]\nthen\n echo -e $usage\n exit 1\nfi\n\n# Test for frequency\nif [ ! -n \"$frequency\" ]\nthen\n frequency=60\nfi\n\n# Test that frequency is an integer\nif [ $frequency -eq $frequency 2> /dev/null ]\nthen\n :\nelse\n echo -e $usage\n exit 3\nfi\n\n# Test that frequency is an integer\nif [ $frequency -lt 1 ]\nthen\n echo -e $usage\n exit 3\nfi\n\nif [ ! -e \"$logFile\" ]\nthen\n echo \"$logFile does not exist.\"\n echo \n echo -e $usage\n exit 2\nfi\n\nlastCount=`wc -l $logFile | sed 's/\\([0-9]*\\).*/\\1/'`\nwhile true\ndo\n newCount=`wc -l $logFile | sed 's/\\([0-9]*\\).*/\\1/'`\n diff=$(( newCount - lastCount ))\n rate=$(echo \"$diff / $frequency\" |bc -l)\n echo $rate\n lastCount=$newCount\n sleep $frequency\ndone\n"
},
{
"answer_id": 7469823,
"author": "xztraz",
"author_id": 952521,
"author_profile": "https://Stackoverflow.com/users/952521",
"pm_score": 2,
"selected": false,
"text": "-f while true; do tail -n0 -f access.log>/tmp/tmp.log & sleep 2; kill $! ; wc -l /tmp/tmp.log | cut -c-2; done 2>/dev/null\n"
},
{
"answer_id": 25505965,
"author": "Jon Daniel",
"author_id": 3978982,
"author_profile": "https://Stackoverflow.com/users/3978982",
"pm_score": 2,
"selected": false,
"text": "# This check is needed because if the logs have just rolled over, then we need a minimum\n# amount of data to report on.\n# You will probably need to adjust the 3500000 - this is roughly the file size when the\n# log file hits 15000 requests.\nFILESIZE=`ls -l /var/log/httpd/access_log | awk '{print $5}' `\nif [ $FILESIZE -le 3500000 ]\nthen\n # not enough data - log file has rolled over\n echo \"APACHE_RPS|0\"\nelse\n # Based on 15000 requests. Depending on the location of the date field in\n # your apache log file you may need to adjust the ...substr($5... bit\n LASTTIME=`tail -15000 /var/log/httpd/access_log | head -1 | awk '{printf(\"%s\\n\",substr($5,2,20));}' `\n APACHE_RPS=`echo $LASTTIME | gawk -vREQUESTS=15000 ' {\n # convert apache datestring into time format accepted by mktime();\n monthstr = substr($0,4,3);\n if(monthstr == \"Jan\"){ monthint = \"01\"; }\n if(monthstr == \"Feb\"){ monthint = \"02\"; }\n if(monthstr == \"Mar\"){ monthint = \"03\"; }\n if(monthstr == \"Apr\"){ monthint = \"04\"; }\n if(monthstr == \"May\"){ monthint = \"05\"; }\n if(monthstr == \"Jun\"){ monthint = \"06\"; }\n if(monthstr == \"Jul\"){ monthint = \"07\"; }\n if(monthstr == \"Aug\"){ monthint = \"08\"; }\n if(monthstr == \"Sep\"){ monthint = \"09\"; }\n if(monthstr == \"Oct\"){ monthint = \"10\"; }\n if(monthstr == \"Nov\"){ monthint = \"11\"; }\n if(monthstr == \"Dec\"){ monthint = \"12\"; }\n mktimeformat=sprintf(\"%s %s %s %s %s %s [DST]\\n\", substr($0,8,4), monthint, substr($0,1,2), substr($0, 13,2), substr($0, 16,2), substr($0, 19,2) );\n # calculate difference\n difference = systime() - mktime(mktimeformat);\n # printf(\"%s - %s = %s\\n\",systime(), mktime(mktimeformat), difference);\n printf(\"%s\\n\",REQUESTS/difference);\n } ' `\n\n echo \"APACHE_RPS|${APACHE_RPS}\"\nfi\n"
},
{
"answer_id": 26632108,
"author": "Wtower",
"author_id": 940098,
"author_profile": "https://Stackoverflow.com/users/940098",
"pm_score": 4,
"selected": false,
"text": "grep \"29/Oct/2014:12\" /var/log/apache2/example.com.log | cut -d[ -f2 | cut -d] -f1 | awk -F: '{print $2\":\"$3}' | sort -nk1 -nk2 | uniq -c | awk '{ if ($1 > 10) print $0}'\n 1913 12:47\n 226 12:48\n 554 12:49\n 918 12:50\n"
}
] | 2008/12/05 | [
"https://Stackoverflow.com/questions/345546",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1100/"
] |
345,547 | <p>I want to use a Simulink mdl to generate C files in an automated fashion. I am currently trying to use an m-script and a dos command shell, but I am having issues with a "do you want to save" dialog hanging the m-script. By experimentation I know that the mdl is being modified when the "set_param" line is run (i.e. no "save" dialog issue if the set_param call is removed), but I need to do some setup of the mdl prior to generating code.</p>
<p>m-script:</p>
<pre><code>rtwdemo_counter
set_param(gcs,'SystemTargetFile','ert.tlc')
rtwbuild(gcs)
exit
</code></pre>
<p>dos</p>
<pre><code>matlab -r samplebuild -nosplash -nodesktop
</code></pre>
<p>Matlab 7.7.0,471 on Windows XP</p>
<p>My ultimate goal is to auto-generate the code on a continuous integration server (CruiseControl) and I feel there must be a more robust way of accomplishing this with the matlab tool-chain.</p>
| [
{
"answer_id": 350867,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 4,
"selected": true,
"text": " close_system(gcs, false);\n rtwdemo_counter\n set_param(gcs,'SystemTargetFile','ert.tlc')\n rtwbuild(gcs)\n close_system(gcs, false);\n exit\n"
}
] | 2008/12/05 | [
"https://Stackoverflow.com/questions/345547",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/34605/"
] |
345,549 | <p>What algorithms are good for interactive/realtime graph-drawing for live data and direct-manipulation?</p>
<p>Failing that - what libraries do you use to draw graphs? </p>
<p>Suggestions; </p>
<ul>
<li><a href="http://prefuse.org/" rel="nofollow noreferrer">Prefuse</a> information-visualization toolkit</li>
<li>any others?</li>
</ul>
<p>BTW- I mean graphs in the graph-theory sense - points and lines</p>
<ul>
<li>any language </li>
<li>by live I mean the graph should be manipulatable once on screen.</li>
</ul>
| [
{
"answer_id": 345658,
"author": "yogman",
"author_id": 24349,
"author_profile": "https://Stackoverflow.com/users/24349",
"pm_score": 2,
"selected": false,
"text": "http://en.wikipedia.org/wiki/DOT_language\n"
}
] | 2008/12/05 | [
"https://Stackoverflow.com/questions/345549",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17398/"
] |
345,559 | <p>When starting a new project that required the use of membership providers I found that I could not connect to a remote database that contained the membership database.</p>
<p>I ran aspnet_regsql and was able to create the membership database on the remote server but when I go to ASPNET Configuration (cassini development server) it will not connect to the remote server.</p>
| [
{
"answer_id": 345570,
"author": "jdiaz",
"author_id": 831,
"author_profile": "https://Stackoverflow.com/users/831",
"pm_score": 5,
"selected": true,
"text": " <connectionStrings>\n <add name=\"aspnet_membership\" connectionString=\"<your_connection_string>\"/>\n </connectionStrings>\n <system.web> <membership>\n <providers>\n <remove name=\"AspNetSqlMembershipProvider\"/>\n <add name=\"AspNetSqlMembershipProvider\" \n type=\"System.Web.Security.SqlMembershipProvider, System.Web, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a\" \n connectionStringName=\"aspnet_membership\"\n enablePasswordRetrieval=\"false\" \n enablePasswordReset=\"true\" \n requiresQuestionAndAnswer=\"true\" \n applicationName=\"/\" \n requiresUniqueEmail=\"false\" \n passwordFormat=\"Hashed\" \n maxInvalidPasswordAttempts=\"5\" \n minRequiredPasswordLength=\"7\" \n minRequiredNonalphanumericCharacters=\"1\" \n passwordAttemptWindow=\"10\" \n passwordStrengthRegularExpression=\"\"/>\n </providers>\n </membership>\n <remove name=\"AspNetSqlMembershipProvider\"/>"
},
{
"answer_id": 5979354,
"author": "vin",
"author_id": 737452,
"author_profile": "https://Stackoverflow.com/users/737452",
"pm_score": 1,
"selected": false,
"text": "<remove name=\"LocalSqlServer\"/>\n\n<add name=\"LocalSqlServer\" connectionString=\"Data Source=VMK\\sqlexpress;Initial Catalog=commodity_exchange;Integrated Security=True\" providerName=\"System.Data.SqlClient\"/>\n"
},
{
"answer_id": 14679110,
"author": "andilabs",
"author_id": 953553,
"author_profile": "https://Stackoverflow.com/users/953553",
"pm_score": 2,
"selected": false,
"text": "<membership>\n <providers>\n <clear/>\n <add name=\"AspNetSqlMembershipProvider\"\n type=\"System.Web.Security.SqlMembershipProvider, System.Web, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a\"\n connectionStringName=\"aspnet_membership\"\n enablePasswordRetrieval=\"false\"\n enablePasswordReset=\"true\"\n requiresQuestionAndAnswer=\"true\"\n applicationName=\"/\"\n requiresUniqueEmail=\"false\"\n passwordFormat=\"Hashed\"\n maxInvalidPasswordAttempts=\"5\"\n minRequiredPasswordLength=\"7\"\n minRequiredNonalphanumericCharacters=\"1\"\n passwordAttemptWindow=\"10\"\n passwordStrengthRegularExpression=\"\"/>\n </providers>\n </membership>\n <profile>\n <providers>\n <clear/>\n <add name=\"AspNetSqlProfileProvider\"\n connectionStringName=\"aspnet_membership\"\n applicationName=\"/\"\n type=\"System.Web.Profile.SqlProfileProvider, System.Web, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a\"/>\n </providers>\n </profile>\n\n <roleManager enabled=\"true\">\n <providers>\n <clear/>\n <add name=\"AspNetSqlRoleProvider\"\n connectionStringName=\"aspnet_membership\"\n applicationName=\"/\"\n type=\"System.Web.Security.SqlRoleProvider, System.Web, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a\"/>\n <add name=\"AspNetWindowsTokenRoleProvider\"\n applicationName=\"/\"\n type=\"System.Web.Security.WindowsTokenRoleProvider, System.Web, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a\"/>\n </providers>\n </roleManager> \n"
}
] | 2008/12/05 | [
"https://Stackoverflow.com/questions/345559",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/831/"
] |
345,562 | <p>I wish to put some text on a page and hide some data in that text. Does anybody know of any methods / patterns that have been used in the past to solve this problem?</p>
<p>Example: I have the following text:
"The cat sat on the dog and was happy."</p>
<p>I also have the number 123. I want to hide this number in that sentence such that the sentence can be placed on a web page and only someone in the know would be able to find the data.</p>
| [
{
"answer_id": 345584,
"author": "Lasse V. Karlsen",
"author_id": 267,
"author_profile": "https://Stackoverflow.com/users/267",
"pm_score": 4,
"selected": false,
"text": "You belong to the beautiful group of people being elite.\n"
},
{
"answer_id": 349152,
"author": "Mecki",
"author_id": 15809,
"author_profile": "https://Stackoverflow.com/users/15809",
"pm_score": 2,
"selected": false,
"text": "0. beautiful\n1. harmless\n2. evil\n3. colorful\n4. weird\n \"The {adj} cat sat on the {adj} dog and the {adj} cat was happy.\"\n \"The harmless cat sat on the evil dog and the colorful cat was happy.\"\n The -> ?\nharmless -> 1\ncat -> ?\nsat -> ?\non -> ?\nthe -> ?\nevil -> 2\n:\n 1. harmless\n 1. harmless/stupid/blue/fashionable\n"
}
] | 2008/12/06 | [
"https://Stackoverflow.com/questions/345562",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1463/"
] |
345,610 | <p>Our logging class, when initialised, truncates the log file to 500,000 bytes. From then on, log statements are appended to the file.</p>
<p>We do this to keep disk usage low, we're a commodity end-user product.</p>
<p>Obviously keeping the first 500,000 bytes is not useful, so we keep the last 500,000 bytes.</p>
<p>Our solution has some serious performance problem. What is an efficient way to do this?</p>
| [
{
"answer_id": 345622,
"author": "gbjbaanb",
"author_id": 13744,
"author_profile": "https://Stackoverflow.com/users/13744",
"pm_score": 0,
"selected": false,
"text": " fstream myfile;\n myfile.open(\"test.txt\",ios::app);\n"
},
{
"answer_id": 345635,
"author": "Max Lybbert",
"author_id": 10593,
"author_profile": "https://Stackoverflow.com/users/10593",
"pm_score": 0,
"selected": false,
"text": "std::string ftruncate SetEndOfFile"
},
{
"answer_id": 345691,
"author": "Steve Jessop",
"author_id": 13005,
"author_profile": "https://Stackoverflow.com/users/13005",
"pm_score": 2,
"selected": false,
"text": "#include <fstream>\n\nstd::ifstream ifs(\"logfile\");\nifs.seekg(-500*1000, std::ios_base::end);\nstd::ofstream ofs(\"logfile.new\");\nofs << ifs.rdbuf();\n const int bufsize = 64*1024; // or whatever\nstd::vector<char> buf(bufsize);\n...\nifs.rdbuf()->pubsetbuf(&buf[0], bufsize);\n"
},
{
"answer_id": 346224,
"author": "user43922",
"author_id": 43922,
"author_profile": "https://Stackoverflow.com/users/43922",
"pm_score": 4,
"selected": true,
"text": "#include <fstream>\nstd::ifstream ifs(\"logfile\"); //One call to start it all. . .\nifs.seekg(-512000, std::ios_base::end); // One call to find it. . .\nchar tmpBuffer[512000];\nifs.read(tmpBuffer, 512000); //One call to read it all. . .\nifs.close();\nstd::ofstream ofs(\"logfile\", ios::trunc);\nofs.write(tmpBuffer, 512000); //And to the FS bind it.\n int myfd = open(\"mylog\", O_RDONLY); // Grab a file descriptor\n(char *) myptr = mmap(mylog, myfd, filesize - 512000) // mmap the last 512K\nstd::string mystr(myptr, 512000) // pull 512K from our mmap'd buffer and load it directly into the std::string\nmunmap(mylog, 512000); //Unmap the file\nclose(myfd); // Close the file descriptor\n"
},
{
"answer_id": 349095,
"author": "MSalters",
"author_id": 15416,
"author_profile": "https://Stackoverflow.com/users/15416",
"pm_score": 2,
"selected": false,
"text": "FSCTL_SET_SPARSE FSCTL_SET_ZERO_DATA"
}
] | 2008/12/06 | [
"https://Stackoverflow.com/questions/345610",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6444/"
] |
345,617 | <p>I am running Ubuntu8.041. Apache/2.2.8 (Ubuntu) PHP/5.2.4-2ubuntu5.3 with Suhosin-Patch configured </p>
<p>Can't get file uploading to work at all. Have tested locally on the Ubuntu box... and from my Vista Box. Ubuntu is running inside VMWare on the Vista box.</p>
<p>Here is uploadTestBrowse.php</p>
<pre><code><?php
?>
<form enctype="multipart/form-data" action="uploadTestBrowse.php" method="post">
<input type="hidden" name="MAX_FILE_SIZE" value="1000000" />
<input type="file" name="fileName" /> <br><br>
<input type="submit" value="Upload Images"/>
</form>
</code></pre>
<p>Here is uploadTestSubmit.php</p>
<pre><code><?php
error_reporting(E_ALL|E_STRICT);
$uploaddir = "var/www/ig/images/";
$uploadfile = $uploaddir . basename($_FILES['userfile']['name']);
if (move_uploaded_file($_FILES['userfile']['tmp_name'], $uploadfile)) {
echo "Success.\n";
} else {
echo "Failure.\n";
}
echo 'Here is some more debugging info:';
print_r($_FILES);
?>
</code></pre>
<p>Here is the output of uploadTestSubmit.php</p>
<blockquote>
<p>Notice: Undefined index: userfile in
/var/www/ig/admin/uploadTestSubmit.php
on line 5</p>
<p>Notice: Undefined index: userfile in
/var/www/ig/admin/uploadTestSubmit.php
on line 7 Failure. Here is some more
debugging info:Array ( [fileName] =>
Array ( [name] => aq.jpg [type] =>
image/pjpeg [tmp_name] =>
/tmpUpload/phpMBwMi9 [error] => 0
[size] => 10543 ) )</p>
</blockquote>
<p>php.ini
file_uploads = On
upload_max_filesize = 2M
upload_tmp_dir = /tmpUpload</p>
<p>I've chmod -R 777 tmpUpload</p>
<p>I can never see any files in tmpUpload</p>
<p>Apache2 error log not showing anything</p>
<p>Apache2 access log showing:
192.168.21.1 - - [06/Dec/2008:13:13:09 +1300] "GET /ig/admin/uploadTestBrowse.php?=PHPE9568F35-D428-11d2-A769-00AA001ACF42 HTTP/1.1" 200 2146 "<a href="http://192.168.21.128/ig/admin/uploadTestBrowse.php" rel="nofollow noreferrer">http://192.168.21.128/ig/admin/uploadTestBrowse.php</a>" "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.0; SLCC1; .NET CLR 2.0.50727; Media Center PC 5.0; .NET CLR 3.5.21022; .NET CLR 1.1.4322; .NET CLR 3.5.30729; .NET CLR 3.0.30618)"</p>
| [
{
"answer_id": 345622,
"author": "gbjbaanb",
"author_id": 13744,
"author_profile": "https://Stackoverflow.com/users/13744",
"pm_score": 0,
"selected": false,
"text": " fstream myfile;\n myfile.open(\"test.txt\",ios::app);\n"
},
{
"answer_id": 345635,
"author": "Max Lybbert",
"author_id": 10593,
"author_profile": "https://Stackoverflow.com/users/10593",
"pm_score": 0,
"selected": false,
"text": "std::string ftruncate SetEndOfFile"
},
{
"answer_id": 345691,
"author": "Steve Jessop",
"author_id": 13005,
"author_profile": "https://Stackoverflow.com/users/13005",
"pm_score": 2,
"selected": false,
"text": "#include <fstream>\n\nstd::ifstream ifs(\"logfile\");\nifs.seekg(-500*1000, std::ios_base::end);\nstd::ofstream ofs(\"logfile.new\");\nofs << ifs.rdbuf();\n const int bufsize = 64*1024; // or whatever\nstd::vector<char> buf(bufsize);\n...\nifs.rdbuf()->pubsetbuf(&buf[0], bufsize);\n"
},
{
"answer_id": 346224,
"author": "user43922",
"author_id": 43922,
"author_profile": "https://Stackoverflow.com/users/43922",
"pm_score": 4,
"selected": true,
"text": "#include <fstream>\nstd::ifstream ifs(\"logfile\"); //One call to start it all. . .\nifs.seekg(-512000, std::ios_base::end); // One call to find it. . .\nchar tmpBuffer[512000];\nifs.read(tmpBuffer, 512000); //One call to read it all. . .\nifs.close();\nstd::ofstream ofs(\"logfile\", ios::trunc);\nofs.write(tmpBuffer, 512000); //And to the FS bind it.\n int myfd = open(\"mylog\", O_RDONLY); // Grab a file descriptor\n(char *) myptr = mmap(mylog, myfd, filesize - 512000) // mmap the last 512K\nstd::string mystr(myptr, 512000) // pull 512K from our mmap'd buffer and load it directly into the std::string\nmunmap(mylog, 512000); //Unmap the file\nclose(myfd); // Close the file descriptor\n"
},
{
"answer_id": 349095,
"author": "MSalters",
"author_id": 15416,
"author_profile": "https://Stackoverflow.com/users/15416",
"pm_score": 2,
"selected": false,
"text": "FSCTL_SET_SPARSE FSCTL_SET_ZERO_DATA"
}
] | 2008/12/06 | [
"https://Stackoverflow.com/questions/345617",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/26086/"
] |
345,626 | <p>I have been assigned a project to develop a set of classes that act as an interface to a storage system. A requirement is that the class support a get method with the following signature:</p>
<pre><code>public CustomObject get(String key, Date ifModifiedSince)
</code></pre>
<p>Basically the method is supposed to return the <code>CustomObject</code> associated with the <code>key</code> if and only if the object has been modified after <code>ifModifiedSince</code>. If the storage system does not contain the <code>key</code> then the method should return null.</p>
<p>My problem is this:</p>
<p><strong>How do I handle the scenario where the key exists but the object has <b>not</b> been modified?</strong></p>
<p>This is important because some applications that use this class will be web services and web applications. Those applications will need to know whether to return a 404 (not found), 304 (not modified), or 200 (OK, here's the data).</p>
<p>The solutions I'm weighing are:</p>
<ol>
<li>Throw a custom exception when the
storage system does not contain the
<code>key</code></li>
<li>Throw a custom exception when the
<code>ifModifiedSince</code> fails.</li>
<li>Add a status property to the CustomObject. Require caller to check property.</li>
</ol>
<p>I'm not happy with any of these three options. I don't like options 1 and 2 because I don't like using exceptions for flow control. Neither do I like returning a value when my intent is to indicate that there was <b>no value</b>.</p>
<p>Nonetheless, I am leaning towards option 3.</p>
<p>Is there an option I'm not considering? Does anyone have strong feelings about any of these three options?</p>
<hr>
<p><b>Answers to this Question, Paraphrased:</b></p>
<ol>
<li>Provide a <code>contains</code>
method and require caller to call it
before calling <code>get(key,
ifModifiedSince)</code>, throw
exception if key does not exist,
return null if object has not been
modified.</li>
<li>Wrap the response and data (if any)
in a composite object. </li>
<li>Use a predefined constant to denote some state (<code>UNMODIFIED, KEY_DOES_NOT_EXIST</code>).</li>
<li>Caller implements interface to be
used as callbacks.</li>
<li>The design sucks.</li>
</ol>
<hr>
<p><b>Why I Cannot Choose Answer #1</b></p>
<p>I agree that this is the ideal solution, but it was one I have already (reluctantly) dismissed. The problem with this approach is that in a majority of the cases in which these classes will be used, the backend storage system will be a third party remote system, like Amazon S3. This means that a <code>contains</code> method would require a round trip to the storage system, which would in most cases be followed by another round trip. Because this <b>would cost both time and money</b>, it is not an option.</p>
<p><strong>If not for that limitation, this would be the best approach.</strong></p>
<p>(I realize I didn't mention this important element in the question, but I was trying to keep it brief. Obviously it was relevant.)</p>
<hr>
<p><strong>Conclusion:</strong></p>
<p>After reading all of the answers I have come to the conclusion that a wrapper is the best approach in this case. Essentially I'll mimic HTTP, with meta data (headers) including a response code, and content body (message).</p>
| [
{
"answer_id": 345631,
"author": "Lawrence Dol",
"author_id": 8946,
"author_profile": "https://Stackoverflow.com/users/8946",
"pm_score": 2,
"selected": false,
"text": "static public final CustomObject UNCHANGED=new CustomObject();\n"
},
{
"answer_id": 345633,
"author": "tvanfosson",
"author_id": 12950,
"author_profile": "https://Stackoverflow.com/users/12950",
"pm_score": 2,
"selected": false,
"text": "public bool exists( String key ) { ... }\n if (exists(key)) {\n CustomObject modified = get(key,DateTime.Today.AddDays(-1));\n if (modified != null) { ... }\n}\n\nor\n\ntry {\n CustomObject modified = get(key,DateTime.Today.AddDays(-1));\n}\ncatch (NotFoundException) { ... }\n"
},
{
"answer_id": 345674,
"author": "OscarRyz",
"author_id": 20654,
"author_profile": "https://Stackoverflow.com/users/20654",
"pm_score": 3,
"selected": false,
"text": "exists(key): bool\n if (exists(key)) {\n CustomObject o = get(key, ifModifiedSince);\n if (o == null) { \n setResponseCode(302);\n } else {\n setResponseCode(200);\n push(o);\n }\n\n} else {\n setResponseCode(400);\n}\n CustomObject o = get(key, ifModifiedSince);\n\n if (o != null) {\n setResponseCode(200);\n push(o);\n } else {\n setResponseCode(404); // either not found or not modified.\n }\n"
},
{
"answer_id": 345711,
"author": "James",
"author_id": 41039,
"author_profile": "https://Stackoverflow.com/users/41039",
"pm_score": 4,
"selected": true,
"text": "public class Pair<K,V>{\n public K first;\n public V second;\n}\n null"
},
{
"answer_id": 348662,
"author": "Spencer Kormos",
"author_id": 8528,
"author_profile": "https://Stackoverflow.com/users/8528",
"pm_score": 1,
"selected": false,
"text": "public interface Callback {\n public void keyDoesNotExist();\n public void notModified(CustomObject c);\n public void isNewlyModified(CustomObject c);\n .\n .\n .\n}\n"
}
] | 2008/12/06 | [
"https://Stackoverflow.com/questions/345626",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/28408/"
] |
345,632 | <p>I have redirected some valuable information into a text file. How can I execute each line of that text file in a loop?</p>
<p>What im thinking is to double space my text file, then to use a loop to execute each line invidually. I'm hoping that when i double space the text file every string of commands will have their own line.</p>
<p>For example, this text file:</p>
<blockquote>cat /etc/passwd | head -101 | tail -3 nl /etc/passwd | head -15 | cut -d':' -f1 cat /etc/passwd | cut -d':' -f1,5 | tee users.txt nl /etc/passwd | tail -1 | cut -f1 ls ~/home | nl | tail -1 | cut -f1 ls -lR / 2>/dev/null | sort -n -r +4 | head -1</blockquote>
<p>should look like this when i double space it:</p>
<blockquote>cat /etc/passwd | head -101 | tail -3
<br>nl /etc/passwd | head -15 | cut -d':' -f1
<br>cat /etc/passwd | cut -d':' -f1,5 | tee users.txt
<br>nl /etc/passwd | tail -1 | cut -f1
<br>ls ~/home | nl | tail -1 | cut -f1 ls -lR / 2>/dev/null | sort -n -r +4 | head -1</blockquote>
<p>And then i would use a loop to execute each line.</p>
<p>here is my script:</p>
<pre><code>FILE="$1"
echo "You Entered $FILE"
if [ -f $FILE ]; then
tmp=$(cat $FILE | sed '/./!d' | sed -n '/regex/,/regex/{/regex/d;p}'| sed -n '/---/,+2!p' | sed -n '/#/!p' | sed 's/^[ ]*//' | sed -e\
s/[^:]*:// | sed -n '/==> /!p' | sed -n '/--> /!p' | sed -n '/"lab3.cmd"/,+1!p'\
| sed -n '/======/!p' | sed -n '/regex/!p' | sed -n '/commands are fun/\
!p' | sed -n '/regex/!p')
fi
MyVar=$(echo $tmp > hi.txt)
echo "$MyVar"</code></pre>
<p>Is this the right way of going about it?</p>
| [
{
"answer_id": 345727,
"author": "Norman Ramsey",
"author_id": 41661,
"author_profile": "https://Stackoverflow.com/users/41661",
"pm_score": 0,
"selected": false,
"text": "sh commands.txt\n for i in *; do FILE=\"$i\" sh commands.txt; done\n"
}
] | 2008/12/06 | [
"https://Stackoverflow.com/questions/345632",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/40120/"
] |
345,637 | <p>So I have an SQL dump file that needs to be loaded using mysql_query(). Unfortunately, it's not possible to execute multiple queries with it.</p>
<p>-> It cannot be assumed that the <strong>mysql command-line client</strong> (mysql --help) is installed -- for loading the SQL file directly</p>
<p>-> It cannot be assumed that the <strong>mysqli</strong> extension is installed</p>
<pre><code>/* contents of dump.sql, including comments */
DELETE FROM t3 WHERE body = 'some text; with semicolons; scattered; throughout';
DELETE FROM t2 WHERE name = 'hello';
DELETE FROM t1 WHERE id = 1;
</code></pre>
<p>The explode() below won't work because some of the dump content's values contain semicolons.</p>
<pre><code>$sql = explode(';', file_get_contents('dump.sql'));
foreach ($sql as $key => $val) {
mysql_query($val);
}
</code></pre>
<p>What's the best way to load the SQL without modifying the dump file?</p>
| [
{
"answer_id": 345712,
"author": "Bill Karwin",
"author_id": 20860,
"author_profile": "https://Stackoverflow.com/users/20860",
"pm_score": 5,
"selected": true,
"text": "mysql_query() USE DELIMITER CREATE PROCEDURE"
},
{
"answer_id": 345732,
"author": "Matt",
"author_id": 32881,
"author_profile": "https://Stackoverflow.com/users/32881",
"pm_score": 3,
"selected": false,
"text": "$sql = explode(\";\\n\", file_get_contents('dump.sql'));\nforeach ($sql as $key => $val) {\n mysql_query($val);\n}\n"
},
{
"answer_id": 15025975,
"author": "DolDurma",
"author_id": 1830228,
"author_profile": "https://Stackoverflow.com/users/1830228",
"pm_score": 0,
"selected": false,
"text": "<?php\n//STATIC QUERY\n$sql1 = \"\nCREATE TABLE tblTable (\nstrOne VARCHAR(50) NOT NULL,\nstrTwo VARCHAR(50) NOT NULL,\nstrThree VARCHAR(50) NOT NULL\n);\nINSERT INTO tblTable\n(strOne, strTwo, strThree)\nVALUES ('String 1', 'String 2', 'String 3');\nUPDATE tblTable\nSET\nstrOne = 'String One',\nstrTwo = 'String Two'\nWHERE strThree = 'String 3';\n\"; \n//GET FROM FILE\n$sql2 = file_get_contents('dump.sql');\n$queries = preg_split(\"/;+(?=([^'|^\\\\\\']*['|\\\\\\'][^'|^\\\\\\']*['|\\\\\\'])*[^'|^\\\\\\']*[^'|^\\\\\\']$)/\", $sql);\nforeach ($queries as $query){\n if (strlen(trim($query)) > 0) mysql_query($query);\n}\n?>\n"
}
] | 2008/12/06 | [
"https://Stackoverflow.com/questions/345637",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/32881/"
] |
345,680 | <p>I have a ticker which items are updated using polling. I have written a simple jQuery plugin for the ticker which is invoked like so:</p>
<pre><code>$("#cont ul").ticker();
</code></pre>
<p>Which turns a ul into a ticker, scrolling through the li. To add new items I have to add lis to the ul, which works fine. However, the OO in me wishes I could have an addItem function on a ticker object. However, I don't want to lose the chainability that jQuery uses.</p>
<p>Is there some method which is more obvious than adding ul's to the list but that fit's with the jQuery way of doing things?</p>
| [
{
"answer_id": 345778,
"author": "nickf",
"author_id": 9021,
"author_profile": "https://Stackoverflow.com/users/9021",
"pm_score": 2,
"selected": true,
"text": "$.fn.addTickerItem = function(contents) {\n this.append(\n $(\"<li></li>\").html(contents);\n );\n return this;\n};\n"
},
{
"answer_id": 345784,
"author": "Andrew Theken",
"author_id": 32238,
"author_profile": "https://Stackoverflow.com/users/32238",
"pm_score": 3,
"selected": false,
"text": "jQuery.ticker = function(settings)\n{\nvar settings = \njQuery.extend(\n{\naction : 'create',\nitem : $(this)\n}\n,settings);\n\nreturn $(this).each(function(){\nif(settings.action =='create')\n{\n //initialize ticker..\n}\nelse if(settings.action == 'add')\n{\n //add to ticker.\n}\n}//end each.\n}//end plugin.\n\n$('#ticker').ticker(); //this will initialize it, no problem.\n\nvar settings1 = { action : 'add', item : $(expr1) }\n$('#ticker').ticker(settings1);//this will execute the \"add\" action.\n"
}
] | 2008/12/06 | [
"https://Stackoverflow.com/questions/345680",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/214/"
] |
345,683 | <p>I am working a project that does not have a trunk / branches / tags directory structure - ie. everything is in the root of the svn repo.</p>
<p>I would like to create a trunk directory and in the root directory, and move everything in the root directory into the new trunk directory.</p>
<p>What is the best way to do this?</p>
<p>The first thing I considered was</p>
<pre><code>svn mkdir trunk
(for each file or directory that is not called trunk: )
svn mv FILEorDIR trunk/
</code></pre>
<p>But this effectively deletes every file and then adds it again. Is there a better way?</p>
<p>Thanks.</p>
| [
{
"answer_id": 345697,
"author": "Greg Hewgill",
"author_id": 893,
"author_profile": "https://Stackoverflow.com/users/893",
"pm_score": 4,
"selected": true,
"text": "svn switch"
},
{
"answer_id": 13688913,
"author": "zhihong",
"author_id": 877513,
"author_profile": "https://Stackoverflow.com/users/877513",
"pm_score": 0,
"selected": false,
"text": "svn mkdir svn+ssh://username@host/projectname/trunk -m \"Create the trunk folder\"\n"
},
{
"answer_id": 27242978,
"author": "jxmallett",
"author_id": 1151228,
"author_profile": "https://Stackoverflow.com/users/1151228",
"pm_score": 5,
"selected": false,
"text": "svn switch //REPO_URL = The URL for the repo on the SVN server.\n//In my case it was https://IP_ADDRESS:PORT/svn/my_repo\n\n//Make the trunk dir in the root of your SVN repo\nsvn mkdir REPO_URL/trunk -m \"making trunk dir\"\n\n//Move everything from your root dir to your new trunk dir\nsvn move REPO_URL/A_FOLDER REPO_URL/trunk/A_FOLDER -m \"moving folders to trunk\"\nsvn move REPO_URL/ANOTHER_FOLDER REPO_URL/trunk/ANOTHER_FOLDER -m \"blah\"\nsvn move REPO_URL/A_FILE.TXT REPO_URL/trunk/A_FILE.TXT -m \"moving files to trunk\"\n//Keep going until you've moved everything from your root dir to the trunk dir...\n svn switch trunk svn switch REPO_URL/trunk --ignore-ancestry At revision X X"
},
{
"answer_id": 48347107,
"author": "BarclayVision",
"author_id": 664334,
"author_profile": "https://Stackoverflow.com/users/664334",
"pm_score": 2,
"selected": false,
"text": "git svn clone git svn clone --username byname http://www.MySVNserver.com:81/repos/project1 --no-metadata --trunk=."
},
{
"answer_id": 66883794,
"author": "malisokan",
"author_id": 1119695,
"author_profile": "https://Stackoverflow.com/users/1119695",
"pm_score": 1,
"selected": false,
"text": "/svn/my_project /svn/trunk /svn/my_project /svn/trunk /svn/my_project /svn/trunk/ /svn/my_project/ /svn/trunk/ /svn/my_project/trunk /svn/trunk/"
}
] | 2008/12/06 | [
"https://Stackoverflow.com/questions/345683",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/31092/"
] |
345,704 | <p>You guys were very helpful yesterday. I am still a bit confused here though. </p>
<p>I want to make it so that the numbers on the rightmost column are rounded off to the nearest dollar:</p>
<p><a href="http://www.nextadvisor.com/voip_services/voip_calculator.php?monthlybill=50&Submit=Submit" rel="nofollow noreferrer">http://www.nextadvisor.com/voip_services/voip_calculator.php?monthlybill=50&Submit=Submit</a></p>
<p>the code for the table looks like this:</p>
<p>I want $offer[1,2,3,4,5,6,7]calcsavingsann to be rounded, how can do this?</p>
<pre><code> <table width="100%;" border="0" cellspacing="0" cellpadding="0"class="credit_table2" >
<tr class="credit_table2_brd">
<td class="credit_table2_brd_lbl" width="100px;">Services:</td>
<td class="credit_table2_brd_lbl" width="120px;">Our Ratings:</td>
<td class="credit_table2_brd_lbl" width="155px;">Monthly VoIP Bill:</td>
<td class="credit_table2_brd_lbl" width="155px;">Annual Savings:</td>
</tr>
<?php
$offer1price="24.99";
$offer2price="20.00";
$offer3price="21.95";
$offer4price="23.95";
$offer5price="19.95";
$offer6price="23.97";
$offer7price="24.99";
$offer1calcsavings= $monthlybill - $offer1price;
$offer2calcsavings= $monthlybill - $offer2price;
$offer3calcsavings= $monthlybill - $offer3price;
$offer4calcsavings= $monthlybill - $offer4price;
$offer5calcsavings= $monthlybill - $offer5price;
$offer6calcsavings= $monthlybill - $offer6price;
$offer7calcsavings= $monthlybill - $offer7price;
$monthybill="monthlybill";
$offer1calcsavingsann= $offer1calcsavings * 12;
$offer2calcsavingsann= $offer2calcsavings * 12;
$offer3calcsavingsann= $offer3calcsavings * 12;
$offer4calcsavingsann= $offer4calcsavings * 12;
$offer5calcsavingsann= $offer5calcsavings * 12;
$offer6calcsavingsann= $offer6calcsavings * 12;
$offer7calcsavingsann= $offer7calcsavings * 12;
$re=1;
$offer ='offer'.$re.'name';
$offername= ${$offer};
while($offername!=""){
$offerlo ='offer'.$re.'logo';
$offerlogo=${$offerlo};
$offerli ='offer'.$re.'link';
$offerlink=${$offerli};
$offeran ='offer'.$re.'anchor';
$offeranchor=${$offeran};
$offerst ='offer'.$re.'star1';
$offerstar=${$offerst};
$offerbot='offer'.$re.'bottomline';
$offerbottomline=${$offerbot};
$offerca ='offer'.$re.'calcsavings';
$offercalcsavings=${$offerca};
$offerpr ='offer'.$re.'price';
$offerprice=${$offerpr};
$offersavann ='offer'.$re.'calcsavingsann';
$offercalcsavingsann=${$offersavann};
echo '<tr >
<td >
<a href="'.$offerlink.'" target="blank"><img src="http://www.nextadvisor.com'.$offerlogo.'" alt="'.$offername.'" />
</a>
</td>
<td ><span class="rating_text">Rating:</span>
<span class="star_rating1">
<img src="http://www.nextadvisor.com'.$offerstar.'" alt="" />
</span>
<br />
<div style="margin-top:5px; color:#0000FF;">
<a href="'.$offerlink.'" target="blank">Go to Site</a>
<span style="margin:0px 7px 0px 7px;">|</span><a href="'.$offeranchor.'">Review</a>
</div> </td>
<td >$'.$offerprice.'</td>
<td >$'.$offercalcsavingsann.'</td>
</tr>';
$re=$re+1;
$offer ='offer'.$re.'name';
$offername= ${$offer};
}
?>
</table>
</code></pre>
| [
{
"answer_id": 351974,
"author": "Joe",
"author_id": 41880,
"author_profile": "https://Stackoverflow.com/users/41880",
"pm_score": 0,
"selected": false,
"text": "money_format() $myNumber <?php echo (\"<td>\".money_format('%n',$myNumber).\"</td>\"); ?>\n for n"
},
{
"answer_id": 467347,
"author": "pg.",
"author_id": 43035,
"author_profile": "https://Stackoverflow.com/users/43035",
"pm_score": 0,
"selected": false,
"text": "echo '<tr >\n\n <td ><a href=\"'.$offerlink.'\" target=\"blank\"><img src=\"http://www.nextadvisor.com'.$offerlogo.'\" alt=\"'.$offername.'\" /></a></td>\n\n <td ><span class=\"rating_text\">Rating:</span><span class=\"star_rating1\"><img src=\"http://www.nextadvisor.com'.$offerstar.'\" alt=\"\" /></span><br />\n\n <div style=\"margin-top:5px; color:#0000FF;\"><a href=\"'.$offerlink.'\" target=\"blank\">Go to Site</a><span style=\"margin:0px 7px 0px 7px;\">|</span><a href=\"'.$offeranchor.'\">Review</a></div> </td>\n\n <td >$'.$offerprice.'</td>\n\n<td >$'.$offercalcsavingsann.'</td>\n\n\n </tr>';\n \"<?php\" \n"
}
] | 2008/12/06 | [
"https://Stackoverflow.com/questions/345704",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/43035/"
] |
345,705 | <p>Here's one that has me perplexed. I'm trying to implement a basic Hibernate DAO structure, but am having a problem.</p>
<p>Here's the essential code:</p>
<pre><code>int startingCount = sfdao.count();
sfdao.create( sf );
SecurityFiling sf2 = sfdao.read( sf.getId() );
sfdao.delete( sf );
int endingCount = sfdao.count();
assertTrue( startingCount == endingCount );
assertTrue( sf.getId().longValue() == sf2.getId().longValue() );
assertTrue( sf.getSfSubmissionType().equals( sf2.getSfSubmissionType() ) );
assertTrue( sf.getSfTransactionNumber().equals( sf2.getSfTransactionNumber() ) );
</code></pre>
<p>It fails on the third assertTrue where it's trying to compare a value in sf to the corresponding value in sf2. Here's the exception:</p>
<pre><code>org.hibernate.LazyInitializationException: could not initialize proxy - no Session
at org.hibernate.proxy.AbstractLazyInitializer.initialize(AbstractLazyInitializer.java:86)
at org.hibernate.proxy.AbstractLazyInitializer.getImplementation(AbstractLazyInitializer.java:140)
at org.hibernate.proxy.pojo.javassist.JavassistLazyInitializer.invoke(JavassistLazyInitializer.java:190)
at com.freightgate.domain.SecurityFiling_$$_javassist_7.getSfSubmissionType(SecurityFiling_$$_javassist_7.java)
at com.freightgate.dao.SecurityFilingTest.test(SecurityFilingTest.java:73)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:40)
</code></pre>
| [
{
"answer_id": 346338,
"author": "digitalsanctum",
"author_id": 22436,
"author_profile": "https://Stackoverflow.com/users/22436",
"pm_score": 4,
"selected": false,
"text": "HibernateTemplate.initialize(object name) lazy=false"
},
{
"answer_id": 3489837,
"author": "Rolando Quezada",
"author_id": 421254,
"author_profile": "https://Stackoverflow.com/users/421254",
"pm_score": 2,
"selected": false,
"text": "@TransactionAttribute(TransactionAttributeType.REQUIRES_NEW)"
},
{
"answer_id": 3634167,
"author": "chris",
"author_id": 414173,
"author_profile": "https://Stackoverflow.com/users/414173",
"pm_score": 2,
"selected": false,
"text": " <many-to-one name=\"classA\" \n class=\"classB\"\n lazy=\"false\">\n <column name=\"classb_id\"\n sql-type=\"bigint(10)\" \n not-null=\"true\"/>\n </many-to-one> \n"
},
{
"answer_id": 3635595,
"author": "pakore",
"author_id": 222851,
"author_profile": "https://Stackoverflow.com/users/222851",
"pm_score": 6,
"selected": false,
"text": "session.update(object);\n lazy=false lazy=false"
},
{
"answer_id": 4093312,
"author": "Shayanlinux",
"author_id": 449527,
"author_profile": "https://Stackoverflow.com/users/449527",
"pm_score": 2,
"selected": false,
"text": "lazy=false default-lazy=\"false\" <hibernate-mapping> @Proxy(lazy=false)"
},
{
"answer_id": 10430609,
"author": "Kartoch",
"author_id": 199148,
"author_profile": "https://Stackoverflow.com/users/199148",
"pm_score": 2,
"selected": false,
"text": "// open a session, get the number of entity and close the session\nint startingCount = sfdao.count();\n\n// open a session, create a new entity and close the session\nsfdao.create( sf );\n\n// open a session, read an entity and close the session\nSecurityFiling sf2 = sfdao.read( sf.getId() );\n\n// open a session, delete an entity and close the session\nsfdao.delete( sf );\n\netc...\n sf.getSfSubmissionType().equals( sf2.getSfSubmissionType() )"
},
{
"answer_id": 29004181,
"author": "Vlad Mihalcea",
"author_id": 1025118,
"author_profile": "https://Stackoverflow.com/users/1025118",
"pm_score": 2,
"selected": false,
"text": "one-to-many many-to-many transactionTemplate.execute(new TransactionCallback<Void>() {\n @Override\n public Void doInTransaction(TransactionStatus transactionStatus) {\n\n int startingCount = sfdao.count();\n\n sfdao.create( sf );\n\n SecurityFiling sf2 = sfdao.read( sf.getId() );\n\n sfdao.delete( sf );\n\n int endingCount = sfdao.count();\n\n assertTrue( startingCount == endingCount );\n assertTrue( sf.getId().longValue() == sf2.getId().longValue() );\n assertTrue( sf.getSfSubmissionType().equals( sf2.getSfSubmissionType() ) );\n assertTrue( sf.getSfTransactionNumber().equals( sf2.getSfTransactionNumber() ) );\n\n return null;\n }\n});\n SecurityFiling sf2 = sfdao.read( sf.getId() );\n submissionType select sf\nfrom SecurityFiling sf\nleft join fetch.sf.submissionType\n [one|many]-to-one"
},
{
"answer_id": 30937561,
"author": "DmRomantsov",
"author_id": 3203062,
"author_profile": "https://Stackoverflow.com/users/3203062",
"pm_score": 1,
"selected": false,
"text": "@PersistenceContext \n @PersistenceContext(type = PersistenceContextType.EXTENDED)\n"
}
] | 2008/12/06 | [
"https://Stackoverflow.com/questions/345705",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17304/"
] |
345,707 | <p>I am working on a rails application (I have some experience with rails). But, this time I am using RESTful to build it. I am wondering how do I validate my models in a RESTful fashion? What I mean by that is when a user enters data into a form, but the model validations prevent the model from being created what is a RESTful way to redirect the user back to the <code>new</code> action <strong>with the data they entered still present in the form?</strong></p>
| [
{
"answer_id": 346076,
"author": "Tim Knight",
"author_id": 43043,
"author_profile": "https://Stackoverflow.com/users/43043",
"pm_score": 3,
"selected": true,
"text": "def create\n @customer = Customer.new(params[:customer])\n if @customer.save\n flash[:notice] = 'Customer was successfully created.'\n redirect_to(@customer)\n else\n render :action => \"new\"\n end\nend\n redirect_to(@customer)"
}
] | 2008/12/06 | [
"https://Stackoverflow.com/questions/345707",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5004/"
] |
345,745 | <p>I just came across this idiom in some open-source Python, and I choked on my drink.</p>
<p>Rather than:</p>
<pre><code>if isUp:
return "Up"
else:
return "Down"
</code></pre>
<p>or even:</p>
<pre><code>return "Up" if isUp else "Down"
</code></pre>
<p>the code read:</p>
<pre><code>return isUp and "Up" or "Down"
</code></pre>
<p>I can see this is the same result, but is this a typical idiom in Python? If so, is it some performance hack that runs fast? Or is it just a once-off that needs a code review?</p>
| [
{
"answer_id": 345764,
"author": "OscarRyz",
"author_id": 20654,
"author_profile": "https://Stackoverflow.com/users/20654",
"pm_score": -1,
"selected": false,
"text": "val if cond else alt\n if cond:\n val\nelse:\n alt\n"
},
{
"answer_id": 345773,
"author": "Martin v. Löwis",
"author_id": 33006,
"author_profile": "https://Stackoverflow.com/users/33006",
"pm_score": 5,
"selected": true,
"text": " return (a and [b] or [c])[0]\n return (b,c)[not a]\n return (c,b)[bool(a)]\n"
},
{
"answer_id": 345774,
"author": "Kozyarchuk",
"author_id": 52490,
"author_profile": "https://Stackoverflow.com/users/52490",
"pm_score": -1,
"selected": false,
"text": "return isUp and \"Up\" or \"Down\"\n"
}
] | 2008/12/06 | [
"https://Stackoverflow.com/questions/345745",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8014/"
] |
345,746 | <p>This is related to a <a href="https://stackoverflow.com/questions/343517/how-do-i-work-with-multiple-git-branches-of-a-python-module">previous question</a> of mine.</p>
<p>I understand how to store and read configuration files. There are choices such as <a href="http://www.python.org/doc/2.5.2/lib/module-ConfigParser.html" rel="nofollow noreferrer">ConfigParser</a> and <a href="http://www.voidspace.org.uk/python/configobj.html" rel="nofollow noreferrer">ConfigObj</a>.</p>
<p>Consider this structure for a hypothetical 'eggs' module:</p>
<pre>
eggs/
common/
__init__.py
config.py
foo/
__init__.py
a.py
</pre>
<p>'eggs.foo.a' needs some configuration information. What I am currently doing is, in 'a', <pre>import eggs.common.config</pre>. One problem with this is that if 'a' is moved to a deeper level in the module tree, the relative imports break. Absolute imports don't, but they require your module to be on your PYTHONPATH.</p>
<p>A possible alternative to the above absolute import is a relative import. Thus, in 'a',</p>
<pre>import .common.config</pre>
<p>Without debating the merits of relative vs absolute imports, I was wondering about other possible solutions?</p>
<p>edit- Removed the VCS context</p>
| [
{
"answer_id": 345799,
"author": "jfs",
"author_id": 4279,
"author_profile": "https://Stackoverflow.com/users/4279",
"pm_score": 0,
"selected": false,
"text": "sys.path git"
},
{
"answer_id": 346330,
"author": "S.Lott",
"author_id": 10661,
"author_profile": "https://Stackoverflow.com/users/10661",
"pm_score": 2,
"selected": false,
"text": "PYTHONPATH"
},
{
"answer_id": 347027,
"author": "rob",
"author_id": 43927,
"author_profile": "https://Stackoverflow.com/users/43927",
"pm_score": 0,
"selected": false,
"text": "egg/__init__.py __path__.append(__path__[0]+\"\\\\common\")\n__path__.append(__path__[0]+\"\\\\foo\")\n import egg.bar __init__.py"
}
] | 2008/12/06 | [
"https://Stackoverflow.com/questions/345746",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/37984/"
] |
345,753 | <p>I'm using TopLink as my ORM and MySQL as the DB.</p>
<p>I traded my auto-increment primary keys for GUIDs for one of my tables (alright, not quite: I'm actually using a random 64 bit integer, but that's good enough for my needs).</p>
<p>Anyway, now queries, which don't even use the key, are taking much longer.</p>
<p>What can I do?</p>
| [
{
"answer_id": 345801,
"author": "Frank Krueger",
"author_id": 338,
"author_profile": "https://Stackoverflow.com/users/338",
"pm_score": 0,
"selected": false,
"text": "create index Table_creationDate on Table(creationDate);\n"
}
] | 2008/12/06 | [
"https://Stackoverflow.com/questions/345753",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20498/"
] |
345,760 | <p>We were having a debate if enums should have uninitialized values. For example. We have </p>
<pre><code>public enum TimeOfDayType
{
Morning
Afternoon
Evening
}
</code></pre>
<p>or </p>
<pre><code>public enum TimeOfDayType
{
None
Morning
Afternoon
Evening
}
</code></pre>
<p>I think that there shouldn't be any none but then you have to default to some valid value on initialization. But others thought there should be some indication of uniitized state by having another enum that is None or NotSet.</p>
<p>thoughts?</p>
| [
{
"answer_id": 345786,
"author": "Frank Krueger",
"author_id": 338,
"author_profile": "https://Stackoverflow.com/users/338",
"pm_score": 5,
"selected": true,
"text": "enum Color { Red, Blue }\n void Draw(Color c);\n Color void Draw(Color? c);\n null None"
},
{
"answer_id": 345877,
"author": "JaredPar",
"author_id": 23283,
"author_profile": "https://Stackoverflow.com/users/23283",
"pm_score": 3,
"selected": false,
"text": "enum Color { Unknown, Red, Blue }\nenum Color2 { Red,Blue }\nstruct Example<T> {\n Color color;\n}\n\nstatic void SomeMethod() {\n var v1 = new Example<Color>();\n var v2 = new Example<Color2>();\n}\n enum Color2 { Red = 1, Blue = 2 }\nstatic void SomeOtherMethod(p1 as Example<Color2>) {\n switch ( p1.color ) {\n case Color.Red: {} \n case Color.Blue: {}\n default: {throw new Exception(\"What happened?\"); }\n }\n}\n"
}
] | 2008/12/06 | [
"https://Stackoverflow.com/questions/345760",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4653/"
] |
345,766 | <p>Has anyone managed to do this? I tried making a managed wrapper class for IPropertyStore but am getting AccessViolationExceptions on the methods (i.e. IPropertyStore::GetValue) that take a pointer to PROPVARIANT (rendered as a MarshalAs(UnmanagedType.Struct) out parameter in my managed version) Probably my understanding of COM and interop is inadequate --- I'm not sure if the problems are in my PROPVARIANT struct declaration (which currently just uses StructLayout.Sequential, declares a sequence of bytes, and manually manipulates the bytes to get values of the various types in the union etc.), COM issues with what process owns what, or something else. I've tried various other versions of the PROPVARIANT such as using StructLayout.Explicit for the unions, nothing's worked. Retrieving PROPERTYKEYs with IPropertyStore::GetAt --- which is declared natively as taking a pointer to PROPERTYKEY and as having an out parameter of my own StructLayout.Sequential PROPERTYKEY in my wrapper --- works just fine, by the way.</p>
| [
{
"answer_id": 345786,
"author": "Frank Krueger",
"author_id": 338,
"author_profile": "https://Stackoverflow.com/users/338",
"pm_score": 5,
"selected": true,
"text": "enum Color { Red, Blue }\n void Draw(Color c);\n Color void Draw(Color? c);\n null None"
},
{
"answer_id": 345877,
"author": "JaredPar",
"author_id": 23283,
"author_profile": "https://Stackoverflow.com/users/23283",
"pm_score": 3,
"selected": false,
"text": "enum Color { Unknown, Red, Blue }\nenum Color2 { Red,Blue }\nstruct Example<T> {\n Color color;\n}\n\nstatic void SomeMethod() {\n var v1 = new Example<Color>();\n var v2 = new Example<Color2>();\n}\n enum Color2 { Red = 1, Blue = 2 }\nstatic void SomeOtherMethod(p1 as Example<Color2>) {\n switch ( p1.color ) {\n case Color.Red: {} \n case Color.Blue: {}\n default: {throw new Exception(\"What happened?\"); }\n }\n}\n"
}
] | 2008/12/06 | [
"https://Stackoverflow.com/questions/345766",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19393/"
] |
345,788 | <p>I want my client code to look somewhat like this:</p>
<pre><code> val config:Config = new MyConfig("c:/etc/myConfig.txt")
println(config.param1)
println(config.param2)
println(config.param3)
</code></pre>
<p>Which means that:</p>
<ul>
<li>The Config interface defines the config fields</li>
<li>MyConfig is a Config implementation -- all the wiring needed is the instantiation of the desired implementation</li>
<li>Data is loaded lazily -- it should happen on first field reference (config.param1 in this case)</li>
</ul>
<p>So, I want the client code to be friendly, with support for interchangeable implementations, with statically typed fields, hiding lazy loading. I also want it to be as simple as possible for making alternative implementations, so Config should somewhat guide you.</p>
<p>I am not satisfied with what I came up with so far:</p>
<pre><code>trait Config {
lazy val param1:String = resolveParam1
lazy val param2:String = resolveParam2
lazy val param3:Int = resolveParam3
protected def resolveParam1:String
protected def resolveParam2:String
protected def resolveParam3:Int
}
class MyConfig(fileName:String) extends Config {
lazy val data:Map[String, Any] = readConfig
// some dummy impl here, should read from a file
protected def readConfig:Map[String,Any] = Map[String, Any]("p1" -> "abc", "p2" -> "defgh", "p3" -> 43)
protected def resolveParam1:String = data.get("p1").get.asInstanceOf[String]
protected def resolveParam2:String = data.get("p2").get.asInstanceOf[String]
protected def resolveParam3:Int = data.get("p3").get.asInstanceOf[Int]
}
</code></pre>
<p>I'm sure there are better solutions, that's where you can help :)</p>
<p>One thing I especially don't like here is that MyConfig defines an intermediate container with some arbitrary keys, and since it is Map[String, <strong>Any</strong>], I need to cast the values.</p>
| [
{
"answer_id": 345869,
"author": "sblundy",
"author_id": 4893,
"author_profile": "https://Stackoverflow.com/users/4893",
"pm_score": 0,
"selected": false,
"text": "trait Config {\n def param1:String\n def param2:String\n def param3:Int\n}\n\nclass MyConfig(fileName:String) extends Config {\n lazy val data:Map[String, Any] = readConfig\n\n // some dummy impl here, should read from a file\n protected def readConfig:Map[String,Any] = \n Map[String, Any](\"p1\" -> \"abc\", \"p2\" -> \"defgh\", \"p3\" -> 43)\n\n def param1:String = data.get(\"p1\").get.asInstanceOf[String]\n def param2:String = data.get(\"p2\").get.asInstanceOf[String]\n def param3:Int = data.get(\"p3\").get.asInstanceOf[Int]\n}\n MyConfig MyConfig class MyConfig(fileName:String) extends Config {\n private class NonLazyConfig(val p1:String, p2:String, p3:int) extends Config {\n def param1 = p1\n def param2 = p2\n def param1 = p3\n }\n lazy val inner:Config = readConfig\n\n // some dummy impl here, should read from a file\n protected def readConfig:Config = {\n return new NonLazyConfig(\"abc\", \"defgh\", 43)\n }\n def param1:String = inner.param1\n def param2:String = inner.param2\n def param3:Int = inner.param3\n}\n"
},
{
"answer_id": 346000,
"author": "Daniel Spiewak",
"author_id": 9815,
"author_profile": "https://Stackoverflow.com/users/9815",
"pm_score": 1,
"selected": false,
"text": "trait Config {\n val param1: String\n val param2: String\n val param3: Int\n}\n\nclass MyConfig extends Config {\n lazy val param1 = readConfig().(\"p1\")\n ...\n\n def readConfig(): Map[String, String] = ...\n}\n readConfig()"
}
] | 2008/12/06 | [
"https://Stackoverflow.com/questions/345788",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17138/"
] |
345,794 | <p>Below is the command I tried executing, without success:</p>
<pre><code>exec('ln -s ' . PLUGIN_DIR . '/.htaccess ' . ABSPATH . '/.htaccess');
</code></pre>
<p>When you add a die() at the end, it catches that there's an error:</p>
<pre><code>exec('ln -s ' . PLUGIN_DIR . '/.htaccess ' . ABSPATH . '/.htaccess') or die('what?!');
</code></pre>
<p>For the above exec() statement, a permissions problem is causing the error, but PHP isn't displaying it. How do you display from PHP what error is occurring?</p>
| [
{
"answer_id": 345802,
"author": "Eran Galperin",
"author_id": 10585,
"author_profile": "https://Stackoverflow.com/users/10585",
"pm_score": 5,
"selected": true,
"text": "exec('ln -s ' . PLUGIN_DIR . '/.htaccess ' . ABSPATH . '/.htaccess',$output);\nvar_dump($output);\n"
},
{
"answer_id": 24091183,
"author": "S.ov",
"author_id": 1269624,
"author_profile": "https://Stackoverflow.com/users/1269624",
"pm_score": 4,
"selected": false,
"text": "$cmd.=\" > $error_log 2>&1\"\n"
},
{
"answer_id": 40293890,
"author": "Amaynut",
"author_id": 3010827,
"author_profile": "https://Stackoverflow.com/users/3010827",
"pm_score": 5,
"selected": false,
"text": "exec('ln -s ' . PLUGIN_DIR . '/.htaccess ' . ABSPATH . '/.htaccess 2>&1',$output);\nvar_dump($output);\n"
},
{
"answer_id": 43387654,
"author": "Bonfix Ngetich",
"author_id": 6831102,
"author_profile": "https://Stackoverflow.com/users/6831102",
"pm_score": 4,
"selected": false,
"text": " ob_start();\n exec($cmd . \" 2>&1\", $output);\n $result = ob_get_contents();\n ob_end_clean();\n var_dump($output);\n"
},
{
"answer_id": 51400385,
"author": "maximusin9",
"author_id": 183991,
"author_profile": "https://Stackoverflow.com/users/183991",
"pm_score": 2,
"selected": false,
"text": "exec('command', $out, $res);\n"
}
] | 2008/12/06 | [
"https://Stackoverflow.com/questions/345794",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/32881/"
] |
345,795 | <p>I recently started Erlang, and I notice I constantly get "Warning: variable X is unused" while compiling. For example, take the following function, which finds the maximum element in a list:</p>
<pre><code> max([Head|Tail]) ->
max(Head,Tail).
max(Element,[Head | Tail]) when Element < Head ->
max(Head,Tail);
max(Element,[Head | Tail]) ->
max(Element, Tail);
max(Element,[]) ->
Element.
</code></pre>
<p>The compiler warns me that in the 3rd case of the function, Head is unused. How can the function be written without Head?</p>
| [
{
"answer_id": 345803,
"author": "Dustin",
"author_id": 39975,
"author_profile": "https://Stackoverflow.com/users/39975",
"pm_score": 4,
"selected": true,
"text": "max(Element,[_Head | Tail]) ->\n max(Element, Tail);\n"
},
{
"answer_id": 345804,
"author": "Nicholas Mancuso",
"author_id": 8945,
"author_profile": "https://Stackoverflow.com/users/8945",
"pm_score": 3,
"selected": false,
"text": " max([Head|Tail]) ->\n max(Head,Tail).\n\n max(Element,[Head | Tail]) when Element < Head ->\n max(Head,Tail);\n max(Element,[_| Tail]) ->\n max(Element, Tail);\n max(Element,[]) ->\n Element.\n"
},
{
"answer_id": 366895,
"author": "Adam Lindberg",
"author_id": 2457,
"author_profile": "https://Stackoverflow.com/users/2457",
"pm_score": 3,
"selected": false,
"text": "_ Name _ Head _Name Name _Head Head _ _Head _"
}
] | 2008/12/06 | [
"https://Stackoverflow.com/questions/345795",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/43791/"
] |
345,823 | <p>My question pertains to multi-threading in Java. I'm translating an app I wrote in Visual Basic 2008 into Java. There is a class in VB called <a href="http://msdn.microsoft.com/en-us/library/system.componentmodel.backgroundworker_members.aspx" rel="nofollow noreferrer">BackgroundWorker</a>, which allows the coder to perform a task on another thread, a lot like <code>SwingWorker</code> in Java. The only distinct difference is that, with the <code>BackgroundWorker</code> thread is <code>run()</code>, it fires an event called <code>DoWork()</code> on the mainline which contains the code to execute in the background. Furthermore, after the code has executed, a <code>RunWorkerCompleted()</code> event is fired back on the foreground thread to interpret results.</p>
<p>I have found the <code>BackgroundWorker</code> setup quite useful and it seems a little more flexible than <code>SwingWorker</code> and I was just wondering whether it was possible (and acceptable) to fire events in the same way in Java? And if so, how would I go about it? Since I've only done a quick scan over <code>SwingWorker</code>, it's possible that it has a similar functionality that would work just as well, in which case I would be happy to know about that instead.</p>
<p>Cheers,</p>
<p>Hoopla</p>
<p>EDIT:</p>
<p>Kewl. Cheers guys, thanks for the prompt replies, and apologies for my rather time-lax reply. I'll give your idea a go Oscar, sorry coobird, I didn't quite follow - any further explanation would be welcome (perhaps an example).</p>
<p>Just to recap: I want to have a runnable class, that I instantiate an instance of in my code. The runnable class has two events, one of which is fired from the background thread and contains the code to run in the background (<code>DoWork()</code>), and the other event is fired on the foreground thread after the background thread has completed it's task (<code>RunWorkerCompleted()</code>).</p>
<p>And if I understand your advice correctly, I can fire the <code>DoWork()</code> event from the runnable class' <code>run()</code> method so that it will be executed on the background thread, and then I can use the <code>SwingUtilities.invokeLater()</code> method to fire the <code>RunWorkerCompleted()</code> event on the foreground thread, once the background thread has finished execution.</p>
<p>Yes?</p>
| [
{
"answer_id": 345851,
"author": "coobird",
"author_id": 17172,
"author_profile": "https://Stackoverflow.com/users/17172",
"pm_score": 0,
"selected": false,
"text": "PropertyChangeListener SwingWorker PropertyChangeEvent firePropertyChange PropertyListener SwingWorker SwingWorker doInBackground() firePropertyChange"
},
{
"answer_id": 345882,
"author": "OscarRyz",
"author_id": 20654,
"author_profile": "https://Stackoverflow.com/users/20654",
"pm_score": 1,
"selected": true,
"text": "import java.awt.*;\nimport java.awt.event.*;\nimport javax.swing.*;\n\npublic class InvokeLaterEffect {\n\n static JTextArea text = new JTextArea();\n\n\n // See the diff by commenting.\n static void done() {\n SwingUtilities.invokeLater( doneAction ); \n //doneAction.run();\n }\n\n\n public static void main( String [] args ) {\n JFrame frame = new JFrame();\n frame.add( text );\n frame.pack();\n frame.setVisible( true );\n\n bacgroundTask.start();\n }\n // run a task in the background\n static Thread bacgroundTask = new Thread(){\n public void run(){\n try { \n System.out.println( Thread.currentThread().getName() + \" Started background task \");\n Thread.sleep( 5000 );\n System.out.println( Thread.currentThread().getName() + \" Finished background task\");\n done();\n } catch ( InterruptedException ie ){}\n }\n };\n\n // called whtn id done\n static Runnable doneAction = new Runnable(){\n public void run(){\n System.out.println( Thread.currentThread().getName() + \" start setting text \");\n text.setText(\"Hello\");\n System.out.println( Thread.currentThread().getName() + \" finish setting text \");\n }\n };\n\n\n}\n Thread-2 Started background task\nThread-2 Finished background task\nAWT-EventQueue-0 start setting text\nAWT-EventQueue-0 finish setting text\n"
}
] | 2008/12/06 | [
"https://Stackoverflow.com/questions/345823",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/43874/"
] |
345,832 | <p>What's the best way to "see what is happening" in an algorithm/data structure? If it's something like a binary search I just imagine a bunch of boxes in a row, and throwing half of them out each time. Is there something more powerful that will let us grok something as abstract as an algorithm/data structure?</p>
<p>Clarification: I'm looking for something a little more general. Example: in order to visualize time - some people use a clock in there head but thats slow, whereas a more natural feel would be a globe and if you are trying to get a 'feel' for how an algorithm works you can imagine two objects moving in different directions on that globe.</p>
| [
{
"answer_id": 345850,
"author": "Ryan Fox",
"author_id": 55,
"author_profile": "https://Stackoverflow.com/users/55",
"pm_score": 0,
"selected": false,
"text": "digraph G {\n A->B;\n B->C;\n C->D;\n D->B;\n}\n"
}
] | 2008/12/06 | [
"https://Stackoverflow.com/questions/345832",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/750/"
] |
345,838 | <p>With the help of the Stack Overflow community I've written a pretty basic-but fun physics simulator.</p>
<p><img src="https://i.stack.imgur.com/EeqSP.png" alt="alt text" /></p>
<p>You click and drag the mouse to launch a ball. It will bounce around and eventually stop on the "floor".</p>
<p>My next big feature I want to add in is ball to ball collision. The ball's movement is broken up into a x and y speed vector. I have gravity (small reduction of the y vector each step), I have friction (small reduction of both vectors each collision with a wall). The balls honestly move around in a surprisingly realistic way.</p>
<p>I guess my question has two parts:</p>
<ol>
<li><strong>What is the best method to detect ball to ball collision?</strong><br />
Do I just have an O(n^2) loop that iterates over each ball and checks every other ball to see if it's radius overlaps?</li>
<li><strong>What equations do I use to handle the ball to ball collisions? Physics 101</strong><br />
How does it effect the two balls speed x/y vectors? What is the resulting direction the two balls head off in? How do I apply this to each ball?</li>
</ol>
<p><img src="https://upload.wikimedia.org/wikipedia/commons/2/2c/Elastischer_sto%C3%9F_2D.gif" alt="alt text" /></p>
<p>Handling the collision detection of the "walls" and the resulting vector changes were easy but I see more complications with ball-ball collisions. With walls I simply had to take the negative of the appropriate x or y vector and off it would go in the correct direction. With balls I don't think it is that way.</p>
<p>Some quick clarifications: for simplicity I'm ok with a perfectly elastic collision for now, also all my balls have the same mass right now, but I might change that in the future.</p>
<hr />
<p>Edit: Resources I have found useful</p>
<p>2d Ball physics with vectors: <a href="https://www.vobarian.com/collisions/2dcollisions2.pdf" rel="nofollow noreferrer">2-Dimensional Collisions Without Trigonometry.pdf</a><br />
2d Ball collision detection example: <a href="https://web.archive.org/web/20210125052930/http://geekswithblogs.net/robp/archive/2008/05/15/adding-collision-detection.aspx" rel="nofollow noreferrer">Adding Collision Detection</a></p>
<hr />
<h2>Success!</h2>
<p>I have the ball collision detection and response working great!</p>
<p>Relevant code:</p>
<p>Collision Detection:</p>
<pre><code>for (int i = 0; i < ballCount; i++)
{
for (int j = i + 1; j < ballCount; j++)
{
if (balls[i].colliding(balls[j]))
{
balls[i].resolveCollision(balls[j]);
}
}
}
</code></pre>
<p>This will check for collisions between every ball but skip redundant checks (if you have to check if ball 1 collides with ball 2 then you don't need to check if ball 2 collides with ball 1. Also, it skips checking for collisions with itself).</p>
<p>Then, in my ball class I have my colliding() and resolveCollision() methods:</p>
<pre><code>public boolean colliding(Ball ball)
{
float xd = position.getX() - ball.position.getX();
float yd = position.getY() - ball.position.getY();
float sumRadius = getRadius() + ball.getRadius();
float sqrRadius = sumRadius * sumRadius;
float distSqr = (xd * xd) + (yd * yd);
if (distSqr <= sqrRadius)
{
return true;
}
return false;
}
public void resolveCollision(Ball ball)
{
// get the mtd
Vector2d delta = (position.subtract(ball.position));
float d = delta.getLength();
// minimum translation distance to push balls apart after intersecting
Vector2d mtd = delta.multiply(((getRadius() + ball.getRadius())-d)/d);
// resolve intersection --
// inverse mass quantities
float im1 = 1 / getMass();
float im2 = 1 / ball.getMass();
// push-pull them apart based off their mass
position = position.add(mtd.multiply(im1 / (im1 + im2)));
ball.position = ball.position.subtract(mtd.multiply(im2 / (im1 + im2)));
// impact speed
Vector2d v = (this.velocity.subtract(ball.velocity));
float vn = v.dot(mtd.normalize());
// sphere intersecting but moving away from each other already
if (vn > 0.0f) return;
// collision impulse
float i = (-(1.0f + Constants.restitution) * vn) / (im1 + im2);
Vector2d impulse = mtd.normalize().multiply(i);
// change in momentum
this.velocity = this.velocity.add(impulse.multiply(im1));
ball.velocity = ball.velocity.subtract(impulse.multiply(im2));
}
</code></pre>
<p>Source Code: <a href="https://www.dropbox.com/s/1j4aiu2aahjc19p/ballbounce.zip?dl=0" rel="nofollow noreferrer">Complete source for ball to ball collider.</a></p>
<p>If anyone has some suggestions for how to improve this basic physics simulator let me know! One thing I have yet to add is angular momentum so the balls will roll more realistically. Any other suggestions? Leave a comment!</p>
| [
{
"answer_id": 345863,
"author": "Jay Conrod",
"author_id": 1891,
"author_profile": "https://Stackoverflow.com/users/1891",
"pm_score": 8,
"selected": true,
"text": "void Simulation::collide(Storage::Iterator a, Storage::Iterator b)\n{\n // Check whether there actually was a collision\n if (a == b)\n return;\n\n Vector collision = a.position() - b.position();\n double distance = collision.length();\n if (distance == 0.0) { // hack to avoid div by zero\n collision = Vector(1.0, 0.0);\n distance = 1.0;\n }\n if (distance > 1.0)\n return;\n\n // Get the components of the velocity vectors which are parallel to the collision.\n // The perpendicular component remains the same for both fish\n collision = collision / distance;\n double aci = a.velocity().dot(collision);\n double bci = b.velocity().dot(collision);\n\n // Solve for the new velocities using the 1-dimensional elastic collision equations.\n // Turns out it's really simple when the masses are the same.\n double acf = bci;\n double bcf = aci;\n\n // Replace the collision velocity components with the new ones\n a.velocity() += (acf - aci) * collision;\n b.velocity() += (bcf - bci) * collision;\n}\n"
},
{
"answer_id": 345945,
"author": "FlySwat",
"author_id": 1965,
"author_profile": "https://Stackoverflow.com/users/1965",
"pm_score": 2,
"selected": false,
"text": "public Rectangle getBoundingRect()\n{\n int ballHeight = (int)Ball.Height * 0.80f;\n int ballWidth = (int)Ball.Width * 0.80f;\n int x = Ball.X - ballWidth / 2;\n int y = Ball.Y - ballHeight / 2;\n\n return new Rectangle(x,y,ballHeight,ballWidth);\n}\n // Checks every ball against every other ball. \n// For best results, split it into quadrants like Ryan suggested. \n// I didn't do that for simplicity here.\nfor (int i = 0; i < balls.count; i++)\n{\n Rectangle r1 = balls[i].getBoundingRect();\n\n for (int k = 0; k < balls.count; k++)\n {\n\n if (balls[i] != balls[k])\n {\n Rectangle r2 = balls[k].getBoundingRect();\n\n if (r1.Intersects(r2))\n {\n // balls[i] collided with balls[k]\n }\n }\n }\n}\n"
},
{
"answer_id": 6794843,
"author": "trashgod",
"author_id": 230513,
"author_profile": "https://Stackoverflow.com/users/230513",
"pm_score": 2,
"selected": false,
"text": "KineticModel"
},
{
"answer_id": 19203806,
"author": "Stefan Musarra",
"author_id": 877314,
"author_profile": "https://Stackoverflow.com/users/877314",
"pm_score": 2,
"selected": false,
"text": "dot_velocity = ball_1.velocity.dot(ball_2.velocity);\nmtd_factor = 1. + 0.5 * Math.abs(dot_velocity * Math.sin(collision_angle));\nmtd.multplyScalar(mtd_factor);\n"
},
{
"answer_id": 62671243,
"author": "Estid Felipe Lozano Reyes",
"author_id": 10782857,
"author_profile": "https://Stackoverflow.com/users/10782857",
"pm_score": 2,
"selected": false,
"text": "float dx = circle1.x - circle2.x,\n dy = circle1.y - circle2.y,\n r = circle1.r + circle2.r;\nreturn (dx * dx + dy * dy <= r * r);\n"
},
{
"answer_id": 64023365,
"author": "gordon_freeman",
"author_id": 14321038,
"author_profile": "https://Stackoverflow.com/users/14321038",
"pm_score": 1,
"selected": false,
"text": " //you just need a ball object with a speed and position vector.\n class TBall {\n constructor(x, y, vx, vy) {\n this.r = [x, y];\n this.v = [0, 0];\n }\n }\n\n //throw two balls into this function and it'll update their speed vectors\n //if they collide, you need to call this in your main loop for every pair of \n //balls.\n function collision(ball1, ball2) {\n n = [ (ball1.r)[0] - (ball2.r)[0], (ball1.r)[1] - (ball2.r)[1] ];\n un = [n[0] / vecNorm(n), n[1] / vecNorm(n) ] ;\n ut = [ -un[1], un[0] ]; \n v1n = dotProd(un, (ball1.v));\n v1t = dotProd(ut, (ball1.v) );\n v2n = dotProd(un, (ball2.v) );\n v2t = dotProd(ut, (ball2.v) );\n v1t_p = v1t; v2t_p = v2t;\n v1n_p = v2n; v2n_p = v1n;\n v1n_pvec = [v1n_p * un[0], v1n_p * un[1] ]; \n v1t_pvec = [v1t_p * ut[0], v1t_p * ut[1] ]; \n v2n_pvec = [v2n_p * un[0], v2n_p * un[1] ]; \n v2t_pvec = [v2t_p * ut[0], v2t_p * ut[1] ];\n ball1.v = vecSum(v1n_pvec, v1t_pvec); ball2.v = vecSum(v2n_pvec, v2t_pvec);\n }\n\n"
},
{
"answer_id": 68538139,
"author": "zezba9000",
"author_id": 456832,
"author_profile": "https://Stackoverflow.com/users/456832",
"pm_score": 0,
"selected": false,
"text": "private void CollideBalls(Transform ball1, Transform ball2, ref Vector3 vel1, ref Vector3 vel2, float radius1, float radius2)\n{\n var vec = ball1.position - ball2.position;\n float dis = vec.magnitude;\n if (dis < radius1 + radius2)\n {\n var n = vec.normalized;\n ReflectVelocity(ref vel1, ref vel2, ballMass1, ballMass2, n);\n\n var c = Vector3.Lerp(ball1.position, ball2.position, radius1 / (radius1 + radius2));\n ball1.position = c + (n * radius1);\n ball2.position = c - (n * radius2);\n }\n}\n\npublic static void ReflectVelocity(ref Vector3 vel1, ref Vector3 vel2, float mass1, float mass2, Vector3 intersectionNormal)\n{\n float velImpact1 = Vector3.Dot(vel1, intersectionNormal);\n float velImpact2 = Vector3.Dot(vel2, intersectionNormal);\n\n float totalMass = mass1 + mass2;\n float massTransfure1 = mass1 / totalMass;\n float massTransfure2 = mass2 / totalMass;\n\n vel1 += ((velImpact2 * massTransfure2) - (velImpact1 * massTransfure2)) * intersectionNormal;\n vel2 += ((velImpact1 * massTransfure1) - (velImpact2 * massTransfure1)) * intersectionNormal;\n}\n"
}
] | 2008/12/06 | [
"https://Stackoverflow.com/questions/345838",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2635/"
] |
345,865 | <p>I'm adding a record like this:</p>
<pre><code> Dim pathString As String = HttpContext.Current.Request.MapPath("Banking.mdb")
Dim odbconBanking As New OleDbConnection _
("Provider=Microsoft.Jet.OLEDB.4.0;" & _
"Data Source=" + pathString)
Dim sql As String
sql = "INSERT INTO tblUsers ( FirstName, LastName, Address, City, Province, Zip, Phone, UserName, [Password])" & _
" VALUES ('" & firstName & "', '" & lastName & "', '" & address & _
"', '" & city & "', '" & province & "', '" & zip & "', '" & phone & "', '" & username & "', '" & password & "');"
odbconBanking.Open()
Dim cmd As New OleDbCommand(sql, odbconBanking)
cmd.ExecuteNonQuery()
odbconBanking.Close()
</code></pre>
<p>The primary key is an autonumber field called UserID. So, how do I get the primary key of the record I just inserted?</p>
<p>Thanks.</p>
| [
{
"answer_id": 345870,
"author": "Christian C. Salvadó",
"author_id": 5445,
"author_profile": "https://Stackoverflow.com/users/5445",
"pm_score": 2,
"selected": false,
"text": "\"SELECT @@IDENTITY\""
},
{
"answer_id": 345871,
"author": "Kibbee",
"author_id": 1862,
"author_profile": "https://Stackoverflow.com/users/1862",
"pm_score": 2,
"selected": false,
"text": ";select scope_identity();\n"
},
{
"answer_id": 345885,
"author": "Gezim",
"author_id": 32495,
"author_profile": "https://Stackoverflow.com/users/32495",
"pm_score": 2,
"selected": false,
"text": " Dim pathString As String = HttpContext.Current.Request.MapPath(\"Banking.mdb\")\n Dim odbconBanking As New OleDbConnection _\n (\"Provider=Microsoft.Jet.OLEDB.4.0;\" & _\n \"Data Source=\" + pathString)\n Dim sql As String\n sql = \"INSERT INTO tblUsers ( FirstName, LastName, Address, City, Province, Zip, Phone, UserName, [Password])\" & _\n \" VALUES ('\" & firstName & \"', '\" & lastName & \"', '\" & address & _\n \"', '\" & city & \"', '\" & province & \"', '\" & zip & \"', '\" & phone & \"', '\" & username & \"', '\" & password & \"');\"\n odbconBanking.Open()\n Dim cmd As New OleDbCommand(sql, odbconBanking)\n cmd.ExecuteNonQuery()\n Dim newcmd As New OleDbCommand(\"SELECT @@IDENTITY\", odbconBanking)\n uid = newcmd.ExecuteScalar\n\n odbconBanking.Close()\n"
},
{
"answer_id": 345976,
"author": "Chad Braun-Duin",
"author_id": 5458,
"author_profile": "https://Stackoverflow.com/users/5458",
"pm_score": 4,
"selected": true,
"text": "Dim pathString As String = HttpContext.Current.Request.MapPath(\"Banking.mdb\")\nDim odbconBanking As New OleDbConnection _\n (\"Provider=Microsoft.Jet.OLEDB.4.0;\" & _\n \"Data Source=\" + pathString)\nDim sql As String\nsql = \"INSERT INTO tblUsers ( FirstName, LastName, Address, City, Province, Zip, Phone, UserName, [Password])\" & _\n \" VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?);\"\nodbconBanking.Open()\nDim cmd As New OleDbCommand(sql, odbconBanking)\n\n//Add Params here\ncmd.Parameters.Add(new OdbcParameter(\"@FirstName\", firstName))\ncmd.Parameters.Add(new OdbcParameter(\"@LastName\", lastName))\n//..etc\n\n//End add Params here\n\ncmd.ExecuteNonQuery()\nDim newcmd As New OleDbCommand(\"SELECT @@IDENTITY\", odbconBanking)\nuid = newcmd.ExecuteScalar\n\nodbconBanking.Close()\n"
},
{
"answer_id": 346420,
"author": "Philippe Grondier",
"author_id": 11436,
"author_profile": "https://Stackoverflow.com/users/11436",
"pm_score": 1,
"selected": false,
"text": "Dim sql As String, _\n myNewUserId as variant\n\nmyNewUserId = stGuidGen 'this function will generate a new GUID value)'\nsql = \"INSERT INTO tblUsers ( userId, LastName)\" & _\n \" VALUES ('\" & myNewUserId & \"','\" & LastName);\"\n"
}
] | 2008/12/06 | [
"https://Stackoverflow.com/questions/345865",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/32495/"
] |
345,874 | <p>Using Awk I want to match the <em>entire</em> record using a regular expression. By default the regular expression matching is for parts of a record.</p>
<p>The ideal solution would:</p>
<ul>
<li>Be general for all fields, regardless of the field separator used.</li>
<li>Not treat the entire input as a single field and parse it manually using string functions.</li>
<li>Work in a general way and not be specific to gawk for example.</li>
</ul>
<p>However any and all solutions are of interest as long as they <strong>use Awk without calls to external programs</strong>.</p>
<p>An example, I have:</p>
<pre><code>$ ls
indata.txt t1.awk
$ cat indata.txt
a1010_
1010_
1010_b
$ cat t1.awk
/[01]*_[01]*/ { print $0 }
</code></pre>
<p>I get:</p>
<pre><code>$ awk -f t1.awk indata.txt
a1010_
1010_
1010_b
</code></pre>
<p>This is the result I am seeking:</p>
<pre><code>$ awk -f t1.awk indata.txt
1010_
</code></pre>
| [
{
"answer_id": 345900,
"author": "Paul Tomblin",
"author_id": 3333,
"author_profile": "https://Stackoverflow.com/users/3333",
"pm_score": 3,
"selected": true,
"text": "/^[01]*_[01]*$/ { print $0 }\n"
},
{
"answer_id": 345904,
"author": "jfs",
"author_id": 4279,
"author_profile": "https://Stackoverflow.com/users/4279",
"pm_score": 2,
"selected": false,
"text": "$ gawk '/^[01]*_[01]*$/' indata.txt\n1010_\n"
}
] | 2008/12/06 | [
"https://Stackoverflow.com/questions/345874",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
345,883 | <p>Since String implements <code>IEnumerable<char></code>, I was expecting to see the Enumerable extension methods in Intellisense, for example, when typing the period in</p>
<pre><code>String s = "asdf";
s.
</code></pre>
<p>I was expecting to see <code>.Select<char>(...)</code>, <code>.ToList<char>()</code>, etc.
I was then suprised to see that the extension methods <strong>do</strong> in fact work on the string class, they just don't show up in Intellisense. Does anyone know why this is?
This may be related to <a href="https://stackoverflow.com/questions/295287/how-can-i-prevent-a-public-class-that-provides-extension-methods-from-appearing">this</a> question.</p>
| [
{
"answer_id": 345889,
"author": "JaredPar",
"author_id": 23283,
"author_profile": "https://Stackoverflow.com/users/23283",
"pm_score": 5,
"selected": true,
"text": "IEnumerable<T>"
},
{
"answer_id": 355131,
"author": "Tarik",
"author_id": 44852,
"author_profile": "https://Stackoverflow.com/users/44852",
"pm_score": -1,
"selected": false,
"text": "For example you can write it public static string myExtensionMethod(this String yuppi){\n}\n"
}
] | 2008/12/06 | [
"https://Stackoverflow.com/questions/345883",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/22539/"
] |
345,920 | <p>I need to invoke a VBA macro within an Excel workbook from a python script. Someone else has provided the Excel workbook with the macro. The macro grabs updated values from an external database, and performs some fairly complex massaging of the data. I need the results from this massaging, and I don't really want to duplicate this in my Python script, if I can avoid it. So, it would be great if I could just invoke the macro from my script, and grab the massaged results.</p>
<p>Everything I know about COM I learned from "Python Programming on Win32". Good book, but not enough for my task at hand. I searched, but haven't found any good examples on how to do this. Does anyone have any good examples, or perhaps some skeleton code of how to address/invoke the VBA macro? A general reference (book, web link, etc) on the Excel COM interfaces would also help here. Thanks.</p>
| [
{
"answer_id": 345995,
"author": "shahkalpesh",
"author_id": 23574,
"author_profile": "https://Stackoverflow.com/users/23574",
"pm_score": 2,
"selected": true,
"text": "\nSub test(ByVal i As Integer)\nMsgBox \"hello world \" & i\nEnd Sub\n"
},
{
"answer_id": 346421,
"author": "jbrogdon",
"author_id": 40514,
"author_profile": "https://Stackoverflow.com/users/40514",
"pm_score": 3,
"selected": false,
"text": "import win32com.client\nxl=win32com.client.Dispatch(\"Excel.Application\")\nxl.Workbooks.Open(Filename=\"<your Excel File>\",ReadOnly=1)\nxl.Application.Run(\"<your macro name>\")\n#...access spreadsheet data...\nxl.Workbooks(1).Close(SaveChanges=0)\nxl.Application.Quit()\nxl=0\n"
}
] | 2008/12/06 | [
"https://Stackoverflow.com/questions/345920",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/40514/"
] |
345,939 | <p>I want to open a file dialog box in user control. I used <code>using System.Windows.Forms</code>, but still I can't access SaveFileDialog class. Can anybody tell me how to do this? Thanks.</p>
| [
{
"answer_id": 345951,
"author": "oglester",
"author_id": 2017,
"author_profile": "https://Stackoverflow.com/users/2017",
"pm_score": 0,
"selected": false,
"text": "<input type=file> \n <asp:FileUpLoad id=\"FileUpLoad1\" runat=\"server\" />\n"
}
] | 2008/12/06 | [
"https://Stackoverflow.com/questions/345939",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/43886/"
] |
345,970 | <p>How can a program capture <del>generates</del> events from a dynamically created button control in asp.net?</p>
| [
{
"answer_id": 345974,
"author": "FlySwat",
"author_id": 1965,
"author_profile": "https://Stackoverflow.com/users/1965",
"pm_score": 2,
"selected": false,
"text": "Button myButton = new Button();\nmyButton.Click += new ClickEventHandler...etc\n"
}
] | 2008/12/06 | [
"https://Stackoverflow.com/questions/345970",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/42791/"
] |
345,987 | <p>I'm building a site which will have a 'Login/Register' link on every page. Whenever someone clicks this link, I want a JavaScript/div based signup form to float on top of the content with a link to 'close' it if they want.</p>
<p>I also want the capability of the div showing up near the position of their mouse, i.e so if they click the link near the middle of the page it should show up near the middle, and they don't have to scroll all the way to the top to see it. (To clarify, may be it should automatically determine the mouse coordinates or have a way to specify the (x, y) coordinates.)</p>
<p>I'm a good JavaScript developer myself, but not an expert so I'm sure there will be some libraries doing this better than I can. Any links/tutorials to share? </p>
| [
{
"answer_id": 346185,
"author": "Lucas Jones",
"author_id": 41981,
"author_profile": "https://Stackoverflow.com/users/41981",
"pm_score": 1,
"selected": false,
"text": "<div id=\"loginBox\"><!-- insert content here--></div><br />\n<style type=\"text/css\"><br />\n #loginBox { <br/>\n display:none; <br/>\n position:absolute; <br/>\n /* left and top */<br/>\n }<br/>\n</style><br/>\n<script type=\"text/javascript\"><br/>\n function showLoginBox() { document.getElementById('loginBox').style.display = 'block'; }<br/>\n</script><br/>\n<a href=\"#\" onclick=\"showLoginBox()\" >Show login box</a><br />\n"
}
] | 2008/12/06 | [
"https://Stackoverflow.com/questions/345987",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
345,991 | <p>Okay, what is it, and why does it occur on Win2003 server, but not on WinXP.</p>
<p>It doesn't seem to affect my application at all, but I get this error message when I close the application. And it's annoying (as errors messages should be).</p>
<p>I am using pyOpenGl and wxPython to do the graphics stuff. Unfortunately, I'm a C# programmer that has taken over this Python app, and I had to learn Python to do it.</p>
<p>I can supply code and version numbers etc, but I'm still learning the technical stuff, so any help would be appreciated.</p>
<p>Python 2.5, wxPython and pyOpenGL</p>
| [
{
"answer_id": 346501,
"author": "Kozyarchuk",
"author_id": 52490,
"author_profile": "https://Stackoverflow.com/users/52490",
"pm_score": 9,
"selected": true,
"text": "import logging\nlogging.basicConfig()\n"
}
] | 2008/12/06 | [
"https://Stackoverflow.com/questions/345991",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/30862/"
] |
345,997 | <p>I accidentally committed too many files to an SVN repository and changed some things I didn't mean to. (Sigh.) In order to revert them to their prior state, the best I could come up with was </p>
<pre><code>svn rm l3toks.dtx
svn copy -r 854 svn+ssh://<repository URL>/l3toks.dtx ./l3toks.dtx
</code></pre>
<p>Jeez! Is there no better way? Why can't I just write something like this: </p>
<pre><code>svn revert -r 854 l3toks.dtx
</code></pre>
<p>Okay, I'm only using v1.4.4, but I skimmed over the changes list for the 1.5 branch and I couldn't see anything directly related to this. Did I miss anything?</p>
<hr>
<p>Edit: I guess I wasn't clear enough. I don't think I want to reverse merge, because then I'll lose the changes that I <em>did</em> want to make! Say that <code>fileA</code> and <code>fileB</code> were both modified but I only wanted to commit <code>fileA</code>; accidentally typing </p>
<pre><code>svn commit -m "small change"
</code></pre>
<p>commits both files, and now I want to roll back <code>fileB</code>. Reverse merging makes this task no easier (as far as I can tell) than the steps I outlined above.</p>
| [
{
"answer_id": 346120,
"author": "orip",
"author_id": 37020,
"author_profile": "https://Stackoverflow.com/users/37020",
"pm_score": 9,
"selected": true,
"text": "svn merge -r 854:853 l3toks.dtx\n svn merge -c -854 l3toks.dtx\n"
},
{
"answer_id": 4272145,
"author": "sdaau",
"author_id": 277826,
"author_profile": "https://Stackoverflow.com/users/277826",
"pm_score": 5,
"selected": false,
"text": "svn copy -r 851 svn+ssh://<repository URL>/l3toks.dtx ./l3toks.dtx\n svn up -r 851 ./l3toks.dtx\n svn ci -m \"rolled back to r 851\" subversion svn merge -r HEAD:851 l3toks.dtx\n--- Reverse-merging r854 through r852 into 'l3toks.dtx':\nU l3toks.dtx\n svn diff svn ci -m \"rolled back to r 851\" svn up svn revert --recursive . svn merge -r HEAD:851 l3toks.dtx svn export -r 851 l3toks.dtx\nA l3toks.dtx\nExport complete.\n"
},
{
"answer_id": 11442911,
"author": "Igor",
"author_id": 1519290,
"author_profile": "https://Stackoverflow.com/users/1519290",
"pm_score": 3,
"selected": false,
"text": "svn up -r 3340 (or what ever your desired revision number)\n svn up\n"
},
{
"answer_id": 14231156,
"author": "Ken Russell",
"author_id": 950149,
"author_profile": "https://Stackoverflow.com/users/950149",
"pm_score": 2,
"selected": false,
"text": "svn merge -r head:prev l3toks.dtx\n"
},
{
"answer_id": 22322607,
"author": "Dylan",
"author_id": 3102549,
"author_profile": "https://Stackoverflow.com/users/3102549",
"pm_score": 2,
"selected": false,
"text": "svn cat -r 851 l3toks.dtx > l3toks.dtx\n"
}
] | 2008/12/06 | [
"https://Stackoverflow.com/questions/345997",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4161/"
] |
346,012 | <p>I was browsing the SGI STL documentation and ran into <a href="http://www.sgi.com/tech/stl/project1st.html" rel="nofollow noreferrer"><code>project1st<Arg1, Arg2></code></a>. I understand its definition, but I am having a hard time imagining a practical usage.</p>
<p>Have you ever used project1st or can you imagine a scenario?</p>
| [
{
"answer_id": 346032,
"author": "Head Geek",
"author_id": 12193,
"author_profile": "https://Stackoverflow.com/users/12193",
"pm_score": 0,
"selected": false,
"text": "identity std::transform std::copy"
},
{
"answer_id": 349080,
"author": "MSalters",
"author_id": 15416,
"author_profile": "https://Stackoverflow.com/users/15416",
"pm_score": 2,
"selected": false,
"text": "std::pair .first std::transform std::map<K,V> std::vector<K> project2nd vector<V>"
}
] | 2008/12/06 | [
"https://Stackoverflow.com/questions/346012",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/338/"
] |
346,015 | <p>I have a problem with an object I have created that looks something like this:</p>
<pre><code>var myObject = {
AddChildRowEvents: function(row, p2) {
if(document.attachEvent) {
row.attachEvent('onclick', function(){this.DoSomething();});
} else {
row.addEventListener('click', function(){this.DoSomething();}, false);
}
},
DoSomething: function() {
this.SomethingElse(); //<-- Error here, object 'this' does not support this method.
}
}
</code></pre>
<p>The problem is that when I am inside the 'DoSomething' function, 'this' does not refer to 'myObject' what am I doing wrong?</p>
| [
{
"answer_id": 346044,
"author": "Mike Kantor",
"author_id": 14607,
"author_profile": "https://Stackoverflow.com/users/14607",
"pm_score": 5,
"selected": false,
"text": "AddChildRowEvents: function(row, p2) {\n var theObj = this;\n if(document.attachEvent) {\n row.attachEvent('onclick', function(){theObj.DoSomething();});\n } else {\n row.addEventListener('click', function(){theObj.DoSomething();}, false);\n }\n},\n"
},
{
"answer_id": 545759,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "var myObject = { \n AddChildRowEvents: function(row, p2) { \n var self = this;\n\n if(document.attachEvent) { \n row.attachEvent('onclick', function(){this.DoSomething(self);}); \n } else { \n row.addEventListener('click', function(){this.DoSomething(self);}, false); \n } \n }, \n\n DoSomething: function(self) { \n self.SomethingElse(); \n }\n}\n"
},
{
"answer_id": 545802,
"author": "Svante Svenson",
"author_id": 19707,
"author_profile": "https://Stackoverflow.com/users/19707",
"pm_score": 4,
"selected": false,
"text": "this this var myObject = {\n AddChildRowEvents: function(row, p2) {\n var that = this;\n if(document.attachEvent) {\n row.attachEvent('onclick', function(){that.DoSomething();});\n } else {\n row.addEventListener('click', function(){that.DoSomething();}, false);\n }\n }\n}\n"
},
{
"answer_id": 18286126,
"author": "Farshid Saberi",
"author_id": 1790801,
"author_profile": "https://Stackoverflow.com/users/1790801",
"pm_score": 2,
"selected": false,
"text": " row.attachEvent('onclick', function(){this.DoSomething();});\n row.addEventListener('click', function(){this.DoSomething();}, false);\n var myObject = {\n\n AddChildRowEvents: function(row, p2) {\n if(document.attachEvent) {\n row.attachEvent('onclick', $.proxy(function () {\n this.DoSomething();\n }, this));\n } else {\n row.addEventListener('click', $.proxy(function () {\n this.DoSomething();\n },this), false);\n }\n },\n\n DoSomething: function() {\n this.SomethingElse(); //<-- Error here, object 'this' does not support this method.\n }\n}\n"
},
{
"answer_id": 48747755,
"author": "pom421",
"author_id": 2728710,
"author_profile": "https://Stackoverflow.com/users/2728710",
"pm_score": 3,
"selected": false,
"text": "this this myObject DOM element this DOM element myObject bind method arrow function let handler = {\n addEventHandler: function(row) {\n console.log(\"this\", this)\n row.addEventListener(\"click\", () => {\n console.log(\"this\", this)\n this.doSomethingElse()\n })\n },\n \n doSomethingElse: function() {\n console.log(\"something else\")\n }\n}\nvar div = document.querySelector(\"div\")\nhandler.addEventHandler(div) <div>one</div> arrow function ES2015 this arrow function this this addEventHandler myObject let handler = {\n addEventHandler: function(row) {\n console.log(\"this\", this)\n row.addEventListener(\"click\", function() {\n console.log(\"this\", this)\n this.doSomethingElse()\n }.bind(this))\n },\n \n doSomethingElse: function() {\n console.log(\"something else\")\n }\n}\nvar div = document.querySelector(\"div\")\nhandler.addEventHandler(div) <div>one</div> addEventListener this this addEventHandler"
}
] | 2008/12/06 | [
"https://Stackoverflow.com/questions/346015",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
346,021 | <p>Suppose I have this code:</p>
<pre><code>var myArray = new Object();
myArray["firstname"] = "Bob";
myArray["lastname"] = "Smith";
myArray["age"] = 25;
</code></pre>
<p>Now if I wanted to remove "lastname"?....is there some equivalent of
<code>myArray["lastname"].remove()</code>?</p>
<p>(I need the element gone because the number of elements is important and I want to keep things clean.)</p>
| [
{
"answer_id": 346022,
"author": "Dennis C",
"author_id": 40214,
"author_profile": "https://Stackoverflow.com/users/40214",
"pm_score": 11,
"selected": true,
"text": "delete const o = { lastName: 'foo' }\no.hasOwnProperty('lastName') // true\ndelete o['lastName']\no.hasOwnProperty('lastName') // false\n delete Array Array Array#splice Array#pop delete o o delete"
},
{
"answer_id": 346053,
"author": "Jason Bunting",
"author_id": 1790,
"author_profile": "https://Stackoverflow.com/users/1790",
"pm_score": 7,
"selected": false,
"text": "alert(myObj[\"SomeProperty\"]);\nalert(myObj.SomeProperty);\n delete delete myObj[\"SomeProperty\"];\ndelete myObj.SomeProperty;\n"
},
{
"answer_id": 3697726,
"author": "Bipin",
"author_id": 445939,
"author_profile": "https://Stackoverflow.com/users/445939",
"pm_score": 5,
"selected": false,
"text": "array.splice(index, 1);\n"
},
{
"answer_id": 6198616,
"author": "Stefan Steiger",
"author_id": 155077,
"author_profile": "https://Stackoverflow.com/users/155077",
"pm_score": 3,
"selected": false,
"text": " Array.prototype.contains = function(obj)\n {\n var i = this.length;\n while (i--)\n {\n if (this[i] === obj)\n {\n return true;\n }\n }\n return false;\n }\n\n\n Array.prototype.add = function(key, value)\n {\n if(this.contains(key))\n this[key] = value;\n else\n {\n this.push(key);\n this[key] = value;\n }\n }\n\n\n Array.prototype.remove = function(key)\n {\n for(var i = 0; i < this.length; ++i)\n {\n if(this[i] == key)\n {\n this.splice(i, 1);\n return;\n }\n }\n }\n\n\n\n // Read a page's GET URL variables and return them as an associative array.\n function getUrlVars()\n {\n var vars = [], hash;\n var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');\n\n for(var i = 0; i < hashes.length; i++)\n {\n hash = hashes[i].split('=');\n vars.push(hash[0]);\n vars[hash[0]] = hash[1];\n }\n\n return vars;\n }\n\n\n function ForwardAndHideVariables() {\n var dictParameters = getUrlVars();\n\n dictParameters.add(\"mno\", \"pqr\");\n dictParameters.add(\"mno\", \"stfu\");\n\n dictParameters.remove(\"mno\");\n\n\n for(var i = 0; i < dictParameters.length; i++)\n {\n var key = dictParameters[i];\n var value = dictParameters[key];\n alert(key + \"=\" + value);\n }\n // And now forward with HTTP-POST\n aa_post_to_url(\"Default.aspx\", dictParameters);\n }\n\n\n function aa_post_to_url(path, params, method) {\n method = method || \"post\";\n\n var form = document.createElement(\"form\");\n\n // Move the submit function to another variable\n // so that it doesn't get written over if a parameter name is 'submit'\n form._submit_function_ = form.submit;\n\n form.setAttribute(\"method\", method);\n form.setAttribute(\"action\", path);\n\n for(var i = 0; i < params.length; i++)\n {\n var key = params[i];\n\n var hiddenField = document.createElement(\"input\");\n hiddenField.setAttribute(\"type\", \"hidden\");\n hiddenField.setAttribute(\"name\", key);\n hiddenField.setAttribute(\"value\", params[key]);\n\n form.appendChild(hiddenField);\n }\n\n document.body.appendChild(form);\n form._submit_function_(); // Call the renamed function\n }\n"
},
{
"answer_id": 9973592,
"author": "Saul",
"author_id": 426379,
"author_profile": "https://Stackoverflow.com/users/426379",
"pm_score": 5,
"selected": false,
"text": "array typeof var elements = new Array()\n\nelements.push(document.getElementsByTagName(\"head\")[0])\nelements.push(document.getElementsByTagName(\"title\")[0])\nelements[\"prop\"] = document.getElementsByTagName(\"body\")[0]\n\nconsole.log(\"number of elements: \", elements.length) // Returns 2\ndelete elements[1]\nconsole.log(\"number of elements: \", elements.length) // Returns 2 (?!)\n\nfor (var i = 0; i < elements.length; i++)\n{\n // Uh-oh... throws a TypeError when i == 1\n elements[i].onmouseover = function () { window.alert(\"Over It.\")}\n console.log(\"success at index: \", i)\n}\n Object.prototype.removeItem = function (key) {\n if (!this.hasOwnProperty(key))\n return\n if (isNaN(parseInt(key)) || !(this instanceof Array))\n delete this[key]\n else\n this.splice(key, 1)\n};\n\n//\n// Code sample.\n//\nvar elements = new Array()\n\nelements.push(document.getElementsByTagName(\"head\")[0])\nelements.push(document.getElementsByTagName(\"title\")[0])\nelements[\"prop\"] = document.getElementsByTagName(\"body\")[0]\n\nconsole.log(elements.length) // Returns 2\nelements.removeItem(\"prop\")\nelements.removeItem(0)\nconsole.log(elements.hasOwnProperty(\"prop\")) // Returns false as it should\nconsole.log(elements.length) // returns 1 as it should\n"
},
{
"answer_id": 10024825,
"author": "johndodo",
"author_id": 593487,
"author_profile": "https://Stackoverflow.com/users/593487",
"pm_score": 4,
"selected": false,
"text": "var myObject = new Object();\nmyObject[\"firstname\"] = \"Bob\";\nmyObject[\"lastname\"] = \"Smith\";\nmyObject[\"age\"] = 25;\n Array delete delete myObject[\"lastname\"]\n"
},
{
"answer_id": 11141486,
"author": "Dzeimsas Zvirblis",
"author_id": 1366137,
"author_profile": "https://Stackoverflow.com/users/1366137",
"pm_score": 3,
"selected": false,
"text": "var myArray = ['Bob', 'Smith', 25];\nmyArray = myArray.filter(function(item) {\n return item !== 'Smith';\n});\n $.grep myArray = $.grep(myArray, function(item) {\n return item !== 'Smith';\n});\n"
},
{
"answer_id": 16641608,
"author": "Leon",
"author_id": 1509483,
"author_profile": "https://Stackoverflow.com/users/1509483",
"pm_score": 3,
"selected": false,
"text": "// To cut out one element via arr.splice(indexToRemove, numberToRemove);\narray.splice(key, 1)\narray.filter(function(n){return n});\n"
},
{
"answer_id": 23941356,
"author": "vatsal",
"author_id": 1847764,
"author_profile": "https://Stackoverflow.com/users/1847764",
"pm_score": 2,
"selected": false,
"text": "_.omit(myArray, \"lastname\")\n"
},
{
"answer_id": 25152612,
"author": "Ravindra Miyani",
"author_id": 3354432,
"author_profile": "https://Stackoverflow.com/users/3354432",
"pm_score": 2,
"selected": false,
"text": "\"delete\" var arrayElementToDelete = new Object();\n\narrayElementToDelete[\"id\"] = \"XERTYB00G1\";\narrayElementToDelete[\"first_name\"] = \"Employee_one\";\narrayElementToDelete[\"status\"] = \"Active\";\n\ndelete arrayElementToDelete[\"status\"];\n"
},
{
"answer_id": 31578552,
"author": "HarpyWar",
"author_id": 701779,
"author_profile": "https://Stackoverflow.com/users/701779",
"pm_score": 3,
"selected": false,
"text": "splice Object.prototype.removeItem = function (key, value) {\n if (value == undefined)\n return;\n\n for (var i in this) {\n if (this[i][key] == value) {\n this.splice(i, 1);\n }\n }\n};\n\nvar collection = [\n { id: \"5f299a5d-7793-47be-a827-bca227dbef95\", title: \"one\" },\n { id: \"87353080-8f49-46b9-9281-162a41ddb8df\", title: \"two\" },\n { id: \"a1af832c-9028-4690-9793-d623ecc75a95\", title: \"three\" }\n];\n\ncollection.removeItem(\"id\", \"87353080-8f49-46b9-9281-162a41ddb8df\");\n"
},
{
"answer_id": 34662850,
"author": "Omkar Kamale",
"author_id": 4891279,
"author_profile": "https://Stackoverflow.com/users/4891279",
"pm_score": 2,
"selected": false,
"text": "var removeItem = function (object, key, value) {\n if (value == undefined)\n return;\n\n for (var i in object) {\n if (object[i][key] == value) {\n object.splice(i, 1);\n }\n }\n};\n\nvar collection = [\n { id: \"5f299a5d-7793-47be-a827-bca227dbef95\", title: \"one\" },\n { id: \"87353080-8f49-46b9-9281-162a41ddb8df\", title: \"two\" },\n { id: \"a1af832c-9028-4690-9793-d623ecc75a95\", title: \"three\" }\n];\n\nremoveItem(collection, \"id\", \"87353080-8f49-46b9-9281-162a41ddb8df\");\n"
},
{
"answer_id": 44538173,
"author": "Lalith kumar",
"author_id": 4981163,
"author_profile": "https://Stackoverflow.com/users/4981163",
"pm_score": -1,
"selected": false,
"text": "var myArray = newmyArray = new Object();\nmyArray[\"firstname\"] = \"Bob\";\nmyArray[\"lastname\"] = \"Smith\";\nmyArray[\"age\"] = 25;\n\nvar s = JSON.stringify(myArray);\n\ns.replace(/\"lastname[^,}]+,/g, '');\nnewmyArray = JSON.parse(p);\n"
},
{
"answer_id": 52665048,
"author": "paveldroo",
"author_id": 9521312,
"author_profile": "https://Stackoverflow.com/users/9521312",
"pm_score": 4,
"selected": false,
"text": "const myObject = {\n a: 1,\n b: 2,\n c: 3\n};\nconst { a, ...noA } = myObject;\nconsole.log(noA); // => { b: 2, c: 3 }\n"
},
{
"answer_id": 57026512,
"author": "Arvind K.",
"author_id": 350193,
"author_profile": "https://Stackoverflow.com/users/350193",
"pm_score": 0,
"selected": false,
"text": "array.splice(index, 1);\n function removeItem(array, value) {\n var index = array.indexOf(value);\n if (index > -1) {\n array.splice(index, 1);\n }\n return array;\n}\n delete delete empty delete ,,"
},
{
"answer_id": 57128423,
"author": "T.Todua",
"author_id": 2377343,
"author_profile": "https://Stackoverflow.com/users/2377343",
"pm_score": 0,
"selected": false,
"text": "function removeItem (array, value) {\n var i = 0;\n while (i < array.length) {\n if(array[i] === value) {\n array.splice(i, 1);\n } else {\n ++i;\n }\n }\n return array;\n}\n var new = removeItem( [\"apple\",\"banana\", \"orange\"], \"apple\");\n// ---> [\"banana\", \"orange\"]\n"
},
{
"answer_id": 68798300,
"author": "Kenan Soylu",
"author_id": 8295460,
"author_profile": "https://Stackoverflow.com/users/8295460",
"pm_score": 3,
"selected": false,
"text": "const o = { firstName: \"foo\", lastName: \"bar\" };\nconst { lastName, ...removed } = o;\nlastName // bar\nremoved // { firstName: \"foo\" }\n removed"
}
] | 2008/12/06 | [
"https://Stackoverflow.com/questions/346021",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
346,045 | <p>I'm trying to figure out how to fix the selection box size under JCrop. The documentation mentions how to set an initial selection area but not how to make it fixed size. Does anybody knows how could I make it fixed. Thanks in advance.</p>
<p><a href="http://deepliquid.com/content/Jcrop_Manual.html" rel="noreferrer">http://deepliquid.com/content/Jcrop_Manual.html</a></p>
| [
{
"answer_id": 346302,
"author": "muhuk",
"author_id": 42188,
"author_profile": "https://Stackoverflow.com/users/42188",
"pm_score": 3,
"selected": false,
"text": "$(function(){\n $('#jcrop_target').Jcrop({\n onChange: function(){ $(this).setSelect([x, y, x2, y2]); }\n });\n});\n"
},
{
"answer_id": 1210788,
"author": "The Disintegrator",
"author_id": 92462,
"author_profile": "https://Stackoverflow.com/users/92462",
"pm_score": 4,
"selected": false,
"text": "$(function(){\n $('#cropbox').Jcrop({\n aspectRatio: 1\n });\n});\n"
},
{
"answer_id": 2102465,
"author": "Corey Ballou",
"author_id": 185882,
"author_profile": "https://Stackoverflow.com/users/185882",
"pm_score": 5,
"selected": false,
"text": "var api;\nvar cropWidth = 100;\nvar cropHeight = 100;\n\n$(window).load(function() {\n\n // set default options\n var opt = {};\n\n // if height and width must be exact, dont allow resizing\n opt.allowResize = false;\n opt.allowSelect = false;\n\n // initialize jcrop\n api = $.Jcrop('#objectId', opt);\n\n // set the selection area [left, top, width, height]\n api.animateTo([0,0,cropWidth,cropHeight]);\n\n // you can also set selection area without the fancy animation\n api.setSelect([0,0,cropWidth,cropHeight]);\n\n});\n"
},
{
"answer_id": 2225015,
"author": "tuffkid",
"author_id": 269014,
"author_profile": "https://Stackoverflow.com/users/269014",
"pm_score": 4,
"selected": false,
"text": "$('#jcrop_target').Jcrop({\n setSelect: [0,0,150,100],\n aspectRatio: 150/100\n});\n"
},
{
"answer_id": 5242457,
"author": "Vipul Pawsakar",
"author_id": 1402731,
"author_profile": "https://Stackoverflow.com/users/1402731",
"pm_score": 1,
"selected": false,
"text": "<script>\n$(window).load(function() {\n var jcrop_api;\n var i, ac;\n\n initJcrop();\n\n function initJcrop() {\n jcrop_api = $.Jcrop('#imgCrop', {\n onSelect: storeCoords,\n onChange: storeCoords\n });\n jcrop_api.setOptions({ aspectRatio: 1/ 1 });\n jcrop_api.setOptions({\n minSize: [180, 180],\n maxSize: [180, 250]\n });\n jcrop_api.setSelect([140, 180, 160, 180]);\n };\n function storeCoords(c) {\n jQuery('#X').val(c.x);\n jQuery('#Y').val(c.y);\n jQuery('#W').val(c.w);\n jQuery('#H').val(c.h);\n }; \n});\n</script>\n"
},
{
"answer_id": 11379092,
"author": "CyberJunkie",
"author_id": 468312,
"author_profile": "https://Stackoverflow.com/users/468312",
"pm_score": 3,
"selected": false,
"text": "aspectRatio: 1,\nminSize: [ 100, 100 ],\nmaxSize: [ 100, 100 ]\n"
},
{
"answer_id": 16688696,
"author": "WalterEgo",
"author_id": 2152144,
"author_profile": "https://Stackoverflow.com/users/2152144",
"pm_score": 2,
"selected": false,
"text": "allowResize: false\n $(function(){\n $(\"#CropSource\").Jcrop({\n aspectRatio: 1,\n setSelect: [50, 0, 300,300],\n allowResize: false\n });\n});\n"
}
] | 2008/12/06 | [
"https://Stackoverflow.com/questions/346045",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/43092/"
] |
346,047 | <p>Title says everything.</p>
<p>I've enabled NSZombieEnabled for project.</p>
<p>cheers</p>
| [
{
"answer_id": 16042891,
"author": "biloshkurskyi.ss",
"author_id": 1278744,
"author_profile": "https://Stackoverflow.com/users/1278744",
"pm_score": 0,
"selected": false,
"text": "contentUrl = [NSURL URLWithString:step.Videolink];\n [contentUrl release];\n NSURL URLWithString: autorelease"
}
] | 2008/12/06 | [
"https://Stackoverflow.com/questions/346047",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/451867/"
] |
346,048 | <p>I have this code:</p>
<pre><code> Dim pathString As String = HttpContext.Current.Request.MapPath("Banking.mdb")
Dim odbconBanking As New OleDbConnection _
("Provider=Microsoft.Jet.OLEDB.4.0;" & _
"Data Source=" + pathString)
Dim sql As String
sql = "UPDATE tblAccounts balance = " & CDbl(balance + value) & " WHERE(accountID = " & accountID & ")"
odbconBanking.Open()
Dim cmd As New OleDbCommand(sql, odbconBanking)
cmd.ExecuteNonQuery()
</code></pre>
<p>However, an exception is thrown, when I run it:
Syntax error in UPDATE statement. </p>
<p>I tried to run a similar statement in Access and it works fine.</p>
| [
{
"answer_id": 346055,
"author": "Joan Pham",
"author_id": 43867,
"author_profile": "https://Stackoverflow.com/users/43867",
"pm_score": 2,
"selected": true,
"text": "sql = \"UPDATE tblAccounts SET balance = \" & CDbl(balance + value) & \" WHERE(accountID = \" & accountID & \")\"\n"
},
{
"answer_id": 346321,
"author": "alextansc",
"author_id": 19582,
"author_profile": "https://Stackoverflow.com/users/19582",
"pm_score": 1,
"selected": false,
"text": "Dim sql As String = \"UPDATE tblAccounts \" & _\n \"SET balance = ? \" & _\n \"WHERE(accountID = ?)\"\n\nDim cmd As New OleDbCommand(sql, odbconBanking)\n\ncmd.Parameters.Add(\"Balance\", CDbl(balance + value))\ncmd.Parameters.Add(\"AccountId\", accountID\n\ncmd.ExecuteNonQuery()\n"
}
] | 2008/12/06 | [
"https://Stackoverflow.com/questions/346048",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/32495/"
] |
346,057 | <p>I have a Delphi 7 app using <code>ADO/MSDASQL.1</code> provider and I wonder if it is possible to "log" the SQL queries sent to the DB in a easy way? Just like the SQL profiler in SQL Server?</p>
| [
{
"answer_id": 346221,
"author": "Cesar Romero",
"author_id": 36875,
"author_profile": "https://Stackoverflow.com/users/36875",
"pm_score": 3,
"selected": false,
"text": "procedure TForm23.ADOConnection1WillExecute(Connection: TADOConnection; var\n CommandText: WideString; var CursorType: TCursorType; var LockType:\n TADOLockType; var CommandType: TCommandType; var ExecuteOptions:\n TExecuteOptions; var EventStatus: TEventStatus; const Command: _Command;\n const Recordset: _Recordset);\nbegin\n LogToFile( CommandText );\nend;\n"
}
] | 2008/12/06 | [
"https://Stackoverflow.com/questions/346057",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/38165/"
] |
346,058 | <p>What are the C++ coding and file organization guidelines you suggest for people who have to deal with lots of interdependent classes spread over several source and header files?</p>
<p>I have this situation in my project and solving class definition related errors crossing over several header files has become quite a headache.</p>
| [
{
"answer_id": 346098,
"author": "Tom",
"author_id": 40620,
"author_profile": "https://Stackoverflow.com/users/40620",
"pm_score": 7,
"selected": true,
"text": "foo.cxx foo.h #include A.cxx A.h B.h B.cxx A.h B.h A.h B.h B.h A.h include/ src/ include/ src/"
},
{
"answer_id": 346191,
"author": "Jonathan Leffler",
"author_id": 15168,
"author_profile": "https://Stackoverflow.com/users/15168",
"pm_score": 3,
"selected": false,
"text": "<pqr.h> <pqr.h> <abc.h> <pqr.h> <abc.h> <abc.h> def.h <pqr.h> <def.h>"
},
{
"answer_id": 346283,
"author": "Rob Wells",
"author_id": 2974,
"author_profile": "https://Stackoverflow.com/users/2974",
"pm_score": 3,
"selected": false,
"text": "foo.cpp"
},
{
"answer_id": 17388039,
"author": "Alex",
"author_id": 892932,
"author_profile": "https://Stackoverflow.com/users/892932",
"pm_score": 2,
"selected": false,
"text": "#include \"foo.h\" // always the first directive\n"
}
] | 2008/12/06 | [
"https://Stackoverflow.com/questions/346058",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1630/"
] |
346,092 | <p>I have a staging Rails site up that's running on MySQL 5.0.32-Debian.</p>
<p>On this particular site, all of my tables are using <code>utf8 / utf8_general_ci</code> encoding.</p>
<p>Inside that database, I have some data that looks like so:</p>
<pre><code>mysql> select * from currency_types limit 1,10;
+------+-----------------+---------+
| code | name | symbol |
+------+-----------------+---------+
| CAD | Canadian Dollar | $ |
| CNY | Chinese Yuan | å…ƒ |
| EUR | Euro | € |
| GBP | Pound | £ |
| INR | Indian Rupees | ₨ |
| JPY | Yen | ¥ |
| MXN | Mexican Peso | $ |
| USD | US Dollar | $ |
| PHP | Philippine Peso | ₱ |
| DKK | Denmark Kroner | kr |
+------+-----------------+---------+
</code></pre>
<p><strong>Here's the issue I'm having</strong></p>
<p>On staging (with the db and Rails site running on the debian box), the characters for symbols are appearing correctly when displayed from Rails. For instance, the Chinese Yuan is appearing as 元 in my browser, not å…ƒ as it shows inside the database.</p>
<p>When I download that data to my local OS X development machine and run the db and Rails locally, I see the representation from inside the DB (å…ƒ) on my browser, not the character 元 as I see in staging.</p>
<p><strong>Debugging I've done</strong></p>
<p>I've ensured all headers for Content-Type are coming back as utf8 from each webserver (local, staging).</p>
<p>My local mysql server and the staging server are both setup to use utf8 as the default charset. I'm using "set names 'utf8'" before I make any calls.</p>
<p>I can even connect to my staging db from my OS X Rails host, and I still see the characters å…ƒ representing the yuan. I'm guessing then, perhaps there's an issue with my mysql local client, but I can't figure out what the issue is.</p>
<p><em>Perhaps this might lend a clue</em></p>
<p>To make it even more confusing, if I paste the character 元 into the db on my local machine, I see that in the web browser fine. --- YET if I paste that same character into my staging db, I get a ? mark in it's place on the page from my staging Rails site.</p>
<p>Also, locally on my OS X rails machine if I use "set names 'latin1'" before my queries, the characters all come back properly. I did have these tables set as latin1 before - could this be the issue? </p>
<p>Someone please help me out here, I'm going crazy trying to figure out what's wrong!</p>
| [
{
"answer_id": 346109,
"author": "Subimage",
"author_id": 10596,
"author_profile": "https://Stackoverflow.com/users/10596",
"pm_score": 6,
"selected": true,
"text": "mysqldump -u root -p --opt --default-character-set=latin1 --skip-set-charset DBNAME > DBNAME.sql\n\nmysql -u root -p --default-character-set=utf8 DBNAME < DBNAME.sql\n"
},
{
"answer_id": 347521,
"author": "Can Berk Güder",
"author_id": 2119,
"author_profile": "https://Stackoverflow.com/users/2119",
"pm_score": 5,
"selected": false,
"text": "database.yml encoding: utf8\ncollation: utf8_general_ci\n"
},
{
"answer_id": 16079399,
"author": "RameshVel",
"author_id": 97572,
"author_profile": "https://Stackoverflow.com/users/97572",
"pm_score": 1,
"selected": false,
"text": "SQL for t in $(mysql --user=root --password=admin --database=DBNAME -e \"show tables\";);do echo \"Altering\" $t;mysql --user=root --password=admin --database=DBNAME -e \"ALTER TABLE $t CONVERT TO CHARACTER SET utf8 COLLATE utf8_unicode_ci;\";done\n for t in $(mysql --user=root --password=admin --database=DBNAME -e \"show tables\";);\n do \n echo \"Altering\" $t;\n mysql --user=root --password=admin --database=DBNAME -e \"ALTER TABLE $t CONVERT TO CHARACTER SET utf8 COLLATE utf8_unicode_ci;\";\n done\n"
},
{
"answer_id": 26796016,
"author": "mak arthur",
"author_id": 4157093,
"author_profile": "https://Stackoverflow.com/users/4157093",
"pm_score": 0,
"selected": false,
"text": "<meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" />\n connection.php - mysqli_set_charset($bd, 'utf8') Connection.php <?php\n $mysql_hostname = \"localhost\";\n $mysql_user = \"username\";\n $mysql_password = \"password\";\n $mysql_database = \"dbname\";\n $prefix = \"\";\n $bd = mysqli_connect($mysql_hostname, $mysql_user, $mysql_password) or die(\"Could not connect database\");\n mysqli_select_db($bd, $mysql_database) or die(\"Could not select database\");\n if(!mysqli_set_charset($bd, 'utf8')) {\n exit() ;\n }\n?>\n <?php\n //Include database connection details\n require_once('connection.php');\n\n //Enter code here...\n\n //Create query\n $qry = \"SELECT * FROM subject\";\n $result = mysqli_query($bd, $qry);\n?>\n\n//Other stuff\n"
},
{
"answer_id": 29644658,
"author": "Rokibul Hasan",
"author_id": 2409515,
"author_profile": "https://Stackoverflow.com/users/2409515",
"pm_score": 0,
"selected": false,
"text": "schema = File.open('db/schema.rb', 'r').read\nrows = schema.split(\"\\n\")\n\ntable_name = nil\nrows.each do |row|\n if row =~ /create_table/\n table_name = row.match(/create_table \"(.+)\"/)[1]\n puts \"ALTER TABLE `#{table_name}` CONVERT TO CHARACTER SET utf8 COLLATE utf8_general_ci;\"\n end\nend\n"
},
{
"answer_id": 33958979,
"author": "mauriciomdea",
"author_id": 1481074,
"author_profile": "https://Stackoverflow.com/users/1481074",
"pm_score": 0,
"selected": false,
"text": "rails generate migration ChangeDatabaseCollation\n def change\n # for each table that will store the new collation execute:\n execute \"ALTER TABLE my_table CONVERT TO CHARACTER SET utf8 COLLATE utf8_general_ci\"\nend\n rake db:migrate\n development:\n adapter: mysql2\n encoding: utf8\n collation: utf8_general_ci\n"
}
] | 2008/12/06 | [
"https://Stackoverflow.com/questions/346092",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10596/"
] |
346,107 | <p>how to create a shortcut for a exe from a batch file.</p>
<p>i tried </p>
<pre><code>call link.bat "c:\program Files\App1\program1.exe" "C:\Documents and Settings\%USERNAME%\Desktop" "C:\Documents and Settings\%USERNAME%\Start Menu\Programs" "Program1 shortcut"
</code></pre>
<p>but it did not worked.</p>
<p>link.bat can be found at
<a href="http://www.robvanderwoude.com/amb_shortcuts.html" rel="noreferrer">http://www.robvanderwoude.com/amb_shortcuts.html</a></p>
| [
{
"answer_id": 346118,
"author": "Martin",
"author_id": 770,
"author_profile": "https://Stackoverflow.com/users/770",
"pm_score": 1,
"selected": false,
"text": "xxmklink spath opath \n\nwhere \n\n spath path of the shortcut (.lnk added as needed)\n opath path of the object represented by the shortcut\n"
},
{
"answer_id": 346133,
"author": "Jay",
"author_id": 20840,
"author_profile": "https://Stackoverflow.com/users/20840",
"pm_score": 3,
"selected": false,
"text": "set WshShell = WScript.CreateObject(\"WScript.Shell\" )\nstrDesktop = WshShell.SpecialFolders(\"AllUsersDesktop\" )\nset oShellLink = WshShell.CreateShortcut(strDesktop & \"\\shortcut name.lnk\" )\noShellLink.TargetPath = \"c:\\application folder\\application.exe\"\noShellLink.WindowStyle = 1\noShellLink.IconLocation = \"c:\\application folder\\application.ico\"\noShellLink.Description = \"Shortcut Script\"\noShellLink.WorkingDirectory = \"c:\\application folder\"\noShellLink.Save \n"
},
{
"answer_id": 346134,
"author": "VVS",
"author_id": 21038,
"author_profile": "https://Stackoverflow.com/users/21038",
"pm_score": 6,
"selected": true,
"text": "set objWSHShell = CreateObject(\"WScript.Shell\")\nset objFso = CreateObject(\"Scripting.FileSystemObject\")\n\n' command line arguments\n' TODO: error checking\nsShortcut = objWSHShell.ExpandEnvironmentStrings(WScript.Arguments.Item(0))\nsTargetPath = objWSHShell.ExpandEnvironmentStrings(WScript.Arguments.Item(1))\nsWorkingDirectory = objFso.GetAbsolutePathName(sShortcut)\n\nset objSC = objWSHShell.CreateShortcut(sShortcut) \n\nobjSC.TargetPath = sTargetPath\nobjSC.WorkingDirectory = sWorkingDirectory\n\nobjSC.Save\n cscript createLink.vbs \"C:\\Documents and Settings\\%USERNAME%\\Desktop\\Program1 shortcut.lnk\" \"c:\\program Files\\App1\\program1.exe\" \ncscript createLink.vbs \"C:\\Documents and Settings\\%USERNAME%\\Start Menu\\Programs\\Program1 shortcut.lnk\" \"c:\\program Files\\App1\\program1.exe\" \n"
},
{
"answer_id": 542492,
"author": "Jay Bazuzi",
"author_id": 5314,
"author_profile": "https://Stackoverflow.com/users/5314",
"pm_score": 4,
"selected": false,
"text": "[Environment]::GetFolderPath(\"Desktop\")\n WScript.Shell New-Object -ComObject WScript.Shell).CreateShortcut( ... )\n $linkPath = Join-Path ([Environment]::GetFolderPath(\"Desktop\")) \"MyShortcut.lnk\"\n$targetPath = Join-Path ([Environment]::GetFolderPath(\"ProgramFiles\")) \"MyCompany\\MyProgram.exe\"\n$link = (New-Object -ComObject WScript.Shell).CreateShortcut( $linkpath )\n$link.TargetPath = $targetPath\n$link.Save()\n IShellLinkDataList"
},
{
"answer_id": 4203960,
"author": "martski",
"author_id": 510713,
"author_profile": "https://Stackoverflow.com/users/510713",
"pm_score": 2,
"selected": false,
"text": "Set oWS = WScript.CreateObject(\"WScript.Shell\")\nIf wscript.arguments.count < 4 then\n WScript.Echo \"usage: makeshortcut.vbs shortcutPath targetPath arguments workingDir \"\n WScript.Quit\nend If\nshortcutPath = wscript.arguments(0) & \".LNK\"\ntargetPath = wscript.arguments(1)\narguments = wscript.arguments(2)\nworkingDir = wscript.arguments(3)\n\nWScript.Echo \"Creating shortcut \" & shortcutPath & \" targetPath=\" & targetPath & \" arguments=\" & arguments & \" workingDir=\" & workingDir\n\nSet oLink = oWS.CreateShortcut(shortcutPath) \noLink.TargetPath = targetPath\noLink.Arguments = arguments\n' oLink.Description = \"MyProgram\"\n' oLink.HotKey = \"ALT+CTRL+F\"\n' oLink.IconLocation = \"C:\\Program Files\\MyApp\\MyProgram.EXE, 2\"\n' oLink.WindowStyle = \"1\"\noLink.WorkingDirectory = workingDir\noLink.Save\n"
},
{
"answer_id": 9744391,
"author": "Gabriel Ramirez",
"author_id": 983896,
"author_profile": "https://Stackoverflow.com/users/983896",
"pm_score": 0,
"selected": false,
"text": "shortcut -T source.exe destination.lnk\n"
},
{
"answer_id": 19207234,
"author": "Michael Przybylski",
"author_id": 1727310,
"author_profile": "https://Stackoverflow.com/users/1727310",
"pm_score": 0,
"selected": false,
"text": "@echo on\nset VBS=createSCUT.vbs \nset SRC_LNK=\"shortcut1.lnk\"\nset ARG1_APPLCT=\"C:\\Program Files\\Google\\Chrome\\Application\\chrome.exe\"\nset ARG2_APPARG=\"--profile-directory=QuteQProfile 25QuteQ\"\nset ARG3_WRKDRC=\"C:\\Program Files\\Google\\Chrome\\Application\"\nset ARG4_ICOLCT=\"%USERPROFILE%\\Local Settings\\Application Data\\Google\\Chrome\\User Data\\Profile 25\\Google Profile.ico\"\ncscript %VBS% %SRC_LNK% %ARG1_APPLCT% %ARG2_APPARG% %ARG3_WRKDRC% %ARG4_ICOLCT%\n Set objWSHShell = WScript.CreateObject(\"WScript.Shell\")\nset objWSHShell = CreateObject(\"WScript.Shell\")\nset objFso = CreateObject(\"Scripting.FileSystemObject\")\nIf WScript.arguments.count = 5 then\n WScript.Echo \"usage: makeshortcut.vbs shortcutPath targetPath arguments workingDir IconLocation\"\n sShortcut = objWSHShell.ExpandEnvironmentStrings(WScript.Arguments.Item(0))\n set objSC = objWSHShell.CreateShortcut(sShortcut) \n sTargetPath = objWSHShell.ExpandEnvironmentStrings(WScript.Arguments.Item(1))\n sArguments = objWSHShell.ExpandEnvironmentStrings(WScript.Arguments.Item(2))\n sWorkingDirectory = objWSHShell.ExpandEnvironmentStrings(WScript.Arguments.Item(3))\n sIconLocation = objWSHShell.ExpandEnvironmentStrings(WScript.Arguments.Item(4))\n objSC.TargetPath = sTargetPath\n rem http://www.bigresource.com/VB-simple-replace-function-5bAN30qRDU.html#\n objSC.Arguments = Replace(sArguments, \"QuteQ\", Chr(34))\n rem http://msdn.microsoft.com/en-us/library/f63200h0(v=vs.90).aspx http://msdn.microsoft.com/en-us/library/267k4fw5(v=vs.90).aspx\n objSC.WorkingDirectory = sWorkingDirectory\n objSC.Description = \"Love Peace Bliss\"\n rem 1 restore 3 max 7 min\n objSC.WindowStyle = \"3\"\n rem objSC.Hotkey = \"Ctrl+Alt+e\";\n objSC.IconLocation = sIconLocation\n objSC.Save\n WScript.Quit\nend If\nIf WScript.arguments.count = 4 then\n WScript.Echo \"usage: makeshortcut.vbs shortcutPath targetPath arguments workingDir \"\n\n sShortcut = objWSHShell.ExpandEnvironmentStrings(WScript.Arguments.Item(0))\n set objSC = objWSHShell.CreateShortcut(sShortcut) \n sTargetPath = objWSHShell.ExpandEnvironmentStrings(WScript.Arguments.Item(1))\n sArguments = objWSHShell.ExpandEnvironmentStrings(WScript.Arguments.Item(2))\n sWorkingDirectory = objWSHShell.ExpandEnvironmentStrings(WScript.Arguments.Item(3))\n objSC.TargetPath = sTargetPath\n objSC.Arguments = Replace(sArguments, \"QuteQ\", Chr(34))\n objSC.WorkingDirectory = sWorkingDirectory\n objSC.Description = \"Love Peace Bliss\"\n objSC.WindowStyle = \"3\"\n objSC.Save\n WScript.Quit\nend If\nIf WScript.arguments.count = 2 then\n WScript.Echo \"usage: makeshortcut.vbs shortcutPath targetPath\"\n sShortcut = objWSHShell.ExpandEnvironmentStrings(WScript.Arguments.Item(0))\n set objSC = objWSHShell.CreateShortcut(sShortcut) \n sTargetPath = objWSHShell.ExpandEnvironmentStrings(WScript.Arguments.Item(1))\n sWorkingDirectory = objFso.GetAbsolutePathName(sShortcut)\n objSC.TargetPath = sTargetPath\n objSC.WorkingDirectory = sWorkingDirectory\n objSC.Save\n WScript.Quit\nend If\n"
},
{
"answer_id": 24342741,
"author": "npocmaka",
"author_id": 388389,
"author_profile": "https://Stackoverflow.com/users/388389",
"pm_score": 1,
"selected": false,
"text": "::creates a shortcut that will start the target with minimized window and admin permissions\nshortcutjs.bat -linkfile myscriptMin.lnk -target \"%cd%\\myscript.bat\" -windowstyle 7 -adminpermissions yes\n\n::creates a shortcut with a hot keys\nshortcutjs.bat -linkfile myscriptHK.lnk -target \"%cd%\\myscript.bat\" -hotkey \"ALT+CTRL+P\"\n"
}
] | 2008/12/06 | [
"https://Stackoverflow.com/questions/346107",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/32670/"
] |
346,111 | <p>I'm using C# with <a href="http://en.wikipedia.org/wiki/.NET_Framework" rel="noreferrer">.NET</a> 3.5. Is it possible to serialize a block of code, transmit it somewhere, deserialize it, and then execute it?</p>
<p>An example usage of this would be:</p>
<pre><code>Action<object> pauxPublish = delegate(object o)
{
if (!(o is string))
{
return;
}
Console.WriteLine(o.ToString());
};
Transmitter.Send(pauxPublish);
</code></pre>
<p>With some remote program doing:</p>
<pre><code>var action = Transmitter.Recieve();
action("hello world");
</code></pre>
<p>My end goal is to be able to execute arbitrary code in a different process (which has no prior knowledge of the code).</p>
| [
{
"answer_id": 346126,
"author": "Tarks",
"author_id": 398,
"author_profile": "https://Stackoverflow.com/users/398",
"pm_score": 2,
"selected": false,
"text": "using System;\nusing System.CodeDom.Compiler;\nusing System.Collections.Generic;\nusing System.Collections.Specialized;\nusing System.IO;\nusing System.Linq;\nusing System.Reflection;\nusing System.Text;\nusing Microsoft.CSharp;\n\nnamespace DynamicCodeApplication\n{\n class azCodeCompiler\n {\n private List<string> assemblies;\n\n public azCodeCompiler()\n {\n assemblies = new List<string>();\n scanAndCacheAssemblies();\n }\n\n public Assembly BuildAssembly(string code)\n {\n\n CodeDomProvider prov = CodeDomProvider.CreateProvider(\"CSharp\");\n string[] references = new string[] { }; // Intentionally empty, using csc.rsp\n CompilerParameters cp = new CompilerParameters(references)\n {\n GenerateExecutable = false,\n GenerateInMemory = true\n };\n string path = System.Runtime.InteropServices.RuntimeEnvironment.GetRuntimeDirectory();\n cp.CompilerOptions = \"@\" + path + @\"\\csc.rsp\";\n CompilerResults cr = prov.CompileAssemblyFromSource(cp, code);\n\n foreach (CompilerError err in cr.Errors)\n {\n Console.WriteLine(err.ToString());\n }\n return cr.CompiledAssembly;\n }\n\n public object ExecuteCode(string code,\n string namespacename, string classname,\n string functionname, bool isstatic, params object[] args)\n {\n object returnval = null;\n Assembly asm = BuildAssembly(code);\n object instance = null;\n Type type = null;\n if (isstatic)\n {\n type = asm.GetType(namespacename + \".\" + classname);\n }\n else\n {\n instance = asm.CreateInstance(namespacename + \".\" + classname);\n type = instance.GetType();\n }\n MethodInfo method = type.GetMethod(functionname);\n returnval = method.Invoke(instance, args);\n return returnval;\n }\n\n private void scanAndCacheAssemblies()\n {\n\n /*\n foreach (string str in Directory.GetFiles(@\"C:\\WINDOWS\\Microsoft.NET\\Framework\\v2.0.50727\"))\n {\n if (str.Contains(\".dll\"))\n {\n foreach (string st in str.Split(new char[] { '\\\\' }))\n {\n if (st.Contains(\".dll\"))\n {\n assemblies.Add(st);\n }\n }\n }\n }\n * */\n\n assemblies.Add(\"Accessibility.dll\");\n assemblies.Add(\"AspNetMMCExt.dll\");\n assemblies.Add(\"cscompmgd.dll\");\n assemblies.Add(\"CustomMarshalers.dll\");\n assemblies.Add(\"IEExecRemote.dll\");\n assemblies.Add(\"IEHost.dll\");\n assemblies.Add(\"IIEHost.dll\");\n assemblies.Add(\"Microsoft.Build.Conversion.dll\");\n assemblies.Add(\"Microsoft.Build.Engine.dll\");\n assemblies.Add(\"Microsoft.Build.Framework.dll\");\n assemblies.Add(\"Microsoft.Build.Tasks.dll\");\n assemblies.Add(\"Microsoft.Build.Utilities.dll\");\n assemblies.Add(\"Microsoft.Build.VisualJSharp.dll\");\n assemblies.Add(\"Microsoft.CompactFramework.Build.Tasks.dll\");\n assemblies.Add(\"Microsoft.JScript.dll\");\n assemblies.Add(\"Microsoft.VisualBasic.Compatibility.Data.dll\");\n assemblies.Add(\"Microsoft.VisualBasic.Compatibility.dll\");\n assemblies.Add(\"Microsoft.VisualBasic.dll\");\n assemblies.Add(\"Microsoft.VisualBasic.Vsa.dll\");\n assemblies.Add(\"Microsoft.Vsa.dll\");\n assemblies.Add(\"Microsoft.Vsa.Vb.CodeDOMProcessor.dll\");\n assemblies.Add(\"Microsoft_VsaVb.dll\");\n assemblies.Add(\"mscorlib.dll\");\n assemblies.Add(\"sysglobl.dll\");\n assemblies.Add(\"System.configuration.dll\");\n assemblies.Add(\"System.Configuration.Install.dll\");\n assemblies.Add(\"System.Data.dll\");\n assemblies.Add(\"System.Data.OracleClient.dll\");\n assemblies.Add(\"System.Data.SqlXml.dll\");\n assemblies.Add(\"System.Deployment.dll\");\n assemblies.Add(\"System.Design.dll\");\n assemblies.Add(\"System.DirectoryServices.dll\");\n assemblies.Add(\"System.DirectoryServices.Protocols.dll\");\n assemblies.Add(\"System.dll\");\n assemblies.Add(\"System.Drawing.Design.dll\");\n assemblies.Add(\"System.Drawing.dll\");\n assemblies.Add(\"System.EnterpriseServices.dll\");\n assemblies.Add(\"System.Management.dll\");\n assemblies.Add(\"System.Messaging.dll\");\n assemblies.Add(\"System.Runtime.Remoting.dll\");\n assemblies.Add(\"System.Runtime.Serialization.Formatters.Soap.dll\");\n assemblies.Add(\"System.Security.dll\");\n assemblies.Add(\"System.ServiceProcess.dll\");\n assemblies.Add(\"System.Transactions.dll\");\n assemblies.Add(\"System.Web.dll\");\n assemblies.Add(\"System.Web.Mobile.dll\");\n assemblies.Add(\"System.Web.RegularExpressions.dll\");\n assemblies.Add(\"System.Web.Services.dll\");\n assemblies.Add(\"System.Windows.Forms.dll\");\n assemblies.Add(\"System.XML.dll\");\n assemblies.Add(\"vjscor.dll\");\n assemblies.Add(\"vjsjbc.dll\");\n assemblies.Add(\"vjslib.dll\");\n assemblies.Add(\"vjslibcw.dll\");\n assemblies.Add(\"vjssupuilib.dll\");\n assemblies.Add(\"vjsvwaux.dll\");\n assemblies.Add(\"vjswfc.dll\");\n assemblies.Add(\"VJSWfcBrowserStubLib.dll\");\n assemblies.Add(\"vjswfccw.dll\");\n assemblies.Add(\"vjswfchtml.dll\");\n assemblies.Add(\"Accessibility.dll\");\n assemblies.Add(\"AspNetMMCExt.dll\");\n assemblies.Add(\"cscompmgd.dll\");\n assemblies.Add(\"CustomMarshalers.dll\");\n assemblies.Add(\"IEExecRemote.dll\");\n assemblies.Add(\"IEHost.dll\");\n assemblies.Add(\"IIEHost.dll\");\n assemblies.Add(\"Microsoft.Build.Conversion.dll\");\n assemblies.Add(\"Microsoft.Build.Engine.dll\");\n assemblies.Add(\"Microsoft.Build.Framework.dll\");\n assemblies.Add(\"Microsoft.Build.Tasks.dll\");\n assemblies.Add(\"Microsoft.Build.Utilities.dll\");\n assemblies.Add(\"Microsoft.Build.VisualJSharp.dll\");\n assemblies.Add(\"Microsoft.CompactFramework.Build.Tasks.dll\");\n assemblies.Add(\"Microsoft.JScript.dll\");\n assemblies.Add(\"Microsoft.VisualBasic.Compatibility.Data.dll\");\n assemblies.Add(\"Microsoft.VisualBasic.Compatibility.dll\");\n assemblies.Add(\"Microsoft.VisualBasic.dll\");\n assemblies.Add(\"Microsoft.VisualBasic.Vsa.dll\");\n assemblies.Add(\"Microsoft.Vsa.dll\");\n assemblies.Add(\"Microsoft.Vsa.Vb.CodeDOMProcessor.dll\");\n assemblies.Add(\"Microsoft_VsaVb.dll\");\n assemblies.Add(\"mscorlib.dll\");\n assemblies.Add(\"sysglobl.dll\");\n assemblies.Add(\"System.configuration.dll\");\n assemblies.Add(\"System.Configuration.Install.dll\");\n assemblies.Add(\"System.Data.dll\");\n assemblies.Add(\"System.Data.OracleClient.dll\");\n assemblies.Add(\"System.Data.SqlXml.dll\");\n assemblies.Add(\"System.Deployment.dll\");\n assemblies.Add(\"System.Design.dll\");\n assemblies.Add(\"System.DirectoryServices.dll\");\n assemblies.Add(\"System.DirectoryServices.Protocols.dll\");\n assemblies.Add(\"System.dll\");\n assemblies.Add(\"System.Drawing.Design.dll\");\n assemblies.Add(\"System.Drawing.dll\");\n assemblies.Add(\"System.EnterpriseServices.dll\");\n assemblies.Add(\"System.Management.dll\");\n assemblies.Add(\"System.Messaging.dll\");\n assemblies.Add(\"System.Runtime.Remoting.dll\");\n assemblies.Add(\"System.Runtime.Serialization.Formatters.Soap.dll\");\n assemblies.Add(\"System.Security.dll\");\n assemblies.Add(\"System.ServiceProcess.dll\");\n assemblies.Add(\"System.Transactions.dll\");\n assemblies.Add(\"System.Web.dll\");\n assemblies.Add(\"System.Web.Mobile.dll\");\n assemblies.Add(\"System.Web.RegularExpressions.dll\");\n assemblies.Add(\"System.Web.Services.dll\");\n assemblies.Add(\"System.Windows.Forms.dll\");\n assemblies.Add(\"System.XML.dll\");\n assemblies.Add(\"vjscor.dll\");\n assemblies.Add(\"vjsjbc.dll\");\n assemblies.Add(\"vjslib.dll\");\n assemblies.Add(\"vjslibcw.dll\");\n assemblies.Add(\"vjssupuilib.dll\");\n assemblies.Add(\"vjsvwaux.dll\");\n assemblies.Add(\"vjswfc.dll\");\n assemblies.Add(\"VJSWfcBrowserStubLib.dll\");\n assemblies.Add(\"vjswfccw.dll\");\n assemblies.Add(\"vjswfchtml.dll\");\n\n\n return;\n }\n }\n}\n"
}
] | 2008/12/06 | [
"https://Stackoverflow.com/questions/346111",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/38438/"
] |
346,112 | <p>What is the fastest way to fill ComboBox in C#?</p>
<ol>
<li>With <code>Add()</code></li>
<li>Bind the ComboBox to Dataset</li>
</ol>
<p>Or there is a faster way ?</p>
<p>Thanks.</p>
| [
{
"answer_id": 346335,
"author": "John Rudy",
"author_id": 14048,
"author_profile": "https://Stackoverflow.com/users/14048",
"pm_score": 0,
"selected": false,
"text": "Add() Add()"
}
] | 2008/12/06 | [
"https://Stackoverflow.com/questions/346112",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/43907/"
] |
346,116 | <p>As the subject says I want to insert an image into the 2nd column of grid
defined with 2 columndefintions.</p>
<p>Programmatically that is???</p>
<p>I cannot see how to select the column using grid.Children.insert(1, img)
does not work.</p>
<p>Malcolm</p>
| [
{
"answer_id": 346166,
"author": "Matt Hamilton",
"author_id": 615,
"author_profile": "https://Stackoverflow.com/users/615",
"pm_score": 3,
"selected": false,
"text": "Grid.SetColumn(img, 1);\n"
},
{
"answer_id": 346168,
"author": "sflanker",
"author_id": 43912,
"author_profile": "https://Stackoverflow.com/users/43912",
"pm_score": 4,
"selected": true,
"text": "Image imgControl = new Image();\nGrid.SetColumn(imgControl, 1);\ngridContainer.Children.Add(imgControl);\n"
}
] | 2008/12/06 | [
"https://Stackoverflow.com/questions/346116",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/40568/"
] |
346,127 | <p>Here is a VB.NET code snippet</p>
<pre><code>Public Class OOPDemo
Private _strtString as String
Public Function Func(obj as OOPDemo) as boolean
obj._strString = "I can set value to private member using a object"
End Function
End Class
</code></pre>
<p>I thought we cannot access the private members using the object, but perhaps CLR allows us to do that. So that means that access modifiers are based on the type and not on the instance of that type. I have also heard that c++ also allows that..</p>
<p>Any guesses what could be the reason for this?</p>
<p>Edit:</p>
<p>I think this line from the msdn link given by RoBorg explains this behaviour
"Code in the type that declares a private element, including code within contained types, can access the element "</p>
| [
{
"answer_id": 346166,
"author": "Matt Hamilton",
"author_id": 615,
"author_profile": "https://Stackoverflow.com/users/615",
"pm_score": 3,
"selected": false,
"text": "Grid.SetColumn(img, 1);\n"
},
{
"answer_id": 346168,
"author": "sflanker",
"author_id": 43912,
"author_profile": "https://Stackoverflow.com/users/43912",
"pm_score": 4,
"selected": true,
"text": "Image imgControl = new Image();\nGrid.SetColumn(imgControl, 1);\ngridContainer.Children.Add(imgControl);\n"
}
] | 2008/12/06 | [
"https://Stackoverflow.com/questions/346127",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/38997/"
] |
346,132 | <p>I have unevenly distributed data (wrt <code>date</code>) for a few years (2003-2008). I want to query data for a given set of start and end date, grouping the data by any of the supported intervals (day, week, month, quarter, year) in <a href="https://www.postgresql.org/docs/8.3/functions-datetime.html#FUNCTIONS-DATETIME-TRUNC" rel="nofollow noreferrer">PostgreSQL 8.3</a>.</p>
<p>The problem is that some of the queries give results continuous over the required period, as this one:</p>
<pre><code>select to_char(date_trunc('month',date), 'YYYY-MM-DD'), count(distinct post_id)
from some_table
where category_id = 1
and entity_id = 77
and entity2_id = 115
and date <= '2008-12-06'
and date >= '2007-12-01'
group by date_trunc('month',date)
order by date_trunc('month',date);
to_char | count
------------+-------
2007-12-01 | 64
2008-01-01 | 31
2008-02-01 | 14
2008-03-01 | 21
2008-04-01 | 28
2008-05-01 | 44
2008-06-01 | 100
2008-07-01 | 72
2008-08-01 | 91
2008-09-01 | 92
2008-10-01 | 79
2008-11-01 | 65
(12 rows)
</code></pre>
<p>But some of them miss some intervals because there is no data present, as this one:</p>
<pre><code>select to_char(date_trunc('month',date), 'YYYY-MM-DD'), count(distinct post_id)
from some_table
where category_id=1
and entity_id = 75
and entity2_id = 115
and date <= '2008-12-06'
and date >= '2007-12-01'
group by date_trunc('month',date)
order by date_trunc('month',date);
to_char | count
------------+-------
2007-12-01 | 2
2008-01-01 | 2
2008-03-01 | 1
2008-04-01 | 2
2008-06-01 | 1
2008-08-01 | 3
2008-10-01 | 2
(7 rows)
</code></pre>
<p>where the required resultset is:</p>
<pre><code> to_char | count
------------+-------
2007-12-01 | 2
2008-01-01 | 2
2008-02-01 | 0
2008-03-01 | 1
2008-04-01 | 2
2008-05-01 | 0
2008-06-01 | 1
2008-07-01 | 0
2008-08-01 | 3
2008-09-01 | 0
2008-10-01 | 2
2008-11-01 | 0
(12 rows)
</code></pre>
<p>A count of 0 for missing entries.</p>
<p>I have seen earlier discussions on Stack Overflow but they don't solve my problem it seems, since my grouping period is one of (day, week, month, quarter, year) and decided on runtime by the application. So an approach like left join with a calendar table or sequence table will not help I guess.</p>
<p>My current solution to this is to fill in these gaps in Python (in a Turbogears App) using the calendar module.</p>
<p>Is there a better way to do this?</p>
| [
{
"answer_id": 346195,
"author": "Martin v. Löwis",
"author_id": 33006,
"author_profile": "https://Stackoverflow.com/users/33006",
"pm_score": 5,
"selected": true,
"text": "select distinct date_trunc('month', (current_date - offs)) as date \nfrom generate_series(0,365,28) as offs;\n date\n------------------------\n 2007-12-01 00:00:00+01\n 2008-01-01 00:00:00+01\n 2008-02-01 00:00:00+01\n 2008-03-01 00:00:00+01\n 2008-04-01 00:00:00+02\n 2008-05-01 00:00:00+02\n 2008-06-01 00:00:00+02\n 2008-07-01 00:00:00+02\n 2008-08-01 00:00:00+02\n 2008-09-01 00:00:00+02\n 2008-10-01 00:00:00+02\n 2008-11-01 00:00:00+01\n 2008-12-01 00:00:00+01\n"
},
{
"answer_id": 15733103,
"author": "Erwin Brandstetter",
"author_id": 939860,
"author_profile": "https://Stackoverflow.com/users/939860",
"pm_score": 5,
"selected": false,
"text": "SELECT *\nFROM (\n SELECT day::date\n FROM generate_series(timestamp '2007-12-01'\n , timestamp '2008-12-01'\n , interval '1 month') day\n ) d\nLEFT JOIN (\n SELECT date_trunc('month', date_col)::date AS day\n , count(*) AS some_count\n FROM tbl\n WHERE date_col >= date '2007-12-01'\n AND date_col <= date '2008-12-06'\n-- AND ... more conditions\n GROUP BY 1\n ) t USING (day)\nORDER BY day;\n LEFT JOIN generate_series() timestamp date ::date to_char() GROUP BY 1 GROUP BY day GROUP BY date_trunc('month', date_col)::date date_trunc() count() NULL 0 LEFT JOIN 0 NULL SELECT COALESCE(some_count, 0) AS some_count"
}
] | 2008/12/06 | [
"https://Stackoverflow.com/questions/346132",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/33612/"
] |
346,138 | <p>I tried to combined tables which is <strong>fus_shift and root table</strong> into a new table which is <strong>final table</strong> but it outputs like "<strong>ERROR at line 2:
ORA-01789: query block has incorrect number of result columns</strong>". I tried also joining table as my alternative but it also outputs "<strong>ERROR at line 3: ORA-00918: column ambiguously defined</strong>". Is there another way to do combining and joining two table with different number of columns and having the same column name respectively? Thanks again:-)<br><br>
code error:<br>
create table final as<br>
select * from fus_shift<br>
union<br>
select * from root;<br></p>
<p>code error:<br>
select record_num,test_num,t_date,t_time,system_type,category,comments,val<br>
from fus_shiftrpt,root<br>
where record_num=record_num;<br><br></p>
<p>my tables:<br><br></p>
<pre><code> fus_shift Table
Record_Num test date time system
-----------------------------------------------------------
1 test15 08-11-12 13:20:01 sys23
2 test17 08-11-03 14:24:00 sys24
3 test13 08-11-13 17:25:04 sys45
4 test15 08-11-14 18:24:00 sys67
5 test16 08-11-15 19:24:06 sys45
root Table
Record_Num category comments validated by
---------------------------------------------------
1 dirt checked admin
2 prog checked admin
3 dirt checked pe
4 wires checked ee
5 prog repair admin
</code></pre>
<p><em>emphasized text</em></p>
| [
{
"answer_id": 346145,
"author": "MOZILLA",
"author_id": 38997,
"author_profile": "https://Stackoverflow.com/users/38997",
"pm_score": 2,
"selected": false,
"text": "select \n table1.record_num,\n table1.test_num,\n table1.t_date,\n table1.t_time,\n table1.system_type,\n table2.category,\n table2.comments,\n table2.val\nfrom \n fus_shift table1,root table2\nwhere \n table1.record_num = table2.record_num;\n"
},
{
"answer_id": 347555,
"author": "Coentje",
"author_id": 41424,
"author_profile": "https://Stackoverflow.com/users/41424",
"pm_score": 1,
"selected": false,
"text": "SELECT * \nFROM fus_shift\nINNER JOIN root ON root.record_num = fus_shift.record_num\n"
}
] | 2008/12/06 | [
"https://Stackoverflow.com/questions/346138",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/28607/"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.