qid
int64 4
19.1M
| question
stringlengths 18
48.3k
| answers
list | date
stringlengths 10
10
| metadata
list |
|---|---|---|---|---|
183,114
|
<p>I have a folder that is my working copy. How do I remove all SVN functionality from this folder? There is a reason for me doing this, somehow my master folder that contains all my working copies of sites, has somehow been turned into a working copy itself, so I have a working copy within itself as such.</p>
<p>So, is there an easy way of removing version control from a folder? </p>
|
[
{
"answer_id": 183193,
"author": "Scott Kramer",
"author_id": 3522,
"author_profile": "https://Stackoverflow.com/users/3522",
"pm_score": 2,
"selected": false,
"text": "for /f \"tokens=* delims=\" %%i in ('dir /s /b /a:d \".svn\"') do rd /s /q \"%%i\"\n"
},
{
"answer_id": 189805,
"author": "Andy Lester",
"author_id": 8454,
"author_profile": "https://Stackoverflow.com/users/8454",
"pm_score": 5,
"selected": false,
"text": "find . -type d -name .svn -print0 | xargs -0 rm -fr\n"
},
{
"answer_id": 1182135,
"author": "sakra",
"author_id": 112955,
"author_profile": "https://Stackoverflow.com/users/112955",
"pm_score": 2,
"selected": false,
"text": "@echo off\nrem cleanup .svn subdirs\n\nsetlocal enabledelayedexpansion\n\nrem change to directory that this batch script resides in\n\nif \"%~1\"==\"\" (\n echo Usage: svncleanup svn_working_copy_dir\n exit /b 1\n)\n\necho cleaning up .svn subdirs in \"%~1\" ...\n\nfor /R \"%~1\" %%I in (.svn) do rmdir /Q /S \"%%I\" > NUL 2>&1\n"
}
] |
2008/10/08
|
[
"https://Stackoverflow.com/questions/183114",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/26107/"
] |
183,115
|
<p>I'm writing a shell script to do some web server configuration. I need to disable all currently active virtual hosts. <code>a2dissite</code> doesn't accept multiple arguments, so I can't do</p>
<pre><code>a2dissite `ls /etc/apache2/sites-enabled`
</code></pre>
<p>Should I use <code>find</code>? Is it safe to manually delete the symlinks in <code>/etc/apache2/sites-enabled</code>?</p>
|
[
{
"answer_id": 183188,
"author": "Vinko Vrsalovic",
"author_id": 5190,
"author_profile": "https://Stackoverflow.com/users/5190",
"pm_score": 5,
"selected": true,
"text": " find /etc/apache2/sites-enabled/ -type l -exec rm -i \"{}\" \\;\n"
},
{
"answer_id": 183210,
"author": "Christian Oudard",
"author_id": 3757,
"author_profile": "https://Stackoverflow.com/users/3757",
"pm_score": 4,
"selected": false,
"text": "a2dissite rm rm /etc/apache2/sites-enabled/*\n"
},
{
"answer_id": 24546177,
"author": "Rob",
"author_id": 491950,
"author_profile": "https://Stackoverflow.com/users/491950",
"pm_score": 5,
"selected": false,
"text": "sudo a2dissite '*'\n sudo a2dissite\n sudo systemctl restart apache2\n sudo service apache2 reload\n"
},
{
"answer_id": 27671518,
"author": "Supravat Mondal",
"author_id": 2460470,
"author_profile": "https://Stackoverflow.com/users/2460470",
"pm_score": 3,
"selected": false,
"text": "sudo a2dissite sitename\n sudo /etc/init.d/apache2 reload\n sudo rm /etc/apache2/sites-available/sitename\n"
},
{
"answer_id": 45646505,
"author": "Telvin Nguyen",
"author_id": 1041471,
"author_profile": "https://Stackoverflow.com/users/1041471",
"pm_score": 0,
"selected": false,
"text": "# a2dissite removing dangling symlink /etc/apache2/sites-enabled/siteA.conf\nremoving dangling symlink /etc/apache2/sites-enabled/siteB.conf\nremoving dangling symlink /etc/apache2/sites-enabled/siteC.conf\nremoving dangling symlink /etc/apache2/sites-enabled/siteD.conf\n"
}
] |
2008/10/08
|
[
"https://Stackoverflow.com/questions/183115",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3757/"
] |
183,118
|
<p>I've got an application that is very graphics intensive and built on DirectX and Windows Forms. It has an automation and replay framework around which is built an automated testing system. Unfortunately, when the tests run unattended during a nightly build, the display is inactive or tied up with the screensaver, and our IT security policies don't allow us to disable that.</p>
<p>So my question: is there a way to do a "screen" capture of an application that is running without the display? I'd like to ensure that the graphics card is engaged so that my rendering pipeline is the same, but the testing framework shouldn't need to care about the state of the display.</p>
<p>Any help wildly appreciated!</p>
|
[
{
"answer_id": 183354,
"author": "korona",
"author_id": 25731,
"author_profile": "https://Stackoverflow.com/users/25731",
"pm_score": 0,
"selected": false,
"text": "GetDIBits"
},
{
"answer_id": 186255,
"author": "faulty",
"author_id": 20007,
"author_profile": "https://Stackoverflow.com/users/20007",
"pm_score": 3,
"selected": true,
"text": "Dim tempSurface As Direct3D.Surface\ntempSurface = device.GetBackBuffer(0, 0, Direct3D.BackBufferType.Mono)\nDirect3D.SurfaceLoader.Save(tempFilename, Direct3D.ImageFileFormat.Png, tempSurface)\n ' Need to use flip to enable screen capture\npresentParams.SwapEffect = Direct3D.SwapEffect.Flip \npresentParams.PresentationInterval = Direct3D.PresentInterval.One\n"
},
{
"answer_id": 5669804,
"author": "Paul",
"author_id": 708794,
"author_profile": "https://Stackoverflow.com/users/708794",
"pm_score": 0,
"selected": false,
"text": "PresentParams.PresentFlag = PresentFlag.LockableBackBuffer PresentInterval.One SwapEffect.Flip PresentParams.Multisample = Multisample.None"
}
] |
2008/10/08
|
[
"https://Stackoverflow.com/questions/183118",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1382162/"
] |
183,124
|
<p>I need to generate multiple random values under SQL Server 2005 and somehow this simply wont work</p>
<pre><code>with Random(Value) as
(
select rand() Value
union all
select rand() from Random
)select top 10 * from Random
</code></pre>
<p>Whats the preffered workaround?</p>
|
[
{
"answer_id": 183138,
"author": "Torbjörn Gyllebring",
"author_id": 21182,
"author_profile": "https://Stackoverflow.com/users/21182",
"pm_score": 0,
"selected": false,
"text": "with Random(Value) as\n(\n select rand(checksum(newid())) Value\n union all\n select rand(checksum(newid())) from Random \n)select top 10 * from Random\n"
},
{
"answer_id": 183183,
"author": "Mauro",
"author_id": 2208,
"author_profile": "https://Stackoverflow.com/users/2208",
"pm_score": 3,
"selected": true,
"text": "CREATE VIEW vRandNumber\nAS\nSELECT RAND() as RandNumber\nGO\n CREATE FUNCTION RandNumber()\nRETURNS float\nAS\n BEGIN\n RETURN (SELECT RandNumber FROM vRandNumber)\n END\nGO\n select RAND(CAST(NEWID() AS BINARY(6))), * from myTable\n"
}
] |
2008/10/08
|
[
"https://Stackoverflow.com/questions/183124",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21182/"
] |
183,153
|
<p>We are using Visual Studio 2008 as our primary development IDE. Our security team has set up McAfee to scan files in our \Local Settings\Temp folder. Unfortunately VS uses this directory during code builds which is slowing the developers down. We've reached an impasse with the security team on this, and wonder if anyone knows of a configuration setting in VS where we could change the folder to where those temporary files are written.</p>
<p>Thanks</p>
|
[
{
"answer_id": 1255303,
"author": "Cory Grimster",
"author_id": 69104,
"author_profile": "https://Stackoverflow.com/users/69104",
"pm_score": 3,
"selected": false,
"text": "<compilation debug=\"true\" tempDirectory=\"C:\\Foo\">\n"
}
] |
2008/10/08
|
[
"https://Stackoverflow.com/questions/183153",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/26165/"
] |
183,161
|
<p>What's the best way to break from nested loops in Javascript?</p>
<pre><code>//Write the links to the page.
for (var x = 0; x < Args.length; x++)
{
for (var Heading in Navigation.Headings)
{
for (var Item in Navigation.Headings[Heading])
{
if (Args[x] == Navigation.Headings[Heading][Item].Name)
{
document.write("<a href=\""
+ Navigation.Headings[Heading][Item].URL + "\">"
+ Navigation.Headings[Heading][Item].Name + "</a> : ");
break; // <---HERE, I need to break out of two loops.
}
}
}
}
</code></pre>
|
[
{
"answer_id": 183168,
"author": "swilliams",
"author_id": 736,
"author_profile": "https://Stackoverflow.com/users/736",
"pm_score": 8,
"selected": false,
"text": "return"
},
{
"answer_id": 183197,
"author": "ephemient",
"author_id": 20713,
"author_profile": "https://Stackoverflow.com/users/20713",
"pm_score": 11,
"selected": true,
"text": "loop1:\n for (var i in set1) {\nloop2:\n for (var j in set2) {\nloop3:\n for (var k in set3) {\n break loop2; // breaks out of loop3 and loop2\n }\n }\n }\n continue break goto"
},
{
"answer_id": 184513,
"author": "harley.333",
"author_id": 26259,
"author_profile": "https://Stackoverflow.com/users/26259",
"pm_score": 5,
"selected": false,
"text": "var str = \"\";\nfor (var x = 0; x < 3; x++) {\n (function() { // here's an anonymous function\n for (var y = 0; y < 3; y++) {\n for (var z = 0; z < 3; z++) {\n // you have access to 'x' because of closures\n str += \"x=\" + x + \" y=\" + y + \" z=\" + z + \"<br />\";\n if (x == z && z == 2) {\n return;\n }\n }\n }\n })(); // here, you execute your anonymous function\n}\n"
},
{
"answer_id": 727811,
"author": "aleemb",
"author_id": 50475,
"author_profile": "https://Stackoverflow.com/users/50475",
"pm_score": 7,
"selected": false,
"text": "for (var x = Set1.length; x > 0; x--)\n{\n for (var y = Set2.length; y > 0; y--)\n {\n for (var z = Set3.length; z > 0; z--)\n {\n z = y = -1; // terminates second loop\n // z = y = x = -1; // terminate first loop\n }\n }\n}\n"
},
{
"answer_id": 1138394,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 6,
"selected": false,
"text": "var a = [1, 2, 3];\nvar b = [4, 5, 6];\nvar breakCheck1 = false;\n\nfor (var i in a) {\n for (var j in b) {\n breakCheck1 = true;\n break;\n }\n if (breakCheck1) break;\n}\n"
},
{
"answer_id": 11461531,
"author": "Triqui",
"author_id": 1522151,
"author_profile": "https://Stackoverflow.com/users/1522151",
"pm_score": -1,
"selected": false,
"text": "XXX.Validation = function() {\n var ok = false;\nloop:\n do {\n for (...) {\n while (...) {\n if (...) {\n break loop; // Exist the outermost do-while loop\n }\n if (...) {\n continue; // skips current iteration in the while loop\n }\n }\n }\n if (...) {\n break loop;\n }\n if (...) {\n break loop;\n }\n if (...) {\n break loop;\n }\n if (...) {\n break loop;\n }\n ok = true;\n break;\n } while(true);\n CleanupAndCallbackBeforeReturning(ok);\n return ok;\n};\n"
},
{
"answer_id": 19734110,
"author": "zord",
"author_id": 2381321,
"author_profile": "https://Stackoverflow.com/users/2381321",
"pm_score": 6,
"selected": false,
"text": "var a, b, abort = false;\nfor (a = 0; a < 10 && !abort; a++) {\n for (b = 0; b < 10 && !abort; b++) {\n if (condition) {\n doSomeThing();\n abort = true;\n }\n }\n}\n"
},
{
"answer_id": 30158489,
"author": "Drakes",
"author_id": 1938889,
"author_profile": "https://Stackoverflow.com/users/1938889",
"pm_score": 4,
"selected": false,
"text": "Number.MAX_VALUE // No breaks needed\nfor (var i = 0; i < 10; i++) {\n for (var j = 0; j < 10; j++) {\n if (condition) {\n console.log(\"condition met\");\n i = j = Number.MAX_VALUE; // Blast the loop variables\n }\n }\n}\n // No breaks needed\nfor (var i = 0; i < 89; i++) {\n for (var j = 0; j < 1002; j++) {\n for (var k = 0; k < 16; k++) {\n for (var l = 0; l < 2382; l++) {\n if (condition) {\n console.log(\"condition met\");\n i = j = k = l = Number.MAX_VALUE; // Blast the loop variables\n }\n }\n }\n }\n}\n"
},
{
"answer_id": 31928837,
"author": "Nick Perkins",
"author_id": 138939,
"author_profile": "https://Stackoverflow.com/users/138939",
"pm_score": 2,
"selected": false,
"text": "do ->\n for a in first_loop\n for b in second_loop\n if condition(...)\n return\n"
},
{
"answer_id": 32189353,
"author": "Zachary Ryan Smith",
"author_id": 4087001,
"author_profile": "https://Stackoverflow.com/users/4087001",
"pm_score": 2,
"selected": false,
"text": "Object.keys() Args.forEach(function (arg) {\n // This guard is not necessary,\n // since writing an empty string to document would not change it.\n if (!getAnchorTag(arg))\n return;\n\n document.write(getAnchorTag(arg));\n });\n\n function getAnchorTag (name) {\n var res = '';\n\n Object.keys(Navigation.Headings).some(function (Heading) {\n return Object.keys(Navigation.Headings[Heading]).some(function (Item) {\n if (name == Navigation.Headings[Heading][Item].Name) {\n res = (\"<a href=\\\"\"\n + Navigation.Headings[Heading][Item].URL + \"\\\">\"\n + Navigation.Headings[Heading][Item].Name + \"</a> : \");\n return true;\n }\n });\n });\n\n return res;\n }\n var remainingArgs = Args.slice(0);\n\n Object.keys(Navigation.Headings).some(function (Heading) {\n return Object.keys(Navigation.Headings[Heading]).some(function (Item) {\n var i = remainingArgs.indexOf(Navigation.Headings[Heading][Item].Name);\n\n if (i === -1)\n return;\n\n document.write(\"<a href=\\\"\"\n + Navigation.Headings[Heading][Item].URL + \"\\\">\"\n + Navigation.Headings[Heading][Item].Name + \"</a> : \");\n remainingArgs.splice(i, 1);\n\n if (remainingArgs.length === 0)\n return true;\n }\n });\n });\n"
},
{
"answer_id": 46424593,
"author": "user889030",
"author_id": 889030,
"author_profile": "https://Stackoverflow.com/users/889030",
"pm_score": 2,
"selected": false,
"text": " for(var a=0; a<data_a.length; a++){\n for(var b=0; b<data_b.length; b++){\n for(var c=0; c<data_c.length; c++){\n for(var d=0; d<data_d.length; d++){\n a = data_a.length;\n b = data_b.length;\n c = data_b.length;\n d = data_d.length;\n }\n }\n }\n }\n"
},
{
"answer_id": 53775094,
"author": "Matt Borja",
"author_id": 901156,
"author_profile": "https://Stackoverflow.com/users/901156",
"pm_score": 2,
"selected": false,
"text": "// Function wrapping inner for loop\nfunction CriteriaMatch(record, criteria) {\n for (var k in criteria) {\n if (!(k in record))\n return false;\n\n if (record[k] != criteria[k])\n return false;\n }\n\n return true;\n}\n\n// Outer for loop implementing continue if inner for loop returns false\nvar result = [];\n\nfor (var i = 0; i < _table.length; i++) {\n var r = _table[i];\n\n if (!CriteriaMatch(r[i], criteria))\n continue;\n\n result.add(r);\n}\n"
},
{
"answer_id": 53981923,
"author": "Dan Bray",
"author_id": 2452680,
"author_profile": "https://Stackoverflow.com/users/2452680",
"pm_score": 6,
"selected": false,
"text": "for (i = 0; i < 5; i++)\n{\n for (j = 0; j < 5; j++)\n {\n if (j === 2)\n {\n i = 5;\n break;\n }\n }\n}\n exit_loops:\nfor (i = 0; i < 5; i++)\n{\n for (j = 0; j < 5; j++)\n {\n if (j === 2)\n break exit_loops;\n }\n}\n var exit_loops = false;\nfor (i = 0; i < 5; i++)\n{\n for (j = 0; j < 5; j++)\n {\n if (j === 2)\n {\n exit_loops = true;\n break;\n }\n }\n if (exit_loops)\n break;\n}\n (function()\n{\n for (i = 0; i < 5; i++)\n {\n for (j = 0; j < 5; j++)\n {\n if (j === 2)\n return;\n }\n }\n})();\n function nested_loops()\n{\n for (i = 0; i < 5; i++)\n {\n for (j = 0; j < 5; j++)\n {\n if (j === 2)\n return;\n }\n }\n}\nnested_loops();\n"
},
{
"answer_id": 56672159,
"author": "Azutanguy",
"author_id": 11504900,
"author_profile": "https://Stackoverflow.com/users/11504900",
"pm_score": 1,
"selected": false,
"text": "var condition = true\nfor (var i = 0 ; i < Args.length && condition ; i++) {\n for (var j = 0 ; j < Args[i].length && condition ; j++) {\n if (Args[i].obj[j] == \"[condition]\") {\n condition = false\n }\n }\n}\n Args.some((listObj) => {\n return listObj.some((obj) => {\n return !(obj == \"[condition]\")\n })\n})\n"
},
{
"answer_id": 65605754,
"author": "Tom Chen",
"author_id": 7176037,
"author_profile": "https://Stackoverflow.com/users/7176037",
"pm_score": 2,
"selected": false,
"text": "try{ \n for (var i in set1) {\n for (var j in set2) {\n for (var k in set3) {\n throw error;\n }\n }\n }\n}catch (error) {\n\n}\n"
},
{
"answer_id": 69300047,
"author": "Pratik Khadtale",
"author_id": 6565662,
"author_profile": "https://Stackoverflow.com/users/6565662",
"pm_score": 1,
"selected": false,
"text": "function test(){\n for(var i=0;i<10;i++)\n {\n for(var j=0;j<10;j++)\n {\n if(somecondition)\n {\n //code to Break out of both loops here\n i=10;\n j=10;\n }\n \n }\n }\n\n //Continue from here\n"
},
{
"answer_id": 72521388,
"author": "Timo",
"author_id": 1705829,
"author_profile": "https://Stackoverflow.com/users/1705829",
"pm_score": 0,
"selected": false,
"text": "for .. of abort test()\nfunction test() {\n var arr = [1, 2, 3,]\n var abort = false;\n for (var elem of arr) {\n console.log(1, elem)\n\n for (var elem2 of arr) {\n if (elem2 == 2) abort = true; \n if (!abort) {\n console.log(2, elem2)\n }\n }\n }\n}\n 1 1\n2 1\n1 2\n1 3\n"
}
] |
2008/10/08
|
[
"https://Stackoverflow.com/questions/183161",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13227/"
] |
183,179
|
<p>I have a table that is created in a DataList in ASP.Net. This table has three fields of text, then a field with an edit button, and a field with a delete button. When a person clicks the delete button, it posts back, deletes the items, and then binds the DataList again. The DataList is in an UpdatePanel so the item smoothly disappears after a half of a second or maybe a little more, but what I'd really like is for the row to slide out (up) as soon as they hit the delete button, and then have it delete the item on the post back.</p>
<p>I can make the row slide out with jQuery, but the postback gets in the way. How do you deal with that? </p>
|
[
{
"answer_id": 183257,
"author": "Marko Dumic",
"author_id": 5817,
"author_profile": "https://Stackoverflow.com/users/5817",
"pm_score": 0,
"selected": false,
"text": "$(\"form\").submit(function() {\n\n // if user initiated delete action \n // do your thing with deleted row (effects, etc.)\n\n // after you're done with it, submit the form from script\n // (you can queue the submission after the effect)\n // the submission from the script won't trigger this event handler\n\n return false; // prevent submission\n}\n"
},
{
"answer_id": 194181,
"author": "Aleris",
"author_id": 20417,
"author_profile": "https://Stackoverflow.com/users/20417",
"pm_score": 3,
"selected": true,
"text": "<asp:Button id=\"myButton\" OnClientClick=\"return fadeThenAllowSubmit()\" ... />\n var allowSubmit = false;\nfunction fadeThenAllowSubmit() {\n if (allowSubmit) return true\n // do the jquery stuff that will be completed in, let's say, 1000ms\n setTimeout(function() {\n allowSubmit = true\n $(\"input[id$=myButton]\").click()\n allowSubmit = false\n }, 1000)\n return false\n}\n"
}
] |
2008/10/08
|
[
"https://Stackoverflow.com/questions/183179",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3226/"
] |
183,185
|
<p>Is it possible to make hibernate do "the right thing" for some value of "right" in this situation?</p>
<pre><code>from ClassA a, ClassB b
where a.prop = b.prop
</code></pre>
<p>The thing is that prop is a UserType with different representation in the joined tables. In table A it is represented as an integer and in table B it is represented as a char. So the eq test translates to see if 1 == 'a' more or less, which is false but the object represented by 1 or 'a' should is the same so they should compare true.</p>
|
[
{
"answer_id": 183436,
"author": "Vineet Bhatia",
"author_id": 18716,
"author_profile": "https://Stackoverflow.com/users/18716",
"pm_score": -1,
"selected": false,
"text": "public boolean equals(Object x, Object y) throws HibernateException {\n boolean retValue = false;\n if (x == y) retValue = true;\n\n if (x!=null && y!=null){\n Character xChar = new Character(x);\n Character yChar = new Character(y);\n if (xChar.equals(ychar)){\n retValue = true;\n }\n }\n\n return retValue;\n}\n"
},
{
"answer_id": 231225,
"author": "Ian McLaird",
"author_id": 18796,
"author_profile": "https://Stackoverflow.com/users/18796",
"pm_score": 2,
"selected": false,
"text": "<formula> <many-to-one name=\"myClassB\" class=\"ClassB\">\n <formula>--Some SQL Expression that converts between ClassA.prop and ClassB.prop</formula>\n</many-to-one>\n"
}
] |
2008/10/08
|
[
"https://Stackoverflow.com/questions/183185",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/24243/"
] |
183,190
|
<p>I have one question maybe someone here can help me. If i do "ps aux --sort user" on linux console I have one list of users and their processes runing on the machine. My question is how do I remove the users name and print that list like this <strong>in a C program</strong>:</p>
<p>for example:</p>
<pre><code>(…)
--------------------------------------------------------------------------
user: APACHE
--------------------------------------------------------------------------
3169 0.0 1.2 39752 12352 ? S 04:10 0:00 /usr/sbin/httpd
--------------------------------------------------------------------------
user: VASCO
--------------------------------------------------------------------------
23030 0.0 0.1 4648 1536 pts/1 Ss 20:02 0:00 –bash
(…)
</code></pre>
<p>I print the user name then I print his processes... any ideas ?</p>
<p>thx</p>
|
[
{
"answer_id": 183200,
"author": "bmdhacks",
"author_id": 14032,
"author_profile": "https://Stackoverflow.com/users/14032",
"pm_score": 2,
"selected": false,
"text": "ps aux --sort user | perl -npe 's/^(\\w+)//g; if ($user ne $1) {$user=$1; print \"user: \" . uc($user) . \"\\n\";}'\n"
},
{
"answer_id": 183538,
"author": "Mark Baker",
"author_id": 11815,
"author_profile": "https://Stackoverflow.com/users/11815",
"pm_score": 0,
"selected": false,
"text": "ps haux --sort user | perl -npe 's/^(\\S+)\\s+//; if ($user ne $1) {$user=$1; print \"user: \" . uc($user) . \"\\n\";}'\n"
}
] |
2008/10/08
|
[
"https://Stackoverflow.com/questions/183190",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
183,201
|
<p>Oftentimes a developer will be faced with a choice between two possible ways to solve a problem -- one that is idiomatic and readable, and another that is less intuitive, but may perform better. For example, in C-based languages, there are two ways to multiply a number by 2:</p>
<pre><code>int SimpleMultiplyBy2(int x)
{
return x * 2;
}
</code></pre>
<p>and</p>
<pre><code>int FastMultiplyBy2(int x)
{
return x << 1;
}
</code></pre>
<p>The first version is simpler to pick up for both technical and non-technical readers, but the second one may perform better, since bit shifting is a simpler operation than multiplication. (For now, let's assume that the compiler's optimizer would not detect this and optimize it, though that is also a consideration).</p>
<p>As a developer, which would be better as an initial attempt?</p>
|
[
{
"answer_id": 185394,
"author": "Andy Lester",
"author_id": 8454,
"author_profile": "https://Stackoverflow.com/users/8454",
"pm_score": 0,
"selected": false,
"text": "x*2 x<<1"
}
] |
2008/10/08
|
[
"https://Stackoverflow.com/questions/183201",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1674/"
] |
183,209
|
<p>I have unmanaged C++ calling a managed delegate via the function pointer provided by Marshal::GetFunctionPointerForDelegate. This delegate has the potential to throw an exception. I need to be able to properly handle this exception in my unmanaged C++ to ensure things like pointer cleanup, and potentially rethrow the exception up into more managed code. The call stack is similar to this:</p>
<p>Managed Code -> Unmanaged C++ -> callback to Managed Code via delegate (exception can be thrown here).</p>
<p>Anyone have pointers for properly handling this situation so that the resources in unmanaged code can be cleaned up and a usable exception can be thrown out to the managed code which initiated the whole call stack?</p>
|
[
{
"answer_id": 183241,
"author": "Bert Huijben",
"author_id": 2094,
"author_profile": "https://Stackoverflow.com/users/2094",
"pm_score": 2,
"selected": false,
"text": "try\n{\n throw gcnew InvalidOperationException();\n}\ncatch(InvalidOperationException^ e)\n{\n // Process e\n throw;\n}\n [assembly:RuntimeCompatibility(WrapNonExceptionThrows = true)];\n"
}
] |
2008/10/08
|
[
"https://Stackoverflow.com/questions/183209",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/24965/"
] |
183,214
|
<p>I'm having some trouble with plain old JavaScript (no frameworks) in referencing my object in a callback function.</p>
<pre><code>function foo(id) {
this.dom = document.getElementById(id);
this.bar = 5;
var self = this;
this.dom.addEventListener("click", self.onclick, false);
}
foo.prototype = {
onclick : function() {
this.bar = 7;
}
};
</code></pre>
<p>Now when I create a new object (after the DOM has loaded, with a span#test)</p>
<pre><code>var x = new foo('test');
</code></pre>
<p>The 'this' inside the onclick function points to the span#test and not the foo object.</p>
<p>How do I get a reference to my foo object inside the onclick function?</p>
|
[
{
"answer_id": 183247,
"author": "Sergey Ilinsky",
"author_id": 23815,
"author_profile": "https://Stackoverflow.com/users/23815",
"pm_score": 4,
"selected": false,
"text": "this.dom.addEventListener(\"click\", function(event) {\n self.onclick(event)\n}, false);\n"
},
{
"answer_id": 193853,
"author": "hishadow",
"author_id": 7188,
"author_profile": "https://Stackoverflow.com/users/7188",
"pm_score": 7,
"selected": true,
"text": "this.dom.addEventListener(\"click\", self.onclick, false);\n this.dom.addEventListener(\n \"click\",\n function(event) {self.onclick(event)},\n false);\n function bind(scope, fn) {\n return function () {\n fn.apply(scope, arguments);\n };\n}\n this.dom.addEventListener(\"click\", bind(this, this.onclick), false);\n Function.prototype.bind this.dom.addEventListener(\"click\", this.onclick.bind(this), false);\n if (!Function.prototype.bind) { \n Function.prototype.bind = function (oThis) { \n if (typeof this !== \"function\") { \n // closest thing possible to the ECMAScript 5 internal IsCallable function \n throw new TypeError(\"Function.prototype.bind - what is trying to be bound is not callable\"); \n } \n\n var aArgs = Array.prototype.slice.call(arguments, 1), \n fToBind = this, \n fNOP = function () {}, \n fBound = function () { \n return fToBind.apply(this instanceof fNOP \n ? this \n : oThis || window, \n aArgs.concat(Array.prototype.slice.call(arguments))); \n }; \n\n fNOP.prototype = this.prototype; \n fBound.prototype = new fNOP(); \n\n return fBound; \n }; \n} \n"
},
{
"answer_id": 193913,
"author": "Vincent Robert",
"author_id": 268,
"author_profile": "https://Stackoverflow.com/users/268",
"pm_score": 2,
"selected": false,
"text": "self.onclick onclick self self var obj = ...;\nfunction callback(){ return obj.method() };\nsomething.bind(callback);\n"
}
] |
2008/10/08
|
[
"https://Stackoverflow.com/questions/183214",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18146/"
] |
183,231
|
<p>I'm looking to execute a series of queries as part of a migration project. The scripts to be generated are produced from a tool which analyses the legacy database then produces a script to map each of the old entities to an appropriate new record. THe scripts run well for small entities but some have records in the hundreds of thousands which produce script files of around 80 MB. </p>
<p>What is the best way to run these scripts? </p>
<p>Is there some SQLCMD from the prompt which deals with larger scripts? </p>
<p>I could also break the scripts down into further smaller scripts but I don't want to have to execute hundreds of scripts to perform the migration.</p>
|
[
{
"answer_id": 183259,
"author": "Cade Roux",
"author_id": 18255,
"author_profile": "https://Stackoverflow.com/users/18255",
"pm_score": 0,
"selected": false,
"text": "INSERT"
},
{
"answer_id": 183756,
"author": "Cade Roux",
"author_id": 18255,
"author_profile": "https://Stackoverflow.com/users/18255",
"pm_score": 1,
"selected": false,
"text": "BULK INSERT BCP XML XML SET IDENTITY INSERT ON OUTPUT INTO"
}
] |
2008/10/08
|
[
"https://Stackoverflow.com/questions/183231",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
183,249
|
<p>.Net contains a nice control called <a href="http://msdn.microsoft.com/en-us/library/system.windows.controls.documentviewer.aspx" rel="noreferrer"><code>DocumentViewer</code></a>. it also offers a subcontrol for finding text in the loaded document (that's at least what it is supposed to do).</p>
<p>When inserting <a href="http://msdn.microsoft.com/en-us/library/system.windows.documents.fixeddocument.aspx" rel="noreferrer"><code>FixedPage</code></a>'s objects as document source for the <code>DocumentViewer</code>, the find-functionality just does not find anything. Not even single letters. I haven't tried <a href="http://msdn.microsoft.com/en-us/library/system.windows.documents.flowdocument.aspx" rel="noreferrer"><code>FlowDocument</code></a>'s yet,
as the documentation for <code>DocumentViewer</code> is not that useful and the resources on the net are not actually existing, I now want to ask the stackoverflow community:</p>
<p>What does it need to get the Find-Function of the WPF <code>DocumentViewer</code> working with <code>FixedPage</code> documents?</p>
<p>[btw, I don't use custom <code>ControlTemplates</code> for <code>DocumentViewer</code>]</p>
|
[
{
"answer_id": 860709,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 4,
"selected": true,
"text": "// Add to xaml: <DocumentViewer x:Name=\"documentViewer\" />\n// Add project references to \"ReachFramework\" and \"System.Printing\"\nusing System;\nusing System.Windows;\nusing System.Windows.Controls;\nusing System.Windows.Documents;\nusing System.IO;\nusing System.IO.Packaging;\nusing System.Windows.Xps.Packaging;\n\nnamespace WpfApplication1\n{\n public partial class MainWindow : Window\n {\n public MainWindow()\n {\n InitializeComponent();\n\n // Set up demo FixedDocument containing text to be searched\n var fixedDocument = new FixedDocument();\n var pageContent = new PageContent();\n var fixedPage = new FixedPage();\n fixedPage.Children.Add(new TextBlock() { Text = \"Demo document text.\" });\n pageContent.Child = fixedPage;\n fixedDocument.Pages.Add(pageContent);\n\n // Set up fresh XpsDocument\n var stream = new MemoryStream();\n var uri = new Uri(\"pack://document.xps\");\n var package = Package.Open(stream, FileMode.Create, FileAccess.ReadWrite);\n PackageStore.AddPackage(uri, package);\n var xpsDoc = new XpsDocument(package, CompressionOption.NotCompressed, uri.AbsoluteUri);\n\n // Write FixedDocument to the XpsDocument\n var docWriter = XpsDocument.CreateXpsDocumentWriter(xpsDoc);\n docWriter.Write(fixedDocument);\n\n // Display XpsDocument in DocumentViewer\n documentViewer.Document = xpsDoc.GetFixedDocumentSequence();\n }\n }\n}\n"
}
] |
2008/10/08
|
[
"https://Stackoverflow.com/questions/183249",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20227/"
] |
183,250
|
<p>I have a c# object with a property called Gender which is declared as a char.</p>
<pre><code>private char _Gender;
public char Gender
{
get{ return _Gender; }
set{ _Gender = value; }
}
</code></pre>
<p>What string is returned/created when I call MyObject.Gender.ToString()?</p>
<p>I ask because I am calling a webservice (which accepts a string rather than a char) so I am doing a ToString on the property as I pass it over. I was expecting it to send an empty string if the char is not set.</p>
<p>However this doesn't appear to be the case, so the question is what is the string?</p>
|
[
{
"answer_id": 183270,
"author": "Marc Gravell",
"author_id": 23354,
"author_profile": "https://Stackoverflow.com/users/23354",
"pm_score": 2,
"selected": false,
"text": "string s = c == 0 ? \"\" : c.ToString();\n char? c; // a field\n...\nstring s = c.ToString(); // is \"\"\nc = 'a';\ns = c.ToString(); // is \"a\"\n"
}
] |
2008/10/08
|
[
"https://Stackoverflow.com/questions/183250",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1970/"
] |
183,254
|
<p>I'm making my way into web development and have seen the word <strong><em>postback</em></strong> thrown around. Coming from a non-web based background, <strong>what does a new web developer have to know about postbacks? (i.e. what are they and when do they arise?)</strong> </p>
<p>Any more information you'd like to share to help a newbie in the web world be aware of postbacks would be most greatly appreciated.</p>
|
[
{
"answer_id": 183309,
"author": "Joel Coehoorn",
"author_id": 3043,
"author_profile": "https://Stackoverflow.com/users/3043",
"pm_score": 4,
"selected": false,
"text": "<form>"
},
{
"answer_id": 183700,
"author": "Chris Cudmore",
"author_id": 18907,
"author_profile": "https://Stackoverflow.com/users/18907",
"pm_score": 4,
"selected": false,
"text": "if (!IsPostback)\n // generate form\nelse\n process submitted data;\n"
},
{
"answer_id": 20656583,
"author": "user3114934",
"author_id": 3114934,
"author_profile": "https://Stackoverflow.com/users/3114934",
"pm_score": 2,
"selected": false,
"text": "if(!ispostback)\n{\n // do some task here\n}\nelse\n{\n //do another task here\n}\n"
}
] |
2008/10/08
|
[
"https://Stackoverflow.com/questions/183254",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4916/"
] |
183,277
|
<p>I have an object that I'm passing in a method call. Say I'm using a language that only allows you to pass objects by reference, like Java or PHP. If the method makes changes to the object, it will affect the caller. I don't want this to happen. So it seems like I need to make a copy of the object.</p>
<p>My question is: whose responsibility is it to clone the object? The caller, before it calls the method? Or the callee, before it changes the object?</p>
<p>EDIT: Just to clarify, I want this to be part of the contract of this method -- that it never modifies the original object. So it seems like it should be up to the method to make the copy. But then the caller has no protection from a method that doesn't do this properly. I guess that's acceptable -- the only other alternative seems to be to have this built into the language.</p>
|
[
{
"answer_id": 183994,
"author": "Jeffrey L Whitledge",
"author_id": 10174,
"author_profile": "https://Stackoverflow.com/users/10174",
"pm_score": 0,
"selected": false,
"text": "void RemoveZeroDollarPayments(Order order)\n Order CloneOrderAndRemoveZeroDollarPaymentsFromClone(Order order)\n"
}
] |
2008/10/08
|
[
"https://Stackoverflow.com/questions/183277",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4321/"
] |
183,292
|
<p>Is it possible to specify a Java <code>classpath</code> that includes a JAR file contained within another JAR file?</p>
|
[
{
"answer_id": 7362930,
"author": "ecbrodie",
"author_id": 814576,
"author_profile": "https://Stackoverflow.com/users/814576",
"pm_score": 5,
"selected": false,
"text": "<jar destfile=\"your.jar\" basedir=\"java/dir\">\n ...\n <zipgroupfileset dir=\"dir/of/jars\" />\n</jar>\n"
},
{
"answer_id": 10321910,
"author": "ntg",
"author_id": 508907,
"author_profile": "https://Stackoverflow.com/users/508907",
"pm_score": 3,
"selected": false,
"text": "<jar destfile=\"${plugin.jar}\" basedir=\"${plugin.build.dir}\">\n <manifest>\n <attribute name=\"Author\" value=\"ntg\"/>\n ................................\n <attribute name=\"Plugin-Version\" value=\"${version.entry.commit.revision}\"/>\n </manifest>\n</jar>\n <jar ....\">\n <zipgroupfileset dir=\"${external-lib-dir}\" includes=\"*.jar\"/>\n <manifest>\n ................................\n </manifest>\n</jar>\n <property name=\"external-lib-dir\" \n value=\"C:\\...\\eclipseWorkspace\\Filter\\external\\...\\lib\" />\n"
},
{
"answer_id": 21777294,
"author": "Tezar",
"author_id": 1086220,
"author_profile": "https://Stackoverflow.com/users/1086220",
"pm_score": 5,
"selected": false,
"text": "Manifest-Version: 1.0\nCreated-By: Bundle\nClass-Path: ./custom_lib.jar\nMain-Class: YourMainClass\n jar cfm Testing.jar MANIFEST.MF *.class custom_lib.jar c f v m"
},
{
"answer_id": 73948674,
"author": "armagedescu",
"author_id": 4582948,
"author_profile": "https://Stackoverflow.com/users/4582948",
"pm_score": 0,
"selected": false,
"text": "path/yourApp/yourApp.jar\npath/yourApp/lib/lib1.jar\npath/yourApp/lib/megalib1.jar\npath/yourApp/lib/supermegalib1.jar\n Manifest-Version: 1.0\nMain-Class: com.company.MyProgram\nClass-Path: ./lib/lib1.jar ./lib/megalib1.jar ./lib/supermegalib1.jar\n"
}
] |
2008/10/08
|
[
"https://Stackoverflow.com/questions/183292",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7648/"
] |
183,316
|
<p>How do I go about the <code>[HandleError]</code> filter in asp.net MVC Preview 5?<br>
I set the customErrors in my Web.config file</p>
<pre><code><customErrors mode="On" defaultRedirect="Error.aspx">
<error statusCode="403" redirect="NoAccess.htm"/>
<error statusCode="404" redirect="FileNotFound.htm"/>
</customErrors>
</code></pre>
<p>and put [HandleError] above my Controller Class like this:</p>
<pre><code>[HandleError]
public class DSWebsiteController: Controller
{
[snip]
public ActionResult CrashTest()
{
throw new Exception("Oh Noes!");
}
}
</code></pre>
<p>Then I let my controllers inherit from this class and call CrashTest() on them.
Visual studio halts at the error and after pressing f5 to continue, I get rerouted to Error.aspx?aspxerrorpath=/sxi.mvc/CrashTest (where sxi is the name of the used controller.
Off course the path cannot be found and I get "Server Error in '/' Application." 404.</p>
<p>This site was ported from preview 3 to 5.
Everything runs (wasn't that much work to port) except the error handling.
When I create a complete new project the error handling seems to work.</p>
<p>Ideas?</p>
<p><strong>--Note--</strong><br>
Since this question has over 3K views now, I thought it would be beneficial to put in what I'm currently (ASP.NET MVC 1.0) using.
In the <a href="http://www.codeplex.com/MVCContrib" rel="noreferrer">mvc contrib project</a> there is a brilliant attribute called "RescueAttribute"
You should probably check it out too ;)</p>
|
[
{
"answer_id": 192371,
"author": "Elijah Manor",
"author_id": 4481,
"author_profile": "https://Stackoverflow.com/users/4481",
"pm_score": 8,
"selected": true,
"text": "[HandleError]\n [HandleError(ExceptionType = typeof(SqlException), View = \"DatabaseError\")]\n[HandleError(ExceptionType = typeof(NullReferenceException), View = \"LameErrorHandling\")]\n"
},
{
"answer_id": 2769307,
"author": "Raul",
"author_id": 332872,
"author_profile": "https://Stackoverflow.com/users/332872",
"pm_score": 4,
"selected": false,
"text": "public class Error: System.Web.Mvc.HandleErrorAttribute\n{\n public override void OnException(System.Web.Mvc.ExceptionContext filterContext)\n {\n\n if (filterContext.HttpContext.IsCustomErrorEnabled)\n {\n filterContext.ExceptionHandled = true;\n\n }\n base.OnException(filterContext);\n //OVERRIDE THE 500 ERROR \n filterContext.HttpContext.Response.StatusCode = 200;\n }\n\n private static void RaiseErrorSignal(Exception e)\n {\n var context = HttpContext.Current;\n // using.Elmah.ErrorSignal.FromContext(context).Raise(e, context);\n } \n\n}\n [Error]\n[HandleError]\n[PopulateSiteMap(SiteMapName=\"Mifel1\", ViewDataKey=\"Mifel1\")]\npublic class ApplicationController : Controller\n{\n}\n"
},
{
"answer_id": 29246981,
"author": "Jack",
"author_id": 4710067,
"author_profile": "https://Stackoverflow.com/users/4710067",
"pm_score": -1,
"selected": false,
"text": " [HandleError]\n public class ErrorController : Controller\n { \n [AcceptVerbs(HttpVerbs.Get)]\n public ViewResult NotAuthorized()\n {\n //401\n Response.StatusCode = (int)HttpStatusCode.Unauthorized;\n\n return View();\n }\n\n [AcceptVerbs(HttpVerbs.Get)]\n public ViewResult Forbidden()\n {\n //403\n Response.StatusCode = (int)HttpStatusCode.Forbidden;\n\n return View();\n }\n\n [AcceptVerbs(HttpVerbs.Get)]\n public ViewResult NotFound()\n {\n //404\n Response.StatusCode = (int)HttpStatusCode.NotFound;\n return View();\n }\n\n public ViewResult ServerError()\n {\n //500\n Response.StatusCode = (int)HttpStatusCode.NotFound;\n return View();\n }\n"
},
{
"answer_id": 38450727,
"author": "Sandip - Frontend Developer",
"author_id": 6606630,
"author_profile": "https://Stackoverflow.com/users/6606630",
"pm_score": 4,
"selected": false,
"text": "/// <summary>\n/// Base Controller\n/// </summary>\npublic class BaseController : Controller\n{ \n protected override void OnException(ExceptionContext filterContext)\n {\n Exception ex = filterContext.Exception;\n\n //Save error log in file\n if (ConfigurationManager.AppSettings[\"SaveErrorLog\"].ToString().Trim().ToUpper() == \"TRUE\")\n {\n SaveErrorLog(ex, filterContext);\n }\n\n // if the request is AJAX return JSON else view.\n if (IsAjax(filterContext))\n {\n //Because its a exception raised after ajax invocation\n //Lets return Json\n filterContext.Result = new JsonResult()\n {\n Data = Convert.ToString(filterContext.Exception),\n JsonRequestBehavior = JsonRequestBehavior.AllowGet\n };\n }\n else\n {\n filterContext.ExceptionHandled = true;\n filterContext.HttpContext.Response.Clear();\n\n filterContext.Result = new ViewResult()\n {\n //Error page to load\n ViewName = \"Error\",\n ViewData = new ViewDataDictionary()\n };\n\n base.OnException(filterContext);\n }\n }\n\n /// <summary>\n /// Determines whether the specified filter context is ajax.\n /// </summary>\n /// <param name=\"filterContext\">The filter context.</param>\n private bool IsAjax(ExceptionContext filterContext)\n {\n return filterContext.HttpContext.Request.Headers[\"X-Requested-With\"] == \"XMLHttpRequest\";\n }\n\n /// <summary>\n /// Saves the error log.\n /// </summary>\n /// <param name=\"ex\">The ex.</param>\n /// <param name=\"filterContext\">The filter context.</param>\n void SaveErrorLog(Exception ex, ExceptionContext filterContext)\n {\n string logMessage = ex.ToString();\n\n string logDirectory = Server.MapPath(Url.Content(\"~/ErrorLog/\"));\n\n DateTime currentDateTime = DateTime.Now;\n string currentDateTimeString = currentDateTime.ToString();\n CheckCreateLogDirectory(logDirectory);\n string logLine = BuildLogLine(currentDateTime, logMessage, filterContext);\n logDirectory = (logDirectory + \"\\\\Log_\" + LogFileName(DateTime.Now) + \".txt\");\n\n StreamWriter streamWriter = null;\n try\n {\n streamWriter = new StreamWriter(logDirectory, true);\n streamWriter.WriteLine(logLine);\n }\n catch\n {\n }\n finally\n {\n if (streamWriter != null)\n {\n streamWriter.Close();\n }\n }\n }\n\n /// <summary>\n /// Checks the create log directory.\n /// </summary>\n /// <param name=\"logPath\">The log path.</param>\n bool CheckCreateLogDirectory(string logPath)\n {\n bool loggingDirectoryExists = false;\n DirectoryInfo directoryInfo = new DirectoryInfo(logPath);\n if (directoryInfo.Exists)\n {\n loggingDirectoryExists = true;\n }\n else\n {\n try\n {\n Directory.CreateDirectory(logPath);\n loggingDirectoryExists = true;\n }\n catch\n {\n }\n }\n\n return loggingDirectoryExists;\n }\n\n /// <summary>\n /// Builds the log line.\n /// </summary>\n /// <param name=\"currentDateTime\">The current date time.</param>\n /// <param name=\"logMessage\">The log message.</param>\n /// <param name=\"filterContext\">The filter context.</param> \n string BuildLogLine(DateTime currentDateTime, string logMessage, ExceptionContext filterContext)\n {\n string controllerName = filterContext.RouteData.Values[\"Controller\"].ToString();\n string actionName = filterContext.RouteData.Values[\"Action\"].ToString();\n\n RouteValueDictionary paramList = ((System.Web.Routing.Route)(filterContext.RouteData.Route)).Defaults;\n if (paramList != null)\n {\n paramList.Remove(\"Controller\");\n paramList.Remove(\"Action\");\n }\n\n StringBuilder loglineStringBuilder = new StringBuilder();\n\n loglineStringBuilder.Append(\"Log Time : \");\n loglineStringBuilder.Append(LogFileEntryDateTime(currentDateTime));\n loglineStringBuilder.Append(System.Environment.NewLine);\n\n loglineStringBuilder.Append(\"Username : \");\n loglineStringBuilder.Append(Session[\"LogedInUserName\"]);\n loglineStringBuilder.Append(System.Environment.NewLine);\n\n loglineStringBuilder.Append(\"ControllerName : \");\n loglineStringBuilder.Append(controllerName);\n loglineStringBuilder.Append(System.Environment.NewLine);\n\n loglineStringBuilder.Append(\"ActionName : \");\n loglineStringBuilder.Append(actionName);\n loglineStringBuilder.Append(System.Environment.NewLine);\n\n loglineStringBuilder.Append(\"----------------------------------------------------------------------------------------------------------\");\n loglineStringBuilder.Append(System.Environment.NewLine);\n\n loglineStringBuilder.Append(logMessage);\n loglineStringBuilder.Append(System.Environment.NewLine);\n loglineStringBuilder.Append(\"==========================================================================================================\");\n\n return loglineStringBuilder.ToString();\n }\n\n /// <summary>\n /// Logs the file entry date time.\n /// </summary>\n /// <param name=\"currentDateTime\">The current date time.</param>\n string LogFileEntryDateTime(DateTime currentDateTime)\n {\n return currentDateTime.ToString(\"dd-MMM-yyyy HH:mm:ss\");\n }\n\n /// <summary>\n /// Logs the name of the file.\n /// </summary>\n /// <param name=\"currentDateTime\">The current date time.</param>\n string LogFileName(DateTime currentDateTime)\n {\n return currentDateTime.ToString(\"dd_MMM_yyyy\");\n }\n\n}\n /// <summary>\n/// Filter Config\n/// </summary>\npublic class FilterConfig\n{\n /// <summary>\n /// Registers the global filters.\n /// </summary>\n /// <param name=\"filters\">The filters.</param>\n public static void RegisterGlobalFilters(GlobalFilterCollection filters)\n {\n filters.Add(new HandleErrorAttribute());\n }\n}\n function CheckAJAXError() {\n $(document).ajaxError(function (event, jqXHR, ajaxSettings, thrownError) {\n\n var ex;\n if (String(thrownError).toUpperCase() == \"LOGIN\") {\n var url = '@Url.Action(\"Login\", \"Login\")';\n window.location = url;\n }\n else if (String(jqXHR.responseText).toUpperCase().indexOf(\"THE DELETE STATEMENT CONFLICTED WITH THE REFERENCE CONSTRAINT\") >= 0) {\n\n toastr.error('ReferanceExistMessage');\n }\n else if (String(thrownError).toUpperCase() == \"INTERNAL SERVER ERROR\") {\n ex = ajaxSettings.url;\n //var url = '@Url.Action(\"ErrorLog\", \"Home\")?exurl=' + ex;\n var url = '@Url.Action(\"ErrorLog\", \"Home\")';\n window.location = url;\n }\n });\n};\n"
}
] |
2008/10/08
|
[
"https://Stackoverflow.com/questions/183316",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11333/"
] |
183,325
|
<p>For some reason, Section 1 works but Section 2 does not. When run in the opposite order (2 before 1), Section 1 (Affiliation) is not run at all. All the data is the same.</p>
<pre><code>//Section 1
UserService.DsUserAttributes dsAffiliation = us_service.GetUserAttributeDropDown(systemId, "Affiliation");
Affiliation.DataSource = dsAffiliation.tblDropDownValues;
Affiliation.DataTextField = "AttrValue";
Affiliation.DataValueField = "Id";
Affiliation.DataBind();
//Section 2
UserService.DsUserAttributes dsCountry = us_service.GetUserAttributeDropDown(systemId, "Country");
Country.DataSource = dsCountry.tblDropDownValues;
Country.DataTextField = "AttrValue";
Country.DataValueField = "Id";
Country.DataBind();
</code></pre>
|
[
{
"answer_id": 183357,
"author": "bdukes",
"author_id": 2688,
"author_profile": "https://Stackoverflow.com/users/2688",
"pm_score": 3,
"selected": true,
"text": "us_service.GetUserAttributeDropDown(systemId, \"Country\") dsCountry.tblDropDownValues"
}
] |
2008/10/08
|
[
"https://Stackoverflow.com/questions/183325",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/24565/"
] |
183,338
|
<p>I'm looking for something that will monitor Windows directories for size and file count over time. I'm talking about a handful of servers and a few thousand folders (millions of files).</p>
<p>Requirements:</p>
<ul>
<li>Notification on X increase in size over Y time</li>
<li>Notification on X increase in file count over Y time</li>
<li>Historical graphing (or at least saving snapshot data over time) of size and file count</li>
<li>All of this on a set of directories and their child directories</li>
</ul>
<p>I'd prefer a free solution but would also appreciate getting pointed in the right direction. If we were to write our own, how would we go about doing that? Available languages being Ruby, Groovy, Java, Perl, or PowerShell (since I'd be writing it).</p>
|
[
{
"answer_id": 183464,
"author": "Steven Murawski",
"author_id": 1233,
"author_profile": "https://Stackoverflow.com/users/1233",
"pm_score": 3,
"selected": true,
"text": "$size = 0\n$count = 0\n$path = '\\\\unc\\path\\to\\directory\\to\\monitor'\nget-childitem -path $path -recurse | Where-Object {$_ -is [System.IO.FileInfo]} | ForEach-Object {$size += $_.length; $count += 1}\n $ESCkey = 27\nWrite-Host \"Press the ESC key to stop sniffing\" -foregroundcolor \"CYAN\"\n$Running=$true\n\nWhile ($Running)\n { \n if ($host.ui.RawUi.KeyAvailable) {\n $key = $host.ui.RawUI.ReadKey(\"NoEcho,IncludeKeyUp,IncludeKeyDown\")\n if ($key.VirtualKeyCode -eq $ESCkey) { \n $Running=$False\n }\n #rest of function here \n } \n"
}
] |
2008/10/08
|
[
"https://Stackoverflow.com/questions/183338",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9861/"
] |
183,353
|
<p>Passing an undimensioned array to the VB6's Ubound function will cause an error, so I want to check if it has been dimensioned yet before attempting to check its upper bound. How do I do this?</p>
|
[
{
"answer_id": 183356,
"author": "raven",
"author_id": 4228,
"author_profile": "https://Stackoverflow.com/users/4228",
"pm_score": 4,
"selected": false,
"text": "Dim someArray() As Integer\n\nIf ((Not someArray) = -1) Then\n Debug.Print \"this array is NOT initialized\"\nEnd If\n"
},
{
"answer_id": 183386,
"author": "Andrew Harmel-Law",
"author_id": 2455,
"author_profile": "https://Stackoverflow.com/users/2455",
"pm_score": -1,
"selected": false,
"text": "Dim someArray() as Integer \n\nIf someArray Is Nothing Then\n Debug.print \"this array is not initialised\"\nEnd If\n"
},
{
"answer_id": 183553,
"author": "Perry Pederson",
"author_id": 26037,
"author_profile": "https://Stackoverflow.com/users/26037",
"pm_score": 0,
"selected": false,
"text": "Private Sub Test()\n\n Dim ArrayToTest() As String\n\n MsgBox StringArrayCheck(ArrayToTest) ' returns \"false\"\n\n ReDim ArrayToTest(1 To 10)\n\n MsgBox StringArrayCheck(ArrayToTest) ' returns \"true\"\n\n ReDim ArrayToTest(0 To 0)\n\n MsgBox StringArrayCheck(ArrayToTest) ' returns \"false\"\n\nEnd Sub\n\n\nFunction StringArrayCheck(o As Variant) As Boolean\n\n Dim x As String\n\n x = Join(o)\n\n StringArrayCheck = (Len(x) <> 0)\n\nEnd Function\n"
},
{
"answer_id": 183668,
"author": "GSerg",
"author_id": 11683,
"author_profile": "https://Stackoverflow.com/users/11683",
"pm_score": 5,
"selected": false,
"text": "GetMem4 CopyMemory pArrPtr Private Declare Sub CopyMemory Lib \"kernel32\" Alias \"RtlMoveMemory\" _\n(ByRef Destination As Any, ByRef Source As Any, ByVal length As Long)\n\nPrivate Const VT_BYREF As Long = &H4000&\n\n' When declared in this way, the passed array is wrapped in a Variant/ByRef. It is not copied.\n' Returns *SAFEARRAY, not **SAFEARRAY\nPublic Function pArrPtr(ByRef arr As Variant) As Long\n 'VarType lies to you, hiding important differences. Manual VarType here.\n Dim vt As Integer\n CopyMemory ByVal VarPtr(vt), ByVal VarPtr(arr), Len(vt)\n\n If (vt And vbArray) <> vbArray Then\n Err.Raise 5, , \"Variant must contain an array\"\n End If\n\n 'see https://msdn.microsoft.com/en-us/library/windows/desktop/ms221627%28v=vs.85%29.aspx\n If (vt And VT_BYREF) = VT_BYREF Then\n 'By-ref variant array. Contains **pparray at offset 8\n CopyMemory ByVal VarPtr(pArrPtr), ByVal VarPtr(arr) + 8, Len(pArrPtr) 'pArrPtr = arr->pparray;\n CopyMemory ByVal VarPtr(pArrPtr), ByVal pArrPtr, Len(pArrPtr) 'pArrPtr = *pArrPtr;\n Else\n 'Non-by-ref variant array. Contains *parray at offset 8\n CopyMemory ByVal VarPtr(pArrPtr), ByVal VarPtr(arr) + 8, Len(pArrPtr) 'pArrPtr = arr->parray;\n End If\nEnd Function\n\nPublic Function ArrayExists(ByRef arr As Variant) As Boolean\n ArrayExists = pArrPtr(arr) <> 0\nEnd Function\n ? ArrayExists(someArray)\n"
},
{
"answer_id": 184909,
"author": "raven",
"author_id": 4228,
"author_profile": "https://Stackoverflow.com/users/4228",
"pm_score": 5,
"selected": false,
"text": "Public Function IsArrayInitialized(arr) As Boolean\n\n Dim rv As Long\n\n On Error Resume Next\n\n rv = UBound(arr)\n IsArrayInitialized = (Err.Number = 0)\n\nEnd Function\n Dim arr() As String\n\narr = Split(vbNullString, \",\")\nDebug.Print UBound(arr)\n"
},
{
"answer_id": 444810,
"author": "raven",
"author_id": 4228,
"author_profile": "https://Stackoverflow.com/users/4228",
"pm_score": 5,
"selected": true,
"text": "Private Declare Sub CopyMemory Lib \"kernel32\" Alias \"RtlMoveMemory\" _\n (pDst As Any, pSrc As Any, ByVal ByteLen As Long)\n\nPublic Function ArrayIsInitialized(arr) As Boolean\n\n Dim memVal As Long\n\n CopyMemory memVal, ByVal VarPtr(arr) + 8, ByVal 4 'get pointer to array\n CopyMemory memVal, ByVal memVal, ByVal 4 'see if it points to an address... \n ArrayIsInitialized = (memVal <> 0) '...if it does, array is intialized\n\nEnd Function\n"
},
{
"answer_id": 11036850,
"author": "SJ00",
"author_id": 1449954,
"author_profile": "https://Stackoverflow.com/users/1449954",
"pm_score": 2,
"selected": false,
"text": "Public Function IsArrayInitalized(ByRef arr() As String) As Boolean\n'Return True if array is initalized\nOn Error GoTo errHandler 'Raise error if directory doesnot exist\n\n Dim temp As Long\n temp = UBound(arr)\n\n 'Reach this point only if arr is initalized i.e. no error occured\n If temp > -1 Then IsArrayInitalized = True 'UBound is greater then -1\n\nExit Function\nerrHandler:\n 'if an error occurs, this function returns False. i.e. array not initialized\nEnd Function\n"
},
{
"answer_id": 11919682,
"author": "Tim.F",
"author_id": 1592985,
"author_profile": "https://Stackoverflow.com/users/1592985",
"pm_score": 0,
"selected": false,
"text": "Public Function ArrayIsInitialized(ByRef arr As Variant) As Boolean\n On Error Resume Next\n ArrayIsInitialized = False\n If UBound(arr) >= 0 Then If Err.Number = 0 Then ArrayIsInitialized = True\nEnd Function\n"
},
{
"answer_id": 12571599,
"author": "iCodeInVB6",
"author_id": 1695378,
"author_profile": "https://Stackoverflow.com/users/1695378",
"pm_score": 3,
"selected": false,
"text": "Private Function IsArray(vTemp As Variant) As Boolean\n On Error GoTo ProcError\n Dim lTmp As Long\n\n lTmp = UBound(vTemp) ' Error would occur here\n\n IsArray = True: Exit Function\nProcError:\n 'If error is something other than \"Subscript\n 'out of range\", then display the error\n If Not Err.Number = 9 Then Err.Raise (Err.Number)\nEnd Function\n"
},
{
"answer_id": 24402027,
"author": "madhu_p",
"author_id": 2910423,
"author_profile": "https://Stackoverflow.com/users/2910423",
"pm_score": -1,
"selected": false,
"text": "If IsEmpty(a) Then\n Exit Function\nEnd If\n"
},
{
"answer_id": 29521906,
"author": "Frodo",
"author_id": 4765386,
"author_profile": "https://Stackoverflow.com/users/4765386",
"pm_score": 2,
"selected": false,
"text": "Private Declare Sub CopyMemory Lib \"kernel32\" Alias \"RtlMoveMemory\" (Destination As Any, Source As Any, ByVal Length As Long)\nPrivate Declare Function ArrPtr Lib \"msvbvm60\" Alias \"VarPtr\" (arr() As Any) As Long\n\nPrivate Type SafeArray\n cDims As Integer\n fFeatures As Integer\n cbElements As Long\n cLocks As Long\n pvData As Long\nEnd Type\n\nPrivate Function ArrayInitialized(ByVal arrayPointer As Long) As Boolean\n Dim pSafeArray As Long\n\n CopyMemory pSafeArray, ByVal arrayPointer, 4\n\n Dim tArrayDescriptor As SafeArray\n\n If pSafeArray Then\n CopyMemory tArrayDescriptor, ByVal pSafeArray, LenB(tArrayDescriptor)\n\n If tArrayDescriptor.cDims > 0 Then ArrayInitialized = True\n End If\n\nEnd Function\n Private Type tUDT\n t As Long\nEnd Type\n\nPrivate Sub Form_Load()\n Dim longArrayNotDimmed() As Long\n Dim longArrayDimmed(1) As Long\n\n Dim stringArrayNotDimmed() As String\n Dim stringArrayDimmed(1) As String\n\n Dim udtArrayNotDimmed() As tUDT\n Dim udtArrayDimmed(1) As tUDT\n\n Dim objArrayNotDimmed() As Collection\n Dim objArrayDimmed(1) As Collection\n\n\n Debug.Print \"longArrayNotDimmed \" & ArrayInitialized(ArrPtr(longArrayNotDimmed))\n Debug.Print \"longArrayDimmed \" & ArrayInitialized(ArrPtr(longArrayDimmed))\n\n Debug.Print \"stringArrayNotDimmed \" & ArrayInitialized(ArrPtr(stringArrayNotDimmed))\n Debug.Print \"stringArrayDimmed \" & ArrayInitialized(ArrPtr(stringArrayDimmed))\n\n Debug.Print \"udtArrayNotDimmed \" & ArrayInitialized(ArrPtr(udtArrayNotDimmed))\n Debug.Print \"udtArrayDimmed \" & ArrayInitialized(ArrPtr(udtArrayDimmed))\n\n Debug.Print \"objArrayNotDimmed \" & ArrayInitialized(ArrPtr(objArrayNotDimmed))\n Debug.Print \"objArrayDimmed \" & ArrayInitialized(ArrPtr(objArrayDimmed))\n\n Unload Me\nEnd Sub\n"
},
{
"answer_id": 29976878,
"author": "DarrenMB",
"author_id": 813266,
"author_profile": "https://Stackoverflow.com/users/813266",
"pm_score": 1,
"selected": false,
"text": "Dim data() as string ' creates the untestable holder.\ndata = Split(vbNullString, \",\") ' causes array to return ubound(data) = -1\nIf Ubound(data)=-1 then ' has no contents\n ' do something\nEnd If\nredim preserve data(Ubound(data)+1) ' works to increase array size regardless of it being empty or not.\n\ndata = Split(vbNullString, \",\") ' MUST use this to clear the array again.\n"
},
{
"answer_id": 34247077,
"author": "omegastripes",
"author_id": 2165759,
"author_profile": "https://Stackoverflow.com/users/2165759",
"pm_score": 0,
"selected": false,
"text": "Ubound() VBArray() Sub Test()\n\n Dim a() As Variant\n Dim b As Variant\n Dim c As Long\n\n ' Uninitialized array of variant\n ' MsgBox UBound(a) ' gives 'Subscript out of range' error\n MsgBox GetElementsCount(a) ' 0\n\n ' Variant containing an empty array\n b = Array()\n MsgBox GetElementsCount(b) ' 0\n\n ' Any other types, eg Long or not Variant type arrays\n MsgBox GetElementsCount(c) ' -1\n\nEnd Sub\n\nFunction GetElementsCount(aSample) As Long\n\n Static oHtmlfile As Object ' instantiate once\n\n If oHtmlfile Is Nothing Then\n Set oHtmlfile = CreateObject(\"htmlfile\")\n oHtmlfile.parentWindow.execScript (\"function arrlength(arr) {try {return (new VBArray(arr)).toArray().length} catch(e) {return -1}}\"), \"jscript\"\n End If\n GetElementsCount = oHtmlfile.parentWindow.arrlength(aSample)\n\nEnd Function\n ScriptControl"
},
{
"answer_id": 38333764,
"author": "Senchiu Peter",
"author_id": 6231641,
"author_profile": "https://Stackoverflow.com/users/6231641",
"pm_score": 0,
"selected": false,
"text": "If ChkArray(MyArray)=True then\n ....\nEnd If\n\nPublic Function ChkArray(ByRef b) As Boolean\n On Error goto 1\n If UBound(b) > 0 Then ChkArray = True\nEnd Function\n"
},
{
"answer_id": 39487795,
"author": "Bucket123",
"author_id": 6830358,
"author_profile": "https://Stackoverflow.com/users/6830358",
"pm_score": 0,
"selected": false,
"text": "Split(vbNullString, \",\") String LBound=0 UBound=-1 Public Function IsInitialised(arr() As String) As Boolean\n On Error Resume Next\n IsInitialised = UBound(arr) <> 0.5\nEnd Function\n\nPublic Function IsInitialisedAndHasElements(arr() As String) As Boolean\n On Error Resume Next\n IsInitialisedAndHasElements = UBound(arr) >= LBound(arr)\nEnd Function\n"
},
{
"answer_id": 46369161,
"author": "Kip Densley",
"author_id": 8657020,
"author_profile": "https://Stackoverflow.com/users/8657020",
"pm_score": 1,
"selected": false,
"text": "Dim arySomeArray() As sometype\n Private Sub Form_Load()\n\nReDim arySomeArray(1) As sometype 'insure that the array is initialized\n\nEnd Sub \n ReDim arySomeArray(i) As sometype 'i is the size needed to hold the new data\n"
},
{
"answer_id": 48798482,
"author": "stenci",
"author_id": 1899628,
"author_profile": "https://Stackoverflow.com/users/1899628",
"pm_score": 1,
"selected": false,
"text": "UBound Function UBound2(Arr) As Integer\n On Error Resume Next\n UBound2 = UBound(Arr)\n If Err.Number = 9 Then UBound2 = -1\n On Error GoTo 0\nEnd Function\n Arr Arr ReDim UBound(Arr) UBound2(Arr) UBound(Arr) Arr UBound2() UBound(Arr) Arr UBound2() Dim Arr() As Whatever ReDim Arr(X)"
},
{
"answer_id": 52508629,
"author": "Evan TOder",
"author_id": 9499395,
"author_profile": "https://Stackoverflow.com/users/9499395",
"pm_score": -1,
"selected": false,
"text": "Function ifuncRedimUbound(ByRef byrefArr, Optional bPreserve As Boolean)\nOn Error GoTo err:\n\n1: Dim upp%: upp% = (UBound(byrefArr) + 1)\n\nerrContinue:\n\nIf bPreserve Then\n ReDim Preserve byrefArr(upp%)\nElse\n ReDim byrefArr(upp%)\nEnd If\n\nifuncRedimUbound = upp%\n\n\nExit Function\nerr:\nIf err.Number = 0 Then Resume Next\n If err.Number = 9 Then ' subscript out of range (array has not been initialized yet)\n If Erl = 1 Then\n upp% = 0\n GoTo errContinue:\n End If\n Else\n ErrHandler.ReportError \"modArray\", ifuncRedimUbound, \"1\", err.Number, err.Description\n End If\nEnd Function\n"
},
{
"answer_id": 54413405,
"author": "Scruff",
"author_id": 7099352,
"author_profile": "https://Stackoverflow.com/users/7099352",
"pm_score": 1,
"selected": false,
"text": "Public Declare Function SafeArrayGetDim Lib \"oleaut32.dll\" (psa() As Any) As Long\n\nPublic Sub Main()\n Dim MyArray() As String\n\n Debug.Print SafeArrayGetDim(MyArray) ' zero\n\n ReDim MyArray(64)\n Debug.Print SafeArrayGetDim(MyArray) ' non-zero\n\n Erase MyArray\n Debug.Print SafeArrayGetDim(MyArray) ' zero\n\n ReDim MyArray(31, 15, 63)\n Debug.Print SafeArrayGetDim(MyArray) ' non-zero\n\n Erase MyArray\n Debug.Print SafeArrayGetDim(MyArray) ' zero\n\n ReDim MyArray(127)\n Debug.Print SafeArrayGetDim(MyArray) ' non-zero\n\n Dim vArray As Variant\n vArray = MyArray\n ' If you uncomment the next line, the program won't compile or run.\n 'Debug.Print SafeArrayGetDim(vArray) ' <- Type mismatch\nEnd Sub\n"
},
{
"answer_id": 58472962,
"author": "Francisco Costa",
"author_id": 11554034,
"author_profile": "https://Stackoverflow.com/users/11554034",
"pm_score": 2,
"selected": false,
"text": "Dim someArray() As Integer\n\nIf ((Not someArray) = -1) Then\n Debug.Print \"this array is NOT initialized\"\nEnd If\n Dim x As Integer\nx = 3 And 5 'x=1\n"
},
{
"answer_id": 74490992,
"author": "Uno Buscando",
"author_id": 12421921,
"author_profile": "https://Stackoverflow.com/users/12421921",
"pm_score": 0,
"selected": false,
"text": "(Not myArray) = -1\n(Not Not myArray) = 0\n"
},
{
"answer_id": 74564243,
"author": "Ardax",
"author_id": 15565257,
"author_profile": "https://Stackoverflow.com/users/15565257",
"pm_score": 0,
"selected": false,
"text": "' Function CountElements return counted elements of an array.\n' Returns:\n' [ -1]. If the argument is not an array.\n' [ 0]. If the argument is a not initialized array.\n' [Count of elements]. If the argument is an initialized array.\nPrivate Function CountElements(ByRef vArray As Variant) As Integer\n\n ' Check whether the argument is an array.\n If (VarType(vArray) And vbArray) <> vbArray Then\n \n ' Not an array. CountElements is set to -1.\n Let CountElements = -1\n \n Else\n \n On Error Resume Next\n \n ' Calculate number of elements in array.\n ' Scenarios:\n ' - Array is initialized. CountElements is set to counted elements.\n ' - Array is NOT initialized. CountElements is never set and keeps its\n ' initial value of zero (since an error is\n ' raised).\n Let CountElements = (UBound(vArray) - LBound(vArray)) + 1\n \n End If\n \nEnd Function\n\n\n' Test of function CountElements.\n\n Dim arrStr() As String\n Dim arrV As Variant\n \n Let iCount = CountElements(arrStr) ' arrStr is not initialized, returns 0.\n ReDim arrStr(2)\n Let iCount = CountElements(arrStr) ' arrStr is initialized, returns 3.\n ReDim arrStr(5 To 8)\n Let iCount = CountElements(arrStr) ' arrStr is initialized, returns 4.\n Let arrV = arrStr\n Let iCount = CountElements(arrV) ' arrV contains a boxed arrStr which is initialized, returns 4\n Erase arrStr\n Let iCount = CountElements(arrStr) ' arrStr size is erased, returns 0.\n \n Let iCount = CountElements(Nothing) ' Nothing is not an array, returns -1.\n Let iCount = CountElements(Null) ' Null is not an array, returns -1.\n Let iCount = CountElements(5) ' Figure is not an array, returns -1.\n Let iCount = CountElements(\"My imaginary array\") ' Text is not an array, returns -1.\n Let iCount = CountElements(Array(1, 2, 3, 4, 5)) ' Created array of Integer elements, returns 5.\n Let iCount = CountElements(Array(\"A\", \"B\", \"C\")) ' Created array of String elements, returns 3.\n"
}
] |
2008/10/08
|
[
"https://Stackoverflow.com/questions/183353",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4228/"
] |
183,367
|
<p>Is it possible to unsubscribe an anonymous method from an event?</p>
<p>If I subscribe to an event like this:</p>
<pre><code>void MyMethod()
{
Console.WriteLine("I did it!");
}
MyEvent += MyMethod;
</code></pre>
<p>I can un-subscribe like this:</p>
<pre><code>MyEvent -= MyMethod;
</code></pre>
<p>But if I subscribe using an anonymous method:</p>
<pre><code>MyEvent += delegate(){Console.WriteLine("I did it!");};
</code></pre>
<p>is it possible to unsubscribe this anonymous method? If so, how?</p>
|
[
{
"answer_id": 183389,
"author": "casademora",
"author_id": 5619,
"author_profile": "https://Stackoverflow.com/users/5619",
"pm_score": 3,
"selected": false,
"text": "public class SomeClass\n{\n private readonly IList<Action> _eventList = new List<Action>();\n\n ...\n\n public event Action OnDoSomething\n {\n add {\n _eventList.Add(value);\n }\n remove {\n _eventList.Remove(value);\n }\n }\n}\n"
},
{
"answer_id": 183408,
"author": "Jacob Krall",
"author_id": 3140,
"author_profile": "https://Stackoverflow.com/users/3140",
"pm_score": 9,
"selected": true,
"text": "Action myDelegate = delegate(){Console.WriteLine(\"I did it!\");};\n\nMyEvent += myDelegate;\n\n\n// .... later\n\nMyEvent -= myDelegate;\n"
},
{
"answer_id": 183417,
"author": "J c",
"author_id": 25837,
"author_profile": "https://Stackoverflow.com/users/25837",
"pm_score": 7,
"selected": false,
"text": "MyEventHandler foo = null;\nfoo = delegate(object s, MyEventArgs ev)\n {\n Console.WriteLine(\"I did it!\");\n MyEvent -= foo;\n };\nMyEvent += foo;\n"
},
{
"answer_id": 1169186,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 4,
"selected": false,
"text": "MyHandler myDelegate = ()=>Console.WriteLine(\"I did it!\");\nMyEvent += myDelegate;\n...\nMyEvent -= myDelegate;\n"
},
{
"answer_id": 6461687,
"author": "hemme",
"author_id": 249992,
"author_profile": "https://Stackoverflow.com/users/249992",
"pm_score": 4,
"selected": false,
"text": "public class MyClass \n{\n public event EventHandler MyEvent;\n\n public IEnumerable<EventHandler> GetMyEventHandlers() \n { \n return from d in MyEvent.GetInvocationList() \n select (EventHandler)d; \n } \n}\n myClass.MyEvent -= myClass.GetMyEventHandlers().Last();\n"
},
{
"answer_id": 24713749,
"author": "Manuel Marhold",
"author_id": 3832406,
"author_profile": "https://Stackoverflow.com/users/3832406",
"pm_score": 2,
"selected": false,
"text": "MyEventHandler foo = null;\nfoo = (s, ev, mehi) => MyMethod(s, ev, foo);\nMyEvent += foo;\n\nvoid MyMethod(object s, MyEventArgs ev, MyEventHandler myEventHandlerInstance)\n{\n MyEvent -= myEventHandlerInstance;\n Console.WriteLine(\"I did it!\");\n}\n"
},
{
"answer_id": 40013967,
"author": "Larry",
"author_id": 24472,
"author_profile": "https://Stackoverflow.com/users/24472",
"pm_score": 0,
"selected": false,
"text": "static Dictionary<DataGridView, PaintEventHandler> subscriptions = new Dictionary<DataGridView, PaintEventHandler>();\n\npublic static void MergeColumns(this DataGridView dg, bool enable, params ColumnGroup[] mergedColumns) {\n\n if(enable) {\n subscriptions[dg] = (s, e) => Dg_Paint(s, e, mergedColumns);\n dg.Paint += subscriptions[dg];\n }\n else {\n if(subscriptions.ContainsKey(dg)) {\n dg.Paint -= subscriptions[dg];\n subscriptions.Remove(dg);\n }\n }\n}\n"
},
{
"answer_id": 45686903,
"author": "mazharenko",
"author_id": 3237954,
"author_profile": "https://Stackoverflow.com/users/3237954",
"pm_score": 5,
"selected": false,
"text": "void foo(object s, MyEventArgs ev)\n{\n Console.WriteLine(\"I did it!\");\n MyEvent -= foo;\n};\nMyEvent += foo;\n"
},
{
"answer_id": 67039790,
"author": "unggyu",
"author_id": 8910867,
"author_profile": "https://Stackoverflow.com/users/8910867",
"pm_score": 0,
"selected": false,
"text": "public class A\n{\n public void DoSomething()\n {\n ...\n }\n}\n\npublic class B\n{\n public void DoSomething()\n {\n ...\n }\n}\n\npublic class C\n{\n public void DoSomething()\n {\n ...\n }\n}\n A a = new A();\nB b = new B();\nC c = new C();\n private class EventHandlerClosure\n{\n public A a;\n public B b;\n public C c;\n\n public event EventHandler Finished;\n\n public void MyMethod(object, MyEventArgs args)\n {\n a.DoSomething();\n b.DoSomething();\n c.DoSomething();\n Console.WriteLine(\"I did it!\");\n\n Finished?.Invoke(this, EventArgs.Empty);\n }\n}\n var closure = new EventHandlerClosure\n{\n a = a,\n b = b,\n c = c\n};\nvar handler = new MyEventHandler(closure.MyMethod);\nMyEvent += handler;\nclosure.Finished += (s, e)\n{\n MyEvent -= handler;\n}\n"
},
{
"answer_id": 68340973,
"author": "Bobby Oster",
"author_id": 974053,
"author_profile": "https://Stackoverflow.com/users/974053",
"pm_score": 0,
"selected": false,
"text": "internal class EventWrapper<TEventArgs> {\n \n private event EventHandler<TEventArgs> Event;\n private readonly HashSet<EventHandler<TEventArgs>> _subscribeOnces;\n \n internal EventWrapper() {\n _subscribeOnces = new HashSet<EventHandler<TEventArgs>>();\n }\n\n internal void Subscribe(EventHandler<TEventArgs> eventHandler) {\n Event += eventHandler;\n }\n\n internal void SubscribeOnce(EventHandler<TEventArgs> eventHandler) {\n _subscribeOnces.Add(eventHandler);\n Event += eventHandler;\n }\n\n internal void Unsubscribe(EventHandler<TEventArgs> eventHandler) {\n Event -= eventHandler;\n }\n\n internal void UnsubscribeAll() {\n foreach (EventHandler<TEventArgs> eventHandler in Event?.GetInvocationList()) {\n Event -= eventHandler;\n }\n }\n\n internal void Invoke(Object sender, TEventArgs e) {\n Event?.Invoke(sender, e);\n if(_subscribeOnces.Count > 0) {\n foreach (EventHandler<TEventArgs> eventHandler in _subscribeOnces) {\n Event -= eventHandler;\n }\n _subscribeOnces.Clear();\n }\n }\n\n internal void Remove() {\n UnsubscribeAll();\n _subscribeOnces.Clear();\n }\n}\n public class MyClass {\n \n private EventWrapper<MyEventEventArgs> myEvent = new EventWrapper<MyEventEventArgs>();\n \n public void FireMyEvent() {\n myEvent.Invoke(this, new MyEventEventArgs(1000, DateTime.Now));\n }\n \n public void SubscribeOnce(EventHandler<MyEventEventArgs> eventHandler) {\n myEvent.SubscribeOnce(eventHandler);\n }\n \n public class MyEventEventArgs : EventArgs {\n public int MyInt;\n public DateTime MyDateTime;\n \n public MyEventEventArgs(int myInt, DateTime myDateTime) {\n MyInt = myInt;\n MyDateTime = myDateTime;\n }\n }\n}\n"
},
{
"answer_id": 73151101,
"author": "Beauty",
"author_id": 789423,
"author_profile": "https://Stackoverflow.com/users/789423",
"pm_score": 0,
"selected": false,
"text": "if (MyEvent != null)\n foreach (Delegate del in MyEvent.GetInvocationList())\n MyEvent -= (EventHandler<MyEventHandlerType>)del;\n public class SomeClass\n{\n public event EventHandler<NiceEventArgs> NiceEvent;\n\n public void RemoveHandlers()\n {\n if (NiceEvent != null)\n foreach (Delegate del in NiceEvent.GetInvocationList())\n NiceEvent -= (EventHandler<NiceEventArgs>)del;\n }\n}\n"
}
] |
2008/10/08
|
[
"https://Stackoverflow.com/questions/183367",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2610/"
] |
183,369
|
<p>I'm looking for a XPath library to query over XML documents in FF, IE, Opera and Safari... and couldn't find one. Have you seen any?</p>
|
[
{
"answer_id": 7476028,
"author": "Cheeso",
"author_id": 48082,
"author_profile": "https://Stackoverflow.com/users/48082",
"pm_score": 2,
"selected": false,
"text": "// xpath.js\n// ------------------------------------------------------------------\n//\n// a cross-browser xpath class.\n// Derived form code at http://jmvidal.cse.sc.edu/talks/javascriptxml/xpathexample.html.\n//\n// Tested in Chrome, IE9, and FF6.0.2\n//\n// Author : Dino\n// Created : Sun Sep 18 18:39:58 2011\n// Last-saved : <2011-September-19 15:07:20>\n//\n// ------------------------------------------------------------------\n\n/*jshint browser:true */\n\n(function(globalScope) {\n 'use strict';\n\n /**\n * The first argument to this constructor is the text of the XPath expression.\n *\n * If the expression uses any XML namespaces, the second argument must\n * be a JavaScript object that maps namespace prefixes to the URLs that define\n * those namespaces. The properties of this object are taken as prefixes, and\n * the values associated to those properties are the URLs.\n *\n * There's no way to specify a non-null default XML namespace. You need to use\n * prefixes in order to reference a non-null namespace in a query.\n *\n */\n\n var expr = function(xpathText, namespaces) {\n var prefix;\n this.xpathText = xpathText; // Save the text of the expression\n this.namespaces = namespaces || null; // And the namespace mapping\n\n if (document.createExpression) {\n this.xpathExpr = true;\n // I tried using a compiled xpath expression, it worked on Chrome,\n // but it did not work on FF6.0.2. Threw various exceptions.\n // So I punt on \"compiling\" the xpath and just evaluate it.\n //\n // This flag serves only to store the result of the check.\n //\n\n // document.createExpression(xpathText,\n // // This function is passed a\n // // namespace prefix and returns the URL.\n // function(prefix) {\n // return namespaces[prefix];\n // });\n }\n else {\n // assume IE and convert the namespaces object into the\n // textual form that IE requires.\n this.namespaceString = \"\";\n if (namespaces !== null) {\n for(prefix in namespaces) {\n // Add a space if there is already something there\n if (this.namespaceString.length>1) this.namespaceString += ' ';\n // And add the namespace\n this.namespaceString += 'xmlns:' + prefix + '=\"' +\n namespaces[prefix] + '\"';\n }\n }\n }\n };\n\n /**\n * This is the getNodes() method of XPath.Expression. It evaluates the\n * XPath expression in the specified context. The context argument should\n * be a Document or Element object. The return value is an array\n * or array-like object containing the nodes that match the expression.\n */\n expr.prototype.getNodes = function(xmlDomCtx) {\n var self = this, a, i,\n doc = xmlDomCtx.ownerDocument;\n\n // If the context doesn't have ownerDocument, it is the Document\n if (doc === null) doc = xmlDomCtx;\n\n if (this.xpathExpr) {\n // could not get a compiled XPathExpression to work in FF6\n // var result = this.xpathExpr.evaluate(xmlDomCtx,\n // // This is the result type we want\n // XPathResult.ORDERED_NODE_SNAPSHOT_TYPE,\n // null);\n\n var result = doc.evaluate(this.xpathText,\n xmlDomCtx,\n function(prefix) {\n return self.namespaces[prefix];\n },\n XPathResult.ORDERED_NODE_SNAPSHOT_TYPE,\n null);\n\n // Copy the results into an array.\n a = [];\n for(i = 0; i < result.snapshotLength; i++) {\n a.push(result.snapshotItem(i));\n }\n return a;\n }\n else {\n // evaluate the expression using the IE API.\n try {\n // This is IE-specific magic to specify prefix-to-URL mapping\n doc.setProperty(\"SelectionLanguage\", \"XPath\");\n doc.setProperty(\"SelectionNamespaces\", this.namespaceString);\n\n // In IE, the context must be an Element not a Document,\n // so if context is a document, use documentElement instead\n if (xmlDomCtx === doc) xmlDomCtx = doc.documentElement;\n // Now use the IE method selectNodes() to evaluate the expression\n return xmlDomCtx.selectNodes(this.xpathText);\n }\n catch(e2) {\n throw \"XPath is not supported by this browser.\";\n }\n }\n };\n\n\n /**\n * This is the getNode() method of XPath.Expression. It evaluates the\n * XPath expression in the specified context and returns a single matching\n * node (or null if no node matches). If more than one node matches,\n * this method returns the first one in the document.\n * The implementation differs from getNodes() only in the return type.\n */\n expr.prototype.getNode = function(xmlDomCtx) {\n var self = this,\n doc = xmlDomCtx.ownerDocument;\n if (doc === null) doc = xmlDomCtx;\n if (this.xpathExpr) {\n\n // could not get compiled \"XPathExpression\" to work in FF4\n // var result =\n // this.xpathExpr.evaluate(xmlDomCtx,\n // // We just want the first match\n // XPathResult.FIRST_ORDERED_NODE_TYPE,\n // null);\n\n var result = doc.evaluate(this.xpathText,\n xmlDomCtx,\n function(prefix) {\n return self.namespaces[prefix];\n },\n XPathResult.FIRST_ORDERED_NODE_TYPE,\n null);\n return result.singleNodeValue;\n }\n else {\n try {\n doc.setProperty(\"SelectionLanguage\", \"XPath\");\n doc.setProperty(\"SelectionNamespaces\", this.namespaceString);\n if (xmlDomCtx == doc) xmlDomCtx = doc.documentElement;\n return xmlDomCtx.selectSingleNode(this.xpathText);\n }\n catch(e) {\n throw \"XPath is not supported by this browser.\";\n }\n }\n };\n\n\n var getNodes = function(context, xpathExpr, namespaces) {\n return (new globalScope.XPath.Expression(xpathExpr, namespaces)).getNodes(context);\n };\n\n var getNode = function(context, xpathExpr, namespaces) {\n return (new globalScope.XPath.Expression(xpathExpr, namespaces)).getNode(context);\n };\n\n\n /**\n * XPath is a global object, containing three members. The\n * Expression member is a class modelling an Xpath expression. Use\n * it like this:\n *\n * var xpath1 = new XPath.Expression(\"/kml/Document/Folder\");\n * var nodeList = xpath1.getNodes(xmldoc);\n *\n * var xpath2 = new XPath.Expression(\"/a:kml/a:Document\",\n * { a : 'http://www.opengis.net/kml/2.2' });\n * var node = xpath2.getNode(xmldoc);\n *\n * The getNodes() and getNode() methods are just utility methods for\n * one-time use. Example:\n *\n * var oneNode = XPath.getNode(xmldoc, '/root/favorites');\n *\n * var nodeList = XPath.getNodes(xmldoc, '/x:derp/x:twap', { x: 'urn:0190djksj-xx'} );\n *\n */\n\n // place XPath into the global scope.\n globalScope.XPath = {\n Expression : expr,\n getNodes : getNodes,\n getNode : getNode\n };\n\n}(this));\n"
}
] |
2008/10/08
|
[
"https://Stackoverflow.com/questions/183369",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/26183/"
] |
183,391
|
<p>I have a project where I am taking some particularly ugly "live" HTML and forcing it into a formal XML DOM with the HTML Agility Pack. What I would like to be able to do is then query over this with Linq to XML so that I can scrape out the bits I need. I'm using the method described <a href="http://vijay.screamingpens.com/archive/2008/05/26/linq-amp-lambda-part-3-html-agility-pack-to-linq.aspx" rel="nofollow noreferrer">here</a> to parse the HtmlDocument into an XDocument, but when trying to query over this I'm not sure how to handle namespaces. In one particular document the original HTML was actually poorly formatted XHTML with the following tag:</p>
<pre><code><html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
</code></pre>
<p>When trying to query from this document it seems that the namespace attribute is preventing me from doing something like:</p>
<pre><code>var x = xDoc.Descendants("div");
// returns null
</code></pre>
<p>Apparently for those "div" tags only the LocalName is "div", but the proper tag name is the namespace plus "div". I have tried to do some research on the issue of XML namespaces and it seems that I can bypass the namespace by querying this way:</p>
<pre><code>var x =
(from x in xDoc.Descendants()
where x.Name.LocalName == "div"
select x);
// works
</code></pre>
<p>However, this seems like a rather hacky solution and does not properly address the namespace issue. As I understand it a proper XML document can contain multiple namespaces and therefore the proper way to handle it should be to parse out the namespaces I'm querying under. Has anyone else ever had to do this? Am I just making it way to complicated? I know that I could avoid all this by just sticking with HtmlDocument and querying with XPath, but I would rather stick to what I know (Linq) if possible and I would also prefer to know that I am not setting myself up for further namespace-related issues down the road.</p>
<p>What is the proper way to deal with namespaces in this situation?</p>
|
[
{
"answer_id": 183403,
"author": "Mark Cidade",
"author_id": 1659,
"author_profile": "https://Stackoverflow.com/users/1659",
"pm_score": 5,
"selected": true,
"text": "LocalName var ns = \"{http://www.w3.org/1999/xhtml}\";\nvar x = xDoc.Root.Descendants(ns + \"div\");\n var namespaces = (from x in xDoc.Root.DescendantsAndSelf()\n select x.Name.Namespace).Distinct();\n var x = namespaces.SelectMany(ns=>xDoc.Root.Descendants(ns+\"div\"));\n"
},
{
"answer_id": 11832644,
"author": "StriplingWarrior",
"author_id": 120955,
"author_profile": "https://Stackoverflow.com/users/120955",
"pm_score": 2,
"selected": false,
"text": "var ns = xDoc.Root.Name.Namespace;\nvar x = xDoc.Descendants(ns + \"div\");\n"
}
] |
2008/10/08
|
[
"https://Stackoverflow.com/questions/183391",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/24608/"
] |
183,406
|
<p>How can I add a line break to text when it is being set as an attribute i.e.:</p>
<pre><code><TextBlock Text="Stuff on line1 \n Stuff on line2" />
</code></pre>
<p>Breaking it out into the exploded format isn't an option for my particular situation. What I need is some way to emulate the following:</p>
<pre><code><TextBlock>
<TextBlock.Text>
Stuff on line1 <LineBreak/>
Stuff on line2
</TextBlock.Text>
<TextBlock/>
</code></pre>
|
[
{
"answer_id": 183435,
"author": "Bob King",
"author_id": 6897,
"author_profile": "https://Stackoverflow.com/users/6897",
"pm_score": 10,
"selected": true,
"text": "<TextBlock Text=\"Stuff on line1
Stuff on line 2\"/>\n vbCrLf 
"
},
{
"answer_id": 541600,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 4,
"selected": false,
"text": "<TextBlock>Stuff on line1
Stuff on line 2</TextBlock>\n"
},
{
"answer_id": 2189267,
"author": "Batgar",
"author_id": 149910,
"author_profile": "https://Stackoverflow.com/users/149910",
"pm_score": 2,
"selected": false,
"text": "<TextBlock><TextBlock.Text>NO USING ABOVE TECHNIQUE HERE</TextBlock.Text>\n <TextBlock Text=\"Cool 
Newline trick\" />\n"
},
{
"answer_id": 3977700,
"author": "scrat789",
"author_id": 155622,
"author_profile": "https://Stackoverflow.com/users/155622",
"pm_score": 6,
"selected": false,
"text": "<TextBlock xml:space=\"preserve\">\nStuff on line 1\nStuff on line 2\n</TextBlock>\n"
},
{
"answer_id": 4081192,
"author": "Jaykul",
"author_id": 8718,
"author_profile": "https://Stackoverflow.com/users/8718",
"pm_score": 6,
"selected": false,
"text": "xml:space=\"preserve\" <System:String x:Key=\"TwoLiner\" xml:space=\"preserve\">First line Second line</System:String>\n <System:String x:Key=\"TwoLiner\" xml:space=\"preserve\">First line \nSecond line</System:String>\n \\r\\n <System:String x:Key=\"TwoLiner\" xml:space=\"preserve\">\nFirst line \nSecond line \n</System:String>\n"
},
{
"answer_id": 5774785,
"author": "Ahmed Ghoneim",
"author_id": 713777,
"author_profile": "https://Stackoverflow.com/users/713777",
"pm_score": 1,
"selected": false,
"text": "<TextBox \n Name=\"myTextBox\" \n TextWrapping=\"Wrap\" \n AcceptsReturn=\"True\" \n VerticalScrollBarVisibility=\"Visible\" />\n"
},
{
"answer_id": 6592048,
"author": "Neville",
"author_id": 304960,
"author_profile": "https://Stackoverflow.com/users/304960",
"pm_score": 3,
"selected": false,
"text": "<ToolTip Width=\"200\" Style=\"{StaticResource ToolTip}\" \n Content=\"'Text Line 1' \n 

'Text Line 2' \n 

'Text Line 3'\"/>\n"
},
{
"answer_id": 12300618,
"author": "LPL",
"author_id": 620360,
"author_profile": "https://Stackoverflow.com/users/620360",
"pm_score": 4,
"selected": false,
"text": "<TextBlock Text=\"{Binding StringFormat='Stuff on line1{0}Stuff on line2{0}Stuff on line3',\n Source={x:Static s:Environment.NewLine}}\" />\n xmlns:s=\"clr-namespace:System;assembly=mscorlib\""
},
{
"answer_id": 17761816,
"author": "S.M.Mousavi",
"author_id": 1074799,
"author_profile": "https://Stackoverflow.com/users/1074799",
"pm_score": 4,
"selected": false,
"text": "<TextBlock.Text> <Grid Margin=\"20\">\n <TextBlock TextWrapping=\"Wrap\" TextAlignment=\"Justify\" FontSize=\"17\">\n <Bold FontFamily=\"Segoe UI Light\" FontSize=\"70\">I.R. Iran</Bold><LineBreak/>\n <Span FontSize=\"35\">I</Span>ran or Persia, officially the <Italic>Islamic Republic of Iran</Italic>, \n is a country in Western Asia. The country is bordered on the \n north by Armenia, Azerbaijan and Turkmenistan, with Kazakhstan and Russia \n to the north across the Caspian Sea.<LineBreak/>\n <Span FontSize=\"10\">For more information about Iran see <Hyperlink NavigateUri=\"http://en.WikiPedia.org/wiki/Iran\">WikiPedia</Hyperlink></Span>\n <LineBreak/>\n <LineBreak/>\n <Span FontSize=\"12\">\n <Span>Is this page helpful?</Span>\n <Button Content=\"No\"/>\n <Button Content=\"Yes\"/>\n </Span>\n </TextBlock>\n </Grid>\n"
},
{
"answer_id": 21709226,
"author": "Code Maverick",
"author_id": 682480,
"author_profile": "https://Stackoverflow.com/users/682480",
"pm_score": 4,
"selected": false,
"text": "TextBlock.Text ToolTipService.ToolTip public class NewLineConverter : IValueConverter\n{\n public object Convert(object value, Type targetType, object parameter, CultureInfo culture)\n {\n var s = string.Empty;\n\n if (value.IsNotNull())\n {\n s = value.ToString();\n\n if (s.Contains(\"\\\\r\\\\n\"))\n s = s.Replace(\"\\\\r\\\\n\", Environment.NewLine);\n\n if (s.Contains(\"\\\\n\"))\n s = s.Replace(\"\\\\n\", Environment.NewLine);\n\n if (s.Contains(\"

\"))\n s = s.Replace(\"

\", Environment.NewLine);\n\n if (s.Contains(\"
\"))\n s = s.Replace(\"
\", Environment.NewLine);\n\n if (s.Contains(\"
\"))\n s = s.Replace(\"
\", Environment.NewLine);\n\n if (s.Contains(\" \"))\n s = s.Replace(\" \", Environment.NewLine);\n\n if (s.Contains(\" \"))\n s = s.Replace(\" \", Environment.NewLine);\n\n if (s.Contains(\" \"))\n s = s.Replace(\" \", Environment.NewLine);\n\n if (s.Contains(\"<br />\"))\n s = s.Replace(\"<br />\", Environment.NewLine);\n\n if (s.Contains(\"<LineBreak />\"))\n s = s.Replace(\"<LineBreak />\", Environment.NewLine);\n }\n\n return s;\n }\n\n public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)\n {\n throw new NotImplementedException();\n }\n}\n Enivornment.NewLine Environment.NewLine CHAR( 13 ) + CHAR( 10 )\n TextBlock.Text"
},
{
"answer_id": 47471125,
"author": "user829755",
"author_id": 829755,
"author_profile": "https://Stackoverflow.com/users/829755",
"pm_score": 2,
"selected": false,
"text": "<TextBlock>\n Stuff on line1 <LineBreak/>\n Stuff on line2\n</TextBlock>\n"
},
{
"answer_id": 62206459,
"author": "Danny Coleiro",
"author_id": 13075915,
"author_profile": "https://Stackoverflow.com/users/13075915",
"pm_score": -1,
"selected": false,
"text": "private void Button1_Click(object sender, RoutedEventArgs e)\n{\n System.Text.StringBuilder myStringBuilder = new System.Text.StringBuilder();\n myStringBuilder.Append(\"Orange\").AppendLine();\n myStringBuilder.Append(\"\").AppendLine();\n myStringBuilder.Append(\"Apple\").AppendLine();\n myStringBuilder.Append(\"Banana\").AppendLine();\n myStringBuilder.Append(\"\").AppendLine();\n myStringBuilder.Append(\"Plum\").AppendLine();\n TextBox1.Text = myStringBuilder.ToString();\n}\n"
}
] |
2008/10/08
|
[
"https://Stackoverflow.com/questions/183406",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/93/"
] |
183,407
|
<p>Code and preview: <img src="https://i.stack.imgur.com/3J6CX.gif" alt="what i have"></p>
<pre><code><html>
<head>
<title>Testing some CSS</title>
<style type="text/css">
.dDay {
font-size:205%
}
.dMon {
font-weight:bold;
font-variant:small-caps;
font-size:130%;
margin-top:-.7em;
}
.detailContainer {
vertical-align:middle;
display:table-cell;
padding:0em 0em 0em 1em;
}
#dContainer {
border:1px solid green;
display:table;
height:3.25em;
}
</style>
<body>
<div id="dContainer">
<div class="dDay">31</div>
<div class="dMon">sep</div>
<div class="detailContainer">Test O.O</div>
</div>
</body>
</html>
</code></pre>
<p>My question is: is it possible to place another date section next to the first one, so it appears like this: <a href="http://img505.imageshack.us/img505/2787/previewsp2.gif" rel="nofollow noreferrer">what i want http://img505.imageshack.us/img505/2787/previewsp2.gif</a>
<hr>
EDIT: strange, I tried floating before I asked the question and it didn't work...thanks everyone :D</p>
|
[
{
"answer_id": 183425,
"author": "willasaywhat",
"author_id": 12234,
"author_profile": "https://Stackoverflow.com/users/12234",
"pm_score": 3,
"selected": true,
"text": "<html>\n<head>\n<title>Testing some CSS</title>\n<style type=\"text/css\">\n.dDay {\n font-size:205%\n}\n.dMon {\n font-weight:bold;\n font-variant:small-caps;\n font-size:130%;\n margin-top:-.7em;\n}\n.detailContainer {\n vertical-align:middle;\n display:table-cell;\n padding:0em 0em 0em 1em;\n}\n#dContainer, #dContainer2 {\n border:1px solid green;\n display:table;\n height:3.25em;\n float: left;\n }\n</style>\n<body>\n<div id=\"dContainer\">\n <div class=\"dDay\">31</div>\n <div class=\"dMon\">sep</div>\n</div>\n<div id=\"dContainer2\">\n <div class=\"dDay\">31</div>\n <div class=\"dMon\">sep</div>\n <div class=\"detailContainer\">Test O.O</div>\n</div>\n</body>\n</html>\n"
},
{
"answer_id": 183432,
"author": "PhiLho",
"author_id": 15459,
"author_profile": "https://Stackoverflow.com/users/15459",
"pm_score": 0,
"selected": false,
"text": "<html>\n<head>\n<title>Testing some CSS</title>\n<style type=\"text/css\">\n.dDay {\n font-size:205%\n}\n.dMon {\n font-weight:bold;\n font-variant:small-caps;\n font-size:130%;\n margin-top:-.7em;\n}\n.dDate {\n display:table-cell;\n}\n.detailContainer {\n vertical-align:middle;\n display:table-cell;\n padding-left:1em;\n}\n#dContainer {\n border:1px solid green;\n display:table;\n height:3.25em;\n}\n</style>\n<body>\n<div id=\"dContainer\">\n <div class=\"dDate\">\n <div class=\"dDay\">31</div>\n <div class=\"dMon\">sep</div>\n </div>\n <div class=\"dDate\">\n <div class=\"dDay\">31</div>\n <div class=\"dMon\">sep</div>\n </div>\n <div class=\"detailContainer\">Test O.O</div>\n</div>\n</body>\n</html>\n"
}
] |
2008/10/08
|
[
"https://Stackoverflow.com/questions/183407",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/25515/"
] |
183,409
|
<p>Let's say I have a java program that makes an HTTP request on a server using HTTP 1.1 and doesn't close the connection. I make one request, and read all data returned from the input stream I have bound to the socket. However, upon making a second request, I get no response from the server (or there's a problem with the stream - it doesn't provide any more input). If I make the requests in order (Request, request, read) it works fine, but (request, read, request, read) doesn't.</p>
<p>Could someone shed some insight onto why this might be happening? (Code snippets follow). No matter what I do, the second read loop's isr_reader.read() only ever returns -1.</p>
<pre><code>try{
connection = new Socket("SomeServer", port);
con_out = connection.getOutputStream();
con_in = connection.getInputStream();
PrintWriter out_writer = new PrintWriter(con_out, false);
out_writer.print("GET http://somesite HTTP/1.1\r\n");
out_writer.print("Host: thehost\r\n");
//out_writer.print("Content-Length: 0\r\n");
out_writer.print("\r\n");
out_writer.flush();
// If we were not interpreting this data as a character stream, we might need to adjust byte ordering here.
InputStreamReader isr_reader = new InputStreamReader(con_in);
char[] streamBuf = new char[8192];
int amountRead;
StringBuilder receivedData = new StringBuilder();
while((amountRead = isr_reader.read(streamBuf)) > 0){
receivedData.append(streamBuf, 0, amountRead);
}
// Response is processed here.
if(connection != null && !connection.isClosed()){
//System.out.println("Connection Still Open...");
out_writer.print("GET http://someSite2\r\n");
out_writer.print("Host: somehost\r\n");
out_writer.print("Connection: close\r\n");
out_writer.print("\r\n");
out_writer.flush();
streamBuf = new char[8192];
amountRead = 0;
receivedData.setLength(0);
while((amountRead = isr_reader.read(streamBuf)) > 0 || amountRead < 1){
if (amountRead > 0)
receivedData.append(streamBuf, 0, amountRead);
}
}
// Process response here
}
</code></pre>
<p>Responses to questions:
Yes, I'm receiving chunked responses from the server.
I'm using raw sockets because of an outside restriction.</p>
<p>Apologies for the mess of code - I was rewriting it from memory and seem to have introduced a few bugs.</p>
<p>So the consensus is I have to either do (request, request, read) and let the server close the stream once I hit the end, or, if I do (request, read, request, read) stop before I hit the end of the stream so that the stream <em>isn't</em> closed.</p>
|
[
{
"answer_id": 183457,
"author": "Ates Goral",
"author_id": 23501,
"author_profile": "https://Stackoverflow.com/users/23501",
"pm_score": 0,
"selected": false,
"text": "Connection: keep-alive Content-Length Content-Length"
},
{
"answer_id": 185281,
"author": "Alexander",
"author_id": 16724,
"author_profile": "https://Stackoverflow.com/users/16724",
"pm_score": 4,
"selected": true,
"text": "while((amountRead = isr_reader.read(streamBuf)) > 0) {\n receivedData.append(streamBuf, 0, amountRead);\n}\n read -1 PrintWriter US-ASCII"
}
] |
2008/10/08
|
[
"https://Stackoverflow.com/questions/183409",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4924/"
] |
183,415
|
<p>A table row is generated using an asp:Repeater:</p>
<pre><code><asp:repeater ID="announcementsRepeater" OnItemDataBound="announcementsRepeater_ItemDataBound" runat="Server">
<itemtemplate>
<tr id="announcementRow" class="announcementItem" runat="server">...</tr>
</itemtemplate>
</asp:repeater>
</code></pre>
<p>Now in the data-bind i want to mark "unread" announcements with a different css class, so that the web-guy can perform whatever styling he wants to differentiate between read and unread announcements:</p>
<pre><code>protected void announcementsRepeater_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
if (e.Item.ItemType != ListItemType.Item && e.Item.ItemType != ListItemType.AlternatingItem)
return;
// get the associated data item
Announcement announcement = (Announcement)e.Item.DataItem;
WebControl row = (WebControl)e.Item.FindControl("announcementRow");
if (row != null)
row.CssClass = row.CssClass + " announcementItemUnread";
}
</code></pre>
<p>except the cast fails at runtime: </p>
<pre><code>System.InvalidCastException occurred
Message="Unable to cast object of type 'System.Web.UI.HtmlControls.HtmlTableRow' to type 'System.Web.UI.WebControls.WebControl'."
</code></pre>
<p>It turns out that <code>HtmlTableRow</code> has a different parent heirarchy than <code>WebControl</code>:</p>
<pre><code>HtmlTableRow
: HtmlContainerControl
: HtmlControl
: System.Web.UI.Control
</code></pre>
<p>which is ultimately where WebControl comes from</p>
<pre><code>WebControl
: System.Web.UI.Control
</code></pre>
<p>So i changed the code to try to use a System.Web.UI.Control instead:</p>
<pre><code>Control row = (Control)e.Item.FindControl("announcementRow");
if (row != null)
row.CssClass = row.CssClass + " announcementItemUnread";
</code></pre>
<p>But <code>Control</code> doesn't contain a definition for <code>CssClass</code>:</p>
<pre><code>'System.Web.UI.Control' does not contain a definition for 'CssClass'
</code></pre>
<p>so how do i set the css class name for a <code><TR></code> element during DataBind?</p>
|
[
{
"answer_id": 183438,
"author": "Geoff",
"author_id": 1097,
"author_profile": "https://Stackoverflow.com/users/1097",
"pm_score": 0,
"selected": false,
"text": "HtmlTableRow row = (HtmlTableRow)e.Item.FindControl(\"announcementRow\");\n"
},
{
"answer_id": 183460,
"author": "tvanfosson",
"author_id": 12950,
"author_profile": "https://Stackoverflow.com/users/12950",
"pm_score": 4,
"selected": true,
"text": " HtmlControl htmlRow = (HtmlControl)row; \n htmlRow.Attributes[\"class\"] = htmlRow.Attributes[\"class\"] + \" announcementItemUnread\";\n"
},
{
"answer_id": 183463,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<tr id=\"announcementRow\" runat=\"server\" class=\"<#% functionToDetermineWhichtoShow(ItemInBoundSetToPass) %>\">...</tr>\n"
}
] |
2008/10/08
|
[
"https://Stackoverflow.com/questions/183415",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12597/"
] |
183,428
|
<p>I have a batch file that uses this idiom (many times) to read a registry value into an environment variable:</p>
<pre><code>FOR /F "tokens=2* delims= " %%A IN ('REG QUERY "HKLM\SOFTWARE\Path\To\Key" /v ValueName') DO SET MyVariable=%%B
</code></pre>
<p>(There's a tab character after <code>delims=</code>)</p>
<p>This works fine on thousands of customer's computers. But on one customer's computer (running Windows Server 2003, command extensions enabled),<br>
it fails with <code>'REG QUERY "HKLM\SOFTWARE\Path\To\Key" /v ValueName'</code> is not recognized as an internal or external command, operable program or batch file.' Running the "<code>reg query</code>" command alone works fine. <code>Reg.exe</code> is present in <code>C:\Windows\System32</code>. </p>
<p>I was able to work around the problem by changing the code to</p>
<pre><code>REG QUERY "HKLM\SOFTWARE\Path\To\Key" /v ValueName > temp.txt
FOR /F "tokens=2* delims= " %%A IN (temp.txt) DO SET MyVariable=%%B
</code></pre>
<p>This got the customer up and running, but I would like to understand why the problem occurred so I can avoid it in the future.</p>
<p>Slightly off the primary topic - a more direct way to get a registry value (string or DWORD) into an environment variable would also be useful.</p>
|
[
{
"answer_id": 183465,
"author": "agnul",
"author_id": 6069,
"author_profile": "https://Stackoverflow.com/users/6069",
"pm_score": 0,
"selected": false,
"text": "/F cmd /e:on\n HKCU\\Software\\Microsoft\\Command Processor\\EnableExtensions\n help for help cmd"
}
] |
2008/10/08
|
[
"https://Stackoverflow.com/questions/183428",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13012/"
] |
183,446
|
<p>How do I fix that error once and for all? I just want to be able to do unions in MySQL. </p>
<p>(I'm looking for a shortcut, like an option to make MySQL ignore that issue or take it's best guess, not looking to change collations on 100s of tables ... at least not today)</p>
|
[
{
"answer_id": 183624,
"author": "kristof",
"author_id": 3241,
"author_profile": "https://Stackoverflow.com/users/3241",
"pm_score": 4,
"selected": true,
"text": "select column1 from tableWithProperCollation\nunion all\nselect column1 COLLATE SQL_Latin1_General_CP1_CI_AS from tableWithDifferentCollation\n"
},
{
"answer_id": 26258216,
"author": "KevinR",
"author_id": 3276221,
"author_profile": "https://Stackoverflow.com/users/3276221",
"pm_score": 1,
"selected": false,
"text": "ALTER DATABASE databasename COLLATE utf8_unicode_ci;\n"
}
] |
2008/10/08
|
[
"https://Stackoverflow.com/questions/183446",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13009/"
] |
183,461
|
<p>In this particular situation, there are 9 automated steps in a process that take varying lengths of time. We currently have a number showing percentage in the center of a progress bar, but it suffers from the common stop-and-go problem of racing up to 33%, waiting a long time, racing up to 55%, waiting an even longer time, then finishing.</p>
<p>What's the best way to present this to the user? Should we remove the number, remove the whole progress bar in favor of an ajax-type circle animation, add descriptive text for the nine steps and checking them off or leave it the way it is? What are your thoughts?</p>
|
[
{
"answer_id": 410730,
"author": "Roger Lipscombe",
"author_id": 8446,
"author_profile": "https://Stackoverflow.com/users/8446",
"pm_score": 1,
"selected": false,
"text": "UserControl ProgressBar inner public partial class ZenoProgressBar : UserControl\n{\n private const int DEFAULT_FACTOR_VALUE = 10;\n private const int DEFAULT_MAXIMUM_VALUE = 100;\n\n public ZenoProgressBar()\n {\n InitializeComponent();\n\n Maximum = DEFAULT_MAXIMUM_VALUE;\n Factor = DEFAULT_FACTOR_VALUE;\n }\n\n /// <summary>\n /// The \"speed\" of the progress bar. While it will never get to\n /// the end, it uses this number to decide how much further to\n /// go each time Increment is called. For example, setting it to\n /// 2 causes half of the remaining distance to be covered.\n /// </summary>\n [DefaultValue(DEFAULT_FACTOR_VALUE)]\n public int Factor { get; set; }\n\n [DefaultValue(DEFAULT_MAXIMUM_VALUE)]\n public int Maximum { get; set; }\n\n private void ZenoProgressBar_Load(object sender, EventArgs e)\n {\n inner.Dock = DockStyle.Fill;\n }\n\n public void Increment()\n {\n inner.Value += (inner.Maximum - inner.Value) / Factor;\n }\n}\n"
}
] |
2008/10/08
|
[
"https://Stackoverflow.com/questions/183461",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23427/"
] |
183,480
|
<p>Still 'diving in' to Python, and want to make sure I'm not overlooking something. I wrote a script that extracts files from several zip files, and saves the extracted files together in one directory. To prevent duplicate filenames from being over-written, I wrote this little function - and I'm just wondering if there is a better way to do this?
Thanks!</p>
<pre><code>def unique_filename(file_name):
counter = 1
file_name_parts = os.path.splitext(file_name) # returns ('/path/file', '.ext')
while os.path.isfile(file_name):
file_name = file_name_parts[0] + '_' + str(counter) + file_name_parts[1]
counter += 1
return file_name
</code></pre>
<p>I really <em>do</em> require the files to be in a single directory, and numbering duplicates is definitely acceptable in my case, so I'm not looking for a more robust method (tho' I suppose any pointers are welcome), but just to make sure that what this accomplishes is getting done the right way.</p>
|
[
{
"answer_id": 183528,
"author": "S.Lott",
"author_id": 10661,
"author_profile": "https://Stackoverflow.com/users/10661",
"pm_score": 2,
"selected": false,
"text": "base_name, ext = os.path.splitext(file_name) \n file_name = \"%s_%d%s\" % (base_name, str(counter), ext)\n"
},
{
"answer_id": 183533,
"author": "Dan Lenski",
"author_id": 20789,
"author_profile": "https://Stackoverflow.com/users/20789",
"pm_score": 3,
"selected": false,
"text": "os.path.isfile os.path.lexists isfile lexists"
},
{
"answer_id": 183582,
"author": "Brian",
"author_id": 9493,
"author_profile": "https://Stackoverflow.com/users/9493",
"pm_score": 6,
"selected": true,
"text": "def unique_file(file_name):\n counter = 1\n file_name_parts = os.path.splitext(file_name) # returns ('/path/file', '.ext')\n while 1:\n try:\n fd = os.open(file_name, os.O_CREAT | os.O_EXCL | os.O_RDRW)\n return os.fdopen(fd), file_name\n except OSError:\n pass\n file_name = file_name_parts[0] + '_' + str(counter) + file_name_parts[1]\n counter += 1\n def unique_file(file_name):\n dirname, filename = os.path.split(file_name)\n prefix, suffix = os.path.splitext(filename)\n\n fd, filename = tempfile.mkstemp(suffix, prefix+\"_\", dirname)\n return os.fdopen(fd), filename\n\n>>> f, filename=unique_file('/home/some_dir/foo.txt')\n>>> print filename\n/home/some_dir/foo_z8f_2Z.txt\n"
},
{
"answer_id": 185558,
"author": "Jeremy Cantrell",
"author_id": 18866,
"author_profile": "https://Stackoverflow.com/users/18866",
"pm_score": 1,
"selected": false,
"text": "import uuid\n\ndef unique_filename(prefix=None, suffix=None):\n fn = []\n if prefix: fn.extend([prefix, '-'])\n fn.append(str(uuid.uuid4()))\n if suffix: fn.extend(['.', suffix.lstrip('.')])\n return ''.join(fn)\n"
},
{
"answer_id": 691029,
"author": "Manish",
"author_id": 50481,
"author_profile": "https://Stackoverflow.com/users/50481",
"pm_score": 0,
"selected": false,
"text": "def ensure_unique_filename(orig_file_path): \n from time import time\n import os\n\n if os.path.lexists(orig_file_path):\n name, ext = os.path.splitext(orig_file_path)\n orig_file_path = name + str(time()).replace('.', '') + ext\n\n return orig_file_path\n"
}
] |
2008/10/08
|
[
"https://Stackoverflow.com/questions/183480",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/26196/"
] |
183,485
|
<p>I need to convert the punycode <code>NIATO-OTABD</code> to <code>nñiñatoñ</code>.</p>
<p>I found <a href="http://0xcc.net/jsescape/" rel="noreferrer">a text converter in JavaScript</a> the other day, but the punycode conversion doesn't work if there's a dash in the middle.</p>
<p>Any suggestion to fix the "dash" issue?</p>
|
[
{
"answer_id": 301287,
"author": "some",
"author_id": 36866,
"author_profile": "https://Stackoverflow.com/users/36866",
"pm_score": 7,
"selected": true,
"text": "xn-- utf16-class ToASCII ToUnicode //Javascript Punycode converter derived from example in RFC3492.\n//This implementation is created by some@domain.name and released into public domain\nvar punycode = new function Punycode() {\n // This object converts to and from puny-code used in IDN\n //\n // punycode.ToASCII ( domain )\n // \n // Returns a puny coded representation of \"domain\".\n // It only converts the part of the domain name that\n // has non ASCII characters. I.e. it dosent matter if\n // you call it with a domain that already is in ASCII.\n //\n // punycode.ToUnicode (domain)\n //\n // Converts a puny-coded domain name to unicode.\n // It only converts the puny-coded parts of the domain name.\n // I.e. it dosent matter if you call it on a string\n // that already has been converted to unicode.\n //\n //\n this.utf16 = {\n // The utf16-class is necessary to convert from javascripts internal character representation to unicode and back.\n decode:function(input){\n var output = [], i=0, len=input.length,value,extra;\n while (i < len) {\n value = input.charCodeAt(i++);\n if ((value & 0xF800) === 0xD800) {\n extra = input.charCodeAt(i++);\n if ( ((value & 0xFC00) !== 0xD800) || ((extra & 0xFC00) !== 0xDC00) ) {\n throw new RangeError(\"UTF-16(decode): Illegal UTF-16 sequence\");\n }\n value = ((value & 0x3FF) << 10) + (extra & 0x3FF) + 0x10000;\n }\n output.push(value);\n }\n return output;\n },\n encode:function(input){\n var output = [], i=0, len=input.length,value;\n while (i < len) {\n value = input[i++];\n if ( (value & 0xF800) === 0xD800 ) {\n throw new RangeError(\"UTF-16(encode): Illegal UTF-16 value\");\n }\n if (value > 0xFFFF) {\n value -= 0x10000;\n output.push(String.fromCharCode(((value >>>10) & 0x3FF) | 0xD800));\n value = 0xDC00 | (value & 0x3FF);\n }\n output.push(String.fromCharCode(value));\n }\n return output.join(\"\");\n }\n }\n\n //Default parameters\n var initial_n = 0x80;\n var initial_bias = 72;\n var delimiter = \"\\x2D\";\n var base = 36;\n var damp = 700;\n var tmin=1;\n var tmax=26;\n var skew=38;\n var maxint = 0x7FFFFFFF;\n\n // decode_digit(cp) returns the numeric value of a basic code \n // point (for use in representing integers) in the range 0 to\n // base-1, or base if cp is does not represent a value.\n\n function decode_digit(cp) {\n return cp - 48 < 10 ? cp - 22 : cp - 65 < 26 ? cp - 65 : cp - 97 < 26 ? cp - 97 : base;\n }\n\n // encode_digit(d,flag) returns the basic code point whose value\n // (when used for representing integers) is d, which needs to be in\n // the range 0 to base-1. The lowercase form is used unless flag is\n // nonzero, in which case the uppercase form is used. The behavior\n // is undefined if flag is nonzero and digit d has no uppercase form. \n\n function encode_digit(d, flag) {\n return d + 22 + 75 * (d < 26) - ((flag != 0) << 5);\n // 0..25 map to ASCII a..z or A..Z \n // 26..35 map to ASCII 0..9\n }\n //** Bias adaptation function **\n function adapt(delta, numpoints, firsttime ) {\n var k;\n delta = firsttime ? Math.floor(delta / damp) : (delta >> 1);\n delta += Math.floor(delta / numpoints);\n\n for (k = 0; delta > (((base - tmin) * tmax) >> 1); k += base) {\n delta = Math.floor(delta / ( base - tmin ));\n }\n return Math.floor(k + (base - tmin + 1) * delta / (delta + skew));\n }\n\n // encode_basic(bcp,flag) forces a basic code point to lowercase if flag is zero,\n // uppercase if flag is nonzero, and returns the resulting code point.\n // The code point is unchanged if it is caseless.\n // The behavior is undefined if bcp is not a basic code point.\n\n function encode_basic(bcp, flag) {\n bcp -= (bcp - 97 < 26) << 5;\n return bcp + ((!flag && (bcp - 65 < 26)) << 5);\n }\n\n // Main decode\n this.decode=function(input,preserveCase) {\n // Dont use utf16\n var output=[];\n var case_flags=[];\n var input_length = input.length;\n\n var n, out, i, bias, basic, j, ic, oldi, w, k, digit, t, len;\n\n // Initialize the state: \n\n n = initial_n;\n i = 0;\n bias = initial_bias;\n\n // Handle the basic code points: Let basic be the number of input code \n // points before the last delimiter, or 0 if there is none, then\n // copy the first basic code points to the output.\n\n basic = input.lastIndexOf(delimiter);\n if (basic < 0) basic = 0;\n\n for (j = 0; j < basic; ++j) {\n if(preserveCase) case_flags[output.length] = ( input.charCodeAt(j) -65 < 26);\n if ( input.charCodeAt(j) >= 0x80) {\n throw new RangeError(\"Illegal input >= 0x80\");\n }\n output.push( input.charCodeAt(j) );\n }\n\n // Main decoding loop: Start just after the last delimiter if any\n // basic code points were copied; start at the beginning otherwise. \n\n for (ic = basic > 0 ? basic + 1 : 0; ic < input_length; ) {\n\n // ic is the index of the next character to be consumed,\n\n // Decode a generalized variable-length integer into delta,\n // which gets added to i. The overflow checking is easier\n // if we increase i as we go, then subtract off its starting \n // value at the end to obtain delta.\n for (oldi = i, w = 1, k = base; ; k += base) {\n if (ic >= input_length) {\n throw RangeError (\"punycode_bad_input(1)\");\n }\n digit = decode_digit(input.charCodeAt(ic++));\n\n if (digit >= base) {\n throw RangeError(\"punycode_bad_input(2)\");\n }\n if (digit > Math.floor((maxint - i) / w)) {\n throw RangeError (\"punycode_overflow(1)\");\n }\n i += digit * w;\n t = k <= bias ? tmin : k >= bias + tmax ? tmax : k - bias;\n if (digit < t) { break; }\n if (w > Math.floor(maxint / (base - t))) {\n throw RangeError(\"punycode_overflow(2)\");\n }\n w *= (base - t);\n }\n\n out = output.length + 1;\n bias = adapt(i - oldi, out, oldi === 0);\n\n // i was supposed to wrap around from out to 0,\n // incrementing n each time, so we'll fix that now: \n if ( Math.floor(i / out) > maxint - n) {\n throw RangeError(\"punycode_overflow(3)\");\n }\n n += Math.floor( i / out ) ;\n i %= out;\n\n // Insert n at position i of the output: \n // Case of last character determines uppercase flag: \n if (preserveCase) { case_flags.splice(i, 0, input.charCodeAt(ic -1) -65 < 26);}\n\n output.splice(i, 0, n);\n i++;\n }\n if (preserveCase) {\n for (i = 0, len = output.length; i < len; i++) {\n if (case_flags[i]) {\n output[i] = (String.fromCharCode(output[i]).toUpperCase()).charCodeAt(0);\n }\n }\n }\n return this.utf16.encode(output);\n };\n\n //** Main encode function **\n\n this.encode = function (input,preserveCase) {\n //** Bias adaptation function **\n\n var n, delta, h, b, bias, j, m, q, k, t, ijv, case_flags;\n\n if (preserveCase) {\n // Preserve case, step1 of 2: Get a list of the unaltered string\n case_flags = this.utf16.decode(input);\n }\n // Converts the input in UTF-16 to Unicode\n input = this.utf16.decode(input.toLowerCase());\n\n var input_length = input.length; // Cache the length\n\n if (preserveCase) {\n // Preserve case, step2 of 2: Modify the list to true/false\n for (j=0; j < input_length; j++) {\n case_flags[j] = input[j] != case_flags[j];\n }\n }\n\n var output=[];\n\n\n // Initialize the state: \n n = initial_n;\n delta = 0;\n bias = initial_bias;\n\n // Handle the basic code points: \n for (j = 0; j < input_length; ++j) {\n if ( input[j] < 0x80) {\n output.push(\n String.fromCharCode(\n case_flags ? encode_basic(input[j], case_flags[j]) : input[j]\n )\n );\n }\n }\n\n h = b = output.length;\n\n // h is the number of code points that have been handled, b is the\n // number of basic code points \n\n if (b > 0) output.push(delimiter);\n\n // Main encoding loop: \n //\n while (h < input_length) {\n // All non-basic code points < n have been\n // handled already. Find the next larger one: \n\n for (m = maxint, j = 0; j < input_length; ++j) {\n ijv = input[j];\n if (ijv >= n && ijv < m) m = ijv;\n }\n\n // Increase delta enough to advance the decoder's\n // <n,i> state to <m,0>, but guard against overflow: \n\n if (m - n > Math.floor((maxint - delta) / (h + 1))) {\n throw RangeError(\"punycode_overflow (1)\");\n }\n delta += (m - n) * (h + 1);\n n = m;\n\n for (j = 0; j < input_length; ++j) {\n ijv = input[j];\n\n if (ijv < n ) {\n if (++delta > maxint) return Error(\"punycode_overflow(2)\");\n }\n\n if (ijv == n) {\n // Represent delta as a generalized variable-length integer: \n for (q = delta, k = base; ; k += base) {\n t = k <= bias ? tmin : k >= bias + tmax ? tmax : k - bias;\n if (q < t) break;\n output.push( String.fromCharCode(encode_digit(t + (q - t) % (base - t), 0)) );\n q = Math.floor( (q - t) / (base - t) );\n }\n output.push( String.fromCharCode(encode_digit(q, preserveCase && case_flags[j] ? 1:0 )));\n bias = adapt(delta, h + 1, h == b);\n delta = 0;\n ++h;\n }\n }\n\n ++delta, ++n;\n }\n return output.join(\"\");\n }\n\n this.ToASCII = function ( domain ) {\n var domain_array = domain.split(\".\");\n var out = [];\n for (var i=0; i < domain_array.length; ++i) {\n var s = domain_array[i];\n out.push(\n s.match(/[^A-Za-z0-9-]/) ?\n \"xn--\" + punycode.encode(s) :\n s\n );\n }\n return out.join(\".\");\n }\n this.ToUnicode = function ( domain ) {\n var domain_array = domain.split(\".\");\n var out = [];\n for (var i=0; i < domain_array.length; ++i) {\n var s = domain_array[i];\n out.push(\n s.match(/^xn--/) ?\n punycode.decode(s.slice(4)) :\n s\n );\n }\n return out.join(\".\");\n }\n}();\n\n\n// Example of usage:\ndomain.oninput = function() {\n var input = domain.value\n var ascii = punycode.ToASCII(input)\n var display = punycode.ToUnicode(ascii)\n domain_ascii.value = ascii\n domain_display.value = display\n} <p>Try with your own data</p>\n\n<label>\n <div>Input domain</div>\n <div><input id=\"domain\" type=\"text\"></div>\n</label>\n<div>Ascii: <output id=\"domain_ascii\"></div>\n<div>Display: <output id=\"domain_display\"></div>"
},
{
"answer_id": 71605995,
"author": "MyChickenNinja",
"author_id": 1252009,
"author_profile": "https://Stackoverflow.com/users/1252009",
"pm_score": 1,
"selected": false,
"text": "var punycode = new function Punycode() {\n// punycode.ToASCII ( domain )\n// punycode.ToUnicode (domain)\nthis.utf16 = {\n decode:function(input){\n var output = [], i=0, len=input.length,value,extra;\n while (i < len) {\n value = input.charCodeAt(i++);\n if ((value & 0xF800) === 0xD800) {\n extra = input.charCodeAt(i++);\n if ( ((value & 0xFC00) !== 0xD800) || ((extra & 0xFC00) !== 0xDC00) ) {\n throw new RangeError(\"UTF-16(decode): Illegal UTF-16 sequence\");\n }\n value = ((value & 0x3FF) << 10) + (extra & 0x3FF) + 0x10000;\n }\n output.push(value);\n }\n return output;\n },\n encode:function(input){\n var output = [], i=0, len=input.length,value;\n while (i < len) {\n value = input[i++];\n if ( (value & 0xF800) === 0xD800 ) {\n throw new RangeError(\"UTF-16(encode): Illegal UTF-16 value\");\n }\n if (value > 0xFFFF) {\n value -= 0x10000;\n output.push(String.fromCharCode(((value >>>10) & 0x3FF) | 0xD800));\n value = 0xDC00 | (value & 0x3FF);\n }\n output.push(String.fromCharCode(value));\n }\n return output.join(\"\");\n }\n}\nvar initial_n = 0x80;\nvar initial_bias = 72;\nvar delimiter = \"\\x2D\";\nvar base = 36;\nvar damp = 700;\nvar tmin=1;\nvar tmax=26;\nvar skew=38;\nvar maxint = 0x7FFFFFFF;\nfunction decode_digit(cp) {\n return cp - 48 < 10 ? cp - 22 : cp - 65 < 26 ? cp - 65 : cp - 97 < 26 ? cp - 97 : base;\n}\nfunction encode_digit(d, flag) {\n return d + 22 + 75 * (d < 26) - ((flag !== 0) << 5);\n}\nfunction adapt(delta, numpoints, firsttime ) {\n var k;\n delta = firsttime ? Math.floor(delta / damp) : (delta >> 1);\n delta += Math.floor(delta / numpoints);\n for (k = 0; delta > (((base - tmin) * tmax) >> 1); k += base) {\n delta = Math.floor(delta / ( base - tmin ));\n }\n return Math.floor(k + (base - tmin + 1) * delta / (delta + skew));\n}\nfunction encode_basic(bcp, flag) {\n bcp -= (bcp - 97 < 26) << 5;\n return bcp + ((!flag && (bcp - 65 < 26)) << 5);\n}\nthis.decode=function(input,preserveCase) {\n var output=[];\n var case_flags=[];\n var input_length = input.length;\n var n, out, i, bias, basic, j, ic, oldi, w, k, digit, t, len;\n n = initial_n;\n i = 0;\n bias = initial_bias;\n basic = input.lastIndexOf(delimiter);\n if (basic < 0) {basic = 0;}\n for (j = 0; j < basic; ++j) {\n if(preserveCase) {case_flags[output.length] = ( input.charCodeAt(j) -65 < 26);}\n if ( input.charCodeAt(j) >= 0x80) {\n throw new RangeError(\"Illegal input >= 0x80\");\n }\n output.push( input.charCodeAt(j) );\n }\n for (ic = basic > 0 ? basic + 1 : 0; ic < input_length; ) {\n for (oldi = i, w = 1, k = base; ; k += base) {\n if (ic >= input_length) {\n throw RangeError (\"punycode_bad_input(1)\");\n }\n digit = decode_digit(input.charCodeAt(ic++));\n if (digit >= base) {\n throw RangeError(\"punycode_bad_input(2)\");\n }\n if (digit > Math.floor((maxint - i) / w)) {\n throw RangeError (\"punycode_overflow(1)\");\n }\n i += digit * w;\n t = k <= bias ? tmin : k >= bias + tmax ? tmax : k - bias;\n if (digit < t) { break; }\n if (w > Math.floor(maxint / (base - t))) {\n throw RangeError(\"punycode_overflow(2)\");\n }\n w *= (base - t);\n }\n out = output.length + 1;\n bias = adapt(i - oldi, out, oldi === 0);\n if ( Math.floor(i / out) > maxint - n) {\n throw RangeError(\"punycode_overflow(3)\");\n }\n n += Math.floor( i / out ) ;\n i %= out;\n if (preserveCase) { case_flags.splice(i, 0, input.charCodeAt(ic -1) -65 < 26);}\n output.splice(i, 0, n);\n i++;\n }\n if (preserveCase) {\n for (i = 0, len = output.length; i < len; i++) {\n if (case_flags[i]) {\n output[i] = (String.fromCharCode(output[i]).toUpperCase()).charCodeAt(0);\n }\n }\n }\n return this.utf16.encode(output);\n};\nthis.encode = function (input,preserveCase) {\n var n, delta, h, b, bias, j, m, q, k, t, ijv, case_flags;\n if (preserveCase) {\n case_flags = this.utf16.decode(input);\n }\n input = this.utf16.decode(input.toLowerCase());\n var input_length = input.length; // Cache the length\n if (preserveCase) {\n for (j=0; j < input_length; j++) {\n case_flags[j] = input[j] !== case_flags[j];\n }\n }\n var output=[];\n n = initial_n;\n delta = 0;\n bias = initial_bias;\n for (j = 0; j < input_length; ++j) {\n if ( input[j] < 0x80) {\n output.push(\n String.fromCharCode(\n case_flags ? encode_basic(input[j], case_flags[j]) : input[j]\n )\n );\n }\n }\n h = b = output.length;\n if (b > 0) {output.push(delimiter);}\n while (h < input_length) {\n for (m = maxint, j = 0; j < input_length; ++j) {\n ijv = input[j];\n if (ijv >= n && ijv < m) {m = ijv;}\n }\n if (m - n > Math.floor((maxint - delta) / (h + 1))) {\n throw RangeError(\"punycode_overflow (1)\");\n }\n delta += (m - n) * (h + 1);\n n = m;\n for (j = 0; j < input_length; ++j) {\n ijv = input[j];\n if (ijv < n ) {\n if (++delta > maxint) {return Error(\"punycode_overflow(2)\");}\n }\n if (ijv === n) {\n for (q = delta, k = base; ; k += base) {\n t = k <= bias ? tmin : k >= bias + tmax ? tmax : k - bias;\n if (q < t) {break;}\n output.push( String.fromCharCode(encode_digit(t + (q - t) % (base - t), 0)) );\n q = Math.floor( (q - t) / (base - t) );\n }\n output.push( String.fromCharCode(encode_digit(q, preserveCase && case_flags[j] ? 1:0 )));\n bias = adapt(delta, h + 1, h === b);\n delta = 0;\n ++h;\n }\n }\n ++delta, ++n;\n }\n return output.join(\"\");\n};\nfunction formatArray(arr){\n var outStr = \"\";\n if (arr.length === 1) {\n outStr = arr[0];\n } else if (arr.length === 2) {\n outStr = arr.join('.');\n } else if (arr.length > 2) {\n outStr = arr.slice(0, -1).join('@') + '.' + arr.slice(-1);\n }\n return outStr;\n}\n this.ToASCII = function ( domain ) {\n try {\n var domain_array;\n if (domain.includes(\"@\")) {\n domain_array = domain.split(\"@\").join(\".\").split(\".\");\n }\n else {\n domain_array = domain.split(\".\");\n }\n var out = [];\n for (var i=0; i < domain_array.length; ++i) {\n var s = domain_array[i];\n out.push(\n s.match(/[^A-Za-z0-9-]/) ?\n \"xn--\" + punycode.encode(s) :\n s\n );\n }\n return formatArray(out)\n } catch (error) {\n return (domain)\n }\n };\n this.ToUnicode = function ( domain ) {\n try {\n var domain_array;\n if (domain.includes(\"@\")) {\n domain_array = domain.split(\"@\").join(\".\").split(\".\");\n }\n else {\n domain_array = domain.split(\".\");\n }\n var out = [];\n for (var i = 0; i < domain_array.length; ++i) {\n var s = domain_array[i];\n\n out.push(\n s.match(/^xn--/) ?\n punycode.decode(s.slice(4)) :\n s\n );\n\n }\n return formatArray(out)\n } catch (error) {\n return (domain)\n }\n };};\n"
}
] |
2008/10/08
|
[
"https://Stackoverflow.com/questions/183485",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23520/"
] |
183,488
|
<p>We are doing some performance tests on our website and we are getting the following error a lot:</p>
<pre><code>*** 'C:\inetpub\foo.plex' log message at: 2008/10/07 13:19:58
DBD::ODBC::st execute failed: [Microsoft][SQL Native Client]String data, right truncation (SQL-22001) at C:\inetpub\foo.plex line 25.
</code></pre>
<p>Line 25 is the following:</p>
<pre><code>SELECT DISTINCT top 20 ZIP_CODE, CITY, STATE FROM Zipcodes WHERE (ZIP_CODE like ?) OR (CITY like ?) ORDER BY ZIP_CODE
</code></pre>
<p>And lastly, this is perl code.</p>
<p>Any ideas?</p>
<p><strong>EDIT</strong>: the issue here was that I was searching in the zip file with the string "74523%" which is too long. I ended up just not adding the % if they give five digits.</p>
|
[
{
"answer_id": 183518,
"author": "Chris Driver",
"author_id": 5217,
"author_profile": "https://Stackoverflow.com/users/5217",
"pm_score": 6,
"selected": true,
"text": "ZIP_CODE ZIP_CODE CITY CITY ?"
},
{
"answer_id": 72255401,
"author": "luca.vercelli",
"author_id": 5116356,
"author_profile": "https://Stackoverflow.com/users/5116356",
"pm_score": 0,
"selected": false,
"text": "sqlsrv_connect(DB_PTH_HOST, array(\n \"Database\" => ***,\n \"UID\" => ***,\n \"PWD\" => ***,\n \"CharacterSet\" => \"UTF-8\"));\n"
},
{
"answer_id": 74636718,
"author": "user5693936",
"author_id": 5693936,
"author_profile": "https://Stackoverflow.com/users/5693936",
"pm_score": 0,
"selected": false,
"text": "dbConnect odbc encoding SQL_Latin1_General_CP1_CI_AS latin1 dbConnect"
}
] |
2008/10/08
|
[
"https://Stackoverflow.com/questions/183488",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12448/"
] |
183,496
|
<p>I've recently come across this piece of JavaScript code:</p>
<pre><code>if (",>=,<=,<>,".indexOf("," + sCompOp + ",") != -1)
</code></pre>
<p>I was intrigued, because to write this test I would have done:</p>
<pre><code>if (/(>=|<=|<>)/.test(sCompOp))
</code></pre>
<p>Is this just a stylistic difference, or does the author of the other code know something about optimization that I don't? Or perhaps there is a different good reason to do this, or to not use regexes...?</p>
<p>It seems to me that using <code>String.indexOf()</code> for this is a little more difficult to read (but then, I'm quite comfortable with regular expressions), but are there instances where it might be "better" than writing an equivalent regex?</p>
<p>By "better" that might be quicker or more efficient, (although obviously that depends on the browser's JavaScript engine), or some other reason I'm not aware of. Can anyone enlighten me?</p>
|
[
{
"answer_id": 183645,
"author": "Shog9",
"author_id": 811,
"author_profile": "https://Stackoverflow.com/users/811",
"pm_score": 5,
"selected": true,
"text": "sCompOp sCompOp sCompOp /^(>=|<=|<>)$/\n function Time(fn, iter)\n{\n var start = new Date();\n for (var i=0; i<iter; ++i)\n fn();\n var end = new Date();\n console.log(fn.toString().replace(/[\\r|\\n]/g, ' '), \"\\n : \" + (end-start));\n}\n\nfunction IndexMethod(op)\n{\n return (\",>=,<=,<>,\".indexOf(\",\" + op + \",\") != -1);\n}\n\nfunction RegexMethod(op)\n{\n return /(>=|<=|<>)/.test(op);\n}\n\nfunction timeTests()\n{\n var loopCount = 50000;\n \n Time(function(){IndexMethod(\">=\");}, loopCount);\n Time(function(){IndexMethod(\"<=\");}, loopCount);\n Time(function(){IndexMethod(\"<>\");}, loopCount);\n Time(function(){IndexMethod(\"!!\");}, loopCount);\n Time(function(){IndexMethod(\"the quick brown foxes jumped over the lazy dogs\");}, loopCount);\n Time(function(){IndexMethod(\"<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<\");}, loopCount);\n\n Time(function(){RegexMethod(\">=\");}, loopCount);\n Time(function(){RegexMethod(\"<=\");}, loopCount);\n Time(function(){RegexMethod(\"<>\");}, loopCount);\n Time(function(){RegexMethod(\"!!\");}, loopCount);\n Time(function(){RegexMethod(\"the quick brown foxes jumped over the lazy dogs\");}, loopCount);\n Time(function(){RegexMethod(\"<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<\");}, loopCount);\n}\n\ntimeTests();\n"
},
{
"answer_id": 183800,
"author": "J c",
"author_id": 25837,
"author_profile": "https://Stackoverflow.com/users/25837",
"pm_score": 2,
"selected": false,
"text": "var aOps = \">=,<=,<>\".split(\",\");\nvar allowableOps = {};\nfor (var iLoop = 0; iLoop < aOps.length; iLoop++) {\n allowableOps[aOps[iLoop]] = true;\n} //for\n if (allowableOps[sCompOp]) { ... }\n"
},
{
"answer_id": 185770,
"author": "Leo",
"author_id": 20689,
"author_profile": "https://Stackoverflow.com/users/20689",
"pm_score": 2,
"selected": false,
"text": "getElementsByClassName indexOf indexOf \\b indexOf getElementsByClassName"
}
] |
2008/10/08
|
[
"https://Stackoverflow.com/questions/183496",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12559/"
] |
183,499
|
<p>One of the things that always bugs me about using Readers and Streams in Java is that the <code>close()</code> method can throw an exception. Since it's a good idea to put the close method in a finally block, that necessitates a bit of an awkward situation. I usually use this construction:</p>
<pre><code>FileReader fr = new FileReader("SomeFile.txt");
try {
try {
fr.read();
} finally {
fr.close();
}
} catch(Exception e) {
// Do exception handling
}
</code></pre>
<p>But I've also seen this construction:</p>
<pre><code>FileReader fr = new FileReader("SomeFile.txt");
try {
fr.read()
} catch (Exception e) {
// Do exception handling
} finally {
try {
fr.close();
} catch (Exception e) {
// Do exception handling
}
}
</code></pre>
<p>I prefer the first construction because there's only one catch block and it just seems more elegant. Is there a reason to actually prefer the second or an alternate construction?</p>
<p>UPDATE: Would it make a difference if I pointed out that both <code>read</code> and <code>close</code> only throw IOExceptions? So it seems likely to me that, if read fails, close will fail for the same reason.</p>
|
[
{
"answer_id": 183520,
"author": "Steve B.",
"author_id": 19479,
"author_profile": "https://Stackoverflow.com/users/19479",
"pm_score": 1,
"selected": false,
"text": "try\n{\n try{\n ...\n }\n catch(IOException e)\n {\n ..\n }\n}\ncatch(Exception e)\n{\n // we could read, but now something else is broken \n ...\n}\n"
},
{
"answer_id": 183572,
"author": "oxbow_lakes",
"author_id": 16853,
"author_profile": "https://Stackoverflow.com/users/16853",
"pm_score": 5,
"selected": false,
"text": "finally fr.close() return finally IOUtil.closeSilently(fr);\n public static void closeSilently(Closeable c) {\n try { c.close(); } catch (Exception e) {} \n} \n"
},
{
"answer_id": 183575,
"author": "Michael Myers",
"author_id": 13531,
"author_profile": "https://Stackoverflow.com/users/13531",
"pm_score": 2,
"selected": false,
"text": "read() close() close() read() close() try (FileReader fr = new FileReader(\"SomeFile.txt\")) {\n fr.read();\n // no need to close since the try-with-resources statement closes it automatically\n}\n try (FileReader fr = new FileReader(\"SomeFile.txt\")) {\n fr.read();\n // no need to close since the try-with-resources statement closes it automatically\n} catch (IOException e) {\n // Do exception handling\n log(e);\n // If this catch block is run, the FileReader has already been closed.\n // The exception could have come from either read() or close();\n // if both threw exceptions (or if multiple resources were used and had to be closed)\n // then only one exception is thrown and the others are suppressed\n // but can still be retrieved:\n Throwable[] suppressed = e.getSuppressed(); // can be an empty array\n for (Throwable t : suppressed) {\n log(suppressed[t]);\n }\n}\n finally"
},
{
"answer_id": 183646,
"author": "Martin York",
"author_id": 14065,
"author_profile": "https://Stackoverflow.com/users/14065",
"pm_score": 0,
"selected": false,
"text": "try\n{\n // Code\n}\n// Exception handling\nfinally\n{\n // Exception handling that is garanteed not to throw.\n try\n {\n // Exception handling that may throw.\n }\n // Optional Exception handling that should not throw\n finally()\n {}\n}\n"
},
{
"answer_id": 183779,
"author": "Scott Stanchfield",
"author_id": 12541,
"author_profile": "https://Stackoverflow.com/users/12541",
"pm_score": 1,
"selected": false,
"text": "import java.io.Closeable;\nimport java.io.IOException;\nimport java.util.LinkedList;\nimport java.util.List;\n\npublic abstract class AutoFileCloser {\n private static final Closeable NEW_FILE = new Closeable() {\n public void close() throws IOException {\n // do nothing\n }\n };\n\n // the core action code that the implementer wants to run\n protected abstract void doWork() throws Throwable;\n\n // track a list of closeable thingies to close when finished\n private List<Closeable> closeables_ = new LinkedList<Closeable>();\n\n // mark a new file\n protected void newFile() {\n closeables_.add(0, NEW_FILE);\n }\n\n // give the implementer a way to track things to close\n // assumes this is called in order for nested closeables,\n // inner-most to outer-most\n protected void watch(Closeable closeable) {\n closeables_.add(0, closeable);\n }\n\n public AutoFileCloser() {\n // a variable to track a \"meaningful\" exception, in case\n // a close() throws an exception\n Throwable pending = null;\n\n try {\n doWork(); // do the real work\n\n } catch (Throwable throwable) {\n pending = throwable;\n\n } finally {\n // close the watched streams\n boolean skip = false;\n for (Closeable closeable : closeables_) {\n if (closeable == NEW_FILE) {\n skip = false;\n } else if (!skip && closeable != null) {\n try {\n closeable.close();\n // don't try to re-close nested closeables\n skip = true;\n } catch (Throwable throwable) {\n if (pending == null) {\n pending = throwable;\n }\n }\n }\n }\n\n // if we had a pending exception, rethrow it\n // this is necessary b/c the close can throw an\n // exception, which would remove the pending\n // status of any exception thrown in the try block\n if (pending != null) {\n if (pending instanceof RuntimeException) {\n throw (RuntimeException) pending;\n } else {\n throw new RuntimeException(pending);\n }\n }\n }\n }\n}\n try {\n // ...\n\n new AutoFileCloser() {\n @Override protected void doWork() throws Throwable {\n // declare variables for the readers and \"watch\" them\n FileReader fileReader = null;\n BufferedReader bufferedReader = null;\n watch(fileReader = new FileReader(\"somefile\"));\n watch(bufferedReader = new BufferedReader(fileReader));\n\n // ... do something with bufferedReader\n\n // if you need more than one reader or writer\n newFile(); // puts a flag in the \n FileWriter fileWriter = null;\n BufferedWriter bufferedWriter = null;\n watch(fileWriter = new FileWriter(\"someOtherFile\"));\n watch(bufferedWriter = new BufferedWriter(fileWriter));\n\n // ... do something with bufferedWriter\n }\n };\n\n // .. other logic, maybe more AutoFileClosers\n\n} catch (RuntimeException e) {\n // report or log the exception\n}\n"
},
{
"answer_id": 184558,
"author": "Haoest",
"author_id": 10088,
"author_profile": "https://Stackoverflow.com/users/10088",
"pm_score": 0,
"selected": false,
"text": "try{\n string s = File.Open(\"myfile\").ReadToEnd(); // my file has a bunch of numbers\n // I want to get a total of the numbers \n int total = 0;\n foreach(string line in s.split(\"\\r\\n\")){\n try{ \n total += int.Parse(line); \n } catch{}\n }\ncatch{}\n"
},
{
"answer_id": 185382,
"author": "Dunderklumpen",
"author_id": 16239,
"author_profile": "https://Stackoverflow.com/users/16239",
"pm_score": 0,
"selected": false,
"text": "IOUtil.close(fr);\n public static void close(Closeable c) {\n try {\n c.close();\n } catch (Exception e) {\n logger.error(\"An error occurred while closing. Continuing regardless\", e); \n } \n}\n"
}
] |
2008/10/08
|
[
"https://Stackoverflow.com/questions/183499",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23669/"
] |
183,527
|
<p>I have a dtsx package with a precedence constraint that evaluates an expression and a constraint. The constraint is "success" and the expression is "@myVariable" == 3. myVariable is an int32, and when set in Visual Studio's design GUI the package executes fine. There are two other paths that check for the value to be 1 or 2.</p>
<p>However when I try to run the package from the command line and pass in a value for my variable, it errors out claiming the expression does not evaluate to a boolean!</p>
<p><strong>Command:</strong></p>
<pre><code>dtexec /F "c:myPackage.dtsx" /SET
\Package.Variables[User::myVariable].Properties[Value];3
</code></pre>
<p><strong>Error:</strong></p>
<pre><code>The expression "@myVariable == 1" must evaluate to True or False.
Change the expression to evaluate to a Boolean value.
</code></pre>
<p>The fact this runs fine from the GUI and that microsofts documentation claims == (intuiatively) returns a boolean has me very confused. I've also tried surrounding the 3 in double quotes in my command with no luck, and now I am out of ideas.</p>
<p>Anybody have an idea of what is going on?</p>
|
[
{
"answer_id": 195183,
"author": "Michael Entin",
"author_id": 19880,
"author_profile": "https://Stackoverflow.com/users/19880",
"pm_score": 1,
"selected": false,
"text": "dtexec ... /SET \\Package.Variables[User::myVariable].Value;3\n .Value .Properties[Value] .Value .Properties[Value]"
},
{
"answer_id": 221951,
"author": "Aaron Silverman",
"author_id": 26197,
"author_profile": "https://Stackoverflow.com/users/26197",
"pm_score": 3,
"selected": true,
"text": "(DT_I4)@[User::myVariable] == 3"
}
] |
2008/10/08
|
[
"https://Stackoverflow.com/questions/183527",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/26197/"
] |
183,532
|
<p>I would like to ask for some simple examples showing the uses of <code><div></code> and <code><span></code>. I've seen them both used to mark a section of a page with an <code>id</code> or <code>class</code>, but I'm interested in knowing if there are times when one is preferred over the other.</p>
|
[
{
"answer_id": 183535,
"author": "Jason Bunting",
"author_id": 1790,
"author_profile": "https://Stackoverflow.com/users/1790",
"pm_score": 6,
"selected": false,
"text": "<div> <span> <span> <div> <div> <div id=\"Chapter1\">\n <p>Lorem ipsum dolor sit amet, <span id=\"SomeSpecialText1\">consectetuer adipiscing</span> elit. Duis congue vehicula purus.</p>\n <p>Nam <span id=\"SomeSpecialText2\">eget magna nec</span> sapien fringilla euismod. Donec hendrerit.</p> \n</div>\n"
},
{
"answer_id": 183536,
"author": "Chris Marasti-Georg",
"author_id": 96,
"author_profile": "https://Stackoverflow.com/users/96",
"pm_score": 10,
"selected": true,
"text": "div span <div>This a large main division, with <span>a small bit</span> of spanned text!</div>\n <div>Some <span>text that <div>I want</div> to mark</span> up</div>\n <span> <div> <div id=\"header\">\n <div id=\"userbar\">\n Hi there, <span class=\"username\">Chris Marasti-Georg</span> |\n <a href=\"/edit-profile.html\">Profile</a> |\n <a href=\"https://www.bowlsk.com/_ah/logout?...\">Sign out</a>\n </div>\n <h1><a href=\"/\">Bowl<span class=\"sk\">SK</span></a></h1>\n</div> h1 div span span document.createElement"
},
{
"answer_id": 183561,
"author": "Eric R. Rath",
"author_id": 23883,
"author_profile": "https://Stackoverflow.com/users/23883",
"pm_score": 3,
"selected": false,
"text": "div span div span div inline-block inline-block"
},
{
"answer_id": 183565,
"author": "Konrad Rudolph",
"author_id": 1968,
"author_profile": "https://Stackoverflow.com/users/1968",
"pm_score": 5,
"selected": false,
"text": "<span> <span><p>This is a paragraph</p></span>\n <div> <div> <span style=\"display: block\"><p>Still wrong</p></span>\n<span><p style=\"display: inline\">Just as wrong</p></span>\n"
},
{
"answer_id": 183571,
"author": "Pablo Herrero",
"author_id": 366094,
"author_profile": "https://Stackoverflow.com/users/366094",
"pm_score": 3,
"selected": false,
"text": "div span div"
},
{
"answer_id": 185819,
"author": "AmbroseChapel",
"author_id": 242241,
"author_profile": "https://Stackoverflow.com/users/242241",
"pm_score": 9,
"selected": false,
"text": "<p> <li> <blockquote> <div> <span>"
},
{
"answer_id": 19231559,
"author": "Brian",
"author_id": 1486275,
"author_profile": "https://Stackoverflow.com/users/1486275",
"pm_score": 8,
"selected": false,
"text": "<div>This is a div.</div>\n<div>This is a div.</div>\n<div>This is a div.</div>\n<span>This is a span.</span>\n<span>This is a span.</span>\n<span>This is a span.</span> <div> <span>"
},
{
"answer_id": 35671823,
"author": "Robert",
"author_id": 1798677,
"author_profile": "https://Stackoverflow.com/users/1798677",
"pm_score": 2,
"selected": false,
"text": "<p> <ol> <div> <span> <div> <span>"
},
{
"answer_id": 35876865,
"author": "Sam Hobbs",
"author_id": 2392247,
"author_profile": "https://Stackoverflow.com/users/2392247",
"pm_score": 4,
"selected": false,
"text": "<p>This paragraph <span>has</span> a span.</p>\n<p>This paragraph <div>has</div> a div.</p>\n This paragraph has a span.\n\nThis paragraph\n\nhas\na div.\n"
},
{
"answer_id": 50353745,
"author": "Alex W",
"author_id": 1399491,
"author_profile": "https://Stackoverflow.com/users/1399491",
"pm_score": 3,
"selected": false,
"text": "span div span span div <text> <center>"
},
{
"answer_id": 53593274,
"author": "yatheendra k v",
"author_id": 8836967,
"author_profile": "https://Stackoverflow.com/users/8836967",
"pm_score": 2,
"selected": false,
"text": "<p>Am writing<span class=\"time\">this answer</span> in my free time of my day.</p>\n <div class=\"large-time\">\n <p>Am writing <span class=\"time\"> this answer</span> in my free time of my day. \n </p>\n </div>\n"
},
{
"answer_id": 62449945,
"author": "Vivek Mahajan",
"author_id": 11323042,
"author_profile": "https://Stackoverflow.com/users/11323042",
"pm_score": 2,
"selected": false,
"text": "span in line div block element <div>"
}
] |
2008/10/08
|
[
"https://Stackoverflow.com/questions/183532",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3676/"
] |
183,560
|
<p>I have been trying to use the Perl utility/module "prove" as a test harness for some unit tests. The unit tests are a little more "system" than "unit" as I need to fork off some background processes as part of the test, Using the following...</p>
<pre><code>sub SpinupMonitor{
my $base_dir = shift;
my $config = shift;
my $pid = fork();
if($pid){
return $pid;
}else{
my $cmd = "$base_dir\/..\/bin\/monitor_real.pl -config $config -test";
close STDOUT;
exec ($cmd) or die "cannot exec test code [$cmd]\n";
}
}
sub KillMonitor{
my $pid = shift;
print "Killing monitor [$pid]\n";
kill(1,$pid);
}
</code></pre>
<p>However for some reason when I have my .t file spin up some extra processes it causes the test harness to hang at the end of the first .t file after all the tests have finished, rather than going on to the next file, or exiting if there is only one.</p>
<p>At first I wondered if it might be because I was killing of my sub-processes and leaving them defunct. So I added..</p>
<pre><code>$SIG{CHLD} = \&REAPER;
sub REAPER {
my $pid = wait;
$SIG{CHLD} = \&REAPER;
}
</code></pre>
<p>To the code. But that doesn't help. In fact on closed examination it turns out that my perl test file has exited and is now a defunct process and it is the prove wrapper script that has not reaped its child. In fact when I added a die() call at the end of my test script I got...</p>
<pre><code># Looks like your test died just after 7.
</code></pre>
<p>So my script exited but for some reason the harness isn't unraveling.</p>
<p>I did confirm that it is definitely my sub-processes that are upsetting it as when I disabled them while the tests failed the harness exited properly.</p>
<p>Is there anything I am doing wrong with the way I am starting up my processes that might upset the harness in some way?</p>
|
[
{
"answer_id": 183673,
"author": "Kyle",
"author_id": 2237619,
"author_profile": "https://Stackoverflow.com/users/2237619",
"pm_score": 4,
"selected": false,
"text": "fork() $pid $cmd exec() sh -c monitor_real.pl KillMonitor"
},
{
"answer_id": 184929,
"author": "Tanktalus",
"author_id": 23512,
"author_profile": "https://Stackoverflow.com/users/23512",
"pm_score": 4,
"selected": true,
"text": "*?{}() use File::Spec;\nmy @cmd = File::Spec->catfile($basedir,\n File::Spec->updir(),\n qw(bin monitor_real.pl)\n ),\n -config => $config,\n -test =>;\n\nclose STDOUT;\nclose STDERR;\n\nexec (@cmd) or die \"cannot exec test code [@cmd]\\n\";\n"
}
] |
2008/10/08
|
[
"https://Stackoverflow.com/questions/183560",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3720/"
] |
183,567
|
<p>I have a User class which may or may not have an associated Department. This is referenced through the foreign key DepartmentId, and the relevant field in the User table is set to allow nulls.</p>
<p>When I set up my "Create User" form and select no Department, I get a conflict error on SubmitChanges():</p>
<pre><code>The INSERT statement conflicted with the FOREIGN KEY constraint "FK_User_Department".
</code></pre>
<p>How can I convince Linq to SQL to insert a NULL when the "Department" has been selected as the "blank" first option?</p>
<p>Or, perhaps, is there a keyword I am missing for the "optionLabel" parameter of the Html.DropDownList method that does this? I am currently using "None" because using null or "" cause no "blank option" to be displayed, and I suspect that this may be contributing to the problem. Thanks for any assistance.</p>
|
[
{
"answer_id": 183639,
"author": "tags2k",
"author_id": 192,
"author_profile": "https://Stackoverflow.com/users/192",
"pm_score": 2,
"selected": true,
"text": "UsersController.Create // Snipped UpdateModel call\nif (form[\"User.DepartmentId\"].Length == 0)\n{\n createdUser.DepartmentId = null;\n}\nModels.User.DataContext.SubmitChanges();\n"
}
] |
2008/10/08
|
[
"https://Stackoverflow.com/questions/183567",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/192/"
] |
183,578
|
<p>I am trying to install newgem on my linux box (sudo gem install newgem) and i am getting the following error:</p>
<pre><code>Building native extensions. This could take a while...
ERROR: Error installing newgem:
ERROR: Failed to build gem native extension.
/usr/bin/ruby1.8 extconf.rb install newgem
extconf.rb:1:in `require': no such file to load -- mkmf (LoadError)
from extconf.rb:1
Gem files will remain installed in /usr/lib/ruby/gems/1.8/gems/RedCloth-4.0.4 for inspection.
Results logged to /usr/lib/ruby/gems/1.8/gems/RedCloth-4.0.4/ext/redcloth_scan/gem_make.out
</code></pre>
<p>What could the problem be?</p>
|
[
{
"answer_id": 183875,
"author": "ephemient",
"author_id": 20713,
"author_profile": "https://Stackoverflow.com/users/20713",
"pm_score": 4,
"selected": true,
"text": "mkmf ruby1.8-dev mkmf.rb ruby -e'print $:.join(\"\\n\")'"
}
] |
2008/10/08
|
[
"https://Stackoverflow.com/questions/183578",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18811/"
] |
183,585
|
<p>I'm moving DB from MySQL (used ODBC) to MS SQL and I want to "translate" SQL queries to LINQ. Can someone help me with this (it should SUM Charge column for every location and group result by months):</p>
<pre><code>SELECT
sum(case when Location="Location1" then Charge else 0 end) as Location1,
sum(case when Location="Location2" then Charge else 0 end) as Location2,
sum(case when Location="Location3" then Charge else 0 end) as Location3,
MAKEDATE(YEAR(OrderTime),DAYOFYEAR(OrderTime)) AS date FROM Sales
GROUP BY YEAR(OrderTime),MONTH(OrderTime)
ORDER BY OrderTime DESC
</code></pre>
<p>?</p>
<p>Output should look like this:</p>
<pre><code>Location1 | Location2 | Location3 | date
</code></pre>
<p>EDIT:</p>
<p>I tryed to use LINQ sample from here:</p>
<p><a href="https://stackoverflow.com/questions/167304/is-it-possible-to-pivot-data-using-linq">Is it possible to Pivot data using LINQ?</a></p>
<pre><code>var query = context.log_sales
.GroupBy(c => c.OrderTime)
.Select(g => new
{
Date = g.Key,
Location1 = g.Where(c => c.Location == "Location1").Sum(c => c.Charge) ?? 0,
Location2 = g.Where(c => c.Location == "Location2").Sum(c => c.Charge) ?? 0
}).ToList();
</code></pre>
<p>and it is almost what I need. There should be grouping by year too and I don't know how to do this.</p>
|
[
{
"answer_id": 184032,
"author": "Amy B",
"author_id": 8155,
"author_profile": "https://Stackoverflow.com/users/8155",
"pm_score": 4,
"selected": true,
"text": "context.log_sales\n.GroupBy(s => new {Year = OrderTime.Year, Month = OrderTime.Month})\n.Select\n( g => new {\n Date = new DateTime(g.Key.Year, g.Key.Month, 1),\n Location1 = g.Where(s => s.Location == \"Location1\").Sum(s => s.Charge),\n Location2 = g.Where(s => s.Location == \"Location2\").Sum(s => s.Charge),\n Location3 = g.Where(s => s.Location == \"Location3\").Sum(s => s.Charge),\n }\n)\n.OrderBy(x => x.Date);\n"
}
] |
2008/10/08
|
[
"https://Stackoverflow.com/questions/183585",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23280/"
] |
183,589
|
<p>I'm currently in the process of writing my first Windows Forms application. I've read a few C# books now so I've got a relatively good understanding of what language features C# has to deal with exceptions. They're all quite theoretical however so what I haven't got yet is a feel for how to translate the basic concepts into a good exception-handling model in my application.</p>
<p>Would anyone like to share any pearls of wisdom on the subject? Post any common mistakes you've seen newbies like myself make, and any general advice on handling exceptions in a way that will my application more stable and robust.</p>
<p>The main things I'm currently trying to work out are: </p>
<ul>
<li>When should I re-throw an exception?</li>
<li>Should I try to have a central error-handling mechanism of some kind?</li>
<li>Do handling exceptions which might be thrown have a performance hit compared with pre-emptively testing things like whether a file on disk exists?</li>
<li>Should all executable code be enclosed in try-catch-finally blocks?</li>
<li>Are there any times when an empty catch block might be acceptable?</li>
</ul>
<p>All advice gratefully received!</p>
|
[
{
"answer_id": 183626,
"author": "Echostorm",
"author_id": 12862,
"author_profile": "https://Stackoverflow.com/users/12862",
"pm_score": 2,
"selected": false,
"text": "void Main()\n{\n try {\n DoStuff();\n }\n catch(Exception ex) {\n LogStuff(ex.ToString());\n }\n\nvoid DoStuff() {\n... Stuff ...\n}\n"
},
{
"answer_id": 183632,
"author": "itsmatt",
"author_id": 7862,
"author_profile": "https://Stackoverflow.com/users/7862",
"pm_score": 2,
"selected": false,
"text": "try\n{\n // some stuff is done here\n}\ncatch\n{\n}\n"
},
{
"answer_id": 183680,
"author": "John Rudy",
"author_id": 14048,
"author_profile": "https://Stackoverflow.com/users/14048",
"pm_score": 6,
"selected": false,
"text": "Main() System.Exception throw ex;\n throw;\n"
},
{
"answer_id": 183710,
"author": "Brad8118",
"author_id": 7617,
"author_profile": "https://Stackoverflow.com/users/7617",
"pm_score": 1,
"selected": false,
"text": "Try\n{\nint a = 10 / 0;\n}\ncatch(exception e){\n//error logging\nthrow;\n}\n catch(Exception e)\n// logging\nthrow e;\n}\n"
},
{
"answer_id": 184197,
"author": "Robert Rossney",
"author_id": 19403,
"author_profile": "https://Stackoverflow.com/users/19403",
"pm_score": 4,
"selected": false,
"text": "try\n{\n dict.Add(key, value);\n}\ncatch(KeyException)\n{\n}\n if (!dict.ContainsKey(key))\n{\n dict.Add(key, value);\n}\n"
},
{
"answer_id": 518025,
"author": "Jeff Keslinke",
"author_id": 40814,
"author_profile": "https://Stackoverflow.com/users/40814",
"pm_score": 1,
"selected": false,
"text": "try\n{\n/*Doing stuff that may cause an exception*/\nResponse.Redirect(\"http:\\\\www.somewhereelse.com\");\n}\ncatch (ThreadAbortException tex){/*Ignore*/}\ncatch (Exception ex){/*HandleException*/}\n"
},
{
"answer_id": 54201785,
"author": "Omid-RH",
"author_id": 560376,
"author_profile": "https://Stackoverflow.com/users/560376",
"pm_score": 2,
"selected": false,
"text": "using System.Threading;\n Application.ThreadException += new ThreadExceptionEventHandler(Application_ThreadException);\n static void Application_ThreadException(object sender, ThreadExceptionEventArgs e)\n{\n // Do logging or whatever here\n Application.Exit();\n}\n"
}
] |
2008/10/08
|
[
"https://Stackoverflow.com/questions/183589",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4019/"
] |
183,604
|
<p>Let's say I'm writing a Library application for a publishing company who already has a People application.</p>
<p>So in my Library application I have</p>
<pre><code>class Person < ActiveResource::Base
self.site = "http://api.people.mypublisher.com/"
end
</code></pre>
<p>and now I want to store <code>Article</code>s for each <code>Person</code>: </p>
<pre><code>class Article < ActiveRecord::Base
belongs_to :person, :as => :author
end
</code></pre>
<p>I imagine I'd have the following table in my database:</p>
<pre><code>Articles
id (PK) | title (string) | body (text) | author_id (integer)
</code></pre>
<p><code>author_id</code> isn't exactly a Foreign-Key, since I don't have a People table. That leaves several questions:</p>
<ol>
<li><p>how do I tell my <code>Person</code> <code>ActiveResource</code> object that it <code>has_many</code> <code>Articles</code>?</p></li>
<li><p>Will <code>Articles.find(:first).author</code> work? Will <code>belongs_to</code> even work given that there's no <code>ActiveRecord</code> and no backing table?</p></li>
</ol>
|
[
{
"answer_id": 183617,
"author": "James A. Rosen",
"author_id": 1190,
"author_profile": "https://Stackoverflow.com/users/1190",
"pm_score": 3,
"selected": false,
"text": "class Person < ActiveResource::Base\n self.site = \"http://api.people.mypublisher.com/\"\n\n def articles\n Article.find(:all, :conditions => { :person_id => self.id })\n end\n\n def add_article(article)\n article.person_id = self.id\n end\nend\n has_many"
},
{
"answer_id": 3507538,
"author": "dwaynemac",
"author_id": 89063,
"author_profile": "https://Stackoverflow.com/users/89063",
"pm_score": 0,
"selected": false,
"text": "class Person < ActiveResource::Base\n self.site = ..\n. \n def articles\n Article.for_person(self.id)\n end\nend\n\nclass Article < ActiveRecord::Base\n named_scope :for_person, lambda { |pid| { :conditions => { :person_id => pid }}}\nend\n"
}
] |
2008/10/08
|
[
"https://Stackoverflow.com/questions/183604",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1190/"
] |
183,606
|
<p>In the <a href="http://google-styleguide.googlecode.com/svn/trunk/cppguide.xml" rel="noreferrer">Google C++ Style Guide</a>, the <a href="http://google-styleguide.googlecode.com/svn/trunk/cppguide.xml#Operator_Overloading" rel="noreferrer">section on Operator Overloading</a> recommends against overloading <em>any</em> operators ("except in rare, special circumstances"). Specifically, it recommends:</p>
<blockquote>
<p>In particular, do not overload
<code>operator==</code> or <code>operator<</code> just so that
your class can be used as a key in an
STL container; instead, you should
create equality and comparison functor
types when declaring the container.</p>
</blockquote>
<p>I'm a little fuzzy on what such a functor would look like, but my main question is, <em>why</em> would you want to write your own functors for this? Wouldn't defining <code>operator<</code>, and using the standard <code>std::less<T></code> function, be simpler? Is there any advantage to using one over the other?</p>
|
[
{
"answer_id": 183653,
"author": "James Curran",
"author_id": 12725,
"author_profile": "https://Stackoverflow.com/users/12725",
"pm_score": 3,
"selected": false,
"text": "class MyClass {....}\n\nclass LessThanMyClass : std:binary_function<MyClass, MyClass, bool>\n{\n public bool operator()(MyClass lhs, MyClass rhs) \n { return /* determine if lhs < rhs */ ; }\n}\n\nvector<MyClass> objs;\nstd::sort(objs.begin(), objs.end(), LessThanMyClass());\n"
},
{
"answer_id": 183655,
"author": "Mark Ransom",
"author_id": 5987,
"author_profile": "https://Stackoverflow.com/users/5987",
"pm_score": 2,
"selected": false,
"text": "operator () bool class MyClass\n{\n struct LessThan : public std::binary_function<MyClass, MyClass, bool>\n {\n bool operator()(const MyClass & first, const MyClass & second) const\n {\n return first.key < second.key;\n }\n };\n};\n"
},
{
"answer_id": 183666,
"author": "Jim Buck",
"author_id": 2666,
"author_profile": "https://Stackoverflow.com/users/2666",
"pm_score": 1,
"selected": false,
"text": "operator ()"
},
{
"answer_id": 183678,
"author": "Konrad Rudolph",
"author_id": 1968,
"author_profile": "https://Stackoverflow.com/users/1968",
"pm_score": 5,
"selected": true,
"text": "operator < Passenger"
},
{
"answer_id": 183771,
"author": "Greg Rogers",
"author_id": 5963,
"author_profile": "https://Stackoverflow.com/users/5963",
"pm_score": 3,
"selected": false,
"text": "operator< class Person;\n\nstruct CompareByHeight {\n bool operator()(const Person &a, const Person &b);\n};\n\nstruct CompareByWeight {\n bool operator()(const Person &a, const Person &b);\n};\n operator< operator< CompareByHeight CompareByWeight"
},
{
"answer_id": 183809,
"author": "JohnMcG",
"author_id": 1674,
"author_profile": "https://Stackoverflow.com/users/1674",
"pm_score": 2,
"selected": false,
"text": "operator< operator== operator< operator<"
}
] |
2008/10/08
|
[
"https://Stackoverflow.com/questions/183606",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12193/"
] |
183,622
|
<p>I need to compare strings in shell:</p>
<pre><code>var1="mtu eth0"
if [ "$var1" == "mtu *" ]
then
# do something
fi
</code></pre>
<p>But obviously the "*" doesn't work in Shell. Is there a way to do it?</p>
|
[
{
"answer_id": 183647,
"author": "ephemient",
"author_id": 20713,
"author_profile": "https://Stackoverflow.com/users/20713",
"pm_score": 4,
"selected": true,
"text": "bash if [[ \"$var1\" = \"mtu \"* ]]\n [[ ]] [ ] bash --posix if [ \"${var1:0:4}\" == \"mtu \" ]\n ${var1:0:4} $var1 /bin/sh ${var1:0:4} if [ \"$(echo \"$var1\" | cut -c0-4)\" == \"mtu \" ]\n"
},
{
"answer_id": 183650,
"author": "mstrobl",
"author_id": 25965,
"author_profile": "https://Stackoverflow.com/users/25965",
"pm_score": 4,
"selected": false,
"text": "cut if [ \"$(echo $var1 | cut -c 4)\" = \"mtu \" ];\n"
},
{
"answer_id": 183654,
"author": "ayaz",
"author_id": 23191,
"author_profile": "https://Stackoverflow.com/users/23191",
"pm_score": -1,
"selected": false,
"text": "if [[ \"$var1\" =~ \"mtu *\" ]]\n"
},
{
"answer_id": 183707,
"author": "hasseg",
"author_id": 4111,
"author_profile": "https://Stackoverflow.com/users/4111",
"pm_score": 3,
"selected": false,
"text": "expr #!/bin/sh\n\nvar1=\"mtu eth0\"\n\nif [ \"`expr \\\"$var1\\\" : \\\"mtu .*\\\"`\" != \"0\" ];then\n echo \"match\"\nfi\n"
},
{
"answer_id": 184956,
"author": "ADEpt",
"author_id": 10105,
"author_profile": "https://Stackoverflow.com/users/10105",
"pm_score": 2,
"selected": false,
"text": "# Removes anything but first word from \"var1\"\nif [ \"${var1%% *}\" = \"mtu\" ] ; then ... fi\n # Tries to remove the first word if it is \"mtu\", checks if we removed anything\nif [ \"${var1#mtu }\" != \"$var1\" ] ; then ... fi\n"
},
{
"answer_id": 1663007,
"author": "chris",
"author_id": 201148,
"author_profile": "https://Stackoverflow.com/users/201148",
"pm_score": 2,
"selected": false,
"text": "case \"$input\"\nin\n \"$variable1\") echo \"matched the first value\" \n ;;\n \"$variable2\") echo \"matched the second value\"\n ;;\n *[a-z]*) echo \"input has letters\" \n ;;\n '') echo \"input is null!\"\n ;;\n *[0-9]*) echo \"matched numbers (but I don't have letters, otherwise the letter test would have been hit first!)\"\n ;;\n *) echo \"Some wacky stuff in the input!\"\nesac\n case \"$(cat file)\"\nin\n \"$(cat other_file)\") echo \"file and other_file are the same\"\n ;;\n *) echo \"file and other_file are different\"\nesac\n"
},
{
"answer_id": 2225794,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "if [ `echo ${String} | grep -c ${Substr} ` -eq 1 ] ; then\n echo ${String} | grep -c ${Substr} ` if [ `echo ${String} | grep -c \"^${Substr}\"` -eq 1 ] ; then\n...\nif [ `echo ${String} | grep -c \"${Substr}$\"` -eq 1 ] ; then\n"
}
] |
2008/10/08
|
[
"https://Stackoverflow.com/questions/183622",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23420/"
] |
183,636
|
<p>Is there a way to select manually a node in virtualizing TreeView and then bring it into view?</p>
<p>The data model I'm using with my TreeView is implemented based on the VM-M-V model. Each TreeViewItem's IsSelected property is binded to a corresponing property in ViewModel. I've also created a listener for TreeView's ItemSelected event where I call BringIntoView() for the selected TreeViewItem.</p>
<p>The problem with this approach seems to be that the ItemSelected event won't be raised until the actual TreeViewItem is created. So with the virtualization enabled node selection won't do anything until the TreeView is scrolled enough and then it jumps "magically" to the selected node when the event is finally raised.</p>
<p>I'd really like to use virtualization because I have thousands of nodes in my tree and I've already seen quite impressive performance improvements when the virtualization has been enabled. </p>
|
[
{
"answer_id": 183687,
"author": "Micah",
"author_id": 17744,
"author_profile": "https://Stackoverflow.com/users/17744",
"pm_score": 0,
"selected": false,
"text": " {\n\n Dispatcher.BeginInvoke(System.Windows.Threading.DispatcherPriority.Background,\n\n (System.Windows.Threading.DispatcherOperationCallback)delegate(object arg)\n\n {\n\n int N = fileList.Items.Count;\n\n if (N == 0)\n\n return null;\n\n if (index < 0)\n\n {\n\n fileList.ScrollIntoView(fileList.Items[0]); // scroll to first\n\n }\n\n else\n\n {\n\n if (index < N)\n\n {\n\n fileList.ScrollIntoView(fileList.Items[index]); // scroll to item\n\n }\n\n else\n\n {\n\n fileList.ScrollIntoView(fileList.Items[N - 1]); // scroll to last\n\n }\n\n }\n\n return null;\n\n }, null);\n\n }\n"
},
{
"answer_id": 1722804,
"author": "user88520",
"author_id": 88520,
"author_profile": "https://Stackoverflow.com/users/88520",
"pm_score": 1,
"selected": false,
"text": "public class TreeViewItemBehaviour\n{\n #region IsBroughtIntoViewWhenSelected\n\n public static bool GetIsBroughtIntoViewWhenSelected(TreeViewItem treeViewItem)\n {\n return (bool)treeViewItem.GetValue(IsBroughtIntoViewWhenSelectedProperty);\n }\n\n public static void SetIsBroughtIntoViewWhenSelected(\n TreeViewItem treeViewItem, bool value)\n {\n treeViewItem.SetValue(IsBroughtIntoViewWhenSelectedProperty, value);\n }\n\n public static readonly DependencyProperty IsBroughtIntoViewWhenSelectedProperty =\n DependencyProperty.RegisterAttached(\n \"IsBroughtIntoViewWhenSelected\",\n typeof(bool),\n typeof(TreeViewItemBehaviour),\n new UIPropertyMetadata(false, OnIsBroughtIntoViewWhenSelectedChanged));\n\n static void OnIsBroughtIntoViewWhenSelectedChanged(\n DependencyObject depObj, DependencyPropertyChangedEventArgs e)\n {\n TreeViewItem item = depObj as TreeViewItem;\n if (item == null)\n return;\n\n if (e.NewValue is bool == false)\n return;\n\n if ((bool)e.NewValue)\n {\n item.Loaded += item_Loaded;\n }\n else\n {\n item.Loaded -= item_Loaded;\n }\n }\n\n static void item_Loaded(object sender, RoutedEventArgs e)\n {\n TreeViewItem item = e.OriginalSource as TreeViewItem;\n if (item != null)\n item.BringIntoView();\n }\n\n #endregion // IsBroughtIntoViewWhenSelected\n\n}\n <Setter Property=\"Behaviours:TreeViewItemBehaviour.IsBroughtIntoViewWhenSelected\" Value=\"True\" />\n"
},
{
"answer_id": 9206992,
"author": "splintor",
"author_id": 46635,
"author_profile": "https://Stackoverflow.com/users/46635",
"pm_score": 4,
"selected": false,
"text": "Node Parent public class Node\n{\n public Node Parent { get; set; }\n}\n using System;\nusing System.Collections.Generic;\nusing System.Diagnostics;\nusing System.Reflection;\nusing System.Windows;\nusing System.Windows.Controls;\nusing System.Windows.Interactivity;\n\npublic class NodeTreeSelectionBehavior : Behavior<TreeView>\n{\n public Node SelectedItem\n {\n get { return (Node)GetValue(SelectedItemProperty); }\n set { SetValue(SelectedItemProperty, value); }\n }\n\n public static readonly DependencyProperty SelectedItemProperty =\n DependencyProperty.Register(\"SelectedItem\", typeof(Node), typeof(NodeTreeSelectionBehavior),\n new FrameworkPropertyMetadata(null, FrameworkPropertyMetadataOptions.BindsTwoWayByDefault, OnSelectedItemChanged));\n\n private static void OnSelectedItemChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)\n {\n var newNode = e.NewValue as Node;\n if (newNode == null) return;\n var behavior = (NodeTreeSelectionBehavior)d;\n var tree = behavior.AssociatedObject;\n\n var nodeDynasty = new List<Node> { newNode };\n var parent = newNode.Parent;\n while (parent != null)\n {\n nodeDynasty.Insert(0, parent);\n parent = parent.Parent;\n }\n\n var currentParent = tree as ItemsControl;\n foreach (var node in nodeDynasty)\n {\n // first try the easy way\n var newParent = currentParent.ItemContainerGenerator.ContainerFromItem(node) as TreeViewItem;\n if (newParent == null)\n {\n // if this failed, it's probably because of virtualization, and we will have to do it the hard way.\n // this code is influenced by TreeViewItem.ExpandRecursive decompiled code, and the MSDN sample at http://code.msdn.microsoft.com/Changing-selection-in-a-6a6242c8/sourcecode?fileId=18862&pathId=753647475\n // see also the question at http://stackoverflow.com/q/183636/46635\n currentParent.ApplyTemplate();\n var itemsPresenter = (ItemsPresenter)currentParent.Template.FindName(\"ItemsHost\", currentParent);\n if (itemsPresenter != null)\n {\n itemsPresenter.ApplyTemplate();\n }\n else\n {\n currentParent.UpdateLayout();\n }\n\n var virtualizingPanel = GetItemsHost(currentParent) as VirtualizingPanel;\n CallEnsureGenerator(virtualizingPanel);\n var index = currentParent.Items.IndexOf(node);\n if (index < 0)\n {\n throw new InvalidOperationException(\"Node '\" + node + \"' cannot be fount in container\");\n }\n CallBringIndexIntoView(virtualizingPanel, index);\n newParent = currentParent.ItemContainerGenerator.ContainerFromIndex(index) as TreeViewItem;\n }\n\n if (newParent == null)\n {\n throw new InvalidOperationException(\"Tree view item cannot be found or created for node '\" + node + \"'\");\n }\n\n if (node == newNode)\n {\n newParent.IsSelected = true;\n newParent.BringIntoView();\n break;\n }\n\n newParent.IsExpanded = true;\n currentParent = newParent;\n }\n }\n\n protected override void OnAttached()\n {\n base.OnAttached();\n AssociatedObject.SelectedItemChanged += OnTreeViewSelectedItemChanged;\n }\n\n protected override void OnDetaching()\n {\n base.OnDetaching();\n AssociatedObject.SelectedItemChanged -= OnTreeViewSelectedItemChanged;\n }\n\n private void OnTreeViewSelectedItemChanged(object sender, RoutedPropertyChangedEventArgs<object> e)\n {\n SelectedItem = e.NewValue as Node;\n }\n\n #region Functions to get internal members using reflection\n\n // Some functionality we need is hidden in internal members, so we use reflection to get them\n\n #region ItemsControl.ItemsHost\n\n static readonly PropertyInfo ItemsHostPropertyInfo = typeof(ItemsControl).GetProperty(\"ItemsHost\", BindingFlags.Instance | BindingFlags.NonPublic);\n\n private static Panel GetItemsHost(ItemsControl itemsControl)\n {\n Debug.Assert(itemsControl != null);\n return ItemsHostPropertyInfo.GetValue(itemsControl, null) as Panel;\n }\n\n #endregion ItemsControl.ItemsHost\n\n #region Panel.EnsureGenerator\n\n private static readonly MethodInfo EnsureGeneratorMethodInfo = typeof(Panel).GetMethod(\"EnsureGenerator\", BindingFlags.Instance | BindingFlags.NonPublic);\n\n private static void CallEnsureGenerator(Panel panel)\n {\n Debug.Assert(panel != null);\n EnsureGeneratorMethodInfo.Invoke(panel, null);\n }\n\n #endregion Panel.EnsureGenerator\n\n #region VirtualizingPanel.BringIndexIntoView\n\n private static readonly MethodInfo BringIndexIntoViewMethodInfo = typeof(VirtualizingPanel).GetMethod(\"BringIndexIntoView\", BindingFlags.Instance | BindingFlags.NonPublic);\n\n private static void CallBringIndexIntoView(VirtualizingPanel virtualizingPanel, int index)\n {\n Debug.Assert(virtualizingPanel != null);\n BringIndexIntoViewMethodInfo.Invoke(virtualizingPanel, new object[] { index });\n }\n\n #endregion VirtualizingPanel.BringIndexIntoView\n\n #endregion Functions to get internal members using reflection\n}\n <UserControl xmlns=\"http://schemas.microsoft.com/winfx/2006/xaml/presentation\"\n xmlns:i=\"clr-namespace:System.Windows.Interactivity;assembly=System.Windows.Interactivity\"\n xmlns:local=\"clr-namespace:MyProject\">\n <Grid>\n <TreeView ItemsSource=\"{Binding MyItems}\"\n ScrollViewer.CanContentScroll=\"True\"\n VirtualizingStackPanel.IsVirtualizing=\"True\"\n VirtualizingStackPanel.VirtualizationMode=\"Recycling\">\n <i:Interaction.Behaviors>\n <local:NodeTreeSelectionBehavior SelectedItem=\"{Binding MySelectedItem}\" />\n </i:Interaction.Behaviors>\n </TreeView>\n <Grid>\n<UserControl>\n"
},
{
"answer_id": 17883600,
"author": "Heiner",
"author_id": 495910,
"author_profile": "https://Stackoverflow.com/users/495910",
"pm_score": 2,
"selected": false,
"text": "TreeView TreeViewItem VirtualizingStackPanel ITreeItem public interface ITreeItem {\n ITreeItem Parent { get; }\n IList<ITreeItem> Children { get; }\n bool IsSelected { get; set; }\n bool IsExpanded { get; set; }\n}\n IsSelected BringItemIntoView TreeView TreeView TreeViewItems public class SelectableVirtualizingTreeView : TreeView {\n public SelectableVirtualizingTreeView() {\n VirtualizingStackPanel.SetIsVirtualizing(this, true);\n VirtualizingStackPanel.SetVirtualizationMode(this, VirtualizationMode.Recycling);\n var panelfactory = new FrameworkElementFactory(typeof(SelectableVirtualizingStackPanel));\n panelfactory.SetValue(Panel.IsItemsHostProperty, true);\n var template = new ItemsPanelTemplate { VisualTree = panelfactory };\n ItemsPanel = template;\n }\n\n public void BringItemIntoView(ITreeItem treeItemViewModel) {\n if (treeItemViewModel == null) {\n return;\n }\n var stack = new Stack<ITreeItem>();\n stack.Push(treeItemViewModel);\n while (treeItemViewModel.Parent != null) {\n stack.Push(treeItemViewModel.Parent);\n treeItemViewModel = treeItemViewModel.Parent;\n }\n ItemsControl containerControl = this;\n while (stack.Count > 0) {\n var viewModel = stack.Pop();\n var treeViewItem = containerControl.ItemContainerGenerator.ContainerFromItem(viewModel);\n var virtualizingPanel = FindVisualChild<SelectableVirtualizingStackPanel>(containerControl);\n if (virtualizingPanel != null) {\n var index = viewModel.Parent != null ? viewModel.Parent.Children.IndexOf(viewModel) : Items.IndexOf(treeViewItem);\n virtualizingPanel.BringIntoView(index);\n Focus();\n }\n containerControl = (ItemsControl)treeViewItem;\n }\n }\n\n protected override DependencyObject GetContainerForItemOverride() {\n return new SelectableVirtualizingTreeViewItem();\n }\n\n protected override void PrepareContainerForItemOverride(DependencyObject element, object item) {\n base.PrepareContainerForItemOverride(element, item);\n ((TreeViewItem)element).IsExpanded = true;\n }\n\n private static T FindVisualChild<T>(Visual visual) where T : Visual {\n for (var i = 0; i < VisualTreeHelper.GetChildrenCount(visual); i++) {\n var child = (Visual)VisualTreeHelper.GetChild(visual, i);\n if (child == null) {\n continue;\n }\n var correctlyTyped = child as T;\n if (correctlyTyped != null) {\n return correctlyTyped;\n }\n var descendent = FindVisualChild<T>(child);\n if (descendent != null) {\n return descendent;\n }\n }\n return null;\n }\n}\n\npublic class SelectableVirtualizingTreeViewItem : TreeViewItem {\n public SelectableVirtualizingTreeViewItem() {\n var panelfactory = new FrameworkElementFactory(typeof(SelectableVirtualizingStackPanel));\n panelfactory.SetValue(Panel.IsItemsHostProperty, true);\n var template = new ItemsPanelTemplate { VisualTree = panelfactory };\n ItemsPanel = template;\n SetBinding(IsSelectedProperty, new Binding(\"IsSelected\"));\n SetBinding(IsExpandedProperty, new Binding(\"IsExpanded\"));\n }\n\n protected override DependencyObject GetContainerForItemOverride() {\n return new SelectableVirtualizingTreeViewItem();\n }\n\n protected override void PrepareContainerForItemOverride(DependencyObject element, object item) {\n base.PrepareContainerForItemOverride(element, item);\n ((TreeViewItem)element).IsExpanded = true;\n }\n}\n\npublic class SelectableVirtualizingStackPanel : VirtualizingStackPanel {\n public void BringIntoView(int index) {\n if (index < 0) {\n return;\n }\n BringIndexIntoView(index);\n }\n}\n\npublic abstract class TreeItemBase : ITreeItem {\n protected TreeItemBase() {\n Children = new ObservableCollection<ITreeItem>();\n }\n\n public ITreeItem Parent { get; protected set; }\n\n public IList<ITreeItem> Children { get; protected set; }\n\n public abstract bool IsSelected { get; set; }\n\n public abstract bool IsExpanded { get; set; }\n\n public event EventHandler DescendantSelected;\n\n protected void RaiseDescendantSelected(TreeItemViewModel newItem) {\n if (Parent != null) {\n ((TreeItemViewModel)Parent).RaiseDescendantSelected(newItem);\n } else {\n var handler = DescendantSelected;\n if (handler != null) {\n handler.Invoke(newItem, EventArgs.Empty);\n }\n }\n }\n}\n\npublic class MainViewModel : INotifyPropertyChanged {\n private TreeItemViewModel _selectedItem;\n\n public MainViewModel() {\n TreeItemViewModels = new List<TreeItemViewModel> { new TreeItemViewModel { Name = \"Item\" } };\n for (var i = 0; i < 30; i++) {\n TreeItemViewModels[0].AddChildInitial();\n }\n TreeItemViewModels[0].IsSelected = true;\n TreeItemViewModels[0].DescendantSelected += OnDescendantSelected;\n }\n\n public event EventHandler DescendantSelected;\n\n public event PropertyChangedEventHandler PropertyChanged;\n\n public List<TreeItemViewModel> TreeItemViewModels { get; private set; }\n\n public TreeItemViewModel SelectedItem {\n get {\n return _selectedItem;\n }\n set {\n if (_selectedItem == value) {\n return;\n }\n _selectedItem = value;\n var handler = PropertyChanged;\n if (handler != null) {\n handler.Invoke(this, new PropertyChangedEventArgs(\"SelectedItem\"));\n }\n }\n }\n\n private void OnDescendantSelected(object sender, EventArgs eventArgs) {\n var handler = DescendantSelected;\n if (handler != null) {\n handler.Invoke(sender, eventArgs);\n }\n }\n}\n\npublic partial class MainWindow {\n public MainWindow() {\n InitializeComponent();\n var mainViewModel = (MainViewModel)DataContext;\n mainViewModel.DescendantSelected += OnMainViewModelDescendantSelected;\n }\n\n private void OnAddButtonClick(object sender, RoutedEventArgs e) {\n var mainViewModel = (MainViewModel)DataContext;\n var treeItemViewModel = mainViewModel.SelectedItem;\n if (treeItemViewModel != null) {\n treeItemViewModel.AddChild();\n }\n }\n\n private void OnMainViewModelDescendantSelected(object sender, EventArgs eventArgs) {\n _treeView.BringItemIntoView(sender as TreeItemViewModel);\n }\n\n private void OnTreeViewSelectedItemChanged(object sender, RoutedPropertyChangedEventArgs<object> e) {\n if (e.OldValue == e.NewValue) {\n return;\n }\n var treeView = (TreeView)sender;\n var treeItemviewModel = treeView.SelectedItem as TreeItemViewModel;\n var mainViewModel = (MainViewModel)DataContext;\n mainViewModel.SelectedItem = treeItemviewModel;\n }\n}\n <controls:SelectableVirtualizingTreeView x:Name=\"_treeView\" ItemsSource=\"{Binding TreeItemViewModels}\" Margin=\"8\" \n SelectedItemChanged=\"OnTreeViewSelectedItemChanged\">\n <controls:SelectableVirtualizingTreeView.ItemTemplate>\n <HierarchicalDataTemplate ... />\n </controls:SelectableVirtualizingTreeView.ItemTemplate>\n</controls:SelectableVirtualizingTreeView>\n"
},
{
"answer_id": 52218467,
"author": "Бадалов Бадал",
"author_id": 8559138,
"author_profile": "https://Stackoverflow.com/users/8559138",
"pm_score": 1,
"selected": false,
"text": " newParent = currentParent.ItemContainerGenerator.ContainerFromIndex(index) as TreeViewItem;\n if (newParent == null)\n {\n currentParent.UpdateLayout();\n virtualizingPanel.BringIndexIntoViewPublic(index);\n newParent = currentParent.ItemContainerGenerator.ContainerFromIndex(index) as TreeViewItem;\n }\n using System;\nusing System.Collections.Generic;\nusing System.Diagnostics;\nusing System.Reflection;\nusing System.Windows;\nusing System.Windows.Controls;\nusing System.Windows.Interactivity;\n\npublic class NodeTreeSelectionBehavior : Behavior<TreeView>\n{\n public INode SelectedItem\n {\n get { return (INode)GetValue(SelectedItemProperty); }\n set { SetValue(SelectedItemProperty, value); }\n }\n\n public static readonly DependencyProperty SelectedItemProperty =\n DependencyProperty.Register(\"SelectedItem\", typeof(Node), typeof(NodeTreeSelectionBehavior),\n new FrameworkPropertyMetadata(null, FrameworkPropertyMetadataOptions.BindsTwoWayByDefault, OnSelectedItemChanged));\n\n private static void OnSelectedItemChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)\n {\n var newNode = e.NewValue as INode;\n if (newNode == null) return;\n var behavior = (NodeTreeSelectionBehavior)d;\n var tree = behavior.AssociatedObject;\n\n var nodeDynasty = new List<INode> { newNode };\n var parent = newNode.Parent;\n while (parent != null)\n {\n nodeDynasty.Insert(0, parent);\n parent = parent.Parent;\n }\n\n var currentParent = tree as ItemsControl;\n foreach (var node in nodeDynasty)\n {\n // first try the easy way\n var newParent = currentParent.ItemContainerGenerator.ContainerFromItem(node) as TreeViewItem;\n var index = 0;\n VirtualizingPanel virtualizingPanel = null;\n if (newParent == null)\n {\n // if this failed, it's probably because of virtualization, and we will have to do it the hard way.\n // this code is influenced by TreeViewItem.ExpandRecursive decompiled code, and the MSDN sample at http://code.msdn.microsoft.com/Changing-selection-in-a-6a6242c8/sourcecode?fileId=18862&pathId=753647475\n // see also the question at http://stackoverflow.com/q/183636/46635\n currentParent.ApplyTemplate();\n var itemsPresenter = (ItemsPresenter)currentParent.Template.FindName(\"ItemsHost\", currentParent);\n if (itemsPresenter != null)\n {\n itemsPresenter.ApplyTemplate();\n }\n else\n {\n currentParent.UpdateLayout();\n }\n\n virtualizingPanel = GetItemsHost(currentParent) as VirtualizingPanel;\n CallEnsureGenerator(virtualizingPanel);\n index = currentParent.Items.IndexOf(node);\n if (index < 0)\n {\n throw new InvalidOperationException(\"Node '\" + node + \"' cannot be fount in container\");\n }\n if (virtualizingPanel != null)\n {\n virtualizingPanel.BringIndexIntoViewPublic(index);\n }\n newParent = currentParent.ItemContainerGenerator.ContainerFromIndex(index) as TreeViewItem;\n if (newParent == null)\n {\n currentParent.UpdateLayout();\n virtualizingPanel.BringIndexIntoViewPublic(index);\n newParent = currentParent.ItemContainerGenerator.ContainerFromIndex(index) as TreeViewItem;\n }\n }\n\n if (newParent == null)\n {\n throw new InvalidOperationException(\"Tree view item cannot be found or created for node '\" + node + \"'\");\n }\n\n if (node == newNode)\n {\n newParent.IsSelected = true;\n newParent.BringIntoView();\n break;\n }\n\n newParent.IsExpanded = true;\n currentParent = newParent;\n }\n }\n\n protected override void OnAttached()\n {\n base.OnAttached();\n AssociatedObject.SelectedItemChanged += OnTreeViewSelectedItemChanged;\n }\n\n protected override void OnDetaching()\n {\n base.OnDetaching();\n AssociatedObject.SelectedItemChanged -= OnTreeViewSelectedItemChanged;\n }\n\n private void OnTreeViewSelectedItemChanged(object sender, RoutedPropertyChangedEventArgs<object> e)\n {\n SelectedItem = e.NewValue as INode;\n }\n\n #region Functions to get internal members using reflection\n\n // Some functionality we need is hidden in internal members, so we use reflection to get them\n\n #region ItemsControl.ItemsHost\n\n static readonly PropertyInfo ItemsHostPropertyInfo = typeof(ItemsControl).GetProperty(\"ItemsHost\", BindingFlags.Instance | BindingFlags.NonPublic);\n\n private static Panel GetItemsHost(ItemsControl itemsControl)\n {\n Debug.Assert(itemsControl != null);\n return ItemsHostPropertyInfo.GetValue(itemsControl, null) as Panel;\n }\n\n #endregion ItemsControl.ItemsHost\n\n #region Panel.EnsureGenerator\n\n private static readonly MethodInfo EnsureGeneratorMethodInfo = typeof(Panel).GetMethod(\"EnsureGenerator\", BindingFlags.Instance | BindingFlags.NonPublic);\n\n private static void CallEnsureGenerator(Panel panel)\n {\n Debug.Assert(panel != null);\n EnsureGeneratorMethodInfo.Invoke(panel, null);\n }\n\n #endregion Panel.EnsureGenerator\n\n #endregion Functions to get internal members using reflection\n}\n <UserControl xmlns=\"http://schemas.microsoft.com/winfx/2006/xaml/presentation\"\n xmlns:i=\"clr-namespace:System.Windows.Interactivity;assembly=System.Windows.Interactivity\"\n xmlns:local=\"clr-namespace:MyProject\">\n<Grid>\n <TreeView ItemsSource=\"{Binding MyItems}\"\n ScrollViewer.CanContentScroll=\"True\"\n VirtualizingStackPanel.IsVirtualizing=\"True\"\n VirtualizingStackPanel.VirtualizationMode=\"Recycling\">\n <i:Interaction.Behaviors>\n <local:NodeTreeSelectionBehavior SelectedItem=\"{Binding MySelectedItem}\" />\n </i:Interaction.Behaviors>\n </TreeView>\n<Grid>\n"
},
{
"answer_id": 52218926,
"author": "Peregrine",
"author_id": 967885,
"author_profile": "https://Stackoverflow.com/users/967885",
"pm_score": 0,
"selected": false,
"text": "public class perTreeViewHelper : Behavior<TreeView>\n{\n public object BoundSelectedItem\n {\n get { return GetValue(BoundSelectedItemProperty); }\n set { SetValue(BoundSelectedItemProperty, value); }\n }\n\n public static readonly DependencyProperty BoundSelectedItemProperty =\n DependencyProperty.Register(\"BoundSelectedItem\",\n typeof(object),\n typeof(perTreeViewHelper),\n new FrameworkPropertyMetadata(null,\n FrameworkPropertyMetadataOptions.BindsTwoWayByDefault,\n OnBoundSelectedItemChanged));\n\n private static void OnBoundSelectedItemChanged(DependencyObject obj, DependencyPropertyChangedEventArgs args)\n {\n var item = args.NewValue as perTreeViewItemViewModelBase;\n\n if (item != null)\n item.IsSelected = true;\n }\n\n protected override void OnAttached()\n {\n base.OnAttached();\n AssociatedObject.SelectedItemChanged += OnTreeViewSelectedItemChanged;\n }\n\n protected override void OnDetaching()\n {\n AssociatedObject.SelectedItemChanged -= OnTreeViewSelectedItemChanged;\n base.OnDetaching();\n }\n\n private void OnTreeViewSelectedItemChanged(object obj, RoutedPropertyChangedEventArgs<object> args)\n {\n BoundSelectedItem = args.NewValue;\n }\n}\n public static class perTreeViewItemHelper\n{\n public static bool GetBringSelectedItemIntoView(TreeViewItem treeViewItem)\n {\n return (bool)treeViewItem.GetValue(BringSelectedItemIntoViewProperty);\n }\n\n public static void SetBringSelectedItemIntoView(TreeViewItem treeViewItem, bool value)\n {\n treeViewItem.SetValue(BringSelectedItemIntoViewProperty, value);\n }\n\n public static readonly DependencyProperty BringSelectedItemIntoViewProperty =\n DependencyProperty.RegisterAttached(\n \"BringSelectedItemIntoView\",\n typeof(bool),\n typeof(perTreeViewItemHelper),\n new UIPropertyMetadata(false, BringSelectedItemIntoViewChanged));\n\n private static void BringSelectedItemIntoViewChanged(DependencyObject obj, DependencyPropertyChangedEventArgs args)\n {\n if (!(args.NewValue is bool))\n return;\n\n var item = obj as TreeViewItem;\n\n if (item == null)\n return;\n\n if ((bool)args.NewValue)\n item.Selected += OnTreeViewItemSelected;\n else\n item.Selected -= OnTreeViewItemSelected;\n }\n\n private static void OnTreeViewItemSelected(object sender, RoutedEventArgs e)\n {\n var item = e.OriginalSource as TreeViewItem;\n item?.BringIntoView();\n\n // prevent this event bubbling up to any parent nodes\n e.Handled = true;\n }\n\n public static bool GetBringExpandedChildrenIntoView(TreeViewItem treeViewItem)\n {\n return (bool)treeViewItem.GetValue(BringExpandedChildrenIntoViewProperty);\n }\n\n public static void SetBringExpandedChildrenIntoView(TreeViewItem treeViewItem, bool value)\n {\n treeViewItem.SetValue(BringExpandedChildrenIntoViewProperty, value);\n }\n\n public static readonly DependencyProperty BringExpandedChildrenIntoViewProperty =\n DependencyProperty.RegisterAttached(\n \"BringExpandedChildrenIntoView\",\n typeof(bool),\n typeof(perTreeViewItemHelper),\n new UIPropertyMetadata(false, BringExpandedChildrenIntoViewChanged));\n\n private static void BringExpandedChildrenIntoViewChanged(DependencyObject obj, DependencyPropertyChangedEventArgs args)\n {\n if (!(args.NewValue is bool))\n return;\n\n var item = obj as TreeViewItem;\n\n if (item == null)\n return;\n\n if ((bool)args.NewValue)\n item.Expanded += OnTreeViewItemExpanded;\n else\n item.Expanded -= OnTreeViewItemExpanded;\n }\n\n private static void OnTreeViewItemExpanded(object sender, RoutedEventArgs e)\n {\n var item = e.OriginalSource as TreeViewItem;\n\n if (item == null)\n return;\n\n // use DispatcherPriority.ContextIdle, so that we wait for all of the UI elements for any newly visible children to be created\n\n // first bring the last child into view\n Action action = () =>\n {\n var lastChild = item.ItemContainerGenerator.ContainerFromIndex(item.Items.Count - 1) as TreeViewItem;\n lastChild?.BringIntoView();\n };\n\n item.Dispatcher.BeginInvoke(action, DispatcherPriority.ContextIdle);\n\n // then bring the expanded item (back) into view\n action = () => { item.BringIntoView(); };\n item.Dispatcher.BeginInvoke(action, DispatcherPriority.ContextIdle);\n\n // prevent this event bubbling up to any parent nodes\n e.Handled = true;\n }\n}\n <Style x:Key=\"perExpandCollapseToggleStyle\" TargetType=\"ToggleButton\">\n <Setter Property=\"Focusable\" Value=\"False\" />\n <Setter Property=\"Template\">\n <Setter.Value>\n <ControlTemplate TargetType=\"ToggleButton\">\n <Grid Width=\"10\"\n Height=\"10\"\n Background=\"Transparent\">\n <Path x:Name=\"ExpanderGlyph\"\n Margin=\"1\"\n HorizontalAlignment=\"Left\"\n VerticalAlignment=\"Center\"\n Data=\"M 0,3 L 0,5 L 3,5 L 3,8 L 5,8 L 5,5 L 8,5 L 8,3 L 5,3 L 5,0 L 3,0 L 3,3 z\"\n Fill=\"LightGreen\"\n Stretch=\"None\" />\n </Grid>\n\n <ControlTemplate.Triggers>\n <Trigger Property=\"IsChecked\" Value=\"True\">\n <Setter TargetName=\"ExpanderGlyph\" Property=\"Data\" Value=\"M 0,0 M 8,8 M 0,3 L 0,5 L 8,5 L 8,3 z\" />\n <Setter TargetName=\"ExpanderGlyph\" Property=\"Fill\" Value=\"Red\" />\n </Trigger>\n\n <Trigger Property=\"IsEnabled\" Value=\"False\">\n <Setter TargetName=\"ExpanderGlyph\" Property=\"Fill\" Value=\"{DynamicResource {x:Static SystemColors.GrayTextBrushKey}}\" />\n </Trigger>\n </ControlTemplate.Triggers>\n </ControlTemplate>\n </Setter.Value>\n </Setter>\n</Style>\n\n<Style x:Key=\"perTreeViewItemContainerStyle\"\n TargetType=\"{x:Type TreeViewItem}\">\n\n <!-- Link the properties of perTreeViewItemViewModelBase to the corresponding ones on the TreeViewItem -->\n <Setter Property=\"IsExpanded\" Value=\"{Binding IsExpanded, Mode=TwoWay}\" />\n <Setter Property=\"IsSelected\" Value=\"{Binding IsSelected, Mode=TwoWay}\" />\n <Setter Property=\"IsEnabled\" Value=\"{Binding IsEnabled}\" />\n\n <!-- Include the two \"Scroll into View\" behaviors -->\n <Setter Property=\"vhelp:perTreeViewItemHelper.BringSelectedItemIntoView\" Value=\"True\" />\n <Setter Property=\"vhelp:perTreeViewItemHelper.BringExpandedChildrenIntoView\" Value=\"True\" />\n\n <Setter Property=\"Template\">\n <Setter.Value>\n <ControlTemplate TargetType=\"{x:Type TreeViewItem}\">\n <Grid>\n <Grid.ColumnDefinitions>\n <ColumnDefinition Width=\"Auto\"\n MinWidth=\"14\" />\n <ColumnDefinition Width=\"*\" />\n </Grid.ColumnDefinitions>\n <Grid.RowDefinitions>\n <RowDefinition Height=\"Auto\" />\n <RowDefinition Height=\"*\" />\n </Grid.RowDefinitions>\n <ToggleButton x:Name=\"Expander\"\n Grid.Row=\"0\"\n Grid.Column=\"0\"\n ClickMode=\"Press\"\n IsChecked=\"{Binding Path=IsExpanded, RelativeSource={RelativeSource TemplatedParent}}\"\n Style=\"{StaticResource perExpandCollapseToggleStyle}\" />\n\n <Border x:Name=\"PART_Border\"\n Grid.Row=\"0\"\n Grid.Column=\"1\"\n Padding=\"{TemplateBinding Padding}\"\n Background=\"{TemplateBinding Background}\"\n BorderBrush=\"{TemplateBinding BorderBrush}\"\n BorderThickness=\"{TemplateBinding BorderThickness}\">\n\n <ContentPresenter x:Name=\"PART_Header\"\n Margin=\"0,2\"\n HorizontalAlignment=\"{TemplateBinding HorizontalContentAlignment}\"\n ContentSource=\"Header\" />\n\n </Border>\n\n <ItemsPresenter x:Name=\"ItemsHost\"\n Grid.Row=\"1\"\n Grid.Column=\"1\" />\n </Grid>\n\n <ControlTemplate.Triggers>\n <Trigger Property=\"IsExpanded\" Value=\"false\">\n <Setter TargetName=\"ItemsHost\" Property=\"Visibility\" Value=\"Collapsed\" />\n </Trigger>\n\n <Trigger Property=\"HasItems\" Value=\"false\">\n <Setter TargetName=\"Expander\" Property=\"Visibility\" Value=\"Hidden\" />\n </Trigger>\n\n <!-- Use the same colors for a selected item, whether the TreeView is focussed or not -->\n <Trigger Property=\"IsSelected\" Value=\"true\">\n <Setter TargetName=\"PART_Border\" Property=\"Background\" Value=\"{DynamicResource {x:Static SystemColors.HighlightBrushKey}}\" />\n <Setter Property=\"Foreground\" Value=\"{DynamicResource {x:Static SystemColors.HighlightTextBrushKey}}\" />\n </Trigger>\n\n <Trigger Property=\"IsEnabled\" Value=\"false\">\n <Setter Property=\"Foreground\" Value=\"{DynamicResource {x:Static SystemColors.GrayTextBrushKey}}\" />\n </Trigger>\n </ControlTemplate.Triggers>\n </ControlTemplate>\n </Setter.Value>\n </Setter>\n</Style>\n\n<Style TargetType=\"{x:Type TreeView}\">\n <Setter Property=\"ItemContainerStyle\" Value=\"{StaticResource perTreeViewItemContainerStyle}\" />\n</Style>\n"
},
{
"answer_id": 64600450,
"author": "Michel Jansson",
"author_id": 1807542,
"author_profile": "https://Stackoverflow.com/users/1807542",
"pm_score": 0,
"selected": false,
"text": "public class Node\n{\n public Node Parent { get; set; }\n}\n\npublic class NodeTreeSelectionBehavior : Behavior<TreeView>\n{\n public Node SelectedItem\n {\n get { return (Node)GetValue(SelectedItemProperty); }\n set { SetValue(SelectedItemProperty, value); }\n }\n\n public static readonly DependencyProperty SelectedItemProperty =\n DependencyProperty.Register(\n \"SelectedItem\",\n typeof(Node),\n typeof(NodeTreeSelectionBehavior),\n new FrameworkPropertyMetadata(null, FrameworkPropertyMetadataOptions.BindsTwoWayByDefault, OnSelectedItemChanged));\n\n private static void OnSelectedItemChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)\n {\n if (!(e.NewValue is Node newNode)) return;\n\n var treeView = ((NodeTreeSelectionBehavior)d).AssociatedObject;\n\n var ancestors = new List<Node> { newNode };\n var parent = newNode;\n while ((parent = parent.Parent) != null)\n {\n ancestors.Insert(0, parent);\n }\n\n var currentParent = treeView as ItemsControl;\n foreach (var node in ancestors)\n {\n // first try the easy way\n var newParent = currentParent.ItemContainerGenerator.ContainerFromItem(node) as TreeViewItem;\n if (newParent == null)\n {\n // if this failed, it's probably because of virtualization, and we will have to do it the hard way.\n // see also the question at http://stackoverflow.com/q/183636/46635\n var itemsPresenter = (ItemsPresenter)currentParent.Template.FindName(\"ItemsHost\", currentParent);\n var virtualizingPanel = (VirtualizingPanel)VisualTreeHelper.GetChild(itemsPresenter, 0);\n var index = currentParent.Items.IndexOf(node);\n if (index < 0)\n {\n throw new InvalidOperationException(\"Node '\" + node + \"' cannot be fount in container\");\n }\n virtualizingPanel.BringIndexIntoViewPublic(index);\n newParent = currentParent.ItemContainerGenerator.ContainerFromIndex(index) as TreeViewItem;\n }\n\n if (newParent == null)\n {\n throw new InvalidOperationException(\"Tree view item cannot be found or created for node '\" + node + \"'\");\n }\n\n if (node == newNode)\n {\n newParent.IsSelected = true;\n newParent.BringIntoView();\n break;\n }\n\n newParent.IsExpanded = true;\n currentParent = newParent;\n }\n }\n\n protected override void OnAttached()\n {\n base.OnAttached();\n AssociatedObject.SelectedItemChanged += OnTreeViewSelectedItemChanged;\n }\n\n protected override void OnDetaching()\n {\n base.OnDetaching();\n AssociatedObject.SelectedItemChanged -= OnTreeViewSelectedItemChanged;\n }\n\n private void OnTreeViewSelectedItemChanged(object sender, RoutedPropertyChangedEventArgs<object> e)\n {\n SelectedItem = e.NewValue as Node;\n }\n}\n <UserControl xmlns=\"http://schemas.microsoft.com/winfx/2006/xaml/presentation\"\n xmlns:i=\"clr-namespace:System.Windows.Interactivity;assembly=System.Windows.Interactivity\"\n xmlns:local=\"clr-namespace:MyProject\">\n <Grid>\n <TreeView ItemsSource=\"{Binding MyItems}\"\n ScrollViewer.CanContentScroll=\"True\"\n VirtualizingStackPanel.IsVirtualizing=\"True\"\n VirtualizingStackPanel.VirtualizationMode=\"Recycling\">\n <i:Interaction.Behaviors>\n <local:NodeTreeSelectionBehavior SelectedItem=\"{Binding MySelectedItem}\" />\n </i:Interaction.Behaviors>\n </TreeView>\n <Grid>\n<UserControl>\n"
}
] |
2008/10/08
|
[
"https://Stackoverflow.com/questions/183636",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19982/"
] |
183,638
|
<p>I have this code that performs an ajax call and loads the results into two duplicate divs every time a dropdown is changed. I want the results to be faded into the div, to give a more obvious indication that something has changed, as its so seamless its sometimes hard to notice the change!</p>
<pre><code>print("$('.ajaxdropdown').change(function(){
$.ajax({
type: "GET",
url: "/includes/html/gsm-tariff.php",
data: "c_name="+escape($(this).val()),
success: function(html){
$("#charges-gsm").html(html);
//i want to fade result into these 2 divs...
$("#charges-gsm-faq").html(html);
$("#charges-gsm-prices").html(html);
}
});
});");
</code></pre>
<p>I've tried appending the fadein method and a few other things, but no joy.</p>
|
[
{
"answer_id": 183644,
"author": "Adam Bellaire",
"author_id": 21632,
"author_profile": "https://Stackoverflow.com/users/21632",
"pm_score": 7,
"selected": true,
"text": "hide() fadeIn() $(\"#charges-gsm-faq\").hide().html(html).fadeIn();\n$(\"#charges-gsm-prices\").hide().html(html).fadeIn();\n"
},
{
"answer_id": 183755,
"author": "Adam Bellaire",
"author_id": 21632,
"author_profile": "https://Stackoverflow.com/users/21632",
"pm_score": 2,
"selected": false,
"text": "... .css({ opacity: 0 }).fadeTo(\"normal\",1);\n"
},
{
"answer_id": 28162084,
"author": "Brynner Ferreira",
"author_id": 548727,
"author_profile": "https://Stackoverflow.com/users/548727",
"pm_score": 1,
"selected": false,
"text": "$('.element').load('file.html').hide().fadeIn();\n"
}
] |
2008/10/08
|
[
"https://Stackoverflow.com/questions/183638",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/26107/"
] |
183,642
|
<pre><code>select distinct constraint_type from user_constraints;
C
-
C
P
R
U
</code></pre>
<p>Seems P means primary key and R means foreign key, correct? What are U and C? </p>
|
[
{
"answer_id": 183664,
"author": "dacracot",
"author_id": 13930,
"author_profile": "https://Stackoverflow.com/users/13930",
"pm_score": 7,
"selected": true,
"text": "Code Description Acts On Level\n---------------------------------------------\nC Check on a table Column\nO Read Only on a view Object\nP Primary Key Object\nR Referential (Foreign Key) Column\nU Unique Key Column\nV Check Option on a view Object\n"
},
{
"answer_id": 3552727,
"author": "user428974",
"author_id": 428974,
"author_profile": "https://Stackoverflow.com/users/428974",
"pm_score": 6,
"selected": false,
"text": "C - Check constraint on a table \nP - Primary key \nU - Unique key \nR - Referential integrity \nV - With check option, on a view \nO - With read only, on a view \nH - Hash expression \nF - Constraint that involves a REF column \nS - Supplemental logging\n"
}
] |
2008/10/08
|
[
"https://Stackoverflow.com/questions/183642",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13930/"
] |
183,675
|
<p>my goal is to write a stored proc that can collect all field values from multiple rows into one single output variable (maybe varchar(some_length)). It may seem strange solution but i've quite positive its the only one i can use at that situation im in. I have not used Firebird before and stored procs look way different than in other well-known db systems.
My Firebird is 1.5 and dialect 3 (not sure what it means).
So maybe someone could help me with a algorithm example.</p>
|
[
{
"answer_id": 184142,
"author": "Bill Karwin",
"author_id": 20860,
"author_profile": "https://Stackoverflow.com/users/20860",
"pm_score": 4,
"selected": true,
"text": "SET TERM !!;\nCREATE PROCEDURE concat_names\n RETURNS (concat VARCHAR(2000))\nAS\nDECLARE VARIABLE name VARCHAR(100);\nBEGIN\n concat = '';\n FOR SELECT first_name || ' ' || last_name FROM employee INTO :name\n DO BEGIN\n concat = concat || name || ', ';\n END\nEND!!\nSET TERM ;!!\nEXECUTE PROCEDURE concat_names;\n"
},
{
"answer_id": 185930,
"author": "Attila Szasz",
"author_id": 15089,
"author_profile": "https://Stackoverflow.com/users/15089",
"pm_score": 0,
"selected": false,
"text": " CREATE PROCEDURE CONCAT(\n F1 VARCHAR(385),\n F2 VARCHAR(385),\n SEPARATOR VARCHAR(10))\nRETURNS (\n RESULT VARCHAR(780))\nAS\nbegin\n\n if ((:f1 is not null) and (:f1 <> '')) then\n result = :f1;\n\n if ((:f2 is not null) and (:f2 <> '')) then\n if ((result is not null) and (result <> '')) then\n begin\n if ((:separator is not null) and (separator <> '')) then\n result = result||separator||f2;\n else\n result = result||f2;\n end\n else\n result = f2;\n\n suspend;\nend\n"
},
{
"answer_id": 12208149,
"author": "Adamson",
"author_id": 1637559,
"author_profile": "https://Stackoverflow.com/users/1637559",
"pm_score": 0,
"selected": false,
"text": "execute procedure proc_name(value);\n select * from proc_name(value);\n"
}
] |
2008/10/08
|
[
"https://Stackoverflow.com/questions/183675",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/26207/"
] |
183,685
|
<p>Does anyone know if there is a good equivalent to Java's <code>Set</code> collection in C#? I know that you can somewhat mimic a set using a <code>Dictionary</code> or a <code>HashTable</code> by populating but ignoring the values, but that's not a very elegant way. </p>
|
[
{
"answer_id": 183696,
"author": "Jon Skeet",
"author_id": 22656,
"author_profile": "https://Stackoverflow.com/users/22656",
"pm_score": 9,
"selected": false,
"text": "HashSet<T>"
},
{
"answer_id": 1801031,
"author": "thecoop",
"author_id": 79439,
"author_profile": "https://Stackoverflow.com/users/79439",
"pm_score": 4,
"selected": false,
"text": "Dictionary<T, object>"
},
{
"answer_id": 9145345,
"author": "Bob Heck",
"author_id": 1189983,
"author_profile": "https://Stackoverflow.com/users/1189983",
"pm_score": -1,
"selected": false,
"text": "public class UniqueList<T> : List<T>\n{\n public new void Add(T obj)\n {\n if(!Contains(obj))\n {\n base.Add(obj);\n }\n }\n}\n"
},
{
"answer_id": 18551229,
"author": "Derek W",
"author_id": 1608786,
"author_profile": "https://Stackoverflow.com/users/1608786",
"pm_score": 5,
"selected": false,
"text": "SortedSet<T> HashSet<T> O(1) SortedSet<T> O(log n)"
}
] |
2008/10/08
|
[
"https://Stackoverflow.com/questions/183685",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20400/"
] |
183,686
|
<p>Whenever I restore a backup of my database in SQL Server I am presented with the following error:</p>
<pre><code>Msg 3101, Level 16, State 1, Line 1
Exclusive access could not be obtained because the database is in use.
Msg 3013, Level 16, State 1, Line 1
RESTORE DATABASE is terminating abnormally.
</code></pre>
<p>Usually to get around this I just restart the server. This was fine when we were developing on our local instance on our development machines. But we have a few programmers that need to access the database, and the logistics of having everyone script their changes and drop them into <a href="http://en.wikipedia.org/wiki/Apache_Subversion" rel="nofollow noreferrer">Subversion</a> was becoming a nightmare. Regardless our simple solution was to put it on a shared server in the office and backup the server occasionally in case someone screwed up the data.</p>
<p>Well, I screwed up the data and needed to restore. Unfortunately, I have another co-worker in the office who is working on another project and is using the same database server for development. To be nice I'd like to restore without restarting the SQL Server and possibly disrupting his work.</p>
<p>Is there a way to script in T-SQL to be able to take exclusive access or to drop all connections?</p>
|
[
{
"answer_id": 183754,
"author": "mattlant",
"author_id": 14642,
"author_profile": "https://Stackoverflow.com/users/14642",
"pm_score": 5,
"selected": true,
"text": "EXEC sp_dboption N'yourDatabase', N'offline', N'true'\n ALTER DATABASE [yourDatabase] SET OFFLINE WITH\nROLLBACK AFTER 60 SECONDS\n"
},
{
"answer_id": 183938,
"author": "RedWolves",
"author_id": 648,
"author_profile": "https://Stackoverflow.com/users/648",
"pm_score": 3,
"selected": false,
"text": "Use Master\nGo\n\nDeclare @dbname sysname\n\nSet @dbname = 'name of database you want to drop connections from'\n\nDeclare @spid int\nSelect @spid = min(spid) from master.dbo.sysprocesses\nwhere dbid = db_id(@dbname)\nWhile @spid Is Not Null\nBegin\n Execute ('Kill ' + @spid)\n Select @spid = min(spid) from master.dbo.sysprocesses\n where dbid = db_id(@dbname) and spid > @spid\nEnd\n"
},
{
"answer_id": 881280,
"author": "Precipitous",
"author_id": 77784,
"author_profile": "https://Stackoverflow.com/users/77784",
"pm_score": 4,
"selected": false,
"text": "-- set single user, terminate connections\nALTER DATABASE [target] SET SINGLE_USER WITH ROLLBACK IMMEDIATE\nRESTORE ...\nALTER DATABASE [target] SET MULTI_USER\n ALTER DATABASE [target] SET SINGLE_USER WITH ROLLBACK AFTER 5\n ALTER DATABASE [target] SET OFFLINE WITH ROLLBACK AFTER 5\n"
}
] |
2008/10/08
|
[
"https://Stackoverflow.com/questions/183686",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/648/"
] |
183,698
|
<p>I'm using DB2, although a solution using any flavor of SQL would likely be easy enough for me to convert.</p>
<p>I didn't design this database, or the application that uses the database. I haven't the power to change this application, how it works, or the data. Because it defies what I consider to be conventional use of a start and an end date, I am struggling with writing something as simple as a select for a specific point in time.</p>
<p>Here are the relevant/edited parts of the table:</p>
<pre><code>OBJECTID FACILITY_ID START_DATE END_DATE FACILITY_NAME
1001 500 1/1/1980 5/1/2000 Really Old Name
1002 500 1/1/1980 1/1/2006 Old Name
1003 500 1/1/1980 null Current Name
1004 501 1/1/1980 3/1/2008 Closed Facility Name
1004 502 1/1/1980 null Another Current Name
</code></pre>
<p>What I want to return, are the records which are valid for 7/1/2005:</p>
<pre><code>OBJECTID FACILITY_ID START_DATE END_DATE FACILITY_NAME
1002 500 1/1/1980 1/1/2006 Old Name
1004 501 1/1/1980 3/1/2008 Closed Facility Name
1004 502 1/1/1980 null Another Current Name
</code></pre>
<p>I'm trying to avoid subselects, but understand they may be necessary. If I do need a subselect, I'd like to keep it limited to one. Looking between the start and end date doesn't work, because it doesn't return facilities which have only one record with a null end date. Adding an OR condition to include end dates which are null may return more than one record in some cases. This problem seems so simple on the service, that I must be missing a ridiculously obvious solution. Does anyone have any ideas?</p>
|
[
{
"answer_id": 183718,
"author": "Kip",
"author_id": 18511,
"author_profile": "https://Stackoverflow.com/users/18511",
"pm_score": 2,
"selected": false,
"text": "SELECT * FROM table_name\nWHERE START_DATE < '7/1/2005' AND (END_DATE > '7/1/2005' OR END_DATE IS NULL);\n"
},
{
"answer_id": 183720,
"author": "Craig",
"author_id": 2894,
"author_profile": "https://Stackoverflow.com/users/2894",
"pm_score": 1,
"selected": false,
"text": "select * from TAble where START_DATE < @DATE and Coalesce(END_DATE, @DATE+1) > @DATE\n"
},
{
"answer_id": 183732,
"author": "James Curran",
"author_id": 12725,
"author_profile": "https://Stackoverflow.com/users/12725",
"pm_score": 0,
"selected": false,
"text": "select * from facitities\nwhere START_DATE <= @my_date and (@mydate <= END_DATE or END_DATE is null)\n"
},
{
"answer_id": 183762,
"author": "James Curran",
"author_id": 12725,
"author_profile": "https://Stackoverflow.com/users/12725",
"pm_score": 1,
"selected": false,
"text": "select OBJECTID, FACILITY_ID, START_DATE, FACILITY_NAME, MIN(END_DATE) as END_DATE\nfrom facitities\nwhere START_DATE <= @my_date and (@mydate <= END_DATE or END_DATE is null)\ngroup by OBJECTID, FACILITY_ID, START_DATE, FACILITY_NAME\n"
},
{
"answer_id": 184267,
"author": "srclontz",
"author_id": 4606,
"author_profile": "https://Stackoverflow.com/users/4606",
"pm_score": 1,
"selected": false,
"text": "SELECT \n * \nFROM \n FACILITY_TABLE\nWHERE \n (END_DATE IS NULL\n AND OBJECTID NOT IN \n (SELECT A.OBJECTID FROM FACILITY_TABLE A \n WHERE '7/1/2005' BETWEEN A.BEGINDATE AND A.ENDDATE))\n OR \n '7/1/2005' BETWEEN FACILITY_TABLE.START_DATE AND FACILITY_TABLE.ENDDATE\n"
},
{
"answer_id": 391688,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "select * from facilities\nwhere @my_date between START_DATE AND COALESCE(END_DATE, CURRENT DATE)\n"
}
] |
2008/10/08
|
[
"https://Stackoverflow.com/questions/183698",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4606/"
] |
183,702
|
<p>Something like</p>
<pre><code>var life= {
users : {
guys : function(){ this.SOMETHING.mameAndDestroy(this.girls); },
girls : function(){ this.SOMETHING.kiss(this.boys); },
},
mameAndDestroy : function(group){ },
kiss : function(group){ }
};
</code></pre>
<p>this.SOMETHING is what I imagine the format is, but it might not be. What will step back up to the parent of an object?</p>
|
[
{
"answer_id": 183737,
"author": "Shog9",
"author_id": 811,
"author_profile": "https://Stackoverflow.com/users/811",
"pm_score": 4,
"selected": false,
"text": "life life parent var death = { residents : life.users };\nlife.users.smallFurryCreaturesFromAlphaCentauri = { exist : function() {} };\n// death.residents.smallFurryCreaturesFromAlphaCentauri now exists\n// - because life.users references the same object as death.residents!\n function addChild(ob, childName, childOb)\n{\n ob[childName] = childOb;\n childOb.parent = ob;\n}\n\nvar life= {\n mameAndDestroy : function(group){ },\n kiss : function(group){ }\n};\n\naddChild(life, 'users', {\n guys : function(){ this.parent.mameAndDestroy(this.girls); },\n girls : function(){ this.parent.kiss(this.boys); },\n });\n\n// life.users.parent now exists and points to life\n"
},
{
"answer_id": 184536,
"author": "harley.333",
"author_id": 26259,
"author_profile": "https://Stackoverflow.com/users/26259",
"pm_score": 7,
"selected": true,
"text": "var Bobby = {name: \"Bobby\"};\nvar Dad = {name: \"Dad\", children: [ Bobby ]};\nvar Mom = {name: \"Mom\", children: [ Bobby ]};\n"
},
{
"answer_id": 1949628,
"author": "cmcculloh",
"author_id": 58,
"author_profile": "https://Stackoverflow.com/users/58",
"pm_score": 2,
"selected": false,
"text": "var life={\n users:{\n guys:function(){ life.mameAndDestroy(life.users.girls); },\n girls:function(){ life.kiss(life.users.guys); }\n },\n mameAndDestroy : function(group){ \n alert(\"mameAndDestroy\");\n group();\n },\n kiss : function(group){\n alert(\"kiss\");\n //could call group() here, but would result in infinite loop\n }\n};\n\nlife.users.guys();\nlife.users.girls();\n"
},
{
"answer_id": 3861917,
"author": "jazkat",
"author_id": 318380,
"author_profile": "https://Stackoverflow.com/users/318380",
"pm_score": 6,
"selected": false,
"text": "parentThis = this;\n"
},
{
"answer_id": 17885573,
"author": "transilvlad",
"author_id": 1311393,
"author_profile": "https://Stackoverflow.com/users/1311393",
"pm_score": 0,
"selected": false,
"text": "var exScript = (function (undefined) {\n function exScript() {\n this.logInfo = [];\n var that = this;\n this.logInfo.push = function(e) {\n that.logInfo[that.logInfo.length] = e;\n console.log(e);\n };\n }\n})();\n"
},
{
"answer_id": 37283234,
"author": "Rodrigo Morales",
"author_id": 4091841,
"author_profile": "https://Stackoverflow.com/users/4091841",
"pm_score": 0,
"selected": false,
"text": "var Users = function(parent) {\n this.parent = parent;\n};\nUsers.prototype.guys = function(){ \n this.parent.nameAndDestroy(['test-name-and-destroy']);\n};\nUsers.prototype.girls = function(){ \n this.parent.kiss(['test-kiss']);\n};\n\nvar list = {\n users : function() {\n return new Users(this);\n },\n nameAndDestroy : function(group){ console.log(group); },\n kiss : function(group){ console.log(group); }\n};\n\nlist.users().guys(); // should output [\"test-name-and-destroy\"]\nlist.users().girls(); // should output [\"test-kiss\"]\n"
},
{
"answer_id": 38172287,
"author": "Parchandri",
"author_id": 2616181,
"author_profile": "https://Stackoverflow.com/users/2616181",
"pm_score": 1,
"selected": false,
"text": "function myclass() = {\n var instance = this;\n\n this.Days = function() {\n var days = [\"Piątek\", \"Sobota\", \"Niedziela\"];\n return days;\n }\n\n this.EventTime = function(day, hours, minutes) {\n this.Day = instance.Days()[day];\n this.Hours = hours;\n this.minutes = minutes;\n this.TotalMinutes = day*24*60 + 60*hours + minutes;\n }\n}\n"
},
{
"answer_id": 41227400,
"author": "rplaurindo",
"author_id": 2730593,
"author_profile": "https://Stackoverflow.com/users/2730593",
"pm_score": 0,
"selected": false,
"text": "{} (function ($) {\n \"use strict\";\n\n $.defineProperties($, {\n parentKeys: {\n value: function (object) {\n var\n traces = [],\n queue = [{trace: [], node: object}],\n\n block = function () {\n var\n node,\n nodeKeys,\n trace;\n\n // clean the queue\n queue = [];\n return function (map) {\n node = map.node;\n nodeKeys = Object.keys(node);\n\n nodeKeys.forEach(function (nodeKey) {\n if (typeof node[nodeKey] == \"object\") {\n trace = map.trace.concat(nodeKey);\n // put on queue\n queue.push({trace: trace, node: node[nodeKey]});\n\n // traces.unshift(trace);\n traces.push(trace);\n }\n });\n };\n };\n\n while(true) {\n if (queue.length) {\n queue.forEach(block());\n } else {\n break;\n }\n }\n\n return traces;\n },\n\n writable: true\n }\n\n });\n\n})(Object);\n FIFO BFS Object parentKeys literal Object"
},
{
"answer_id": 42048192,
"author": "amurrell",
"author_id": 2100636,
"author_profile": "https://Stackoverflow.com/users/2100636",
"pm_score": 3,
"selected": false,
"text": ".call() addName.call() addName.call({\"name\" : 'angela'}); addName.call({\"name\": \"angela\"}, true); addName append call this var app = {\n init: function() {\n var _this = this; // so we can access the app object in other functions\n\n $('#thingy').click(function(){\n alert(_this.options.thingy());\n });\n\n $('#another').click(function(){\n alert(_this.options.getAnother());\n });\n },\n options: {\n thingy: function() {\n // PROBLEM: the this here refers to options\n return this.getThingy();\n },\n getAnother: function() {\n // PROBLEM 2: we want the this here to refer to options,\n // but thingy will need the parent object\n return 'another ' + this.thingy();\n },\n },\n getThingy: function() {\n return 'thingy';\n }\n};\n var app = {\n init: function() {\n var _this = this; // so we can access the app object in other functions\n\n $('#thingy').click(function(){\n // SOLUTION: use call to pass _this as the 'this' used by thingy\n alert(_this.options.thingy.call(_this));\n });\n\n $('#another').click(function(){\n // SOLUTION 2: Use call to pass parent all the way through\n alert(_this.options.getAnother.call(_this)); \n });\n },\n options: {\n thingy: function() {\n // SOLUTION in action, the this is the app object, not options.\n return this.getThingy(); \n },\n getAnother: function() {\n // SOLUTION 2 in action, we can still access the options \n // AND pass through the app object to the thingy method.\n return 'another ' + this.options.thingy.call(this); \n },\n },\n getThingy: function() {\n return 'thingy';\n }\n};\n .call() app.options.someFunction(arg) .call app.options.someFunction.call(this, arg); app.helpers.anotherFunction() somefunction this _parentThis this"
},
{
"answer_id": 48514729,
"author": "Elliot B.",
"author_id": 1215133,
"author_profile": "https://Stackoverflow.com/users/1215133",
"pm_score": 2,
"selected": false,
"text": "var test = {\"hello\":{\"foo\":{\"bar\":\"world\"}}};\nvar proxy = ObservableSlim.create(test, true, function() { return false });\n\nfunction traverseUp(childObj) {\n console.log(JSON.stringify(childObj.__getParent())); // returns test.hello: {\"foo\":{\"bar\":\"world\"}}\n console.log(childObj.__getParent(2)); // attempts to traverse up two levels, returns undefined because test.hello does not have a parent object\n};\n\ntraverseUp(proxy.hello.foo);\n"
},
{
"answer_id": 71843502,
"author": "Ninroot",
"author_id": 6244121,
"author_profile": "https://Stackoverflow.com/users/6244121",
"pm_score": 0,
"selected": false,
"text": "/**\n * Recursively traverse the rootObject to find the parent of childObject.\n * @param rootObject - root object to inspect\n * @param childObject - child object to match\n * @returns - parent object of child if exists, undefined otherwise\n */\nfunction findParent(rootObject, childObject) {\n if (!(rootObject && typeof rootObject === 'object')) {\n return undefined;\n }\n if (Array.isArray(rootObject)) {\n for (let i = 0; i < rootObject.length; i++) {\n if (rootObject[i] === childObject) {\n return rootObject;\n }\n const child = this.findParent(rootObject[i], childObject);\n if (child) {\n return child;\n }\n }\n } else {\n const keys = Object.keys(rootObject);\n for (let i = 0; i < keys.length; i += 1) {\n const key = keys[i];\n if (rootObject[key] === childObject) {\n return rootObject;\n }\n const child = this.findParent(rootObject[key], childObject);\n if (child) {\n return child;\n }\n }\n }\n return undefined;\n}\n\n// tests\n\nconst obj = {\n l1: { l11: { l111: ['a', 'b', 'c'] } },\n l2: { l21: ['a', 1, {}], l22: 123 },\n l3: [ { l33: {} } ],\n};\n\nassert.equal(findParent(obj, obj.l1), obj);\nassert.equal(findParent(obj, obj.l1.l11), obj.l1);\nassert.equal(findParent(obj, obj.l2), obj);\nassert.equal(findParent(obj, obj.l2.l21), obj.l2);\nassert.equal(findParent(obj, obj.l2.l22), obj.l2);\nassert.equal(findParent(obj, obj.l3[0]), obj.l3);\nassert.equal(findParent(obj, obj.l3[0].l33), obj.l3[0]);\n"
}
] |
2008/10/08
|
[
"https://Stackoverflow.com/questions/183702",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1825034/"
] |
183,742
|
<p>Let's look at an example - books. A book can have 1..n authors. An author can have 1..m books. What is a good way to represent all of the authors of a book?</p>
<p>I came up with an idea to create a Books table and an Authors table. The Authors table has a primary AuthorID key the author's name. The Books table has a primary Book ID and metadata about the book (title, publication date, so on). However, there needs to be a way to link the books to authors and authors to books. And this is where the problem is.</p>
<p>Let's say we have three books by Bob. However, on one book, he wrote it as Bob, PhD. Another he wrote as Dr. Bob, and a third he wrote as Dr. Robert. I want to be able to identify the fact that these authors are, in reality, the same person but credited under different names. I also want to distinguish Bob from another Bob who wrote different books.</p>
<p>Now let's also add in another part to an application, a Person table that keeps track of interesting people. And let's say that Bob is an interesting person. I want to not only say that the author of all three books is Bob, but that this interesting Bob is the same Bob as the author Bob.</p>
<p>So what strategies exist for such potentially complicated mapping, while ensuring that the book authors are identified by the name on the cover?</p>
|
[
{
"answer_id": 11609545,
"author": "dakhota",
"author_id": 946792,
"author_profile": "https://Stackoverflow.com/users/946792",
"pm_score": 0,
"selected": false,
"text": "create table books (\n book_id integer primary key,\n title varchar not null\n);\n\ncreate table aliases (\n alias_id integer primary key,\n alias varchar not null\n);\n\ncreate table books_aliases (\n book_id integer references books (book_id),\n alias_id integer references aliases (alias_id),\n primary key (book_id, alias_id)\n);\n\ncreate table authors (\n author_id integer primary key,\n author varchar not null,\n interesting boolean default false\n);\n\ncreate table aliases_authors (\n alias_id integer references aliases (alias_id),\n author_id integer references authors (author_id),\n primary key (alias_id, author_id)\n);\n\ncreate view books_aliases_authors as\n select * from books \n natural join books_aliases\n natural join aliases\n natural join aliases_authors\n natural join authors;\n create view books_aliases_authors as\n select *\n from books \n join books_aliases using (book_id) \n join aliases using (alias_id) \n join aliases_authors using (alias_id) \n join authors using (author_id);\n create view books_aliases_authors as\n select b.book_id, title, l.alias_id, alias, t.author_id, author, interesting\n from books b\n join books_aliases bl on bl.book_id = b.book_id\n join aliases l on bl.alias_id = l.alias_id\n join aliases_authors lt on lt.alias_id = l.alias_id\n join authors t on t.author_id = lt.author_id;\n"
}
] |
2008/10/08
|
[
"https://Stackoverflow.com/questions/183742",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/572/"
] |
183,773
|
<p>A program receives a list of Messages (base type). Each message in the list has to be processed according to it's type (descendant type). However, different messages need different inputs in order to be processed correctly.</p>
<p>What is the following technique called? (I haven't checked this code in a compiler)</p>
<pre><code>abstract class MessageProcessor
{
public static MessageProcessor GetProcessor(Message message, DataDomain data)
{
if (message.GetType() == typeof(FooMessage))
{
return new FooMessageProcessor(message, data.Name, data.Classification);
}
else if (message.GetType() == typeof(BarMessage))
{
return new BarMessageProcessor(message, data.AccountNo, data.CreditLimit);
}
else
throw new SomeException("Unrecognized type");
}
public abstract void Process();
}
</code></pre>
<p>And this one?</p>
<pre><code>static class MessageProcessorFactory
{
public static MessageProcessor GetProcessor(Message message, DataDomain data)
{
if (message.GetType() == typeof(FooMessage))
{
return new FooMessageProcessor(message, data.Name, data.Classification);
}
else if (message.GetType() == typeof(BarMessage))
{
return new BarMessageProcessor(message, data.AccountNo, data.CreditLimit);
}
else
throw new SomeException("Unrecognized type");
}
}
</code></pre>
<p>And what is it called if I can inject the ProcessBuilder class into a MessageProcessor (using a property or Setter) and then call Process?</p>
<p>What technique would be the best pattern for solving this problem?</p>
|
[
{
"answer_id": 183836,
"author": "Mark Cidade",
"author_id": 1659,
"author_profile": "https://Stackoverflow.com/users/1659",
"pm_score": 4,
"selected": true,
"text": "abstract class MessageProcessorFactory\n { public abstract MessageProcessor GetProcessor\n (Message message, DataDomain data);\n }\n\nclass FooMessageProcessorFactory : MessageProcessorFactory\n { public override MessageProcessor GetProcessor\n (Message message, DataDomain data)\n { return new FooMessageProcessor(data.Name, data.Classification);\n }\n }\n class MessageProcessor\n { ProcessBuilder builder;\n\n public MessageProcessor(ProcessBuilder builder)\n { this.builder = builder;\n }\n\n public void Process()\n { builder.BuildMessage();\n builder.BuildProcess();\n builder.Process();\n }\n }\n\nvar mp = new MessageProcessor(new FooProcessBuilder());\n static void Process(Message msg, DataDomain data)\n { var p = getProcessor(msg.GetType());\n p.Process(msg, data);\n }\n private static MessageProcessor getProcessor(Type msgType)\n { return (msgType == typeof(FooMessage)) ? new FooMessageProcessor()\n : (msgType == typeof(BarMessage)) ? new BarMessageProcessor()\n : new DefaultMessageProcessor();\n }\n Dictionary<Type,MessageProcessor> processors; \n\nprivate static MessageProcessor getProcessor(Type msgType) \n { return processors[msgType];\n }\n"
}
] |
2008/10/08
|
[
"https://Stackoverflow.com/questions/183773",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9825/"
] |
183,780
|
<p>What would you consider best practice for organizing JUnit tests in a project, and why? For example, do you keep your tests next to the classes they test? Do you put them in a separate but parallel package structure? Do you use a different organization strategy entirely?</p>
|
[
{
"answer_id": 184056,
"author": "Aleksandar Dimitrov",
"author_id": 11797,
"author_profile": "https://Stackoverflow.com/users/11797",
"pm_score": 3,
"selected": false,
"text": "mvn archetype:create -DgroupId=com.yoyodyne -DartifactId=UberApp\n"
}
] |
2008/10/08
|
[
"https://Stackoverflow.com/questions/183780",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4287/"
] |
183,783
|
<p>I have a database driven website serving about 50,000 pages.</p>
<p>I want to track each webpage/record hit.
I will do this by creating logs, and then batch processing the logs once a day.
I am not concerned with how I will do the batch process, only with the quickest way to log.</p>
<p>How would you log, which do you think is quicker:</p>
<p>a) Use PHP to append to the end of a text log file.</p>
<p>b) Use MySQL to INSERT INTO a non-indexed log table.</p>
|
[
{
"answer_id": 183828,
"author": "Richard Harrison",
"author_id": 19624,
"author_profile": "https://Stackoverflow.com/users/19624",
"pm_score": 2,
"selected": false,
"text": "DB time: 2.1695\nDB time: 2.3869\nDB time: 2.4305\nDB time: 2.5864\nDB time: 2.7465\nDB time: 3.0182\nDB time: 3.1451\nDB time: 3.3298\nDB time: 3.4483\nDB time: 3.7812\nFile open time: 0.1538\nFile open time: 0.5478\nFile open time: 0.7252\nFile open time: 3.0453\nFile open time: 4.2661\nFile open time: 4.4247\nFile open time: 4.5484\nFile open time: 4.6319\nFile open time: 4.6501\nFile open time: 4.6646\nOpen close file time: 11.3647\nOpen close file time: 12.2849\nOpen close file time: 18.4093\nOpen close file time: 18.4202\nOpen close file time: 21.2621\nOpen close file time: 22.7267\nOpen close file time: 23.4597\nOpen close file time: 25.6293\nOpen close file time: 26.1119\nOpen close file time: 29.1471\n\nfunction debug($d)\n{\n static $start_time = NULL;\n static $start_code_line = 0;\n\n if( $start_time === NULL )\n {\n $start_time = time() + microtime();\n $start_code_line = $code_line;\n return 0;\n }\n\n printf(\"$d time: %.4f\\n\", (time() + microtime() - $start_time));\n $fp = @fopen('dbg.txt','a');\n fprintf($fp,\"$d time: %.4f\\n\", (time() + microtime() - $start_time));\n fclose($fp);\n\n $start_time = time() + microtime();\n $start_code_line = $code_line;\n}\n\nfunction tfile()\n{\n $fp = @fopen('t1.txt','a');\n for ($i=0;$i<10000;$i++)\n {\n $txt = $i.\"How would you log, which do you think is quicker:How would you log, which do you think is quicker:\";\n fwrite($fp,$txt);\n }\n fclose($fp);\n}\nfunction tfile_openclose()\n{\n for ($i=0;$i<10000;$i++)\n {\n $fp = @fopen('t1.txt','a');\n $txt = $i.\"How would you log, which do you think is quicker:How would you log, which do you think is quicker:\";\n fwrite($fp,$txt);\n fclose($fp);\n }\n}\n\nfunction tdb()\n{\n $db = mysql_connect('localhost','tremweb','zzxxcc');\n\n $select_db = mysql_select_db('scratch');\n\n if (!$select_db) \n die('Error selecting database.');\n\n for ($i=0;$i<10000;$i++)\n {\n $txt = $i.\"How would you log, which do you think is quicker:How would you log, which do you think is quicker:\";\n mysql_query(\"INSERT INTO tlog values('\".$txt.\"')\");\n }\n}\n\ndebug(\"\");\n\ntfile();\ndebug(\"File open\");\n\ntfile_openclose();\ndebug(\"Open close file\");\n\ntdb();\ndebug(\"DB\");\n"
},
{
"answer_id": 184487,
"author": "Andrew Moore",
"author_id": 26210,
"author_profile": "https://Stackoverflow.com/users/26210",
"pm_score": 1,
"selected": false,
"text": "INSERT DELAYED INTO `hits` ...\n"
}
] |
2008/10/08
|
[
"https://Stackoverflow.com/questions/183783",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
183,788
|
<p>I've worked on many projects where I've been given code by others to update. More often than not I compile it and get about 1,000+ compiler warnings. When I see compiler warnings they make me feel dirty, so my first task is to clean up the code and remove them all. Typically I find about a dozen problems like uninitialized variables such.</p>
<p>I don't understand why people leave them in and don't have perfectly clean compiles with no warnings. Am I missing something? Is there any valid reason to just leave them? Any horror stories to share?</p>
|
[
{
"answer_id": 183884,
"author": "jwfearn",
"author_id": 10559,
"author_profile": "https://Stackoverflow.com/users/10559",
"pm_score": 4,
"selected": false,
"text": "#pragma typedef struct _X * X; // from external header, not 64-bit portable\n\n#pragma warning( push )\n#pragma warning( disable: 4312 ) // 64-bit portability warning\nX x = reinterpret_cast< X >( 0xDDDDDDDD ); // we know X not 64-bit portable\n#pragma warning( pop )\n"
}
] |
2008/10/08
|
[
"https://Stackoverflow.com/questions/183788",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13676/"
] |
183,791
|
<p>I have two collections which have property <code>Email</code> in both collections. I need to get a list of the items in the first list where <code>Email</code> does not exist in the second list. With SQL I would just use "not in", but I do not know the equivalent in LINQ. How is that done?</p>
<p>So far I have a join, like...</p>
<pre><code>var matches = from item1 in list1
join item2 in list2 on item1.Email equals item2.Email
select new { Email = list1.Email };
</code></pre>
<p>But I cannot join since I need the difference and the join would fail. I need some way of using Contains or Exists I believe. I just have not found an example to do that yet.</p>
|
[
{
"answer_id": 183804,
"author": "Robert Rouse",
"author_id": 25129,
"author_profile": "https://Stackoverflow.com/users/25129",
"pm_score": 9,
"selected": true,
"text": "NorthwindDataContext dc = new NorthwindDataContext(); \ndc.Log = Console.Out;\n\nvar query = \n from c in dc.Customers \n where !(from o in dc.Orders \n select o.CustomerID) \n .Contains(c.CustomerID) \n select c;\n\nforeach (var c in query) Console.WriteLine( c );\n"
},
{
"answer_id": 183806,
"author": "tvanfosson",
"author_id": 12950,
"author_profile": "https://Stackoverflow.com/users/12950",
"pm_score": 2,
"selected": false,
"text": "var secondEmails = (from item in list2\n select new { Email = item.Email }\n ).ToList();\n\nvar matches = from item in list1\n where !secondEmails.Contains(item.Email)\n select new {Email = item.Email};\n"
},
{
"answer_id": 183812,
"author": "Echostorm",
"author_id": 12862,
"author_profile": "https://Stackoverflow.com/users/12862",
"pm_score": 8,
"selected": false,
"text": "var answer = list1.Except(list2);\n Except"
},
{
"answer_id": 183822,
"author": "Inisheer",
"author_id": 2982,
"author_profile": "https://Stackoverflow.com/users/2982",
"pm_score": 1,
"selected": false,
"text": "List<int> list1 = new List<int>();\n// fill data\nList<int> list2 = new List<int>();\n// fill data\n\nvar results = from i in list1\n where !list2.Contains(i)\n select i;\n\nforeach (var result in results)\n Console.WriteLine(result.ToString());\n"
},
{
"answer_id": 183974,
"author": "Amy B",
"author_id": 8155,
"author_profile": "https://Stackoverflow.com/users/8155",
"pm_score": 6,
"selected": false,
"text": "from item1 in List1\nwhere !(list2.Any(item2 => item2.Email == item1.Email))\nselect item1;\n"
},
{
"answer_id": 184251,
"author": "Ryan Lundy",
"author_id": 5486,
"author_profile": "https://Stackoverflow.com/users/5486",
"pm_score": 2,
"selected": false,
"text": "Except Except IEquatable<T> Equals GetHashCode IEqualityComparer<T>"
},
{
"answer_id": 3389553,
"author": "Brett",
"author_id": 188474,
"author_profile": "https://Stackoverflow.com/users/188474",
"pm_score": 3,
"selected": false,
"text": "var linked =\n from x in dc.X\n from y in dc.Y\n where x.MyProperty == y.MyProperty\n select x;\nvar notLinked =\n dc.X.Except(linked);\n class Program\n{\n static void Main(string[] args)\n {\n // Creates some foos\n List<Foo> fooList = new List<Foo>();\n fooList.Add(new Foo { Id = 1, BarId = 11 });\n fooList.Add(new Foo { Id = 2, BarId = 12 });\n fooList.Add(new Foo { Id = 3, BarId = 13 });\n fooList.Add(new Foo { Id = 4, BarId = 14 });\n fooList.Add(new Foo { Id = 5, BarId = -1 });\n fooList.Add(new Foo { Id = 6, BarId = -1 });\n fooList.Add(new Foo { Id = 7, BarId = -1 });\n\n // Create some bars\n List<Bar> barList = new List<Bar>();\n barList.Add(new Bar { Id = 11 });\n barList.Add(new Bar { Id = 12 });\n barList.Add(new Bar { Id = 13 });\n barList.Add(new Bar { Id = 14 });\n barList.Add(new Bar { Id = 15 });\n barList.Add(new Bar { Id = 16 });\n barList.Add(new Bar { Id = 17 });\n\n var linked = from foo in fooList\n from bar in barList\n where foo.BarId == bar.Id\n select foo;\n var notLinked = fooList.Except(linked);\n foreach (Foo item in notLinked)\n {\n Console.WriteLine(\n String.Format(\n \"Foo.Id: {0} | Bar.Id: {1}\",\n item.Id, item.BarId));\n }\n Console.WriteLine(\"Any key to continue...\");\n Console.ReadKey();\n }\n}\n\nclass Foo\n{\n public int Id { get; set; }\n public int BarId { get; set; }\n}\n\nclass Bar\n{\n public int Id { get; set; }\n}\n"
},
{
"answer_id": 3389610,
"author": "StriplingWarrior",
"author_id": 120955,
"author_profile": "https://Stackoverflow.com/users/120955",
"pm_score": 6,
"selected": false,
"text": "var itemIds = inMemoryList.Select(x => x.Id).ToArray();\nvar otherObjects = context.ItemList.Where(x => !itemIds.Contains(x.Id));\n WHERE ... IN (...)"
},
{
"answer_id": 7242227,
"author": "Chintan Udeshi",
"author_id": 919568,
"author_profile": "https://Stackoverflow.com/users/919568",
"pm_score": 3,
"selected": false,
"text": "list1.RemoveAll(Item => list2.Contains(Item));\n"
},
{
"answer_id": 25890827,
"author": "Tarik",
"author_id": 990750,
"author_profile": "https://Stackoverflow.com/users/990750",
"pm_score": 0,
"selected": false,
"text": "NorthwindDataContext dc = new NorthwindDataContext(); \ndc.Log = Console.Out;\n\nvar query = \n from c in dc.Customers \n where !dc.Orders.Any(o => o.CustomerID == c.CustomerID) \n select c;\n NorthwindDataContext dc = new NorthwindDataContext(); \ndc.Log = Console.Out;\n\nvar query = \n from c in dc.Customers \n where dc.Orders.All(o => o.CustomerID != c.CustomerID) \n select c;\n\nforeach (var c in query) \n Console.WriteLine( c );\n"
},
{
"answer_id": 27498081,
"author": "DevT",
"author_id": 1395178,
"author_profile": "https://Stackoverflow.com/users/1395178",
"pm_score": 4,
"selected": false,
"text": "var NotInRecord =list1.Where(p => !list2.Any(p2 => p2.Email == p.Email));\n"
},
{
"answer_id": 29822197,
"author": "Marten Jacobs",
"author_id": 3512199,
"author_profile": "https://Stackoverflow.com/users/3512199",
"pm_score": 0,
"selected": false,
"text": "Dim result = (From a In list1\n Group Join b In list2 \n On a.Value Equals b.Value \n Into grp = Group\n Where Not grp.Any\n Select a)\n"
},
{
"answer_id": 41100707,
"author": "mshwf",
"author_id": 6197785,
"author_profile": "https://Stackoverflow.com/users/6197785",
"pm_score": 1,
"selected": false,
"text": "IN In NotIn var result = list1.In(x => x.Email, list2.Select(z => z.Email));\n var result = list1.In(x => x.Email, \"a@b.com\", \"b@c.com\", \"c@d.com\");\n"
},
{
"answer_id": 45915151,
"author": "Janis S.",
"author_id": 5251960,
"author_profile": "https://Stackoverflow.com/users/5251960",
"pm_score": 3,
"selected": false,
"text": "All() var notInList = list1.Where(p => list2.All(p2 => p2.Email != p.Email));\n"
},
{
"answer_id": 58080005,
"author": "nzrytmn",
"author_id": 3193030,
"author_profile": "https://Stackoverflow.com/users/3193030",
"pm_score": 2,
"selected": false,
"text": "var result = list1.Where(p => list2.All(x => x.Id != p.Id));\n"
},
{
"answer_id": 63037787,
"author": "Arup Mahapatra",
"author_id": 10366755,
"author_profile": "https://Stackoverflow.com/users/10366755",
"pm_score": 0,
"selected": false,
"text": " DynamicWebsiteEntities db = new DynamicWebsiteEntities();\n var data = (from dt_sub in db.Subjects_Details\n //Sub Query - 1\n let sub_s_g = (from sg in db.Subjects_In_Group\n where sg.GroupId == groupId\n select sg.SubjectId)\n //Where Cause\n where !sub_s_g.Contains(dt_sub.Id) && dt_sub.IsLanguage == false\n //Order By Cause\n orderby dt_sub.Subject_Name\n\n select dt_sub)\n .AsEnumerable();\n \n SelectList multiSelect = new SelectList(data, \"Id\", \"Subject_Name\", selectedValue);\n\n //======================================OR===========================================\n\n var data = (from dt_sub in db.Subjects_Details\n\n \n //Where Cause\n where !(from sg in db.Subjects_In_Group\n where sg.GroupId == groupId\n select sg.SubjectId).Contains(dt_sub.Id) && dt_sub.IsLanguage == false\n\n //Order By Cause\n orderby dt_sub.Subject_Name\n\n select dt_sub)\n\n .AsEnumerable();\n"
}
] |
2008/10/08
|
[
"https://Stackoverflow.com/questions/183791",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10366/"
] |
183,830
|
<p>I'm writing a Java app that is accepting URL parameter values that may or may not be encoded. I need an easy way to tell whether or not I need to encode the parameter string.</p>
<p>In other words, I want a function <code>boolean needsEncoding(String param)</code>, which will return true if I pass in the String "foo@test.com", and false if I pass in "foo%40test.com". The problem with this idea is that this is ambiguous. How would I know whether or not the "%" sign in the latter string should be encoded? One way to handle this is to modify my contract - require clients to pass in un-encoded strings so that I know I always need to encode them. Thoughts?</p>
|
[
{
"answer_id": 184664,
"author": "shadit",
"author_id": 9925,
"author_profile": "https://Stackoverflow.com/users/9925",
"pm_score": 0,
"selected": false,
"text": "java.net.URLDecoder URLDecoder boolean boolean URLDecoder"
},
{
"answer_id": 24109456,
"author": "Mike",
"author_id": 1434414,
"author_profile": "https://Stackoverflow.com/users/1434414",
"pm_score": 0,
"selected": false,
"text": "java.net.URLDecoder.decode String properlyencodedstring = \njava.net.URLEncoder.encode(LocalDecoder.localdecode(someformdatastring),\"UTF-8\");\n input type=\"url\" .replaceAll(\"+\", \" \") java.net.URI"
}
] |
2008/10/08
|
[
"https://Stackoverflow.com/questions/183830",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8217/"
] |
183,853
|
<p>Is there a benefit to using one over the other? In Python 2, they both seem to return the same results:</p>
<pre><code>>>> 6/3
2
>>> 6//3
2
</code></pre>
|
[
{
"answer_id": 183863,
"author": "Adam Bellaire",
"author_id": 21632,
"author_profile": "https://Stackoverflow.com/users/21632",
"pm_score": 3,
"selected": false,
"text": "//"
},
{
"answer_id": 183865,
"author": "Mark Roddy",
"author_id": 9940,
"author_profile": "https://Stackoverflow.com/users/9940",
"pm_score": 3,
"selected": false,
"text": "// >>> 7//3\n2\n"
},
{
"answer_id": 183866,
"author": "Kena",
"author_id": 8027,
"author_profile": "https://Stackoverflow.com/users/8027",
"pm_score": 5,
"selected": false,
"text": "// 1.0/2.0 0.5 1/2 1//2 1.0//2.0 0"
},
{
"answer_id": 183870,
"author": "Eli Courtwright",
"author_id": 1694,
"author_profile": "https://Stackoverflow.com/users/1694",
"pm_score": 11,
"selected": true,
"text": "5 / 2 2.5 5 // 2 2 from __future__ import division 5.0 // 2 2.0"
},
{
"answer_id": 1704753,
"author": "u0b34a0f6ae",
"author_id": 137317,
"author_profile": "https://Stackoverflow.com/users/137317",
"pm_score": 5,
"selected": false,
"text": "// // / __future__ -Q old -Q new"
},
{
"answer_id": 11604247,
"author": "Yichun",
"author_id": 766827,
"author_profile": "https://Stackoverflow.com/users/766827",
"pm_score": 6,
"selected": false,
"text": "/ / int float"
},
{
"answer_id": 22487879,
"author": "Jonas Sciangula Street",
"author_id": 2246650,
"author_profile": "https://Stackoverflow.com/users/2246650",
"pm_score": 4,
"selected": false,
"text": ">>> print 5.0 / 2\n2.5\n\n>>> print 5.0 // 2\n2.0\n"
},
{
"answer_id": 30624406,
"author": "G.Ant",
"author_id": 4922716,
"author_profile": "https://Stackoverflow.com/users/4922716",
"pm_score": 2,
"selected": false,
"text": ">>>print 5//2\n2\n>>> print 5.0//2\n2.0\n>>>print 5//2.0\n2.0\n>>>print 5.0//2.0\n2.0\n"
},
{
"answer_id": 38552114,
"author": "N Randhawa",
"author_id": 4854721,
"author_profile": "https://Stackoverflow.com/users/4854721",
"pm_score": 5,
"selected": false,
"text": "print (2/3) ----> 0 Python 2.7\nprint (2/3) ----> 0.6666666666666666 Python 3.5\n print (4/2) ----> 2 Python 2.7\nprint (4/2) ----> 2.0 Python 3.5\n from __future__ import division\nprint (2/3) ----> 0.6666666666666666 # Python 2.7\nprint (4/2) ----> 2.0 # Python 2.7\n 138.93//3 ---> 46.0 # Python 2.7\n138.93//3 ---> 46.0 # Python 3.5\n4//3 ---> 1 # Python 2.7\n4//3 ---> 1 # Python 3.5\n"
},
{
"answer_id": 42053200,
"author": "Abrar Ahmad",
"author_id": 7519298,
"author_profile": "https://Stackoverflow.com/users/7519298",
"pm_score": 3,
"selected": false,
"text": "/ 4 / 2 = 2 // 9//2 = 4 9.0//2.0 = 4.0 -11//3 = -4 -11.0//3 = -4.0 / //"
},
{
"answer_id": 53234075,
"author": "Sebastian Purakan",
"author_id": 10631176,
"author_profile": "https://Stackoverflow.com/users/10631176",
"pm_score": -1,
"selected": false,
"text": "5.0//2 2.0 2 //"
},
{
"answer_id": 55317456,
"author": "Fatema Tuz Zuhora",
"author_id": 5403883,
"author_profile": "https://Stackoverflow.com/users/5403883",
"pm_score": 0,
"selected": false,
"text": "// / / // >>> print (11 / 3)\n3.6666666666666665\n\n>>> print (11 // 3)\n3\n\n>>> print (11.3 / 3)\n3.7666666666666667\n\n>>> print (11.3 // 3)\n3.0\n"
},
{
"answer_id": 56470206,
"author": "jaya ram",
"author_id": 10974987,
"author_profile": "https://Stackoverflow.com/users/10974987",
"pm_score": 2,
"selected": false,
"text": "// / >>> int(755349677599789174 / 2) # Wrong answer\n377674838799894592\n >>> 755349677599789174 // 2 # Correct answer\n377674838799894587\n"
},
{
"answer_id": 66835078,
"author": "iacob",
"author_id": 9067615,
"author_profile": "https://Stackoverflow.com/users/9067615",
"pm_score": 0,
"selected": false,
"text": "x / y x // y 1//2 0 (-1)//2 -1 1//(-2) -1 (-1)//(-2) 0 x / y x // y divmod() abs()"
},
{
"answer_id": 68579034,
"author": "naoki fujita",
"author_id": 5225993,
"author_profile": "https://Stackoverflow.com/users/5225993",
"pm_score": 0,
"selected": false,
"text": "import math\nN = 1004291331219602346 # huge number \n\nprint(N//100) #=> 10042913312196023 is correct answer\nprint(math.floor(N/100)) #=> 10042913312196024 is wrong answer\nprint(math.ceil(N/100)) #=> 10042913312196024 is wrong answer\nprint(int(N/100)) #=> 10042913312196024 is wrong answer\n int(x/y) x/y int(z)"
}
] |
2008/10/08
|
[
"https://Stackoverflow.com/questions/183853",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4872/"
] |
183,856
|
<p>Is there any way to clean up this type of loop using LINQ?</p>
<pre><code> List<Car> result;
List<string> makes;
List<string> models;
for (int i = 0; i < makes.Count() && i < models.Count(); i++)
{
result.Add(new Car() { Make = makes[i], Model = models[i] });
}
</code></pre>
<p>Basically I'm looking for some way to collate multiple arrays of individual fields into a single array of objects made up of those fields. </p>
|
[
{
"answer_id": 183891,
"author": "Bradley Grainger",
"author_id": 23633,
"author_profile": "https://Stackoverflow.com/users/23633",
"pm_score": 4,
"selected": true,
"text": "Enumerable.Range List<Car> result = Enumerable.Range(0, Math.Min(makes.Count, models.Count))\n .Select(i => new Car { Make = makes[i], Model = models[i] }).ToList();\n makes models List<Car> result = makes.Select((make, i) => new Car { Make = make, Model = models[i] }).ToList();\n"
},
{
"answer_id": 184064,
"author": "Robert Rossney",
"author_id": 19403,
"author_profile": "https://Stackoverflow.com/users/19403",
"pm_score": 1,
"selected": false,
"text": "IEnumerable<Car> IEnumerable<Car> cars = new MyClass(makes, models);\nvar result = from cars...\n IEnumerator<Car> IEnumerable<T>"
},
{
"answer_id": 184106,
"author": "Jon Skeet",
"author_id": 22656,
"author_profile": "https://Stackoverflow.com/users/22656",
"pm_score": 2,
"selected": false,
"text": "List<Car> cars = makes.Zip(models)\n .Select(pair => new Car(pair.First, pair.Second))\n .ToList();\n"
},
{
"answer_id": 187883,
"author": "hwiechers",
"author_id": 5883,
"author_profile": "https://Stackoverflow.com/users/5883",
"pm_score": 1,
"selected": false,
"text": "List<Car> result = makes\n .Take(model.Count)\n .Select((make, index) => new Car {Make = make, Model = models[index]});\n"
}
] |
2008/10/08
|
[
"https://Stackoverflow.com/questions/183856",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/327/"
] |
183,859
|
<p>Our base Masterpage has something like the following</p>
<pre><code> <head runat="server">
<title></title>
<script type="text/javascript" src="<%= Page.ResolveClientURL("~/javascript/actions.js")%>"></script>
<script type="text/javascript" src="<%= Page.ResolveClientURL("~/javascript/jquery/jquery-1.2.6.min.js")%>"></script>
<asp:contentplaceholder id="cph_htmlhead" runat="server">
</asp:contentplaceholder>
</head>
</code></pre>
<p>If this Masterpage is the Masterpage for an ASPX page things work fine.</p>
<p>If this Masterpage is the Masterpage for a child Masterpage and then a new ASPX page uses the child Masterpage as it's MasterPage we see:</p>
<p>Server Error in '' Application. </p>
<p>The Controls collection cannot be modified because the control contains code blocks (i.e. <% ... %>).</p>
<p><strong>What is the preferred way to include global resources (Javascript/CSS) in a base Masterpage preserving tilde(~) style relative pathing?</strong></p>
|
[
{
"answer_id": 183905,
"author": "Shawn Miller",
"author_id": 247,
"author_profile": "https://Stackoverflow.com/users/247",
"pm_score": 3,
"selected": false,
"text": "<script type=\"text/javascript\" src='<%= Page.ResolveClientUrl(\"~/javascript/actions.js\") %>'></script>\n"
},
{
"answer_id": 184952,
"author": "Kon",
"author_id": 22303,
"author_profile": "https://Stackoverflow.com/users/22303",
"pm_score": 5,
"selected": true,
"text": " <asp:ScriptManager ID=\"myScriptManager\" runat=\"server\">\n <Scripts>\n <asp:ScriptReference Path = \"~/javascript/actions.js\" /> \n <asp:ScriptReference Path = \"~/javascript/jquery/jquery-1.2.6.min.js\" />\n </Scripts>\n </asp:ScriptManager>\n"
}
] |
2008/10/08
|
[
"https://Stackoverflow.com/questions/183859",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/439/"
] |
183,881
|
<p>I'm working on a home project that involves comparing images to a database of images (using a quadrant - or so - histogram approach). I wanted to know what my options are in regards to web cams or other image capture devices that:</p>
<ul>
<li>Are easy to work with with the
Windows SDK (particularly
<a href="http://msdn.microsoft.com/en-us/library/ms783323(VS.85).aspx" rel="nofollow noreferrer">DirectShow</a>, which I plan to use
with C#) </li>
<li>Have drivers for both
64-bit and 32-bit Windows Vista (and
Server 2008)</li>
</ul>
<p>I'm asking primarily so I can avoid pitfalls that other people may have experienced with web cams and to see if there are other image capture devices (or C# usable APIs) available that I should look at. I suspect that any old web cam will do but I'd rather be safe than sorry.</p>
|
[
{
"answer_id": 183905,
"author": "Shawn Miller",
"author_id": 247,
"author_profile": "https://Stackoverflow.com/users/247",
"pm_score": 3,
"selected": false,
"text": "<script type=\"text/javascript\" src='<%= Page.ResolveClientUrl(\"~/javascript/actions.js\") %>'></script>\n"
},
{
"answer_id": 184952,
"author": "Kon",
"author_id": 22303,
"author_profile": "https://Stackoverflow.com/users/22303",
"pm_score": 5,
"selected": true,
"text": " <asp:ScriptManager ID=\"myScriptManager\" runat=\"server\">\n <Scripts>\n <asp:ScriptReference Path = \"~/javascript/actions.js\" /> \n <asp:ScriptReference Path = \"~/javascript/jquery/jquery-1.2.6.min.js\" />\n </Scripts>\n </asp:ScriptManager>\n"
}
] |
2008/10/08
|
[
"https://Stackoverflow.com/questions/183881",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5645/"
] |
183,882
|
<p>I'm currently in the process of choosing a project for a grad-level compiler course to be done over the next 8 weeks. I'd like to do something related to optimization since I haven't worked much in that area before, but anything in the field is fair game. </p>
<p>What was the most interesting compiler-related project you've done? What did you learn the most from?</p>
<hr>
<p><strong>Edit:</strong> Thank you all for your great suggestions. I apologize for not updating this for so long.</p>
<p>The project I ended up doing was a simple autovectorization optimization on LLVM. LLVM has vector types, but there didn't seem to be any way to take advantage of them without support for the front-end. This optimization converted normal scalar code into vector code.</p>
<p>Since auto-vectorization is a fairly difficult optimization to implement, we limited our scope as much as we could. First, in order to expose instruction level parallelism in the code, we looked for one-block loops that matched our criteria, then unrolled them a specific number of times so they would be conveniently vectorizable. We then implemented the packing algorithm laid out in <a href="http://groups.csail.mit.edu/cag/slp/SLarsen-SM.pdf" rel="noreferrer">Exploiting Superword Level Parallelism with Multimedia Instruction Sets</a> by Larsen and Amarasinghe.</p>
<p>Even a simplified version of this optimization is pretty complicated. There are a lot of constraints; for instance, you don't want to vectorize a variable that lives out of the loop, since the rest of the program expects it to be scalar. We put in a lot of hours in the last few weeks. The project was a lot of fun though, and we learned a lot. </p>
|
[
{
"answer_id": 184156,
"author": "leppie",
"author_id": 15541,
"author_profile": "https://Stackoverflow.com/users/15541",
"pm_score": 2,
"selected": false,
"text": ":)"
}
] |
2008/10/08
|
[
"https://Stackoverflow.com/questions/183882",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1891/"
] |
183,887
|
<p>Every once in a while, typically when I stop debugging in our UI assembly, I get the following error which requires a restart of Visual Studio 2008 and it's killing my productivity:</p>
<blockquote>
<p>Error 13 Unable to copy file
[UI assembly]
to
[output directory].
The process cannot access the file
[output directory][UI assembly]
because it is being used by another
process.</p>
</blockquote>
<p>After restarting, I get this error:</p>
<blockquote>
<p>Error 1 Metadata file [utility function assembly in RELEASE folder] could not
be found.</p>
</blockquote>
<p>I find this really, really odd because we never use the Release configuration.</p>
<p>I'm using VS 2k8 SP1 on Windows Vista. </p>
<p>I know that it's the VS debugger that's not releasing its file handle by using the handle utility (formerly from Sysinternals). The process is devenv.exe.</p>
<p>I've tried closing and reopening the solution. Didn't work. Only a full VS2k8 restart works.</p>
<p>I've tried adding a pre-build event, to move the file as described <a href="http://forums.msdn.microsoft.com/en-US/vbide/thread/cd12f3c7-de96-4353-adce-23975e30933f/" rel="noreferrer">here</a>, but that doesn't work because Windows can't delete the file for the same reason it can't replace it: it's got an open handle.</p>
<p>I even tried manually closing the handle using the handle.exe util described above, then trying the pre-build event. Visual Studio apparently doesn't know its handle has been closed because the VS build fails, but handle.exe shows no open file handles on the file in question.</p>
<p>For the record, here are the add-ins I run:</p>
<ul>
<li>ReSharper 4</li>
<li>Smart Paster 2008</li>
<li>Typemock Isolator</li>
<li>TestDriven.NET 2.13.2184</li>
</ul>
<p>I also use Developer Express controls for this project, so that may have something to do with it as well.</p>
|
[
{
"answer_id": 550359,
"author": "Bryan",
"author_id": 22033,
"author_profile": "https://Stackoverflow.com/users/22033",
"pm_score": 1,
"selected": false,
"text": "<hostingEnvironment shadowCopyBinAssemblies=\"false\"/>\n"
}
] |
2008/10/08
|
[
"https://Stackoverflow.com/questions/183887",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/549/"
] |
183,898
|
<p>How do I do forward referencing / declaration in C++ to avoid circular header file references?</p>
<p>I have the #ifndef guard in the header file, yet memory tells me I need this forward referencing thing - which i've used before >< but can't remember how. </p>
|
[
{
"answer_id": 183908,
"author": "antik",
"author_id": 1625,
"author_profile": "https://Stackoverflow.com/users/1625",
"pm_score": 5,
"selected": true,
"text": "//#include \"Foo.h\" // including Foo.h causes circular reference\nclass Foo;\n\nclass Bar\n{\n...\n};\n"
}
] |
2008/10/08
|
[
"https://Stackoverflow.com/questions/183898",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/209/"
] |
183,901
|
<p>Is there a way to start PowerShell in a specific folder from Windows Explorer, e.g. to right-click in a folder and have an option like "Open PowerShell in this Folder"?</p>
<p>It's really annoying to have to change directories to my project folder the first time I run MSBuild every day.</p>
|
[
{
"answer_id": 183955,
"author": "EBGreen",
"author_id": 1358,
"author_profile": "https://Stackoverflow.com/users/1358",
"pm_score": 7,
"selected": false,
"text": "ii .\n start .\n"
},
{
"answer_id": 6599296,
"author": "Ashwin Nanjappa",
"author_id": 1630,
"author_profile": "https://Stackoverflow.com/users/1630",
"pm_score": 10,
"selected": true,
"text": "powershell powershell_ise"
},
{
"answer_id": 24603961,
"author": "geo",
"author_id": 2002992,
"author_profile": "https://Stackoverflow.com/users/2002992",
"pm_score": 6,
"selected": false,
"text": "Windows Registry Editor Version 5.00\n\n;\n; Add context menu entry to Windows Explorer background\n;\n[HKEY_CLASSES_ROOT\\Directory\\Background\\shell\\powershell]\n@=\"Open PowerShell window here\"\n\"NoWorkingDirectory\"=\"\"\n\n[HKEY_CLASSES_ROOT\\Directory\\Background\\shell\\powershell\\command]\n@=\"C:\\\\Windows\\\\System32\\\\WindowsPowerShell\\\\v1.0\\\\powershell.exe -NoExit -Command Set-Location -LiteralPath '%V'\"\n\n;\n; Add context menu entry to Windows Explorer folders\n;\n[HKEY_CLASSES_ROOT\\Directory\\shell\\powershell]\n@=\"Open PowerShell window here\"\n\"NoWorkingDirectory\"=\"\"\n\n[HKEY_CLASSES_ROOT\\Directory\\shell\\powershell\\command]\n@=\"C:\\\\Windows\\\\System32\\\\WindowsPowerShell\\\\v1.0\\\\powershell.exe -NoExit -Command Set-Location -LiteralPath '%V'\"\n\n;\n; Add context menu entry to Windows Explorer drive icons\n;\n[HKEY_CLASSES_ROOT\\Drive\\shell\\powershell]\n@=\"Open PowerShell window here\"\n\"NoWorkingDirectory\"=\"\"\n\n[HKEY_CLASSES_ROOT\\Drive\\shell\\powershell\\command]\n@=\"C:\\\\Windows\\\\System32\\\\WindowsPowerShell\\\\v1.0\\\\powershell.exe -NoExit -Command Set-Location -LiteralPath '%V'\"\n HKCR\\Directory\\Shell Computer -> C: -> to -> Some -> Target -> Directory"
},
{
"answer_id": 26351189,
"author": "Daniel Sokolowski",
"author_id": 913223,
"author_profile": "https://Stackoverflow.com/users/913223",
"pm_score": 3,
"selected": false,
"text": ".reg power-shell-here-on-shift.reg Windows Registry Editor Version 5.00\n\n[HKEY_CLASSES_ROOT\\Directory\\shell\\powershell]\n@=\"Open PowerShell here\"\n\"NoWorkingDirectory\"=\"\"\n\"Extended\"=\"\"\n\n[HKEY_CLASSES_ROOT\\Directory\\shell\\powershell\\command]\n@=\"C:\\\\Windows\\\\system32\\\\WindowsPowerShell\\\\v1.0\\\\powershell.exe -NoExit -Command Set-Location -LiteralPath '%L'\"\n"
},
{
"answer_id": 34852310,
"author": "Rhys",
"author_id": 5804519,
"author_profile": "https://Stackoverflow.com/users/5804519",
"pm_score": 2,
"selected": false,
"text": "SHIFT + RClick .reg Windows Registry Editor Version 5.00\n\n[HKEY_LOCAL_MACHINE\\SOFTWARE\\Classes\\Directory\\background\\shell\\powershell]\n\"Extended\"=\"\"\n\"NoWorkingDirectory\"=\"\"\n@=\"Open PowerShell here\"\n\"Icon\"=\"%SystemRoot%\\\\system32\\\\WindowsPowerShell\\\\v1.0\\\\powershell.exe\"\n\n[HKEY_LOCAL_MACHINE\\SOFTWARE\\Classes\\Directory\\background\\shell\\powershell\\command]\n@=\"C:\\\\Windows\\\\system32\\\\WindowsPowerShell\\\\v1.0\\\\powershell.exe -NoExit -Command Set-Location -LiteralPath '%V'\"\n\n[HKEY_LOCAL_MACHINE\\SOFTWARE\\Classes\\Directory\\shell\\powershell]\n@=\"Open PowerShell here\"\n\"Extended\"=\"\"\n\"Icon\"=\"%SystemRoot%\\\\system32\\\\WindowsPowerShell\\\\v1.0\\\\powershell.exe\"\n\"NoWorkingDirectory\"=\"\"\n\n[HKEY_LOCAL_MACHINE\\SOFTWARE\\Classes\\Directory\\shell\\powershell\\command]\n@=\"C:\\\\Windows\\\\system32\\\\WindowsPowerShell\\\\v1.0\\\\powershell.exe -NoExit -Command Set-Location -LiteralPath '%V'\"\n"
},
{
"answer_id": 40478085,
"author": "frank tan",
"author_id": 6487391,
"author_profile": "https://Stackoverflow.com/users/6487391",
"pm_score": 1,
"selected": false,
"text": "New-PSDrive -Name HKCR -PSProvider Registry -Root HKEY_CLASSES_ROOT\nif(-not (Test-Path -Path \"HKCR:\\Directory\\shell\\$KeyName\"))\n{\n Try\n {\n New-Item -itemType String \"HKCR:\\Directory\\shell\\$KeyName\" -value \"Open PowerShell in this Folder\" -ErrorAction Stop\n New-Item -itemType String \"HKCR:\\Directory\\shell\\$KeyName\\command\" -value \"$env:SystemRoot\\system32\\WindowsPowerShell\\v1.0\\powershell.exe -noexit -command Set-Location '%V'\" -ErrorAction Stop\n Write-Host \"Successfully!\"\n }\n Catch\n {\n Write-Error $_.Exception.Message\n }\n}\nelse\n{\n Write-Warning \"The specified key name already exists. Type another name and try again.\"\n}\n"
},
{
"answer_id": 44737689,
"author": "np8",
"author_id": 3015186,
"author_profile": "https://Stackoverflow.com/users/3015186",
"pm_score": 1,
"selected": false,
"text": "Ctrl-Alt-T <DefaultPath> ; Ctrl-Alt-T opens PowerShell in the current folder, if using Windows Explorer. Otherwise, just open the Powershell.\n^!T::\nif WinActive(\"ahk_class CabinetWClass\") and WinActive(\"ahk_exe explorer.exe\")\n{\n KeyWait Control\n KeyWait Alt\n Send {Ctrl down}l{Ctrl up}\n Send powershell{Enter}\n}\nelse\n{\n psScript =\n (\n cd 'C:\\<DefaultPath>'\n ls\n )\n Run \"%SystemRoot%\\system32\\WindowsPowerShell\\v1.0\\powershell.exe\" -NoExit -Command &{%psScript%}\n}\nreturn\n"
},
{
"answer_id": 60482308,
"author": "Craigo",
"author_id": 418057,
"author_profile": "https://Stackoverflow.com/users/418057",
"pm_score": 4,
"selected": false,
"text": "Open PowerShell window here File Open Windows PowerShell File Open Windows PowerShell Add to Quick Access Toolbar"
},
{
"answer_id": 67489439,
"author": "Tim Truston",
"author_id": 1619619,
"author_profile": "https://Stackoverflow.com/users/1619619",
"pm_score": 1,
"selected": false,
"text": "Windows Registry Editor Version 5.00\n\n;\n; Add context menu entry to Windows Explorer folders\n;\n[HKEY_CLASSES_ROOT\\Directory\\shell\\powershellmenu]\n@=\"PowerShell Here\"\n\n[HKEY_CLASSES_ROOT\\Directory\\shell\\powershellmenu\\command]\n@=\"C:\\\\\\\\Windows\\\\\\\\system32\\\\\\\\WindowsPowerShell\\\\\\\\v1.0\\\\\\\\powershell.exe -NoExit -Command Set-Location -LiteralPath '%L'\"\n\n;\n; Add context menu entry to Windows Explorer background\n;\n[HKEY_CLASSES_ROOT\\Directory\\Background\\shell\\powershellmenu]\n@=\"PowerShell Here\"\n\"NoWorkingDirectory\"=\"\"\n\n[HKEY_CLASSES_ROOT\\Directory\\Background\\shell\\powershellmenu\\command]\n@=\"C:\\\\Windows\\\\System32\\\\WindowsPowerShell\\\\v1.0\\\\powershell.exe -NoExit -Command Set-Location -LiteralPath '%V'\"\n\n;\n; Add context menu entry to Windows Explorer drive icons\n;\n[HKEY_CLASSES_ROOT\\Drive\\shell\\powershellmenu]\n@=\"PowerShell Here\"\n\"NoWorkingDirectory\"=\"\"\n\n[HKEY_CLASSES_ROOT\\Drive\\shell\\powershellmenu\\command]\n@=\"C:\\\\Windows\\\\System32\\\\WindowsPowerShell\\\\v1.0\\\\powershell.exe -NoExit -Command Set-Location -LiteralPath '%V'\"\n\n"
}
] |
2008/10/08
|
[
"https://Stackoverflow.com/questions/183901",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/549/"
] |
183,904
|
<p>In the following code below:</p>
<pre><code>Image img = new Image();
img.Source = new BitmapImage(new Uri("http://someURL/somefilename.jpg", UriKind.Absolute));
</code></pre>
<p>how can I determine if the image successfully loaded (when there's a valid URI)? i.e., The URI is a valid format, but the file may not exist. </p>
|
[
{
"answer_id": 184069,
"author": "Joel B Fant",
"author_id": 22211,
"author_profile": "https://Stackoverflow.com/users/22211",
"pm_score": 1,
"selected": false,
"text": "Image ImageFailed BitmapSource BitmapImage IsDownloading DownloadProgress DownloadCompleted DownloadFailed"
},
{
"answer_id": 189278,
"author": "Bryant",
"author_id": 10893,
"author_profile": "https://Stackoverflow.com/users/10893",
"pm_score": 0,
"selected": false,
"text": "Error: Sys.InvalidOperationException: ImageError error #4001 in control 'Xaml1': AG_E_NETWORK_ERROR\n"
}
] |
2008/10/08
|
[
"https://Stackoverflow.com/questions/183904",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/26218/"
] |
183,907
|
<p>Say you've loaded a text file into a string, and you'd like to convert all Unicode escapes into actual Unicode characters inside of the string. </p>
<p>Example:</p>
<blockquote>
<p>"The following is the top half of an integral character in Unicode '\u2320', and this is the lower half '\U2321'."</p>
</blockquote>
|
[
{
"answer_id": 183909,
"author": "jr.",
"author_id": 2415,
"author_profile": "https://Stackoverflow.com/users/2415",
"pm_score": 7,
"selected": true,
"text": "Regex rx = new Regex( @\"\\\\[uU]([0-9A-F]{4})\" );\nresult = rx.Replace( result, match => ((char) Int32.Parse(match.Value.Substring(2), NumberStyles.HexNumber)).ToString() );\n Regex rx = new Regex( @\"\\\\[uU]([0-9A-F]{4})\" );\nresult = rx.Replace( result, delegate (Match match) { return ((char) Int32.Parse(match.Value.Substring(2), NumberStyles.HexNumber)).ToString(); } );\n new Regex( @\"\\\\[uU]([0-9A-F]{4})\" );\n ((char) Int32.Parse(match.Value.Substring(2), NumberStyles.HexNumber)).ToString(); });\n match.Value.Substring(2)\n NumberStyles.HexNumber\n (char)\n .ToString()\n"
},
{
"answer_id": 462586,
"author": "George Tsiokos",
"author_id": 5869,
"author_profile": "https://Stackoverflow.com/users/5869",
"pm_score": 3,
"selected": false,
"text": "Regex regex = new Regex (@\"\\\\U([0-9A-F]{4})\", RegexOptions.IgnoreCase);\nstring line = \"...\";\nline = regex.Replace (line, match => ((char)int.Parse (match.Groups[1].Value,\n NumberStyles.HexNumber)).ToString ());\n"
},
{
"answer_id": 11330975,
"author": "Baseem Najjar",
"author_id": 1472118,
"author_profile": "https://Stackoverflow.com/users/1472118",
"pm_score": 1,
"selected": false,
"text": "Regex rx = new Regex(@\"\\\\[uU]([0-9A-Fa-f]{4})\");\nresult = rx.Replace(result, match => ((char) Int32.Parse(match.Value.Substring(2), NumberStyles.HexNumber)).ToString());\n"
},
{
"answer_id": 13142504,
"author": "Tarık Özgün Güner",
"author_id": 1786056,
"author_profile": "https://Stackoverflow.com/users/1786056",
"pm_score": 3,
"selected": false,
"text": "Dim rx As New RegularExpressions.Regex(\"\\\\[uU]([0-9A-Fa-f]{4})\")\nresult = rx.Replace(result, Function(match) CChar(ChrW(Int32.Parse(match.Value.Substring(2), Globalization.NumberStyles.HexNumber))).ToString())\n"
},
{
"answer_id": 70197702,
"author": "Darzi",
"author_id": 17548939,
"author_profile": "https://Stackoverflow.com/users/17548939",
"pm_score": 1,
"selected": false,
"text": "UnicodeExtensions.cs public static class UnicodeExtensions\n{\n private static readonly Regex Regex = new Regex(@\"\\\\[uU]([0-9A-Fa-f]{4})\");\n\n public static string UnescapeUnicode(this string str)\n {\n return Regex.Replace(str,\n match => ((char) int.Parse(match.Value.Substring(2),\n NumberStyles.HexNumber)).ToString());\n }\n}\n var test = \"\\\\u0074\\\\u0068\\\\u0069\\\\u0073 \\\\u0069\\\\u0073 \\\\u0074\\\\u0065\\\\u0073\\\\u0074\\\\u002e\";\nvar output = test.UnescapeUnicode(); // output is => this is test.\n"
}
] |
2008/10/08
|
[
"https://Stackoverflow.com/questions/183907",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2415/"
] |
183,914
|
<pre><code>echo $_POST["name"]; //returns the value a user typed into the "name" field
</code></pre>
<p>I would like to be able to also return the text of the key. In this example, I want to return the text "name". Can I do this?</p>
|
[
{
"answer_id": 183917,
"author": "Matthias Winkelmann",
"author_id": 4494,
"author_profile": "https://Stackoverflow.com/users/4494",
"pm_score": 1,
"selected": false,
"text": "array_keys($_POST)\n"
},
{
"answer_id": 184104,
"author": "Mark Biek",
"author_id": 305,
"author_profile": "https://Stackoverflow.com/users/305",
"pm_score": 5,
"selected": false,
"text": "foreach($_POST as $key=>$value)\n{\n echo \"$key=$value\";\n}\n"
},
{
"answer_id": 261281,
"author": "Tim",
"author_id": 33914,
"author_profile": "https://Stackoverflow.com/users/33914",
"pm_score": 2,
"selected": false,
"text": "while( list( $field, $value ) = each( $_POST )) {\n echo \"<p>\" . $field . \" = \" . $value . \"</p>\\n\";\n}\n"
},
{
"answer_id": 1137018,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": ") while( list( $field, $value ) = each( $_POST )) {\n echo \"<p>\" . $field . \" = \" . $value . \"</p>\\n\";\n}\n"
},
{
"answer_id": 7777353,
"author": "Uğur Gümüşhan",
"author_id": 964196,
"author_profile": "https://Stackoverflow.com/users/964196",
"pm_score": 1,
"selected": false,
"text": "foreach($_POST as $rvar)\n{\n $rvarkey=key($_POST)\n $$rvarkey=mysql_real_escape_string($rvar);\n}\n\nit creates variables having the name of the request parameters which is pretty awesome.\n"
}
] |
2008/10/08
|
[
"https://Stackoverflow.com/questions/183914",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16292/"
] |
183,921
|
<p>I'd like all queries like</p>
<pre><code>http://mysite.com/something/otherthing?foo=bar&x=y
</code></pre>
<p>to be rewritten as</p>
<pre><code>http://mysite.com/something/otherthing.php?foo=bar&x=y
</code></pre>
<p>In other words, just make the .php extension optional, universally.</p>
|
[
{
"answer_id": 183931,
"author": "theraccoonbear",
"author_id": 7210,
"author_profile": "https://Stackoverflow.com/users/7210",
"pm_score": 0,
"selected": false,
"text": "RewriteRule /something/(.+)?(.+) /something/$1.php?$2\n"
},
{
"answer_id": 183969,
"author": "dreeves",
"author_id": 4234,
"author_profile": "https://Stackoverflow.com/users/4234",
"pm_score": 1,
"selected": false,
"text": "RewriteCond %{QUERY_STRING} ^.+$\nRewriteRule ^/?([^/\\.]+)$ /$1.php [L]\n"
},
{
"answer_id": 184544,
"author": "Darryl Hein",
"author_id": 5441,
"author_profile": "https://Stackoverflow.com/users/5441",
"pm_score": 1,
"selected": false,
"text": "ForceType application/x-httpd-php\n"
},
{
"answer_id": 190364,
"author": "eyelidlessness",
"author_id": 17964,
"author_profile": "https://Stackoverflow.com/users/17964",
"pm_score": 0,
"selected": false,
"text": "RewriteRule ^(([^/]+/+)*[^\\.]+)$ $1.php\n RewriteCond %{QUERY_STRING} ^(.*)$\nRewriteRule ^(([^/]+/+)*[^\\.]+)$ $1.php?%1\n"
},
{
"answer_id": 383672,
"author": "Chris Bartow",
"author_id": 497,
"author_profile": "https://Stackoverflow.com/users/497",
"pm_score": 4,
"selected": true,
"text": "RewriteCond %{REQUEST_FILENAME} !-f\nRewriteCond %{REQUEST_FILENAME} !-d\nRewriteRule ^(.+)$ $1.php [QSA,L]\n"
}
] |
2008/10/08
|
[
"https://Stackoverflow.com/questions/183921",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4234/"
] |
183,923
|
<p>I have a class that has a Generic type "G"</p>
<p>In my class model i have</p>
<pre><code>public class DetailElement : ElementDefinition
</code></pre>
<p>Let's say i have a method like this</p>
<pre><code> public void DoSomething<G>(G generic)
where G : ElementDefinition
{
if (generic is DetailElement)
{
((DetailElement)generic).DescEN = "Hello people"; //line 1
//////
ElementDefinition element = generic;
((DetailElement)element).DescEN = "Hello again"; //line 3
//////
(generic as DetailElement).DescEN = "Howdy"; //line 5
}
else
{
//do other stuff
}
}
</code></pre>
<p>Compiler reports one error in line 1:</p>
<pre><code>Cannot convert type 'G' to 'DetailElement'
</code></pre>
<p>But line 3 works fine.
I can workaround this issue by doing the code written in line 5.</p>
<p><strong>What i would like to know is why does the compiler reports the error in line 1 and not the one in line 3, given that, as far as i know, they are identical.</strong></p>
<p>edit: I am afraid i might be missing some important piece of the framework logic</p>
<p>edit2: Although solutions for the compiler error are important, my question is about why the compiler reports an error on line 1 and not in line 3.</p>
|
[
{
"answer_id": 183949,
"author": "benjismith",
"author_id": 22979,
"author_profile": "https://Stackoverflow.com/users/22979",
"pm_score": 1,
"selected": false,
"text": "DetailElement detail = generic as DetailElement;\nif (detail == null) {\n // process other types of ElementDefinition\n} else {\n // process DetailElement objects\n}\n"
},
{
"answer_id": 183951,
"author": "Mark Cidade",
"author_id": 1659,
"author_profile": "https://Stackoverflow.com/users/1659",
"pm_score": 4,
"selected": true,
"text": "G DetailElement where G : DetailElement G (ElementDefinition) generic G ElementDefinition DetailElement ElementDefinition as as ElementDefinition interface ISomeInterface {...}\n class SomeClass {...}\n class MyClass<T> \n {\n void SomeMethod(T t)\n {\n ISomeInterface obj1 = (ISomeInterface)t;//Compiles\n SomeClass obj2 = (SomeClass)t; //Does not compile\n }\n }\n void SomeMethod<T>(T t) \n { object temp = t;\n MyOtherClass obj = (MyOtherClass)temp; \n }\n is as is as public void SomeMethod(T t)\n {\n if(t is int) {...}\n\n string str = t as string;\n if(str != null) {...}\n }\n"
},
{
"answer_id": 184208,
"author": "Guvante",
"author_id": 16800,
"author_profile": "https://Stackoverflow.com/users/16800",
"pm_score": 0,
"selected": false,
"text": " public void DoSomething<G>(G generic)\n where G : ElementDefinition\n {\n DetailElement detail = generic as DetailElement;\n if (detail != null)\n {\n detail.DescEN = \"Hello people\";\n }\n else\n {\n //do other stuff\n }\n }\n DetailElement detail = (DetailElement)(object)generic;\n"
},
{
"answer_id": 184393,
"author": "Michael Meadows",
"author_id": 7643,
"author_profile": "https://Stackoverflow.com/users/7643",
"pm_score": 1,
"selected": false,
"text": "public void DoSomething(DetailElement detailElement)\n{\n // do DetailElement specific stuff\n}\n\npublic void DoSomething<G>(G elementDefinition)\n where G : ElementDefinition\n{\n // do generic ElementDefinition stuff\n}\n DetailElement foo = new DetailElement();\n\nDoSomething(foo); // calls the non-generic method\nDoSomething((ElementDefinition) foo); // calls the generic method\n"
}
] |
2008/10/08
|
[
"https://Stackoverflow.com/questions/183923",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20335/"
] |
183,928
|
<p>How do I create subdomain like <code>http://user.mywebsite.example</code>? Do I have to access <code>.htaccess</code> somehow? Is it actually simply possible to create it via pure PHP code or I need to use some external script-server side language?</p>
<p>To those who answered: Well, then, should I ask my hosting if they provide some sort of DNS access?</p>
|
[
{
"answer_id": 183971,
"author": "Mark Biek",
"author_id": 305,
"author_profile": "https://Stackoverflow.com/users/305",
"pm_score": 8,
"selected": true,
"text": "*.mywebsite.example IN A 127.0.0.1\n 127.0.0.1 server_name .mywebsite.example ServerAlias *.mywebsite.example HTTP_HOST $username = strtok($_SERVER['HTTP_HOST'], \".\");\n http://mywebsite.example/user"
},
{
"answer_id": 184217,
"author": "gradbot",
"author_id": 17919,
"author_profile": "https://Stackoverflow.com/users/17919",
"pm_score": 5,
"selected": false,
"text": "RewriteCond {REQUEST_URI} !\\.(png|gif|jpg)$\nRewriteCond %{REQUEST_FILENAME} !-f\nRewriteRule ^(.*)$ /index.php?uri=$1&hostName=%{HTTP_HOST}\n index.php http://fred.mywebsite.example/album/Dance/now\n http://fred.mywebsite.example/index.php?uri=album/Dance/now&hostName=fred.mywebsite.example\n index.php"
},
{
"answer_id": 185275,
"author": "Willem",
"author_id": 15447,
"author_profile": "https://Stackoverflow.com/users/15447",
"pm_score": 3,
"selected": false,
"text": ".htaccess #include part of the server name in the filenames VirtualDocumentRoot /www/hosts/%2/docs DOCUMENT_ROOT"
},
{
"answer_id": 602683,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 4,
"selected": false,
"text": "*.yourname.example $url=$_SERVER[\"REQUEST_URI\"];\n$account=str_replace(\".yourdomain.com\",\"\",$url);\n $account .htaccess"
},
{
"answer_id": 3617461,
"author": "balupton",
"author_id": 130638,
"author_profile": "https://Stackoverflow.com/users/130638",
"pm_score": 5,
"selected": false,
"text": "<VirtualHost 111.22.33.55>\n DocumentRoot /www/subdomain\n ServerName www.domain.example\n ServerAlias *.domain.example\n</VirtualHost>\n httpd.conf .htaccess"
},
{
"answer_id": 27627125,
"author": "Alex Khimich",
"author_id": 2213708,
"author_profile": "https://Stackoverflow.com/users/2213708",
"pm_score": 3,
"selected": false,
"text": "example.org A record => *.example.org\nA record => *.example.net\n // Request was http://qwerty.example.org\n $q = explode('.', $_SERVER['HTTP_HOST']);\n /*\n We get following array\n Array\n (\n [0] => qwerty\n [1] => example\n [2] => org\n )\n */\n\n // Step 4.\n // If second piece of array exists, request was for\n // SUBDOMAIN which is stored in zero-piece $q[0]\n // otherwise it was for DOMAIN\n\n if(isset($q[2])) {\n // Find stuff in database for login $q[0] or here it is \"qwerty\"\n // Use $q[1] to check which domain is asked if u serve multiple domains\n }\n\n?>\n qwerty.example.org\nqwerty.example.net\n\njohnsmith.somecompany.example\npaulsmith.somecompany.example\n smith.example.org // Show info about John Smith\nsmith.example.net // Show info about Paul Smith\n"
},
{
"answer_id": 36459894,
"author": "Dan Bray",
"author_id": 2452680,
"author_profile": "https://Stackoverflow.com/users/2452680",
"pm_score": 2,
"selected": false,
"text": ".htaccess * .htaccess RewriteEngine On\nRewriteCond %{HTTP_HOST} !^www\\.website\\.example$\nRewriteCond %{HTTP_HOST} ^(\\w+)\\.website\\.example$\nRewriteCond %{REQUEST_URI}:%1 !^/([^/]+)/([^:]*):\\1\nRewriteRule ^(.*)$ /%1/$1 [QSA]\n"
},
{
"answer_id": 58730883,
"author": "Abdo-Host",
"author_id": 2262856,
"author_profile": "https://Stackoverflow.com/users/2262856",
"pm_score": 0,
"selected": false,
"text": ".htaccess .htaccess http://www.yourwebsite.example http://yourwebsite.example RewriteEngine On\n\nRewriteCond %{HTTP_HOST} ^www.yourwebsite.example\nRewriteRule (.*) http://yourwebsite.example/$1 [R=301,L]\n\nRewriteCond %{HTTP_HOST} ^yourwebsite\\.example $\nRewriteCond %{REQUEST_URI} !^/yourwebsite_folder/\nRewriteRule (.*) /yourwebsite_folder/$1\n\nRewriteCond %{HTTP_HOST} ^(^.*)\\.yourwebsite.example\nRewriteCond %{REQUEST_URI} !^/yourwebsite_folder/\nRewriteRule (.*) /yourwebsite_folder/$1\n .htaccess http://yourwebsite.example/index.php?siteName=9lessons http://9lessons.yourwebsite.example Options +FollowSymLinks\nRewriteEngine On\n\nRewriteBase /\n\nRewriteRule ^([aA-zZ])$ index.php?siteName=$1\nRewriteCond %{HTTP_HOST} ^(^.*)\\.yourwebsite.example\nRewriteRule (.*) index.php?siteName=%1\n .htaccess <?php\n$siteName='';\nif($_GET['siteName'] )\n{\n$sitePostName=$_GET['siteName'];\n$siteNameCheck = preg_match('~^[A-Za-z0-9_]{3,20}$~i', $sitePostName);\n if($siteNameCheck)\n {\n //Do something. Eg: Connect database and validate the siteName.\n }\n else\n {\n header(\"Location: http://yourwebsite.example/404.php\");\n }\n}\n?>\n//HTML Code\n<!DOCTYPE html>\n<html>\n<head>\n<title>Project Title</title>\n</head>\n<body>\n<?php if($siteNameCheck) { ?>\n//Home Page\n<?php } else { ?>\n//Redirect to Subdomain Page.\n<?php } ?>\n</body>\n</html>\n .htaccess Options +FollowSymLinks\nRewriteEngine On\n\nRewriteBase /\n\nRewriteCond %{HTTP_HOST} ^www.yourwebsite.example\nRewriteRule (.*) http://yourwebsite.example/$1 [R=301,L]\n\nRewriteRule ^([aA-zZ])$ index.php?siteName=$1\nRewriteCond %{HTTP_HOST} ^(^.*)\\.yourwebsite.example\nRewriteRule (.*) index.php?siteName=%1\n"
},
{
"answer_id": 73524700,
"author": "David Warutumo",
"author_id": 14574573,
"author_profile": "https://Stackoverflow.com/users/14574573",
"pm_score": -1,
"selected": false,
"text": "<?php\n \n$link = $_SERVER['HTTP_HOST'];\n$actual_link = 'http://'.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];\n?>\n\n<!DOCTYPE html>\n<html lang=\"en\">\n \n <head>\n \n <title>Wildcard Subdomain</title>\n \n </head>\n \n <body>\n <h1>The visitor went to \n <?php \n \n echo \"<br>\";\n \n print(\"link is: \".$link);\n \n print(\"<br><br>\");\n \n echo \"actual file: \".$actual_link;\n ?> \n </h1>\n \n </body>\n</html>\n"
}
] |
2008/10/08
|
[
"https://Stackoverflow.com/questions/183928",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21209/"
] |
183,932
|
<p>I have an app using PHP and the PayPal API. The basic way it works to get a payment is that you do a web service call to PayPal to get a token and then do a browser redirect to PayPal with that token for the user to pay. After the payment details have been confirmed, PayPal redirects back to the URL you originally set in the service call.</p>
<p>This all works, millions of people use it every day, et cetera.</p>
<p>Strange thing is, when PayPal redirects back, the PHP session is gone. It's a <a href="http://www.paypaldeveloper.com/pdn/board/message?board.id=sandbox&thread.id=8672" rel="nofollow noreferrer">well-documented issue</a>.</p>
<p>First question: why is this happening? Both pages are on the same domain, both use HTTPS. The session works for all requests up until the PayPal redirect back.</p>
<p>The linked forum thread suggests a workaround, to persist the session ID in the PayPal request and then to retrieve it later and restore the session. Great, except it doesn't seem to work.</p>
<p>I can add some log statements:</p>
<pre><code>log(session_id());
</code></pre>
<p>before and after the various redirects. When coming back from PayPal, I log some more.</p>
<pre><code>log("session id is " . session_id());
$session_id = get_session_id_from_paypal();
log("setting it back to " . $session_id);
session_id($session_id);
session_start();
log("session id is now " . session_id());
</code></pre>
<p>The result is not at all what I'd expect:</p>
<blockquote>
<p><code>session_id</code> is fc8f459a186a3f4695ff9ac71b563825<br>
setting it back to 82460dcf8c8ddd538466e7cb89712e72<br>
<code>session_id</code> is now 360ba3fd99d233e0735397278d2b2e55 </p>
</blockquote>
<p>Second question: why is the session id not at all what I set it to? What am I doing wrong? Or, at least, why do none of the session variables come back?</p>
|
[
{
"answer_id": 184429,
"author": "pmg",
"author_id": 25324,
"author_profile": "https://Stackoverflow.com/users/25324",
"pm_score": 3,
"selected": true,
"text": "session.referer_check session.referer_check"
}
] |
2008/10/08
|
[
"https://Stackoverflow.com/questions/183932",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6010/"
] |
183,950
|
<p>I am developing a WebPart (it will be used in a SharePoint environment, although it does not use the Object Model) that I want to expose AJAX functionality in. Because of the nature of the environment, Adding the Script Manager directly to the page is not an option, and so must be added programmatically. I have attempted to add the ScriptManager control to the page in my webpart code.</p>
<pre><code>protected override void CreateChildControls()
{
if (ScriptManager.GetCurrent(Page) == null)
{
ScriptManager sMgr = new ScriptManager();
// Ensure the ScriptManager is the first control.
Page.Form.Controls.AddAt(0, sMgr);
}
}
</code></pre>
<p>However, when this code is executed, I get the following error message:</p>
<blockquote>
<p>"The control collection cannot be modified during DataBind, Init, Load, PreRender or Unload phases."</p>
</blockquote>
<p>Is there another way to add the ScriptManager to the page from a WebPart, or am I going to have to just add the ScriptManager to each page (or master page) that will use the WebPart?</p>
|
[
{
"answer_id": 184262,
"author": "Kyle Trauberman",
"author_id": 21461,
"author_profile": "https://Stackoverflow.com/users/21461",
"pm_score": 6,
"selected": true,
"text": "protected override void OnInit(EventArgs e)\n{\n Page.Init += delegate(object sender, EventArgs e_Init)\n {\n if (ScriptManager.GetCurrent(Page) == null)\n {\n ScriptManager sMgr = new ScriptManager();\n Page.Form.Controls.AddAt(0, sMgr);\n }\n };\n base.OnInit(e);\n}\n"
},
{
"answer_id": 345497,
"author": "daduffer",
"author_id": 43473,
"author_profile": "https://Stackoverflow.com/users/43473",
"pm_score": 3,
"selected": false,
"text": "<asp:PlaceHolder ID=\"WebGridPlaceholder\" runat=\"server\" >\n</asp:PlaceHolder>\n ScriptManager aSM = new ScriptManager();\naSM.ID = \"GridScriptManager\";\nWebGridPlaceholder.Controls.Add(aSM);\n"
},
{
"answer_id": 684330,
"author": "dkarzon",
"author_id": 75946,
"author_profile": "https://Stackoverflow.com/users/75946",
"pm_score": 0,
"selected": false,
"text": "ScriptManager.GetCurrent(Page).Services.Add(new ServiceReference(virtualPath));\n"
},
{
"answer_id": 1441301,
"author": "Josh",
"author_id": 175121,
"author_profile": "https://Stackoverflow.com/users/175121",
"pm_score": 3,
"selected": false,
"text": " public class ProxiedScriptManager : ScriptManagerProxy\n {\n protected override void OnInit(EventArgs e)\n {\n //double check for script-manager, if one doesn't exist, \n //then create one and add it to the page\n if (ScriptManager.GetCurrent(this.Page) == null)\n {\n ScriptManager sManager = new ScriptManager();\n sManager.ID = \"sManager_\" + DateTime.Now.Ticks;\n Controls.AddAt(0, sManager);\n }\n\n base.OnInit(e);\n }\n }\n"
},
{
"answer_id": 1761003,
"author": "Jon",
"author_id": 214324,
"author_profile": "https://Stackoverflow.com/users/214324",
"pm_score": 3,
"selected": false,
"text": "<asp:PlaceHolder runat=\"server\" ID=\"phScriptManager\"></asp:PlaceHolder> oninit=\"updatePanel1_Init\" protected void updatePanel1_Init(object sender, EventArgs e)\n{\n if (ScriptManager.GetCurrent(this.Page) == null)\n {\n ScriptManager sManager = new ScriptManager();\n sManager.ID = \"sManager_\" + DateTime.Now.Ticks;\n phScriptManager.Controls.AddAt(0, sManager);\n }\n}\n"
},
{
"answer_id": 5625395,
"author": "Paul",
"author_id": 454600,
"author_profile": "https://Stackoverflow.com/users/454600",
"pm_score": 2,
"selected": false,
"text": "<asp:PlaceHolder ID=\"sMgr_place\" runat=\"server\" />\n<asp:UpdatePanel runat=\"server\" OnInit=\"updatePanel_Init\"><ContentTemplate>\n...\n</ContentTemplate></asp:UpdatePanel>\n public void updatePanel_Init(object sender, EventArgs e)\n{\n if (ScriptManager.GetCurrent(Page) == null)\n {\n ScriptManager sMgr = new ScriptManager();\n sMgr.EnablePartialRendering = true;\n sMgr_place.Controls.Add(sMgr);\n }\n}\n"
},
{
"answer_id": 21786935,
"author": "user3311381",
"author_id": 3311381,
"author_profile": "https://Stackoverflow.com/users/3311381",
"pm_score": 1,
"selected": false,
"text": "protected override void OnInit(EventArgs e)\n{\n //...\n if (ScriptManager.GetCurrent(this.Page) == null)\n {\n ScriptManager scriptManager = new ScriptManager();\n scriptManager.ID = \"scriptManager_\" + DateTime.Now.Ticks;\n Controls.AddAt(0, scriptManager);\n }\n //...\n}\n"
}
] |
2008/10/08
|
[
"https://Stackoverflow.com/questions/183950",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21461/"
] |
183,953
|
<p>I'm trying to determine how to open/edit existing SQL Server Reporting Services (SSRS) 2005 report projects (.rptproj) and reports (.rdl) with Visual Studio 2008, <em>without</em> having to install SQL Business Intelligence Development Studio (BIDS) 2005.</p>
|
[
{
"answer_id": 55810066,
"author": "Rakesh Bhanderi",
"author_id": 10284669,
"author_profile": "https://Stackoverflow.com/users/10284669",
"pm_score": 0,
"selected": false,
"text": ".rptproj porject not installed error message displaying during open report project.\n"
}
] |
2008/10/08
|
[
"https://Stackoverflow.com/questions/183953",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5487/"
] |
183,991
|
<p>I wonder if there's a way to do the following: I have a structure containing a member which is a pointer to a block of memory allocated by the kernel when I pass the structure to an API function (the structure is a WAVEHDR, the member is the <em>reserved</em> field.)</p>
<p>I can set a data breakpoint on the value of the reserved member - that in itself is not very helpful. What I'd like to do, when the breakpoint is hit, is to dereference the pointer stored in <em>reserved</em> and set a new data breakpoint on the memory pointed to by that pointer. I would like VisualStudio to break when that memory is set to a known value.</p>
<p>I know how to set a breakpoint from a macro, and how to have Visual Studio invoke that macro from a breakpoint when it's hit, but I don't know whether I can pass the pointer value to the macro so that it can set the breakpoint on the right address. The UI doesn't provide a way to do it.</p>
<p>Is there a way for the macro to access information about the running program, and do things like evaluate global variables or other expressions? I could accomplish what I'm trying to do if I had that kind of programmatic access to the running code (during a breakpoint) from the macro.</p>
|
[
{
"answer_id": 184607,
"author": "Rob Walker",
"author_id": 3631,
"author_profile": "https://Stackoverflow.com/users/3631",
"pm_score": 3,
"selected": true,
"text": " Dim e As EnvDTE.Expression\n\n e = DTE.Debugger.GetExpression(\"<my expression>\", True)\n\n If e.IsValidValue Then\n ... use e.Value to do something\n End If\n"
}
] |
2008/10/08
|
[
"https://Stackoverflow.com/questions/183991",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9047/"
] |
184,002
|
<p>In the following piece of code (taken from the <a href="http://groovy-lang.org/semantics.html#_while_loop" rel="noreferrer">Groovy Semantics Manual page</a>), why prefix the assignment with the keyword <code>def</code>?</p>
<pre><code>def x = 0
def y = 5
while ( y-- > 0 ) {
println "" + x + " " + y
x++
}
assert x == 5
</code></pre>
<p>The <code>def</code> keyword can be removed, and this snippet would produce the same results. So what's the <strong>effect</strong> of the keyword <code>def</code> ?</p>
|
[
{
"answer_id": 184023,
"author": "Ben Hoffstein",
"author_id": 4482,
"author_profile": "https://Stackoverflow.com/users/4482",
"pm_score": 5,
"selected": false,
"text": "def Object"
},
{
"answer_id": 185879,
"author": "Ted Naleid",
"author_id": 8912,
"author_profile": "https://Stackoverflow.com/users/8912",
"pm_score": 9,
"selected": true,
"text": "x = 1\nassert x == 1\nassert this.binding.getVariable(\"x\") == 1\n def y = 2\n\nassert y == 2\n\ntry {\n this.binding.getVariable(\"y\") \n} catch (groovy.lang.MissingPropertyException e) {\n println \"error caught\"\n} \n x = 1\n def y = 2\n\n\npublic bar() {\n assert x == 1\n\n try {\n assert y == 2\n } catch (groovy.lang.MissingPropertyException e) {\n println \"error caught\"\n }\n}\n\nbar()\n"
},
{
"answer_id": 194293,
"author": "Michael Easter",
"author_id": 12704,
"author_profile": "https://Stackoverflow.com/users/12704",
"pm_score": 5,
"selected": false,
"text": "// Groovy imports java.io.* and java.util.* automatically\n// but not java.nio.*\n\nimport java.nio.channels.*\n\nclass Foo {\n public void bar() {\n FileChannel channel = new FileInputStream('Test.groovy').getChannel()\n println channel.toString()\n }\n}\n\nnew Foo().bar()\n // Groovy imports java.io.* and java.util.* automatically\n// but not java.nio.*\nclass Foo {\n public void bar() {\n def channel = new FileInputStream('Test.groovy').getChannel()\n println channel.toString()\n }\n}\n\nnew Foo().bar()\n"
},
{
"answer_id": 18026302,
"author": "Bill K",
"author_id": 12943,
"author_profile": "https://Stackoverflow.com/users/12943",
"pm_score": 3,
"selected": false,
"text": "bill = 7\nbi1l = bill + 3\nassert bill == 7\n"
}
] |
2008/10/08
|
[
"https://Stackoverflow.com/questions/184002",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15649/"
] |
184,009
|
<p>I can't find this anywhere in the Domino Designer help. It seems so straightforward!</p>
<p>All I need to do is find the position of a character in a string.</p>
|
[
{
"answer_id": 195251,
"author": "molasses",
"author_id": 11293,
"author_profile": "https://Stackoverflow.com/users/11293",
"pm_score": 1,
"selected": true,
"text": "REM {\n S Source string\n F Character to find\n R Location of character in string or 0\n};\n\nS := \"My string\";\nF := \"t\";\nLEN_S := @Length(S);\nR := 0;\n\n@For(I := 1; I < LEN_S; I := I + 1;\n @If(@Middle(S; I; 1) = F;\n @Do(R := I; I := LEN_S);\n @Nothing\n )\n);\n"
},
{
"answer_id": 19437044,
"author": "charles ross",
"author_id": 1337544,
"author_profile": "https://Stackoverflow.com/users/1337544",
"pm_score": 2,
"selected": false,
"text": "src:= {your field value to search};\nchar:= {your target character};\nindexof:= @Length(@Left(src;char))\n"
}
] |
2008/10/08
|
[
"https://Stackoverflow.com/questions/184009",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2273/"
] |
184,014
|
<p>Can an XML attribute be the empty string?</p>
<p>In other words, is</p>
<pre><code><element att="" />
</code></pre>
<p>valid XML?</p>
|
[
{
"answer_id": 184024,
"author": "Bradley Grainger",
"author_id": 23633,
"author_profile": "https://Stackoverflow.com/users/23633",
"pm_score": 4,
"selected": false,
"text": "test.xml"
},
{
"answer_id": 184030,
"author": "Greg Hewgill",
"author_id": 893,
"author_profile": "https://Stackoverflow.com/users/893",
"pm_score": 2,
"selected": false,
"text": "</>\n"
},
{
"answer_id": 184046,
"author": "Mitchel Sellers",
"author_id": 13279,
"author_profile": "https://Stackoverflow.com/users/13279",
"pm_score": 4,
"selected": true,
"text": "<elementName></elementName>\n <elementName/>\n"
},
{
"answer_id": 184160,
"author": "Michael Burr",
"author_id": 12711,
"author_profile": "https://Stackoverflow.com/users/12711",
"pm_score": 0,
"selected": false,
"text": "<elementname />\n <elementname></elementname>\n <img\n src='madonna.gif'></img> <img\n src='madonna.gif'/>"
},
{
"answer_id": 3323984,
"author": "coder",
"author_id": 400885,
"author_profile": "https://Stackoverflow.com/users/400885",
"pm_score": 2,
"selected": false,
"text": "<mytag myattrib=\"\"/>\n <mytag myattrib/>\n"
}
] |
2008/10/08
|
[
"https://Stackoverflow.com/questions/184014",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1447/"
] |
184,034
|
<p>What do you do to pass information between forms? Forward is straight forward (sorry) using Properties or maybe parameters in a New() or DoStuff() method, but what about sending something <strong><em>back</em></strong> when the user is done with the second form? (IE. ID of the item selected) We have used all these:</p>
<ul>
<li><strong>Passed the calling form into the called form as a ref</strong> so the called form could access properties or methods on the calling form. I really don't like this because the two forms are very dependent of each other. Passing the calling form as a object only slightly improves this.</li>
<li><strong>Use Events</strong> This somewhat decouples the code, but the signatures must match on the event handler.</li>
<li><strong>Use an Public Interface</strong> I'm talking about the .NET built in one, but I suppose you could create your own. This seems like the best to me.</li>
</ul>
<p>Now raise the bar, what if the forms are in two different DLLs? As long as the forms are not dependent on each other, I would think this wouldn't be a big step.</p>
|
[
{
"answer_id": 184077,
"author": "chills42",
"author_id": 23855,
"author_profile": "https://Stackoverflow.com/users/23855",
"pm_score": 2,
"selected": false,
"text": "NewForm myForm = new NewForm();\nmyForm.ShowDialog();\nstring x = myform.MyProperty;\n"
},
{
"answer_id": 1182528,
"author": "Raiford",
"author_id": 136536,
"author_profile": "https://Stackoverflow.com/users/136536",
"pm_score": 2,
"selected": false,
"text": "NewForm myForm = new NewForm(); \nmyForm.Employee = employeeToEdit; // This can have state \nmyForm.ShowDialog(); \nEmployee editedEmployee= myform.Employee;\n\nEmployeeFacade.SaveEmployee(editedEmployee); // Or whatever\n"
}
] |
2008/10/08
|
[
"https://Stackoverflow.com/questions/184034",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/24991/"
] |
184,074
|
<p>When I debug locally in fire fox 2.0x many times my page won't have the styles added properly or the page will not completely render (the end is seemingly cut off). Sometimes it takes multiple refreshes or shift-refreshes to fix this. Is this a common issue or is it just me? Any solutions?</p>
<p>I want to add that this is happening in fire fox 3.x to me as well. I add my javascript to the pages dynamically and this might be part of the issue. This is when I am working locally with Visual Studio.</p>
<p>Update: This does happen in IE but it happens much more often in Fire Fox. The issue seems to be only javascript and CSS files not loading. For example I get jQuery is not defined, $ is not defined etc. I don't think I have local IIS to test this on but from the server it always works perfectly. Fire Bug shows all my css and javascript files to be requested and received.</p>
|
[
{
"answer_id": 493356,
"author": "splattne",
"author_id": 6461,
"author_profile": "https://Stackoverflow.com/users/6461",
"pm_score": 2,
"selected": false,
"text": "about:config network.dns.disableIPv6 true localhost network.dns.ipv4OnlyDomains C:\\Windows\\System32\\drivers\\etc\\hosts\n :: localhost\n"
}
] |
2008/10/08
|
[
"https://Stackoverflow.com/questions/184074",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18926/"
] |
184,084
|
<blockquote>
<p><strong>Possible Duplicate:</strong><br>
<a href="https://stackoverflow.com/questions/19147/what-is-the-correct-way-to-create-a-single-instance-application">What is the correct way to create a single instance application?</a> </p>
</blockquote>
<p>How to force C# .net app to run only one instance in Windows?</p>
|
[
{
"answer_id": 184143,
"author": "Mitchel Sellers",
"author_id": 13279,
"author_profile": "https://Stackoverflow.com/users/13279",
"pm_score": 7,
"selected": false,
"text": "using System.Threading;\n\n[DllImport(\"user32.dll\")]\n[return: MarshalAs(UnmanagedType.Bool)]\nstatic extern bool SetForegroundWindow(IntPtr hWnd);\n\n/// <summary>\n/// The main entry point for the application.\n/// </summary>\n[STAThread]\nstatic void Main()\n{\n bool createdNew = true;\n using (Mutex mutex = new Mutex(true, \"MyApplicationName\", out createdNew))\n {\n if (createdNew)\n {\n Application.EnableVisualStyles();\n Application.SetCompatibleTextRenderingDefault(false);\n Application.Run(new MainForm());\n }\n else\n {\n Process current = Process.GetCurrentProcess();\n foreach (Process process in Process.GetProcessesByName(current.ProcessName))\n {\n if (process.Id != current.Id)\n {\n SetForegroundWindow(process.MainWindowHandle);\n break;\n }\n }\n }\n }\n}\n"
},
{
"answer_id": 184210,
"author": "Martin Plante",
"author_id": 4898,
"author_profile": "https://Stackoverflow.com/users/4898",
"pm_score": 3,
"selected": false,
"text": "static void Main()\n{\n bool mutexCreated = false;\n System.Threading.Mutex mutex = new System.Threading.Mutex( true, @\"Local\\slimCODE.slimKEYS.exe\", out mutexCreated );\n\n if( !mutexCreated )\n {\n if( MessageBox.Show(\n \"slimKEYS is already running. Hotkeys cannot be shared between different instances. Are you sure you wish to run this second instance?\",\n \"slimKEYS already running\",\n MessageBoxButtons.YesNo,\n MessageBoxIcon.Question ) != DialogResult.Yes )\n {\n mutex.Close();\n return;\n }\n }\n\n // The usual stuff with Application.Run()\n\n mutex.Close();\n}\n"
},
{
"answer_id": 6416663,
"author": "snir",
"author_id": 807301,
"author_profile": "https://Stackoverflow.com/users/807301",
"pm_score": 5,
"selected": false,
"text": "public static Process PriorProcess()\n // Returns a System.Diagnostics.Process pointing to\n // a pre-existing process with the same name as the\n // current one, if any; or null if the current process\n // is unique.\n {\n Process curr = Process.GetCurrentProcess();\n Process[] procs = Process.GetProcessesByName(curr.ProcessName);\n foreach (Process p in procs)\n {\n if ((p.Id != curr.Id) &&\n (p.MainModule.FileName == curr.MainModule.FileName))\n return p;\n }\n return null;\n }\n [STAThread]\n static void Main()\n {\n if (PriorProcess() != null)\n {\n\n MessageBox.Show(\"Another instance of the app is already running.\");\n return;\n }\n Application.EnableVisualStyles();\n Application.SetCompatibleTextRenderingDefault(false);\n Application.Run(new Form());\n }\n"
},
{
"answer_id": 11463450,
"author": "Thyrador",
"author_id": 1478230,
"author_profile": "https://Stackoverflow.com/users/1478230",
"pm_score": 2,
"selected": false,
"text": " [DllImport(\"user32.dll\")]\n [return: MarshalAs(UnmanagedType.Bool)]\n static extern bool SetForegroundWindow(IntPtr hWnd);\n\n public Main()\n {\n InitializeComponent();\n\n Process current = Process.GetCurrentProcess();\n string currentmd5 = md5hash(current.MainModule.FileName);\n Process[] processlist = Process.GetProcesses();\n foreach (Process process in processlist)\n {\n if (process.Id != current.Id)\n {\n try\n {\n if (currentmd5 == md5hash(process.MainModule.FileName))\n {\n SetForegroundWindow(process.MainWindowHandle);\n Environment.Exit(0);\n }\n }\n catch (/* your exception */) { /* your exception goes here */ }\n }\n }\n }\n\n private string md5hash(string file)\n {\n string check;\n using (FileStream FileCheck = File.OpenRead(file))\n {\n MD5 md5 = new MD5CryptoServiceProvider();\n byte[] md5Hash = md5.ComputeHash(FileCheck);\n check = BitConverter.ToString(md5Hash).Replace(\"-\", \"\").ToLower();\n }\n\n return check;\n }\n"
}
] |
2008/10/08
|
[
"https://Stackoverflow.com/questions/184084",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1316/"
] |
184,092
|
<p>Within emacs, what are the best options out there for navigating to a specific function whose name might show up across several different files? Within etags, you are only allowed to cycle through the tags one-at-a-time which could take a while if the function name you are looking for is popular.</p>
|
[
{
"answer_id": 7304934,
"author": "Drew",
"author_id": 729907,
"author_profile": "https://Stackoverflow.com/users/729907",
"pm_score": 0,
"selected": false,
"text": "icicle-find-tag find-tag tags-loop-continue tags-apropos list-tags icicle-find-tag"
}
] |
2008/10/08
|
[
"https://Stackoverflow.com/questions/184092",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18415/"
] |
184,096
|
<p>Suppose there is a fully populated array of data String[n][3] myData.</p>
<p>I want to do this:</p>
<pre><code>for (String[] row : myData)
{
SQL = "update mytable set col3 = row[2]
where col1 = row[0] and col2=row[1];"
}
</code></pre>
<p>Obviously I've left a lot out, but I want to express the idea as succinctly as possible.</p>
<p>Is there a simple way of doing this in a single DB command?
How about a not so simple way?</p>
<p>EDITS:
Data is not coming from another table (it's a web form submission - Multiple Choice exam)<br>
Seeing as the app is web facing, It's got to be injection proof. Parameterized Queries are my preferred way of going.<br>
I'm using MS-SQL Server 2005</p>
<p>EDIT:Closing, and re-asking as <a href="https://stackoverflow.com/questions/184471/multiple-db-updates">Multiple DB Updates:</a></p>
<p>EDIT: Re-opened, as this appears to be a popular question</p>
|
[
{
"answer_id": 184123,
"author": "fmsf",
"author_id": 26004,
"author_profile": "https://Stackoverflow.com/users/26004",
"pm_score": 1,
"selected": false,
"text": "for (String[] row : myData)\n{\n SQL += \"update mytable set col3 = row[2]\n where col1 = row[0] and col2=row[1];\" \n}\n\nsqlDriver.doInsertQuery(SQL); // change this to your way of inserting into the db\n"
},
{
"answer_id": 184126,
"author": "EndangeredMassa",
"author_id": 106,
"author_profile": "https://Stackoverflow.com/users/106",
"pm_score": 0,
"selected": false,
"text": "for each whatever\n sql += \"UPDATE ... ;\"\nend for\nexecute (sql)\n"
},
{
"answer_id": 184263,
"author": "Kevin Berridge",
"author_id": 4407,
"author_profile": "https://Stackoverflow.com/users/4407",
"pm_score": 3,
"selected": false,
"text": "update mytable set mytable.col1 = @tbl.col1\n from mytable \n inner join @tbl on mytable.col2 = @tbl.col2\n"
},
{
"answer_id": 184274,
"author": "helios",
"author_id": 9686,
"author_profile": "https://Stackoverflow.com/users/9686",
"pm_score": 1,
"selected": false,
"text": "UPDATE whatchanges wc INNER JOIN changes c ON <yourcondition>\nSET wc.col1 = c.newvalue\nWHERE ....\n"
},
{
"answer_id": 184360,
"author": "Rob Allen",
"author_id": 149,
"author_profile": "https://Stackoverflow.com/users/149",
"pm_score": 1,
"selected": false,
"text": "DbTransaction transaction = connection.BeginTransaction();\ntry\n{\n for (String[] row : myData)\n {\n ListDictionary params = new Specialized.ListDictionary();\n params.add(\"@col3\", row[2]);\n params.add(\"@col1\", row[0]);\n params.add(\"@col2\", row[1]);\n executeNonQuery(\"myUpdateProcedure\", params);\n }\n\n transaction.commit();\n\n}\ncatch(Exception ex)\n{\n transaction.rollback();\n throw ex;\n}\nfinally\n{\n\n connection.close();\n}\n"
},
{
"answer_id": 184367,
"author": "cmsjr",
"author_id": 23114,
"author_profile": "https://Stackoverflow.com/users/23114",
"pm_score": 1,
"selected": false,
"text": "SQL = \"Update myTable Set Col3 = Case \" \nfor (String[] row : myData)\n{\n SQL += \"When Col1 = \" + Row[0] + \" and Col2 = \" + Row[1] + \" then \" + row[2] + \" \" \n}\nSQL + = \"Else Col3 end\" \n"
},
{
"answer_id": 184468,
"author": "Hafthor",
"author_id": 4489,
"author_profile": "https://Stackoverflow.com/users/4489",
"pm_score": 0,
"selected": false,
"text": "UPDATE myTable SET col3=c FROM myTable JOIN (\n SELECT 1 as a, 2 as b, 'value1' as c UNION ALL\n SELECT 3 as a, 4 as b, 'value2' as c -- etc...\n) x ON myTable.col1=x.a AND myTable.col2=x.b\n // make one of these for each row\nString.Format(\"SELECT {0} as a, {1} as b, '{2}' as c\", \n row[0], row[1], row[2].Replace(\"'\",\"''\")) \n\n// put it together\nstring expr = \"UPDATE myTable SET col3=c FROM myTable JOIN (\" +\n String.Join(stringformatarray, \" UNION ALL \") +\n \") x ON myTable.col1=x.a AND myTable.col2=x.b\"\n"
}
] |
2008/10/08
|
[
"https://Stackoverflow.com/questions/184096",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18907/"
] |
184,099
|
<p>I want to have a reusable button which can be registered for one of many different callbacks, determined by an external source. When a new callback is set, I want to remove the old. I also want to be able to clear the callback externally at any time.</p>
<pre><code>public function registerButtonCallback(function:Function):void
{
clearButtonCallback();
button.addEventListener(MouseEvent.CLICK, function, false, 0, true);
}
public function clearButtonCallback():void
{
if (button.hasEventListener(MouseEvent.CLICK) == true)
{
// do something to remove that listener
}
}
</code></pre>
<p>I've seen suggestions on here to use "arguments.callee" within the callback, but I don't want to have that functionality tied to the callback - for example, I might want to be able to click the button twice.</p>
<p>Suggestions?</p>
|
[
{
"answer_id": 184331,
"author": "Simon",
"author_id": 24039,
"author_profile": "https://Stackoverflow.com/users/24039",
"pm_score": 3,
"selected": false,
"text": "<mx:Button click=\"doCallback()\" .../>\n\npublic var onClickFunction:Function = null;\nprivate function doCallback():void\n{\n if (onClickFunction != null)\n {\n onClickFunction(); // optionally you can pass some parameters in here if you match the signature of your callback\n }\n}\n"
},
{
"answer_id": 196491,
"author": "geraldalewis",
"author_id": 7501,
"author_profile": "https://Stackoverflow.com/users/7501",
"pm_score": 2,
"selected": false,
"text": "\nvar listeners:Dictionary = new Dictionary();\n\noverride public function addEventListener( type : String, listener : Function, useCapture : Boolean = false, priority : int = 0, useWeakReference : Boolean = false) : void {\n\n if( listeners[ type ] ) {\n\n if( listeners[ type ] [ useCapture ] {\n\n //snip... etc: check for existence of the listener\n\n removeEventListener( type, listeners[ type ] [ useCapture ], useCapture );\n\n listeners[ type ] [ useCapture ] = null;\n\n //clean up: if no listeners of this type exist, remove the dictionary key for the type, etc...\n\n }\n\n }\n\n listeners[ type ] [ useCapture ] = listener;\n\n super.addEventListener( type, listener, useCapture, priority, useWeakReference );\n\n};\n\n\n if( listeners[ type ] ) {\n\n if( listeners[ type ] [ useCapture ] {\n\n //snip... etc: check for existence of the listener\n\n removeEventListener( type, listeners[ type ] [ useCapture ], useCapture );\n\n listeners[ type ] [ useCapture ] = null;\n\n //clean up: if no listeners of this type exist, remove the dictionary key for the type, etc...\n\n }\n\n }\n\n listeners[ type ] [ useCapture ] = listener;\n\n super.addEventListener( type, listener, useCapture, priority, useWeakReference );\n\n};\n"
},
{
"answer_id": 550391,
"author": "Jonathan Dumaine",
"author_id": 66584,
"author_profile": "https://Stackoverflow.com/users/66584",
"pm_score": 1,
"selected": false,
"text": "package {\n\nimport flash.display.Sprite;\nimport flash.events.Event;\nimport flash.text.TextField;\n\n[SWF(width=\"750\", height=\"400\", backgroundColor=\"0xcdcdcd\")]\npublic class TestProject extends Sprite\n{ \n public function TestProject()\n {\n addEventListener(Event.ADDED_TO_STAGE, Global['addStageEvent'] = function():void {\n var i:uint = 0;\n //How about an eventlistener inside an eventListener?\n addEventListener(Event.ENTER_FRAME, Global['someEvent'] = function():void {\n //Let's make some text fields\n var t:TextField = new TextField();\n t.text = String(i);\n t.x = stage.stageWidth*Math.random();\n t.y = stage.stageHeight*Math.random();\n addChild(t);\n i++;\n trace(i);\n //How many text fields to we want?\n if(i >= 50) {\n //Time to stop making textFields\n removeEventListener(Event.ENTER_FRAME, Global['someEvent']);\n //make sure we don't have any event listeners\n trace(\"hasEventListener(Event.ENTER_FRAME) = \"+hasEventListener(Event.ENTER_FRAME)); \n }\n });\n\n //Get rid of the listener\n removeEventListener(Event.ADDED_TO_STAGE, Global['addStageEvent']);\n trace('hasEventListener(Event.ADDED_TO_STAGE) = '+hasEventListener(Event.ADDED_TO_STAGE));\n\n });\n }\n\n} \n"
},
{
"answer_id": 1771556,
"author": "Triynko",
"author_id": 88409,
"author_profile": "https://Stackoverflow.com/users/88409",
"pm_score": 2,
"selected": false,
"text": "addEventListener(type:String, listener:Function, useCapture:Boolean = false, priority:int = 0, useWeakReference:Boolean = false):void\ndispatchEvent(event:Event):Boolean\nhasEventListener(type:String):Boolean\nremoveEventListener(type:String, listener:Function, useCapture:Boolean = false):void\nwillTrigger(type:String):Boolean \n"
},
{
"answer_id": 3382227,
"author": "Thomas Thorstensson",
"author_id": 1279151,
"author_profile": "https://Stackoverflow.com/users/1279151",
"pm_score": 2,
"selected": false,
"text": "package\n{\n import flash.events.EventDispatcher;\n import flash.utils.Dictionary;\n /**\n * ...\n * @author Thomas James Thorstensson\n * @version 1.0.1\n */\n public class EventCurb extends EventDispatcher\n {\n private static var instance:EventCurb= new EventCurb();\n private var objDict:Dictionary = new Dictionary(true);\n private var _listener:Function;\n private var objArr:Array;\n private var obj:Object;\n\n public function EventCurb() {\n if( instance ) throw new Error( \"Singleton and can only be accessed through Singleton.getInstance()\" );\n }\n\n public static function getInstance():EventCurb {\n return instance;\n }\n\n override public function addEventListener(type:String, listener:Function, useCapture:Boolean = false, priority:int = 0, useWeakReference:Boolean = false):void\n {\n super.addEventListener(type, listener, useCapture, priority, useWeakReference);\n }\n\n override public function removeEventListener(type:String, listener:Function, useCapture:Boolean = false):void\n {\n super.removeEventListener(type, listener, useCapture);\n }\n\n public function addListener(o:EventDispatcher, type:String, listener:Function, useCapture:Boolean = false, priority:int = 0, useWeakReference:Boolean = false):void {\n // the object as key for an array of its event types\n if (objDict[o] == null) objArr = objDict[o] = [];\n for (var i:int = 0; i < objArr.length; i++) {\n if ( objArr[i].type == type)\n trace (\"_______object already has this listener not adding!\")\n return\n }\n obj = { type:type, listener:listener }\n objArr.push(obj);\n o.addEventListener(type, listener, useCapture, priority, useWeakReference);\n }\n\n public function removeListener(o:EventDispatcher, type:String, listener:Function, useCapture:Boolean = false):void {\n // if the object has listeners (ie exists in dictionary)\n if (objDict[o] as Array !== null) {\n var tmpArr:Array = [];\n tmpArr = objDict[o] as Array;\n for (var i:int = 0; i < tmpArr.length; i++) {\n if (tmpArr[i].type == type) objArr.splice(i);\n }\n\n o.removeEventListener(type, listener, useCapture);\n if (tmpArr.length == 0) {\n delete objDict[o]\n }\n }else {\n trace(\"_______object has no listeners\");\n }\n }\n\n /**\n * If object has listeners, returns an Array which can be accessed\n * as array[index].type,array[index].listeners\n * @param o\n * @return Array\n */\n public function getListeners(o:EventDispatcher):Array{\n if (objDict[o] as Array !== null) {\n var tmpArr:Array = [];\n tmpArr = objDict[o] as Array;\n // forget trying to trace out the function name we use the function literal...\n for (var i:int = 0; i < tmpArr.length; i++) {\n trace(\"_______object \" + o + \" has event types: \" + tmpArr[i].type +\" with listener: \" + tmpArr[i].listener);\n }\n return tmpArr\n\n }else {\n trace(\"_______object has no listeners\");\n return null\n }\n\n }\n\n public function removeAllListeners(o:EventDispatcher, cap:Boolean = false):void {\n if (objDict[o] as Array !== null) {\n var tmpArr:Array = [];\n tmpArr = objDict[o] as Array;\n for (var i:int = 0; i < tmpArr.length; i++) {\n o.removeEventListener(tmpArr[i].type, tmpArr[i].listener, cap);\n }\n for (var p:int = 0; p < tmpArr.length; p++) {\n objArr.splice(p);\n }\n\n if (tmpArr.length == 0) {\n delete objDict[o]\n }\n }else {\n trace(\"_______object has no listeners\");\n }\n }\n }\n}\n"
},
{
"answer_id": 3810384,
"author": "M.Raju",
"author_id": 460280,
"author_profile": "https://Stackoverflow.com/users/460280",
"pm_score": 0,
"selected": false,
"text": "private function callFunction(function:Function):void\n{\n checkObject();\n obj.addEventListener(MouseEvent.CLICK,function);\n}\n\nprivate function checkObject():void\n{\n if(obj.hasEventListener(MouseEvent.CLICK))\n {\n //here remove that objects\n }\n}\n"
}
] |
2008/10/08
|
[
"https://Stackoverflow.com/questions/184099",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
184,108
|
<p>I have a very simple TCP server written in C. It runs indefinitely, waiting for connections. On Windows, I use <code>select</code> to check for activity on the socket, and if there isn't any, I have the following code to allow me to quit by hitting 'q' on the keyboard:</p>
<pre><code>if( kbhit() ) {
char c = getch();
if( c == 'q' ) break;
}
</code></pre>
<p>This doesn't work on unix, since <code>kbhit</code> doesn't exist and <code>getch</code> works differently. I found some <a href="http://www.linuxjournal.com/files/linuxjournal.com/linuxjournal/articles/011/1138/1138l2.html" rel="nofollow noreferrer">sample code</a> that uses <code>tcsetattr</code> to change the terminal settings and allow character-by-character input. After calling the init function, I open /dev/stdin (with <code>O_NONBLOCK</code>) and read a character, but <code>read( f, &c, 1 )</code> blocks until a character is hit.</p>
<p>I suppose I could spawn a separate thread and have <em>it</em> wait indefinitely and then signal the first thread if the user hits 'q', but that seems a little heavy-handed. Surely there's an easier way?</p>
|
[
{
"answer_id": 184346,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "read( f, &c, 1 )\n"
}
] |
2008/10/08
|
[
"https://Stackoverflow.com/questions/184108",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1821/"
] |
184,112
|
<p>Any <a href="http://en.wikipedia.org/wiki/Salt_%28cryptography%29" rel="noreferrer">salt</a> at all will obviously help when salting and hashing a user's password. Are there any best practices for how long the salt should be? I'll be storing the salt in my user table, so I would like the best tradeoff between storage size and security. Is a random 10 character salt enough? Or do I need something longer?</p>
|
[
{
"answer_id": 9669140,
"author": "multitask landscape",
"author_id": 355491,
"author_profile": "https://Stackoverflow.com/users/355491",
"pm_score": 3,
"selected": false,
"text": "128 / 4 = 32"
}
] |
2008/10/08
|
[
"https://Stackoverflow.com/questions/184112",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3351/"
] |
184,132
|
<p>I need some help from the shell-script gurus out there.</p>
<p>I have a .txt file (log) that traces the IP addresses of clients on several lines, in a format similar to this one:</p>
<pre><code>Line1 - Client IP [192.168.0.1] Other data
Line2 - Client IP [192.168.0.2] Other data
Line3 - Client IP [192.168.0.3] Other data
Line4 - Client IP [192.168.0.2] Other data
Line5 - Client IP [192.168.0.1] Other data
...
</code></pre>
<p>I need to create script that:</p>
<ul>
<li>extracts the IP addresses from this file</li>
<li>groups the IP addresses (the same IP address is reported only once)</li>
<li>outputs a file with the resulting IP addresses</li>
</ul>
<p>For the previous example, the resulting file would be:</p>
<pre><code>192.168.0.1
192.168.0.2
192.168.0.3
</code></pre>
<p>I am on the Windows OS, but I can use tools like <a href="http://www.cygwin.com/" rel="nofollow noreferrer">Cygwin</a> or <a href="http://unxutils.sourceforge.net/" rel="nofollow noreferrer">Unix Tools</a> (that provide Unix-like commands as grep, sort, etc. under Windows).</p>
<p>A solution without scripting could be good as well.</p>
<p>Thanks in advance for your help.</p>
|
[
{
"answer_id": 184154,
"author": "Robert Elwell",
"author_id": 23102,
"author_profile": "https://Stackoverflow.com/users/23102",
"pm_score": 2,
"selected": false,
"text": " cat yourfile.txt | sed 's/*\\[//g' | sed 's/\\]*//g' | sort | uniq > newfile.txt\n"
},
{
"answer_id": 184165,
"author": "David Schmitt",
"author_id": 4918,
"author_profile": "https://Stackoverflow.com/users/4918",
"pm_score": 2,
"selected": false,
"text": "sort -u sed -e 's/^.*\\[\\(.*\\)\\].*$/\\1/g' < inputfile | sort -u\n"
},
{
"answer_id": 184273,
"author": "Steven Murawski",
"author_id": 1233,
"author_profile": "https://Stackoverflow.com/users/1233",
"pm_score": 4,
"selected": true,
"text": "$regex = '(?<IPAddress>\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3})'\nget-content log.txt | where-object {if ($_ -match $regex){$matches.ipaddress}} | group-object -noelement\n gc log.txt | % {if ($_ -match $regex){$matches.ipaddress}} | group -n\n"
},
{
"answer_id": 184275,
"author": "bugmagnet",
"author_id": 426,
"author_profile": "https://Stackoverflow.com/users/426",
"pm_score": 1,
"selected": false,
"text": "Option Explicit\n\nDim oFSO\nDim oRgx\nDim oMatch\nDim oMatches\nDim oStream\nDim sLine\nDim oDict\nDim sIP\nDim aKeys\nDim sKey\n\nSet oFSO = CreateObject( \"Scripting.FileSystemObject\" )\nSet oDict = CreateObject( \"Scripting.Dictionary\" )\n\nSet oStream = oFSO.OpenTextFile( \"log.txt\", 1, False )\n\nSet oRgx = new regexp\noRgx.Pattern = \"\\[(.+?)\\]\"\noRgx.Global = True\n\nDo While Not oStream.AtEndOfStream\n sLine = oStream.ReadLine\n Set oMatches = oRgx.Execute(sLine)\n\n For Each omatch in omatches\n sIP = oMatch.SubMatches(0)\n\n If Not oDict.Exists( sIP ) Then\n oDict.Add sIp,1\n End If\n\n Next\n\nLoop\n\naKeys = oDict.Keys\n\nFor Each sKey in aKeys\n wscript.echo sKey\nNext\n"
}
] |
2008/10/08
|
[
"https://Stackoverflow.com/questions/184132",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23034/"
] |
184,147
|
<p>Is there any advantage of using</p>
<p><a href="https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/CountDownLatch.html" rel="noreferrer"><strong>java.util.concurrent.CountdownLatch</strong></a> </p>
<p>instead of</p>
<p><a href="https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/Semaphore.html" rel="noreferrer"><strong>java.util.concurrent.Semaphore</strong></a>? </p>
<p>As far as I can tell the following fragments are almost equivalent:</p>
<p><strong>1. Semaphore</strong></p>
<pre><code>final Semaphore sem = new Semaphore(0);
for (int i = 0; i < num_threads; ++ i)
{
Thread t = new Thread() {
public void run()
{
try
{
doStuff();
}
finally
{
sem.release();
}
}
};
t.start();
}
sem.acquire(num_threads);
</code></pre>
<p><strong>2: CountDownLatch</strong></p>
<pre><code>final CountDownLatch latch = new CountDownLatch(num_threads);
for (int i = 0; i < num_threads; ++ i)
{
Thread t = new Thread() {
public void run()
{
try
{
doStuff();
}
finally
{
latch.countDown();
}
}
};
t.start();
}
latch.await();
</code></pre>
<p>Except that in case #2 the latch cannot be reused and more importantly you need to know in advance how many threads will be created (or wait until they are all started before creating the latch.)</p>
<p>So in what situation might the latch be preferable?</p>
|
[
{
"answer_id": 184441,
"author": "Spencer Kormos",
"author_id": 8528,
"author_profile": "https://Stackoverflow.com/users/8528",
"pm_score": 0,
"selected": false,
"text": "CountdownLatch await() Latch Semaphore Semaphore"
},
{
"answer_id": 184566,
"author": "James Schek",
"author_id": 17871,
"author_profile": "https://Stackoverflow.com/users/17871",
"pm_score": 8,
"selected": true,
"text": "CountDownLatch await() final CountDownLatch countdown = new CountDownLatch(1);\n\nfor (int i = 0; i < 10; ++ i) {\n Thread racecar = new Thread() { \n public void run() {\n countdown.await(); //all threads waiting\n System.out.println(\"Vroom!\");\n }\n };\n racecar.start();\n}\nSystem.out.println(\"Go\");\ncountdown.countDown(); //all threads start now!\n final CountDownLatch countdown = new CountDownLatch(num_thread);\n\nfor (int i = 0; i < num_thread; ++ i) {\n Thread t= new Thread() { \n public void run() {\n doSomething();\n countdown.countDown();\n System.out.printf(\"Waiting on %d other threads.\",countdown.getCount());\n countdown.await(); //waits until everyone reaches this point\n finish();\n }\n };\n t.start();\n}\n CountDownLatch"
},
{
"answer_id": 184800,
"author": "mtruesdell",
"author_id": 6479,
"author_profile": "https://Stackoverflow.com/users/6479",
"pm_score": 6,
"selected": false,
"text": "countDown() acquire() release() CountdownLatch"
},
{
"answer_id": 18005588,
"author": "Raj Srinivas",
"author_id": 2643906,
"author_profile": "https://Stackoverflow.com/users/2643906",
"pm_score": 3,
"selected": false,
"text": "proshopVendorSemaphore.acquire() proshopVendorSemaphore.release() CountDownLatch(4) await() CountDownLatch countDown() await() CountDownLatch(4) CyclicBarrier"
},
{
"answer_id": 33624654,
"author": "Ravindra babu",
"author_id": 4999394,
"author_profile": "https://Stackoverflow.com/users/4999394",
"pm_score": 5,
"selected": false,
"text": "Semaphore CountDownLatch Semaphore CountDownLatch Semaphore Semaphore acquire() release() Semaphore Semaphore acquire() release() Semaphore CountDownLatch CountDownLatch CountDownLatch CountDownLatch CountDownLatch"
}
] |
2008/10/08
|
[
"https://Stackoverflow.com/questions/184147",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12048/"
] |
184,162
|
<p>I'm trying to find the best way to use 'top' as semi-permanent instrumentation in the development of a box running embedded Linux. (The instrumentation will be removed from the final-test and production releases.)</p>
<p>My first pass is to simply add this to init.d:</p>
<pre><code>top -b -d 15 >/tmp/toploop.out &
</code></pre>
<p>This runs top in "batch" mode every 15 seconds. Let's assume that /tmp has plenty of space…</p>
<p>Questions: </p>
<ol>
<li>Is 15 seconds a good value to choose for general-purpose monitoring?</li>
<li>Other than disk space, how seriously is this perturbing the state of the system?</li>
<li>What other (perhaps better) tools could be used like this?</li>
</ol>
|
[
{
"answer_id": 184465,
"author": "terson",
"author_id": 22974,
"author_profile": "https://Stackoverflow.com/users/22974",
"pm_score": 1,
"selected": false,
"text": "man proc"
}
] |
2008/10/08
|
[
"https://Stackoverflow.com/questions/184162",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14028/"
] |
184,178
|
<p>I want to do an HTTP POST that looks like an HMTL form posted from a browser. Specifically, post some text fields and a file field.</p>
<p>Posting text fields is straightforward, there's an example right there in the net/http rdocs, but I can't figure out how to post a file along with it.</p>
<p>Net::HTTP doesn't look like the best idea. <a href="http://curb.rubyforge.org/" rel="noreferrer">curb</a> is looking good.</p>
|
[
{
"answer_id": 184303,
"author": "kch",
"author_id": 13989,
"author_profile": "https://Stackoverflow.com/users/13989",
"pm_score": 3,
"selected": false,
"text": "require 'yaml'\nrequire 'curb'\n\n# prepare post data\npost_data = fields_hash.map { |k, v| Curl::PostField.content(k, v.to_s) }\npost_data << Curl::PostField.file('file', '/path/to/file'), \n\n# post\nc = Curl::Easy.new('http://localhost:3000/foo')\nc.multipart_form_post = true\nc.http_post(post_data)\n\n# print response\ny [c.response_code, c.body_str]\n"
},
{
"answer_id": 213276,
"author": "Cody Brimhall",
"author_id": 18388,
"author_profile": "https://Stackoverflow.com/users/18388",
"pm_score": 5,
"selected": false,
"text": "curb Net::HTTP String File #prepare the query\ndata, headers = Multipart::Post.prepare_query(\"title\" => my_string, \"document\" => my_file)\n POST Net::HTTP http = Net::HTTP.new(upload_uri.host, upload_uri.port)\nres = http.start {|con| con.post(upload_uri.path, data, headers) }\n POST Multipart mime-types # Takes a hash of string and file parameters and returns a string of text\n# formatted to be sent as a multipart form post.\n#\n# Author:: Cody Brimhall <mailto:brimhall@somuchwit.com>\n# Created:: 22 Feb 2008\n# License:: Distributed under the terms of the WTFPL (http://www.wtfpl.net/txt/copying/)\n\nrequire 'rubygems'\nrequire 'mime/types'\nrequire 'cgi'\n\n\nmodule Multipart\n VERSION = \"1.0.0\"\n\n # Formats a given hash as a multipart form post\n # If a hash value responds to :string or :read messages, then it is\n # interpreted as a file and processed accordingly; otherwise, it is assumed\n # to be a string\n class Post\n # We have to pretend we're a web browser...\n USERAGENT = \"Mozilla/5.0 (Macintosh; U; PPC Mac OS X; en-us) AppleWebKit/523.10.6 (KHTML, like Gecko) Version/3.0.4 Safari/523.10.6\"\n BOUNDARY = \"0123456789ABLEWASIEREISAWELBA9876543210\"\n CONTENT_TYPE = \"multipart/form-data; boundary=#{ BOUNDARY }\"\n HEADER = { \"Content-Type\" => CONTENT_TYPE, \"User-Agent\" => USERAGENT }\n\n def self.prepare_query(params)\n fp = []\n\n params.each do |k, v|\n # Are we trying to make a file parameter?\n if v.respond_to?(:path) and v.respond_to?(:read) then\n fp.push(FileParam.new(k, v.path, v.read))\n # We must be trying to make a regular parameter\n else\n fp.push(StringParam.new(k, v))\n end\n end\n\n # Assemble the request body using the special multipart format\n query = fp.collect {|p| \"--\" + BOUNDARY + \"\\r\\n\" + p.to_multipart }.join(\"\") + \"--\" + BOUNDARY + \"--\"\n return query, HEADER\n end\n end\n\n private\n\n # Formats a basic string key/value pair for inclusion with a multipart post\n class StringParam\n attr_accessor :k, :v\n\n def initialize(k, v)\n @k = k\n @v = v\n end\n\n def to_multipart\n return \"Content-Disposition: form-data; name=\\\"#{CGI::escape(k)}\\\"\\r\\n\\r\\n#{v}\\r\\n\"\n end\n end\n\n # Formats the contents of a file or string for inclusion with a multipart\n # form post\n class FileParam\n attr_accessor :k, :filename, :content\n\n def initialize(k, filename, content)\n @k = k\n @filename = filename\n @content = content\n end\n\n def to_multipart\n # If we can tell the possible mime-type from the filename, use the\n # first in the list; otherwise, use \"application/octet-stream\"\n mime_type = MIME::Types.type_for(filename)[0] || MIME::Types[\"application/octet-stream\"][0]\n return \"Content-Disposition: form-data; name=\\\"#{CGI::escape(k)}\\\"; filename=\\\"#{ filename }\\\"\\r\\n\" +\n \"Content-Type: #{ mime_type.simplified }\\r\\n\\r\\n#{ content }\\r\\n\"\n end\n end\nend\n"
},
{
"answer_id": 316338,
"author": "Pedro",
"author_id": 16882,
"author_profile": "https://Stackoverflow.com/users/16882",
"pm_score": 8,
"selected": true,
"text": "require 'rest_client'\nRestClient.post('http://localhost:3000/foo', \n :name_of_file_param => File.new('/path/to/file'))\n gem install rest-client"
},
{
"answer_id": 392903,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "class Multipart\n\n def initialize( file_names )\n @file_names = file_names\n end\n\n def post( to_url )\n boundary = '----RubyMultipartClient' + rand(1000000).to_s + 'ZZZZZ'\n\n parts = []\n streams = []\n @file_names.each do |param_name, filepath|\n pos = filepath.rindex('/')\n filename = filepath[pos + 1, filepath.length - pos]\n parts << StringPart.new ( \"--\" + boundary + \"\\r\\n\" +\n \"Content-Disposition: form-data; name=\\\"\" + param_name.to_s + \"\\\"; filename=\\\"\" + filename + \"\\\"\\r\\n\" +\n \"Content-Type: video/x-msvideo\\r\\n\\r\\n\")\n stream = File.open(filepath, \"rb\")\n streams << stream\n parts << StreamPart.new (stream, File.size(filepath))\n end\n parts << StringPart.new ( \"\\r\\n--\" + boundary + \"--\\r\\n\" )\n\n post_stream = MultipartStream.new( parts )\n\n url = URI.parse( to_url )\n req = Net::HTTP::Post.new(url.path)\n req.content_length = post_stream.size\n req.content_type = 'multipart/form-data; boundary=' + boundary\n req.body_stream = post_stream\n res = Net::HTTP.new(url.host, url.port).start {|http| http.request(req) }\n\n streams.each do |stream|\n stream.close();\n end\n\n res\n end\n\nend\n\nclass StreamPart\n def initialize( stream, size )\n @stream, @size = stream, size\n end\n\n def size\n @size\n end\n\n def read ( offset, how_much )\n @stream.read ( how_much )\n end\nend\n\nclass StringPart\n def initialize ( str )\n @str = str\n end\n\n def size\n @str.length\n end\n\n def read ( offset, how_much )\n @str[offset, how_much]\n end\nend\n\nclass MultipartStream\n def initialize( parts )\n @parts = parts\n @part_no = 0;\n @part_offset = 0;\n end\n\n def size\n total = 0\n @parts.each do |part|\n total += part.size\n end\n total\n end\n\n def read ( how_much )\n\n if @part_no >= @parts.size\n return nil;\n end\n\n how_much_current_part = @parts[@part_no].size - @part_offset\n\n how_much_current_part = if how_much_current_part > how_much\n how_much\n else\n how_much_current_part\n end\n\n how_much_next_part = how_much - how_much_current_part\n\n current_part = @parts[@part_no].read(@part_offset, how_much_current_part )\n\n if how_much_next_part > 0\n @part_no += 1\n @part_offset = 0\n next_part = read ( how_much_next_part )\n current_part + if next_part\n next_part\n else\n ''\n end\n else\n @part_offset += how_much_current_part\n current_part\n end\n end\nend\n"
},
{
"answer_id": 393747,
"author": "Alex",
"author_id": 16974,
"author_profile": "https://Stackoverflow.com/users/16974",
"pm_score": 4,
"selected": false,
"text": " def upload(photo)\n `curl -F media=@#{photo.path} -F username=#{@username} -F password=#{@password} -F message='#{photo.title}' http://twitpic.com/api/uploadAndPost`\n end\n"
},
{
"answer_id": 2603805,
"author": "eric",
"author_id": 312322,
"author_profile": "https://Stackoverflow.com/users/312322",
"pm_score": 5,
"selected": false,
"text": "require 'net/http/post/multipart'\n\nurl = URI.parse('http://www.example.com/upload')\nFile.open(\"./image.jpg\") do |jpg|\n req = Net::HTTP::Post::Multipart.new url.path,\n \"file\" => UploadIO.new(jpg, \"image/jpeg\", \"image.jpg\")\n res = Net::HTTP.start(url.host, url.port) do |http|\n http.request(req)\n end\nend\n $ sudo gem install multipart-post\n n = Net::HTTP.new(url.host, url.port) \nn.use_ssl = true\n# for debugging dev server\n#n.verify_mode = OpenSSL::SSL::VERIFY_NONE\nres = n.start do |http|\n"
},
{
"answer_id": 41176937,
"author": "Feuda",
"author_id": 642616,
"author_profile": "https://Stackoverflow.com/users/642616",
"pm_score": 0,
"selected": false,
"text": "def model_params\n require_params = params.require(:model).permit(:param_one, :param_two, :param_three, :avatar)\n require_params[:avatar] = model_params[:avatar].present? ? UploadIO.new(model_params[:avatar].tempfile, model_params[:avatar].content_type, model_params[:avatar].original_filename) : nil\n require_params\nend\n\nrequire 'net/http/post/multipart'\n\nurl = URI.parse('http://www.example.com/upload')\nNet::HTTP.start(url.host, url.port) do |http|\n req = Net::HTTP::Post::Multipart.new(url, model_params)\n key = \"authorization_key\"\n req.add_field(\"Authorization\", key) #add to Headers\n http.use_ssl = (url.scheme == \"https\")\n http.request(req)\nend\n"
},
{
"answer_id": 45976252,
"author": "airmanx86",
"author_id": 382979,
"author_profile": "https://Stackoverflow.com/users/382979",
"pm_score": 3,
"selected": false,
"text": "ruby stdlib net/http IO :size"
},
{
"answer_id": 46669328,
"author": "Vova Rozhkov",
"author_id": 1434854,
"author_profile": "https://Stackoverflow.com/users/1434854",
"pm_score": 5,
"selected": false,
"text": "uri = URI('https://some.end.point/some/path')\nrequest = Net::HTTP::Post.new(uri)\nrequest['Authorization'] = 'If you need some headers'\nform_data = [['photos', photo.tempfile]] # or File.open() in case of local file\n\nrequest.set_form form_data, 'multipart/form-data'\nresponse = Net::HTTP.start(uri.hostname, uri.port, use_ssl: true) do |http| # pay attention to use_ssl if you need it\n http.request(request)\nend\n"
},
{
"answer_id": 67033925,
"author": "Vova Rozhkov",
"author_id": 1434854,
"author_profile": "https://Stackoverflow.com/users/1434854",
"pm_score": 0,
"selected": false,
"text": "HTTP.post(\"https://here-you-go.com/upload\",\n form: {\n file: HTTP::FormData::File.new(file_path)\n })\n"
}
] |
2008/10/08
|
[
"https://Stackoverflow.com/questions/184178",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13989/"
] |
184,187
|
<p>I would like to write some scripts in python that do some automated changes to source code. If the script determines it needs to change the file I would like to first check it out of perforce. I don't care about checking in because I will always want to build and test first. </p>
|
[
{
"answer_id": 184193,
"author": "Matt Price",
"author_id": 852,
"author_profile": "https://Stackoverflow.com/users/852",
"pm_score": 3,
"selected": false,
"text": "import os\n\ndef CreateNewChangeList(description):\n \"Create a new changelist and returns the changelist number as a string\"\n p4in, p4out = os.popen2(\"p4 changelist -i\")\n p4in.write(\"change: new\\n\")\n p4in.write(\"description: \" + description)\n p4in.close()\n changelist = p4out.readline().split()[1]\n return changelist\n\ndef OpenFileForEdit(file, changelist = \"\"):\n \"Open a file for edit, if a changelist is passed in then open it in that list\"\n cmd = \"p4 edit \"\n if changelist:\n cmd += \" -c \" + changelist + \" \"\n ret = os.popen(cmd + file).readline().strip()\n if not ret.endswith(\"opened for edit\"):\n print \"Couldn't open\", file, \"for edit:\"\n print ret\n raise ValueError\n"
},
{
"answer_id": 184344,
"author": "Troy J. Farrell",
"author_id": 26244,
"author_profile": "https://Stackoverflow.com/users/26244",
"pm_score": 6,
"selected": true,
"text": "PythonWin 2.5.1 (r251:54863, May 1 2007, 17:47:05) [MSC v.1310 32 bit (Intel)] on win32.\nPortions Copyright 1994-2006 Mark Hammond - see 'Help/About PythonWin' for further copyright information.\n>>> import P4\n>>> p4 = P4.P4()\n>>> p4.connect() # connect to the default server, with the default clientspec\n>>> desc = {\"Description\": \"My new changelist description\",\n... \"Change\": \"new\"\n... }\n>>> p4.input = desc\n>>> p4.run(\"changelist\", \"-i\")\n['Change 2579505 created.']\n>>> \n P:\\>p4 changelist -o 2579505\n# A Perforce Change Specification.\n#\n# Change: The change number. 'new' on a new changelist.\n# Date: The date this specification was last modified.\n# Client: The client on which the changelist was created. Read-only.\n# User: The user who created the changelist.\n# Status: Either 'pending' or 'submitted'. Read-only.\n# Description: Comments about the changelist. Required.\n# Jobs: What opened jobs are to be closed by this changelist.\n# You may delete jobs from this list. (New changelists only.)\n# Files: What opened files from the default changelist are to be added\n# to this changelist. You may delete files from this list.\n# (New changelists only.)\n\nChange: 2579505\n\nDate: 2008/10/08 13:57:02\n\nClient: MYCOMPUTER-DT\n\nUser: myusername\n\nStatus: pending\n\nDescription:\n My new changelist description\n"
},
{
"answer_id": 256419,
"author": "Syeberman",
"author_id": 14576,
"author_profile": "https://Stackoverflow.com/users/14576",
"pm_score": 2,
"selected": false,
"text": "p4 [ options ] command [ arg ... ]\n options:\n -c client -C charset -d dir -H host -G -L language\n -p port -P pass -s -Q charset -u user -x file\n The -G flag causes all output (and batch input for form commands\n with -i) to be formatted as marshalled Python dictionary objects.\n"
},
{
"answer_id": 4242307,
"author": "farhany",
"author_id": 90506,
"author_profile": "https://Stackoverflow.com/users/90506",
"pm_score": 2,
"selected": false,
"text": "apt-get install python2.6-dev\n apt-get install python3.1-dev\n"
}
] |
2008/10/08
|
[
"https://Stackoverflow.com/questions/184187",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/852/"
] |
184,195
|
<p>I'm getting married soon and am busy with the seating plan, and am running into the usual issues of who sits where: X and Y <em>must</em> sit together, but A and B cannot stand each other etc.</p>
<p>The numbers I'm dealing with aren't huge (so the manual option will work just fine), but being of the geeky persuasion, I was wondering if there was any software available to do this for me?</p>
<p>Failing an exact match, what should I look for (the problem space, books, reference code) to tweak for my purposes?</p>
|
[
{
"answer_id": 184224,
"author": "Tom Ritter",
"author_id": 8435,
"author_profile": "https://Stackoverflow.com/users/8435",
"pm_score": 0,
"selected": false,
"text": "fact GateRules {\n all g:Gate | one g.loc // Gates have 1 Location\n"
}
] |
2008/10/08
|
[
"https://Stackoverflow.com/questions/184195",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18177/"
] |
184,216
|
<p>Full disclaimer: I'm a CS student, and this question is related to a recently assigned Java program for Object-Oriented Programming. Although we've done some console stuff, this is the first time we've worked with a GUI and Swing or Awt. We were given some code that created a window with some text and a button that rotated through different colors for the text. We were then asked to modify the program to create radio buttons for the colors instead—this was also intended to give us practice researching an API. I've already handed in my assignment and received permission from my instructor to post my code here.</p>
<p>What's the best way to implement button actions in Java? After some fiddling around, I created the buttons like this:</p>
<pre><code>class HelloComponent3 extends JComponent
implements MouseMotionListener, ActionListener
{
int messageX = 75, messageY= 175;
String theMessage;
String redString = "red", blueString = "blue", greenString = "green";
String magentaString = "magenta", blackString = "black", resetString = "reset";
JButton resetButton;
JRadioButton redButton, blueButton, greenButton, magentaButton, blackButton;
ButtonGroup colorButtons;
public HelloComponent3(String message) {
theMessage = message;
//intialize the reset button
resetButton = new JButton("Reset");
resetButton.setActionCommand(resetString);
resetButton.addActionListener(this);
//intialize our radio buttons with actions and labels
redButton = new JRadioButton("Red");
redButton.setActionCommand(redString);
...
</code></pre>
<p>And added action listeners...</p>
<pre><code>redButton.addActionListener(this);
blueButton.addActionListener(this);
...
</code></pre>
<p>A stub was already created for the actionPerformed method to give us an idea on how to use it, but since there was only a single button in the template, it wasn't clear how to implement multiple buttons. I tried switching on a String, but quickly realized that, since a String isn't a primitive type, I couldn't use it for a switch statement. I could have improvised with an if-else chain, but this is what I came up with instead. It seems far from elegant, and there must be a better way. If there is, what is it? Is there a way to switch on a string? Or choose an action in a more scaleable fashion?</p>
<pre><code>public void actionPerformed(ActionEvent e){
if (e.getActionCommand().equals(resetString)) {
messageX = 75; messageY = 175;
setForeground(Color.black);
blackButton.setSelected(true);
repaint();
return;
}
if ( e.getActionCommand().equals(redString) ) {
setForeground(Color.red);
repaint();
return;
}
if ( e.getActionCommand().equals(blueString) ) {
setForeground(Color.blue);
repaint();
return;
}
if ( e.getActionCommand().equals(greenString) ) {
setForeground(Color.green);
repaint();
return;
}
if ( e.getActionCommand().equals(magentaString) ) {
setForeground(Color.magenta);
repaint();
return;
}
if ( e.getActionCommand().equals(blackString) ) {
setForeground(Color.black);
repaint();
return;
}
}
</code></pre>
|
[
{
"answer_id": 184372,
"author": "Patrick Huizinga",
"author_id": 15200,
"author_profile": "https://Stackoverflow.com/users/15200",
"pm_score": 2,
"selected": true,
"text": "resetButton.addActionListener(this);\n resetButton.addActionListener(new ActionListener() {\n public void actionPerformed(ActionEvent evt) {\n resetButtonActionPerformed(evt);\n }\n});\n public void resetButtonActionPerformed(ActionEvent evt) {\n messageX = 75; messageY = 175;\n setForeground(Color.black);\n blackButton.setSelected(true);\n repaint();\n}\n"
},
{
"answer_id": 184419,
"author": "Tom Hawtin - tackline",
"author_id": 4725,
"author_profile": "https://Stackoverflow.com/users/4725",
"pm_score": -1,
"selected": false,
"text": " addColorButton(\"Green\" , Color.GREEN );\n addColorButton(\"Red\" , Color.RED );\n addColorButton(\"Yellow\", Color.YELLOW);\n addColorButton(\"Blue\" , Color.BLUE );\n ...\n\nprivate void addColorButton(String label, Color color) {\n JRadioButton button = new JRadioButton(label);\n button.addActionListener(new ActionListener() {\n public void actionPerformed(ActionEvent event) {\n target.setForeground(color);\n target.repaint();\n } \n });\n colorGroup.add(button);\n panel.add(button);\n}\n"
},
{
"answer_id": 189604,
"author": "Draemon",
"author_id": 26334,
"author_profile": "https://Stackoverflow.com/users/26334",
"pm_score": 0,
"selected": false,
"text": "resetButton = new JButton(new ResetAction());\nredButton = new JButton(new ColorAction(\"Red\", Color.red));\n private class ResetAction extends AbstractAction {\n public ResetAction() {\n super(\"Reset\");\n }\n\n public void actionPerformed(ActionEvent e) {\n messageX = 75; messageY = 175;\n setForeground(Color.black);\n blackButton.setSelected(true);\n repaint();\n }\n}\n\nprivate class ResetAction extends AbstractAction {\n private Color color;\n\n public ColorAction(String title, Color color) {\n super(title);\n this.color = color;\n }\n\n public void actionPerformed(ActionEvent e) {\n setForeground(color);\n repaint();\n }\n}\n"
}
] |
2008/10/08
|
[
"https://Stackoverflow.com/questions/184216",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/26237/"
] |
184,253
|
<p>We may start converting an old VS2003 MFC project to use the fancy new features provided by the MFC Feature Pack and VS2008. Several of the new UI controls would be very nice except for one thing - they automatically save their information to the registry. I don't have a problem with the registry, but for the multiple environments the users use out program from, it's much easier to save user data to the database. </p>
<p>So, I'm hoping that there is one main "access the registry" function that could be overloaded to point the database. But brief investigation hasn't turned up anything. Has anyone else had any success doing something similar?</p>
|
[
{
"answer_id": 184455,
"author": "Rob",
"author_id": 9236,
"author_profile": "https://Stackoverflow.com/users/9236",
"pm_score": 0,
"selected": false,
"text": "CMFCRegistrySP StateCollection"
},
{
"answer_id": 203016,
"author": "ChrisN",
"author_id": 3853,
"author_profile": "https://Stackoverflow.com/users/3853",
"pm_score": 3,
"selected": true,
"text": "CSettingsStore CSettingsStoreSP::SetRuntimeClass"
}
] |
2008/10/08
|
[
"https://Stackoverflow.com/questions/184253",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12567/"
] |
184,254
|
<p>I am using a Session Parameter on an ObjectDataSource. It works fine on the local development machine but I get this error after copying the website to the production server:</p>
<p>Type 'System.Web.UI.WebControls.SessionParameter' does not have a public property named 'DbType'.</p>
|
[
{
"answer_id": 8916585,
"author": "renlo",
"author_id": 1157060,
"author_profile": "https://Stackoverflow.com/users/1157060",
"pm_score": 1,
"selected": false,
"text": "DBType =\"AnsiString\" \n Type=\"String\" \n"
}
] |
2008/10/08
|
[
"https://Stackoverflow.com/questions/184254",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7316/"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.