qid int64 4 19.1M | question stringlengths 18 48.3k | answers list | date stringlengths 10 10 | metadata list |
|---|---|---|---|---|
339,910 | <p>in context of SQL Server 2005, I have a table for which the primary key is a uniqueidentifier (GUID), with a default value generated by the newid() function. I want to write a stored procedure that inserts a new record into the table. How do I get the record's PK value? for an identity-declared field, this is easy - I call scope_identity(). How should I proceed with guids?</p>
<p>Thanks,
Lucian</p>
| [
{
"answer_id": 339918,
"author": "Paul Nearney",
"author_id": 24071,
"author_profile": "https://Stackoverflow.com/users/24071",
"pm_score": 3,
"selected": true,
"text": "DECLARE @newGuid uniqueidentifier\nSET @newGuid = newid()\n\nINSERT INTO myTable(id, stringval)\nVALUES (@newGuid, \"Hello\")\n\nSELECT * FROM myTable\nWHERE id = @newGuid\n"
},
{
"answer_id": 339924,
"author": "Eugene Yokota",
"author_id": 3827,
"author_profile": "https://Stackoverflow.com/users/3827",
"pm_score": 0,
"selected": false,
"text": "SELECT OUTPUT"
},
{
"answer_id": 339929,
"author": "devio",
"author_id": 21336,
"author_profile": "https://Stackoverflow.com/users/21336",
"pm_score": 0,
"selected": false,
"text": "CREATE PROCEDURE Insert_myTable(@values...) AS\n\nDECLARE @pk GUID\nSET @pk = NEWID()\n\nINSERT INTO myTable(PKID, values...) VALUES (@pk, @values...)\n\nSELECT @pk\n"
},
{
"answer_id": 339943,
"author": "Ryan Cook",
"author_id": 43029,
"author_profile": "https://Stackoverflow.com/users/43029",
"pm_score": 1,
"selected": false,
"text": "CREATE PROCEDURE insNewGuidIdRow \n @newId UNIQUEIDENTIFIER output,\n @otherData NVARCHAR(10)\nAS\nBEGIN\n SET @newId = NEWID()\n\n INSERT INTO GuidIdTable(id, otherData)\n VALUES (@newId, @otherData)\nEND\n"
},
{
"answer_id": 339957,
"author": "Valentin V",
"author_id": 430254,
"author_profile": "https://Stackoverflow.com/users/430254",
"pm_score": 2,
"selected": false,
"text": "DECLARE @outputTblCustomer1 TABLE (CustomerID uniqueidentifier)\n\n-- Customer1 \n\nINSERT INTO dbo.Customer1 (CustomerNumber, LastName) OUTPUT INSERTED.CustomerID INTO @outputTblCustomer1 VALUES (-1, N'LastName') \n\nSELECT CustomerID FROM @outputTblCustomer1\n\n-- Customer3 \n\nINSERT INTO dbo.Customer3 (CustomerNumber, LastName) VALUES (-1, N'LastName') \n\nSELECT SCOPE_IDENTITY() AS CustomerID\n"
},
{
"answer_id": 2397654,
"author": "Marco Bettiolo",
"author_id": 26754,
"author_profile": "https://Stackoverflow.com/users/26754",
"pm_score": 0,
"selected": false,
"text": "CREATE TABLE [dbo].[TableName ](\n [Code] [uniqueidentifier] ROWGUIDCOL NOT NULL,\n [Name] [nvarchar](100) NOT NULL)\n\nALTER TABLE [dbo].[TableName ] ADD CONSTRAINT [DF_Questionnaire_Code] DEFAULT (newid()) FOR [Code]\n INSERT INTO TableName (Name)\nOUTPUT Inserted.Code AS NewGUID\nVALUES ('TEST')\n NewGUID\n------------------------------------\nF540C0F8-ADBC-4054-BAB6-1927DE59FA99\n"
},
{
"answer_id": 15587407,
"author": "benahm",
"author_id": 2078289,
"author_profile": "https://Stackoverflow.com/users/2078289",
"pm_score": 0,
"selected": false,
"text": " DECLARE @id uniqueidentifier;\n SELECT @id=NEWID() \n INSERT INTO MyTable(ID,other)\n VALUES(@id,'other');\n"
}
] | 2008/12/04 | [
"https://Stackoverflow.com/questions/339910",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11464/"
] |
339,912 | <p>I have class with internal property:</p>
<pre><code>internal virtual StateEnum EnrolmentState
{
get { ..getter logic }
set { ..setter logic }
}
</code></pre>
<p>However I want to be able to access to this property outside of the assembly so I created method that simply returns this property:</p>
<pre><code>public StateEnum GetCurrentState()
{
return EnrolmentState;
}
</code></pre>
<p>But when I call this method from class outside of this assembly I get an exception</p>
<p><code>(System.TypeLoadException: Method 'get_EnrolmentState' on type 'EnrolmentAopProxy' from assembly '44fe776f-458e-4c5d-aa35-08c55501dd43, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null' is overriding a method that is not visible from that assembly.)</code></p>
<p>So it is possible to access to internal member outside of the assembly in any way, or I should consider a different approach.</p>
<p>Just to mention that this class is used as an O/R mapper entity (NPersist) and it is overrided from the O/R mapper to inject persistence code.</p>
| [
{
"answer_id": 339937,
"author": "Jon Skeet",
"author_id": 22656,
"author_profile": "https://Stackoverflow.com/users/22656",
"pm_score": 3,
"selected": true,
"text": "InternalsVisibleTo"
},
{
"answer_id": 340195,
"author": "Aleksandar",
"author_id": 29511,
"author_profile": "https://Stackoverflow.com/users/29511",
"pm_score": 0,
"selected": false,
"text": "InternalVisibleTo"
}
] | 2008/12/04 | [
"https://Stackoverflow.com/questions/339912",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/29511/"
] |
339,923 | <p>In an HTML table, the <code>cellpadding</code> and <code>cellspacing</code> can be set like this:</p>
<pre class="lang-html prettyprint-override"><code><table cellspacing="1" cellpadding="1">
</code></pre>
<p>How can the same be accomplished using CSS?</p>
| [
{
"answer_id": 339964,
"author": "mat",
"author_id": 42083,
"author_profile": "https://Stackoverflow.com/users/42083",
"pm_score": 6,
"selected": false,
"text": "cellspacing=\"0\" border-collapse: collapse table"
},
{
"answer_id": 339997,
"author": "Will Prescott",
"author_id": 13780,
"author_profile": "https://Stackoverflow.com/users/13780",
"pm_score": 7,
"selected": false,
"text": "cellspacing border-spacing border-collapse: collapse cellspacing"
},
{
"answer_id": 1323014,
"author": "Pup",
"author_id": 125505,
"author_profile": "https://Stackoverflow.com/users/125505",
"pm_score": 9,
"selected": false,
"text": "table\n{\n border-collapse: collapse; /* 'cellspacing' equivalent */\n}\n\ntable td, table th\n{\n padding: 0; /* 'cellpadding' equivalent */\n}\n"
},
{
"answer_id": 2341179,
"author": "corrector",
"author_id": 281970,
"author_profile": "https://Stackoverflow.com/users/281970",
"pm_score": 4,
"selected": false,
"text": "cellpadding=\"0\" cellspacing=\"0\" <td>"
},
{
"answer_id": 3209434,
"author": "Eric Nguyen",
"author_id": 98068,
"author_profile": "https://Stackoverflow.com/users/98068",
"pm_score": 13,
"selected": true,
"text": "padding td { \n padding: 10px;\n}\n border-spacing table { \n border-spacing: 10px;\n border-collapse: separate;\n}\n border-collapse cellspacing=\"0\" border-collapse:collapse cellspacing border-spacing border-collapse:collapse table { \n border-spacing: 0;\n border-collapse: collapse;\n}\n"
},
{
"answer_id": 7129454,
"author": "Malvineous",
"author_id": 308237,
"author_profile": "https://Stackoverflow.com/users/308237",
"pm_score": 6,
"selected": false,
"text": "table {\n border-collapse: separate;\n border-spacing: 2px;\n}\n"
},
{
"answer_id": 8381051,
"author": "Vitalii Fedorenko",
"author_id": 288671,
"author_profile": "https://Stackoverflow.com/users/288671",
"pm_score": 7,
"selected": false,
"text": "table {\n border-collapse: separate;\n border-spacing: 10px; /* cellspacing */\n *border-collapse: expression('separate', cellSpacing = '10px');\n}\n\ntable td, table th {\n padding: 10px; /* cellpadding */\n}\n * expression('separate', cellSpacing = '10px') 'separate'"
},
{
"answer_id": 8433879,
"author": "George Filippakos",
"author_id": 961333,
"author_profile": "https://Stackoverflow.com/users/961333",
"pm_score": 6,
"selected": false,
"text": "table\n{\n border: 1px solid #000000;\n border-collapse: collapse;\n border-spacing: 0px;\n}\ntable td\n{\n padding: 8px 8px;\n}\n"
},
{
"answer_id": 10994718,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 10,
"selected": false,
"text": "table {border-collapse: collapse;}\ntd {padding: 0px;}\n table {border-collapse: collapse;}\ntd {padding: 6px;}\n table {border-spacing: 2px;}\ntd {padding: 0px;}\n table {border-spacing: 2px;}\ntd {padding: 6px;}\n table {border-spacing: 8px 2px;}\ntd {padding: 6px;}\n border-spacing border-collapse separate"
},
{
"answer_id": 11103726,
"author": "Robert White",
"author_id": 830455,
"author_profile": "https://Stackoverflow.com/users/830455",
"pm_score": 6,
"selected": false,
"text": "div.cellwidener {\n margin: 0px 15px 0px 15px;\n}\ntd.tight {\n padding: 0px;\n} <table border=\"0\">\n <tr>\n <td class=\"tight\">\n <div class=\"cellwidener\">My content</div>\n </td>\n </tr>\n</table>"
},
{
"answer_id": 11294946,
"author": "RolanDecoy",
"author_id": 1496208,
"author_profile": "https://Stackoverflow.com/users/1496208",
"pm_score": 4,
"selected": false,
"text": "<table> <div> position: absolute; background: transparent; <table> <div> <form> <tr> <td> <span> <input>"
},
{
"answer_id": 14878532,
"author": "Håkan Nilsson",
"author_id": 2072630,
"author_profile": "https://Stackoverflow.com/users/2072630",
"pm_score": 3,
"selected": false,
"text": "!important border-collapse: collapse !important;\n"
},
{
"answer_id": 17101919,
"author": "Falguni Panchal",
"author_id": 2473201,
"author_profile": "https://Stackoverflow.com/users/2473201",
"pm_score": 4,
"selected": false,
"text": "table {\n border-collapse: separate;\n border-spacing: 10px;\n}\ntable td, table th {\n padding: 10px;\n}\n table {\n border-collapse: collapse;\n}\ntable td, table th {\n padding: 10px;\n}\n"
},
{
"answer_id": 22063676,
"author": "Suraj Rawat",
"author_id": 3011961,
"author_profile": "https://Stackoverflow.com/users/3011961",
"pm_score": 4,
"selected": false,
"text": "selector{\n padding:0 0 10px 0; // Top left bottom right \n}\n"
},
{
"answer_id": 22430621,
"author": "Suraj Rawat",
"author_id": 3011961,
"author_profile": "https://Stackoverflow.com/users/3011961",
"pm_score": 4,
"selected": false,
"text": "td { \n padding: 20px;\n}\n table { \n border-spacing: 1px;\n border-collapse: collapse;\n}\n"
},
{
"answer_id": 23344649,
"author": "Elad Shechter",
"author_id": 2413332,
"author_profile": "https://Stackoverflow.com/users/2413332",
"pm_score": 5,
"selected": false,
"text": "table{\n border:0; /* Replace border */\n border-spacing: 0px; /* Replace cellspacing */\n border-collapse: collapse; /* Patch for Internet Explorer 6 and Internet Explorer 7 */\n}\ntable td{\n padding: 0px; /* Replace cellpadding */\n}\n"
},
{
"answer_id": 27637729,
"author": "Majid Sadr",
"author_id": 3789730,
"author_profile": "https://Stackoverflow.com/users/3789730",
"pm_score": 3,
"selected": false,
"text": "td {\n padding: npx; /* For cellpadding */\n margin: npx; /* For cellspacing */\n border-collapse: collapse; /* For showing borders in a better shape. */\n}\n margin display tr block"
},
{
"answer_id": 45457433,
"author": "Rafiqul Islam",
"author_id": 4788956,
"author_profile": "https://Stackoverflow.com/users/4788956",
"pm_score": 4,
"selected": false,
"text": "table,\nth,\ntd {\n border: 1px solid #666;\n}\n\ntable th,\ntable td {\n padding: 10px;\n /* Apply cell padding */\n} <!DOCTYPE html>\n<html lang=\"en\">\n<head>\n\n <meta charset=\"utf-8\">\n <title>Set Cellpadding in CSS</title>\n\n</head>\n\n<body>\n\n <table>\n <thead>\n <tr>\n <th>Row</th>\n <th>First Name</th>\n <th>Last Name</th>\n <th>Email</th>\n </tr>\n </thead>\n <tbody>\n <tr>\n <td>1</td>\n <td>Clark</td>\n <td>Kent</td>\n <td>clarkkent@mail.com</td>\n </tr>\n <tr>\n <td>2</td>\n <td>Peter</td>\n <td>Parker</td>\n <td>peterparker@mail.com</td>\n </tr>\n <tr>\n <td>3</td>\n <td>John</td>\n <td>Rambo</td>\n <td>johnrambo@mail.com</td>\n </tr>\n </tbody>\n </table>\n\n</body>\n</html> table {\n border-collapse: separate;\n border-spacing: 10px;\n /* Apply cell spacing */\n}\n\ntable,\nth,\ntd {\n border: 1px solid #666;\n}\n\ntable th,\ntable td {\n padding: 5px;\n /* Apply cell padding */\n} <!DOCTYPE html>\n<html lang=\"en\">\n<head>\n\n <meta charset=\"utf-8\">\n <title>Set Cellspacing in CSS</title>\n\n</head>\n\n<body>\n\n <table>\n <thead>\n <tr>\n <th>Row</th>\n <th>First Name</th>\n <th>Last Name</th>\n <th>Email</th>\n </tr>\n </thead>\n <tbody>\n <tr>\n <td>1</td>\n <td>Clark</td>\n <td>Kent</td>\n <td>clarkkent@mail.com</td>\n </tr>\n <tr>\n <td>2</td>\n <td>Peter</td>\n <td>Parker</td>\n <td>peterparker@mail.com</td>\n </tr>\n <tr>\n <td>3</td>\n <td>John</td>\n <td>Rambo</td>\n <td>johnrambo@mail.com</td>\n </tr>\n </tbody>\n </table>\n\n</body>\n</html>"
},
{
"answer_id": 66402456,
"author": "MattAllegro",
"author_id": 3543233,
"author_profile": "https://Stackoverflow.com/users/3543233",
"pm_score": 3,
"selected": false,
"text": "border-collapse separate border-spacing border-collapse collapse border padding:10px td background-color table{border-spacing:15px}\ntd{background-color:#00eb55;padding:10px;border:0} <table>\n<tr>\n<td>Header 1</td><td>Header 2</td>\n</tr>\n<tr>\n<td>1</td><td>2</td>\n</tr>\n<tr>\n<td>3</td><td>4</td>\n</tr>\n</table> table{border-collapse:collapse}\ntd{background-color:#00eb55;padding:10px;border:15px solid #fff} <table>\n<tr>\n<td>Header 1</td><td>Header 2</td>\n</tr>\n<tr>\n<td>1</td><td>2</td>\n</tr>\n<tr>\n<td>3</td><td>4</td>\n</tr>\n</table>"
}
] | 2008/12/04 | [
"https://Stackoverflow.com/questions/339923",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1065/"
] |
339,931 | <p>Javascript client side application.</p>
<p>Trying to eliminate memory leaks leads to ugly (to say the least) code.</p>
<p>I am trying to clean up in window.unload instead on messing up all the code trying to avoid them.</p>
<p>We use mostly <code>element.onevent=function(){..};</code> pattern, that results in closure (mostly wanted) and memory leak.</p>
<p>We do not use javascript frameworks.</p>
<p>Are there any ideas on how to clean up properly on exit?</p>
<p>Has anyone do the same or are you trying to avoid them?</p>
| [
{
"answer_id": 1889571,
"author": "Ruan Mendes",
"author_id": 227299,
"author_profile": "https://Stackoverflow.com/users/227299",
"pm_score": 3,
"selected": true,
"text": "var EvtMgr = (function(){\n var listenerMap = {};\n\n // Public interface\n return {\n addListener: function (evtName, node, handler) {\n node[\"on\" + evtName] = handler;\n var eventList = listenerMap[evtName];\n if (!eventList) {\n eventList = listenerMap[evtName] = [];\n }\n eventList.push(node);\n },\n\n removeAllListeners: function() {\n for (var evtName in listenerMap) {\n var nodeList = listenerMap[evtName];\n for (var i=0, node; node = nodeList[i]; i++) {\n node[\"on\" + evtName] = null;\n }\n }\n }\n }\n})();\n"
}
] | 2008/12/04 | [
"https://Stackoverflow.com/questions/339931",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/28207/"
] |
339,935 | <p>For example:</p>
<p>script.js:</p>
<pre><code>function functionFromScriptJS() {
alert('inside functionFromScriptJS');
}
</code></pre>
<p>iframe.html:</p>
<pre><code><html>
<head>
<script language="Javascript" src="script.js"></script>
</head>
<body>
<iframe>
<body>
<script language="JavaScript">
functionFromScriptJS();
</script>
</body>
</iframe>
</body>
<html>
</code></pre>
<p>The above call to functionFromScriptJS() is not working.</p>
<p>The first guess parent.functionFromScriptJS() is not working too.</p>
<p>Is it possible to access such an external function from an iframe when the include is not in the iframe itself but in the parent document?</p>
<p><strong>@Edit:</strong> So my mistake was that I put the document inside the iframe tag, and I sould have put it in a separate file and specified through the src attrubute of the tag. In this case <em>parent.functionFromScriptJS()</em> works.</p>
| [
{
"answer_id": 339965,
"author": "Ryan Cook",
"author_id": 43029,
"author_profile": "https://Stackoverflow.com/users/43029",
"pm_score": 3,
"selected": true,
"text": "<iframe> <iframe src=\"someFile.html\" width=\"100%\" height=\"300px\">\n <p>Your browser does not support iframes.</p>\n</iframe>\n parent.functionFromScriptJS();"
},
{
"answer_id": 339990,
"author": "adam",
"author_id": 33604,
"author_profile": "https://Stackoverflow.com/users/33604",
"pm_score": 0,
"selected": false,
"text": "<div>"
}
] | 2008/12/04 | [
"https://Stackoverflow.com/questions/339935",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/578/"
] |
339,939 | <h2>My Situation</h2>
<ul>
<li>I have a N rectangles</li>
<li>The rectangles all have the same shape (for example 2 inches wide x 1 inch tall) - Let's refer to this size as Sw and Sh for the width and height</li>
<li>I want to position these rectangles in a grid such that the rects completely on top and next to each other - like what you would see in a spreadsheet </li>
<li>What I need is this: <strong>Given N, Sw, and Sh what are the number of rows (R) and columns (C) that would stack these rects into the most square-like arrangement possible</strong></li>
<li>It is understood that R & C may provide more cells than in needed (for example if N=15,Sw=1,Sh=1 then R=4,C=4 yielding 16 "slots" for 15 rectangles - that is OK.</li>
<li>If Sw=Sh then my humble math skills are enough - when they rectangles have differing widths and heights - well frankly that's beyond me.</li>
</ul>
<h2>Some Notes</h2>
<ul>
<li>Yes I have read this question: <a href="https://stackoverflow.com/questions/251488/stacking-rectangles-to-take-as-little-space-as-possible">Stacking rectangles to take as little space as possible</a> and no it did not help. Also it isnt the same question. That question is about rectangles that could be of different sizes, in this question the rectangles have the same size</li>
<li>Yes I have searched on wolfram.com, etc and no luck there</li>
<li>I don't have a strong math background so I the way I phrasing this problem may itself be preventing me from finding the answer - I've tried related searches relating to tiling, dissecting, decomposing, and not had any success there either</li>
</ul>
<h2>Some examples</h2>
<pre><code>the * indicates the edges of the rects
the | indicates that a cell is "filled-in"
Notice that not all R*C cells are filled in, but only and exactly N cells
IF N=1, Sw=2, Sh=1 THEN R=1, C=1
********
*||||||*
********
IF N=2, Sw=2, Sh=1 THEN R=2, C=1
********
*||||||*
********
*||||||*
********
IF N=3, Sw=2, Sh=1 THEN R=2, C=2
***************
*||||||* *
***************
*||||||*||||||*
***************
IF N=4, Sw=2, Sh=1 THEN R=2, C=2
***************
*||||||*||||||*
***************
*||||||*||||||*
***************
IF N=5, Sw=2, Sh=1 THEN R=3, C=2
***************
*||||||* *
***************
*||||||*||||||*
***************
*||||||*||||||*
***************
</code></pre>
<h2>Implementation of AaronofTomorrow's answer</h2>
<pre><code># Implementation of AaronofTomorrow's answer
# implemented in python 2.6
# reasonable output
# works in constant time
import math
def f( N, Sw, Sh ) :
cols = math.sqrt( float(N) * float(Sh) / float(Sw) )
cols = round(cols)
rows = float(N) / float(cols)
rows = math.ceil(rows)
return (int(cols),int(rows))
</code></pre>
<h2>Another implementation inspired by Will's answer (Updated on 2008-12-08) - this is the one I finally used</h2>
<pre><code># Another implementation inspired by Will's answer
# implemented in python 2.6
# reasonable output - a bit better in yielding more squarelike grids
# works in time proportional to number of rects
#
# strategy used it to try incrementaly adding a rect.
# if the resulting rect requires more space then two
# possibilities are checked - adding a new row or adding a new col
# the one with the best aspect ratio (1:1) will be chosen
def g( N, Sw, Sh ) :
slope = float(Sh)/float(Sw)
cols = 1
rows = 1
for i in xrange( N ) :
num_to_fit =i+1
allocated_cells= cols* rows
if ( num_to_fit <= allocated_cells ) :
pass # do nothing
else :
hc,wc = float(Sh * rows), float(Sw * (cols+1))
hr,wr = float(Sh * (rows+1)), float(Sw * cols)
thetac = math.atan( hc/wc)
thetar = math.atan( hr/wr)
alpha = math.pi/4.0
difr = abs(alpha-thetar)
difc = abs(alpha-thetac)
if ( difr < difc ) :
rows = rows +1
else:
cols = cols + 1
return (cols,rows)
</code></pre>
| [
{
"answer_id": 339982,
"author": "Will Dean",
"author_id": 987,
"author_profile": "https://Stackoverflow.com/users/987",
"pm_score": 1,
"selected": false,
"text": "N/nCols*Sh + nCols*Sw\n"
}
] | 2008/12/04 | [
"https://Stackoverflow.com/questions/339939",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13477/"
] |
339,952 | <p>We are in the process of upgrading our projects from C# 2.0 / VS2005 to C# 3.0 / VS2008. As part of the upgrade, we are adding some items to our coding standards document.</p>
<p>How would (or did) you change your coding standards document when upgrading from C# 2.0 / VS2005 to C# 3.0 / VS2008?</p>
| [
{
"answer_id": 340028,
"author": "Jon Skeet",
"author_id": 22656,
"author_profile": "https://Stackoverflow.com/users/22656",
"pm_score": 4,
"selected": true,
"text": "var var IComparer<T>"
},
{
"answer_id": 341485,
"author": "David Schmitt",
"author_id": 4918,
"author_profile": "https://Stackoverflow.com/users/4918",
"pm_score": 1,
"selected": false,
"text": "var var obj1 = new Something();\nvar obj2 = (Something)ObscureFunction();\nvar obj3 = ObscureStuff() as Something;\n var obj4 = ObscureFunction();\nforeach(Something s in obj4) { ... }\n var obj5 = ctx.GetQuery<Something>()..ToList(..)..GroupJoin(..)...ToLookup(...);\n"
}
] | 2008/12/04 | [
"https://Stackoverflow.com/questions/339952",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2822/"
] |
339,956 | <p>What is the best method for date of birth selector?</p>
<ul>
<li>3 text inputs (month / day / year) or one mask input. User MUST use keyboard</li>
<li>3 select boxes. User can use keyboard or mouse. </li>
<li>One nice <a href="http://jqueryui.com/demos/datepicker/" rel="noreferrer">datepicker</a>.</li>
</ul>
<p>I want to know what is the most usable and problem free solution, so user wont be confused at all.</p>
| [
{
"answer_id": 3261876,
"author": "Bennett McElwee",
"author_id": 61754,
"author_profile": "https://Stackoverflow.com/users/61754",
"pm_score": 4,
"selected": false,
"text": " _______\n|_______| (example: 31/3/1970)\n _________ __ ____\n|March |V| |__| |____|\n"
},
{
"answer_id": 24788502,
"author": "user3845825",
"author_id": 3845825,
"author_profile": "https://Stackoverflow.com/users/3845825",
"pm_score": -1,
"selected": false,
"text": "daysInMonth = new Date(year,month,1,-1).getDate();\n"
}
] | 2008/12/04 | [
"https://Stackoverflow.com/questions/339956",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23810/"
] |
339,961 | <p>I need the perfect algorithm or C# function to calculate the difference (distance) between 2 decimal numbers.</p>
<p>For example the difference between:<br />
<strong>100</strong> and <strong>25</strong> is <strong>75</strong><br />
<strong>100</strong> and <strong>-25</strong> is <strong>125</strong><br />
<strong>-100</strong> and <strong>-115</strong> is <strong>15</strong><br />
<strong>-500</strong> and <strong>100</strong> is <strong>600</strong></p>
<p>Is there a C# function or a very elegant algorithm to calculate this or I have to go and handle every case separately with <em>if</em>s.</p>
<p>If there is such a function or algorithm, which one is it?</p>
| [
{
"answer_id": 339979,
"author": "terjetyl",
"author_id": 29519,
"author_profile": "https://Stackoverflow.com/users/29519",
"pm_score": 8,
"selected": true,
"text": "public decimal FindDifference(decimal nr1, decimal nr2)\n{\n return Math.Abs(nr1 - nr2);\n}\n"
},
{
"answer_id": 339981,
"author": "Martin",
"author_id": 770,
"author_profile": "https://Stackoverflow.com/users/770",
"pm_score": 5,
"selected": false,
"text": "result = Math.Abs(value1 - value2);\n"
},
{
"answer_id": 349207,
"author": "Mecki",
"author_id": 15809,
"author_profile": "https://Stackoverflow.com/users/15809",
"pm_score": 5,
"selected": false,
"text": "Math.Abs(number1 - number2);\n int result = number1 - number2;\nif (result < 0) {\n result *= -1;\n}\n int result = number1 > number2 ? number1 - number2 : number2 - number1;\n *= -1"
},
{
"answer_id": 58775198,
"author": "3263927 contra",
"author_id": 11862877,
"author_profile": "https://Stackoverflow.com/users/11862877",
"pm_score": 1,
"selected": false,
"text": "namespace Extensions\n{\n public class Functions\n {\n public static T Difference<T>(object x1, object x2) where T : IConvertible\n {\n decimal d1 = decimal.Parse(x1.ToString());\n decimal d2 = decimal.Parse(x2.ToString());\n\n return (T)Convert.ChangeType(Math.Abs(d1-d2), typeof(T));\n }\n }\n}\n namespace MixedTests\n{\n [TestClass]\n public class ExtensionsTests\n {\n [TestMethod]\n public void Difference_int_Test()\n {\n int res2 = Functions.Difference<int>(5, 7);\n int res3 = Functions.Difference<int>(-3, 0);\n int res6 = Functions.Difference<int>(-3, -9);\n int res8 = Functions.Difference<int>(3, -5);\n\n Assert.AreEqual(19, res2 + res3 + res6 + res8);\n }\n\n [TestMethod]\n public void Difference_float_Test()\n {\n float res2_1 = Functions.Difference<float>(5.1, 7.2);\n float res3_1 = Functions.Difference<float>(-3.1, 0);\n double res5_9 = Functions.Difference<double>(-3.1, -9);\n decimal res8_3 = Functions.Difference<decimal>(3.1, -5.2);\n\n Assert.AreEqual((float)2.1, res2_1);\n Assert.AreEqual((float)3.1, res3_1);\n Assert.AreEqual(5.9, res5_9);\n Assert.AreEqual((decimal)8.3, res8_3);\n\n }\n }\n}\n"
},
{
"answer_id": 73954193,
"author": "anti materium",
"author_id": 20162391,
"author_profile": "https://Stackoverflow.com/users/20162391",
"pm_score": 0,
"selected": false,
"text": "public static double Diference (double a,double b) {\n return ((System.Math.Max(a,b)-System.Math.Min(a,b)));\n }\n"
}
] | 2008/12/04 | [
"https://Stackoverflow.com/questions/339961",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18631/"
] |
339,962 | <p>What I am trying to do when the user is in a textbox (in silverlight 2.0):</p>
<ul>
<li>When user presses the decimal point
(.) <strong>on the numeric pad</strong>, I want to
have it replaced by the correct
decimal separator (which is comma
(,) in a lot of countries)</li>
</ul>
<p>I can track that the user typed a decimal point by checking in the keydown event </p>
<pre><code>void Cell_KeyDown(object sender, KeyEventArgs e)
{
if (e.Key == Key.Decimal)
</code></pre>
<p>But how do I replace that key with an other in Silverlight. The <code>e.Key</code> is read only. Is there a way to 'send an other key' to the control? Or any other suggestions?</p>
| [
{
"answer_id": 340162,
"author": "Tjipke",
"author_id": 17709,
"author_profile": "https://Stackoverflow.com/users/17709",
"pm_score": 1,
"selected": true,
"text": " void CellText_KeyUp(object sender, KeyEventArgs e)\n {\n var DecSep = System.Threading.Thread.CurrentThread.CurrentCulture.NumberFormat.NumberDecimalSeparator;\n\n if (e.Key == Key.Decimal && DecSep != \".\")\n {\n if (e.OriginalSource is TextBox)\n {\n var TB = (TextBox)e.OriginalSource;\n string sText = TB.Text;\n\n int iPos = TB.SelectionStart - 1;\n if (iPos >= 0)\n {\n System.Diagnostics.Debug.Assert(sText.Substring(iPos, 1) == \".\");\n\n TB.Text = sText.Substring(0, iPos) + DecSep + sText.Substring(iPos + 1);\n TB.SelectionStart = iPos + 1; // reposition cursor\n }\n }\n }\n }\n"
},
{
"answer_id": 1727073,
"author": "Savvy",
"author_id": 210169,
"author_profile": "https://Stackoverflow.com/users/210169",
"pm_score": 0,
"selected": false,
"text": "<html>\n<heaD>\n<script language=\"javascript\">\nfunction keypress1 ()\n{\n var e=window.event || e\n unicode = e.charCode ? e.charCode : e.keyCode; \n if (unicode==46)\n { return (e.charCode ? e.charCode=44 : e.keyCode=44); }\n}\nfunction keypress2 ()\n{\n var e=window.event || e\n unicode = e.charCode ? e.charCode : e.keyCode; \n if (unicode==46)\n { return (e.charCode ? e.charCode=46 : e.keyCode=46); }\n}\nfunction keyDown(e){\n if (!e){\n e = event\n }\n var code=e.keyCode;\n if(code==110)\n return document.onkeypress=keypress1\n else if(code=188)\n { document.onkeypress=keypress2 }\n}\ndocument.onkeydown = keyDown\n</script>\n</head>\n<body>\n<input type=text>\n</body>\n</html>\n"
},
{
"answer_id": 7257837,
"author": "TheOnlyMaX",
"author_id": 921728,
"author_profile": "https://Stackoverflow.com/users/921728",
"pm_score": 1,
"selected": false,
"text": "public class NumericUpDown : System.Windows.Controls.NumericUpDown\n{\n [DebuggerStepThrough]\n protected override double ParseValue(string text)\n {\n text = text.Replace(\".\", Thread.CurrentThread.CurrentCulture.NumberFormat.NumberDecimalSeparator);\n return base.ParseValue(text);\n }\n}\n"
},
{
"answer_id": 10279818,
"author": "Pete",
"author_id": 1351218,
"author_profile": "https://Stackoverflow.com/users/1351218",
"pm_score": 2,
"selected": false,
"text": "Imports System.Threading\nImports System.Windows.Forms\n\nNamespace My\n\n\n ' The following events are available for MyApplication:\n ' \n ' Startup: Raised when the application starts, before the startup form is created.\n ' Shutdown: Raised after all application forms are closed. This event is not raised if the application terminates abnormally.\n ' UnhandledException: Raised if the application encounters an unhandled exception.\n ' StartupNextInstance: Raised when launching a single-instance application and the application is already active. \n ' NetworkAvailabilityChanged: Raised when the network connection is connected or disconnected.\n\n Partial Friend Class MyApplication\n Private Sub MyApplication_Startup(ByVal sender As Object, ByVal e As Microsoft.VisualBasic.ApplicationServices.StartupEventArgs) Handles Me.Startup\n If Globalization.CultureInfo.CurrentCulture.NumberFormat.NumberDecimalSeparator <> \".\" Then\n System.Windows.Forms.Application.AddMessageFilter(New CommaMessageFilter)\n\n End If\n End Sub\n\n End Class\n\n Friend Class CommaMessageFilter\n Implements IMessageFilter\n Private Const WM_KEYDOWN = &H100\n\n Public Function PreFilterMessage(ByRef m As System.Windows.Forms.Message) As Boolean Implements IMessageFilter.PreFilterMessage\n\n If m.Msg = WM_KEYDOWN Then\n Dim toets As Keys = CType(CType(m.WParam.ToInt32 And Keys.KeyCode, Integer), Keys)\n If toets = Keys.Decimal Then\n SendKeys.Send(Thread.CurrentThread.CurrentCulture.NumberFormat.NumberDecimalSeparator)\n Return True\n End If\n End If\n Return False\n End Function\n End Class\n\nEnd Namespace\n"
}
] | 2008/12/04 | [
"https://Stackoverflow.com/questions/339962",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17709/"
] |
339,963 | <p>I'm trying to use System.Transaction.TransactionScope to create a transaction to call a few stored procedures but it doesn't seem to clean up after itself. Once the transaction is finished (commited or not and the transaction scope object is disposed) subsequent connections to the database open up with the read commit level of serializable instead of read commited like they normally would. </p>
<p>I'm opening and closing a connection for each call (well closing and returning to a pool of connections like normal in .NET), am I missing some way to explicitly reset the connection when I'm done using it for a transaction? I thought the idea behind System.Transaction.TransactionScope was to hide all the complexity.</p>
<p>So the code I have looks like this:</p>
<pre><code> using (var scope = new TransactionScope())
{
... make my 3 stored procedure calls ...
scope.Complete();
return returnCode;
}
</code></pre>
<p>which I guess is the normal way to do it. But then if I look in sqlserver profiler I can see connections being opened with </p>
<pre><code>set transaction isolation level serializable
</code></pre>
<p>which is messing with subsequent non-transaction related database activity and also is apparently not as fast. I can get around this by setting a transaction option to explicity do the transaction with ReadCommited but this is not the ideal behaviour for this operation in my opinion. </p>
<p>I've also tried explicitly creating a Commitabletransaction object, creating explict new transactions instead of using the ambient one and still no luck. </p>
<p>Any ideas on how to fix this would be much appreciated as any calls that use the serializable connection will throw an error if they try to use a readpast locking hint.</p>
| [
{
"answer_id": 340045,
"author": "Marc Gravell",
"author_id": 23354,
"author_profile": "https://Stackoverflow.com/users/23354",
"pm_score": 0,
"selected": false,
"text": "sp_reset_connection"
},
{
"answer_id": 341841,
"author": "gbn",
"author_id": 27535,
"author_profile": "https://Stackoverflow.com/users/27535",
"pm_score": 1,
"selected": false,
"text": "TransactionOptions transactionoptions1 = new TransactionOptions();\ntransactionoptions1.IsolationLevel = IsolationLevel.ReadCommitted;\nusing (var scope = new TransactionScope(TransactionScopeOption.Required, transactionoptions1))\n{\n ... make my 3 stored procedure calls ...\n\n scope.Complete();\n\n return returnCode;\n}\n"
}
] | 2008/12/04 | [
"https://Stackoverflow.com/questions/339963",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6084/"
] |
339,969 | <p>I have two models one is Employee and other is Asset, with Many to one relation between Asset and Employee. And Asset is added as StackedInline field to Employee Admin interface, Is there anyway I can make Asset as read only field in the Employee Admin. </p>
<p>My intention was to show all the assets the employee is currently holding in the Admin, so that he will not delete it accidentally.</p>
| [
{
"answer_id": 1078084,
"author": "ha22109",
"author_id": 104824,
"author_profile": "https://Stackoverflow.com/users/104824",
"pm_score": 2,
"selected": false,
"text": "from django import forms\nfrom django.utils.safestring import mark_safe\nfrom datetime import datetime\n\nclass ReadOnlyWidget(forms.Widget):\n def __init__(self, original_value, display_value):\n self.original_value = original_value\n self.display_value = display_value\n super(ReadOnlyWidget, self).__init__()\n\n def render(self, name, value, attrs=None):\n if self.display_value is not None:\n return unicode(self.display_value)\n return unicode(self.original_value)\n\n def value_from_datadict(self, data, files, name):\n return self.original_value\n\n#to make fields foreignkey readonly\n\nclass ReadOnlyAdminFields(object):\n def get_form(self, request, obj=None):\n form = super(ReadOnlyAdminFields, self).get_form(request, obj)\n if hasattr(self, 'readonly') and obj is not None:\n for field_name in self.readonly:\n if field_name in form.base_fields:\n if hasattr(obj, 'get_%s_display' % field_name):\n display_value = getattr(obj, 'get_%s_display' % field_name)()\n else:\n display_value = None\n if getattr(obj, field_name).__class__ in [unicode , long, int, float, datetime, list]:\n form.base_fields[field_name].widget = ReadOnlyWidget(getattr(obj, field_name), display_value)\n else:\n form.base_fields[field_name].widget = ReadOnlyWidget(getattr(obj, field_name).id, display_value)\n form.base_fields[field_name].required = False\n return form\n"
},
{
"answer_id": 5055378,
"author": "Maxim Mai",
"author_id": 264874,
"author_profile": "https://Stackoverflow.com/users/264874",
"pm_score": 0,
"selected": false,
"text": "{% for inline_admin_formset in inline_admin_formsets %}\n{% include inline_admin_formset.opts.template %}\n{% endfor %}\n class EmployeeAdmin(admin.ModelAdmin):\n ...\n\n def change_view(self, request, object_id, extra_context=None):\n assets = Asset.objects.filter(employee=Employee.objects.get(id=object_id))\n context_data = {'inlines': assets, }\n return super(EmployeeAdmin, self).change_view(request, object_id, extra_context=context_data)\n {% for inline in inlines %}\n {{ inline }}\n{% endfor %}\n\n{% for inline_admin_formset in inline_admin_formsets %}\n{% include inline_admin_formset.opts.template %}\n{% endfor %}\n"
}
] | 2008/12/04 | [
"https://Stackoverflow.com/questions/339969",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7965/"
] |
339,971 | <p>I have to include many header files, which are in different sub-directories. Is there a way in Visual Studio (I am using 2005 edition) to set one include path that Visual Studio will search also the sub-directories for header files?</p>
| [
{
"answer_id": 339988,
"author": "Joris Timmermans",
"author_id": 33987,
"author_profile": "https://Stackoverflow.com/users/33987",
"pm_score": 6,
"selected": true,
"text": "#include \"subdirectory/somefile.h\""
},
{
"answer_id": 26518113,
"author": "riderBill",
"author_id": 4079867,
"author_profile": "https://Stackoverflow.com/users/4079867",
"pm_score": 1,
"selected": false,
"text": "MDrive.bat:\nsubst M: /D\nsubst M: \"C:\\Program Files (x86)\\Microsoft Visual Studio 12.0\\VC\"\n\nWDrive.bat:\nsubst W: /D\nsubst W: \"C:\\Program Files (x86)\\Windows Kits\\8.1\\Include\"\n\n... This is just and example. You would do this for your\n project related include directories.\n M:; M:\\atlmfc\\include; W:\\um; W:\\shared; W:\\winrt\n $(VC_IncludePath); $(WindowsSKD_IncludePath)\n C:\\Program Files (x86)\\Windows Kits\\8.1\\Include;C:\\Program Files (x86)\\Windows Kits\\8.1\\Include\\atlmfc\\include;C:\\Program Files (x86)\\Windows Kits\\8.1\\Include\\um;C:\\Program Files (x86)\\Windows Kits\\8.1\\Include\\shared;C:\\Program Files (x86)\\Windows Kits\\8.1\\Include\\winrt\n"
},
{
"answer_id": 66672086,
"author": "Sherif O.",
"author_id": 4780334,
"author_profile": "https://Stackoverflow.com/users/4780334",
"pm_score": 0,
"selected": false,
"text": "${workspaceFolder}\n${workspaceFolder}/**\n"
}
] | 2008/12/04 | [
"https://Stackoverflow.com/questions/339971",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9035/"
] |
339,995 | <p>Is there a better way to develop Java Swing applications?</p>
<p>SWIXML? JavaFX? Anything else that developers out here have liked and recommend?</p>
| [
{
"answer_id": 340088,
"author": "VonC",
"author_id": 6309,
"author_profile": "https://Stackoverflow.com/users/6309",
"pm_score": 3,
"selected": false,
"text": "JPanel panel = new JPanel(new MigLayout());\n\npanel.add(firstNameLabel);\npanel.add(firstNameTextField);\npanel.add(lastNameLabel, \"gap unrelated\");\npanel.add(lastNameTextField, \"wrap\");\npanel.add(addressLabel);\npanel.add(addressTextField, \"span, grow\");\n"
}
] | 2008/12/04 | [
"https://Stackoverflow.com/questions/339995",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/29860/"
] |
340,003 | <p>What is the C++ equivalent to <code>GetObject</code> in <a href="http://en.wikipedia.org/wiki/JavaScript" rel="nofollow noreferrer">JavaScript</a> and <a href="http://en.wikipedia.org/wiki/VBScript" rel="nofollow noreferrer">VBScript</a>?</p>
<p>The closest match I found to my question is:</p>
<p><a href="http://codewiz51.blogspot.com/2008/06/vb-script-getobject-c-api-cogetobject.html" rel="nofollow noreferrer">http://codewiz51.blogspot.com/2008/06/vb-script-getobject-c-api-cogetobject.html</a></p>
<p>However the sample use an unexisting interface and asking for the <code>IUnknown</code> returns null. Did someone have an example that works?</p>
| [
{
"answer_id": 340032,
"author": "1800 INFORMATION",
"author_id": 3146,
"author_profile": "https://Stackoverflow.com/users/3146",
"pm_score": 1,
"selected": false,
"text": "CoGetObject"
},
{
"answer_id": 340117,
"author": "Emmanuel Caradec",
"author_id": 4508,
"author_profile": "https://Stackoverflow.com/users/4508",
"pm_score": 3,
"selected": true,
"text": "\nwinmgmts:{impersonationLevel=impersonate}!\\\\.\\root\\default:StdRegProv\n \n::CoGetObject(L\"winmgmts:{impersonationLevel=impersonate}!\\\\\\\\.\\\\root\\\\default:StdRegProv\", NULL, IID_IUnknown, (void**)&pUnk);\n"
}
] | 2008/12/04 | [
"https://Stackoverflow.com/questions/340003",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4508/"
] |
340,007 | <p>I've recently have a reason to include into our build script the creation of an XML configuration file. The most straightforward way I can think of to do this is to hard-code the XML content as a string into the script and then to simply create a file and write that XML string to the file (named appropriately etc). Is there a more elegant or efficient way of doing this? </p>
<p>The build script that I am looking to modify is written in VBScript.</p>
| [
{
"answer_id": 352035,
"author": "jpoh",
"author_id": 4368,
"author_profile": "https://Stackoverflow.com/users/4368",
"pm_score": 0,
"selected": false,
"text": "Function XMLToString(Nodes)\n dim retStr\n retStr = \"<?xml version=\"\"1.0\"\" encoding=\"\"utf-8\"\" ?>\"\n XMLToString = retStr & vbNewLine & NodesToString(Nodes, 0)\nEnd Function\n\nFunction NodesToString(Nodes, Indent)\n Dim xNode\n Dim retStr\n\n retStr = \"\"\n For Each xNode In Nodes\n Select Case xNode.nodeType\n Case 1: ' NODE_ELEMENT\n If xNode.nodeName <> \"#document\" Then\n ' change DisplayAttrs_(xNode, Indent + 2) to \n ' DisplayAttrs_(xNode, 0) for inline attributes\n retStr = retStr & VBNewLine & strDup(\" \", Indent) & \"<\" & xNode.nodeName & AttributesToString(xNode) & \">\"\n If xNode.hasChildNodes Then\n retStr = retStr & NodesToString(xNode.childNodes, Indent + 2)\n End If\n retStr = retStr & VBNewLine & strDup(\" \", Indent) & \"</\" & xNode.nodeName & \">\"\n Else \n If xNode.hasChildNodes Then\n retStr = retStr & NodesToString(xNode.childNodes, Indent + 2)\n End If\n End If\n Case 3: ' NODE_TEXT \n retStr = retStr & VBNewLine & strDup(\" \", Indent) & xNode.nodeValue\n End Select\n Next\n\n NodesToString = retStr\nEnd Function\n\nFunction AttributesToString(Node)\n Dim xAttr, res\n\n res = \"\"\n For Each xAttr In Node.attributes\n res = res & \" \" & xAttr.name & \"=\"\"\" & xAttr.value & \"\"\"\"\n Next\n\n AttributesToString = res\nEnd Function\n\nFunction strDup(dup, c)\n Dim res, i\n\n res = \"\"\n For i = 1 To c\n res = res & dup\n Next\n strDup = res\nEnd Function\n"
}
] | 2008/12/04 | [
"https://Stackoverflow.com/questions/340007",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4368/"
] |
340,010 | <p>I was reading up about NTVDM.exe as I build a quick test console app and it crashed on a friends machine complaining about this EXE.</p>
<p>As I understand it all DOS cmd windows (C# console apps included) run as 16bit not 32bit.</p>
<p>Is this true? Does this mean all my works console app back office apps are running as 16bit rather than making the most of the 32bit available?</p>
<p>What about Windows services? As I believe we wrote it as a console app then made it run as a windows service?</p>
<p>Thanks</p>
| [
{
"answer_id": 588720,
"author": "RBerteig",
"author_id": 68204,
"author_profile": "https://Stackoverflow.com/users/68204",
"pm_score": 0,
"selected": false,
"text": ".COM .EXE"
}
] | 2008/12/04 | [
"https://Stackoverflow.com/questions/340010",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6486/"
] |
340,020 | <p>I'm using this query to get all employees of {clients with name starting with lowercase "a"}:</p>
<pre><code>SELECT * FROM employees
WHERE client_id IN (SELECT id FROM clients WHERE name LIKE 'a%')
</code></pre>
<p>Column <code>employees.client_id</code> is an int, with <code>INDEX client_id (index_id)</code>. The subquery should IMHO return a list of id-s, which is then used in the WHERE clause.</p>
<p>When I <code>EXPLAIN</code> the query, the primary query uses no indexes (<code>type:ALL</code>). But when I <code>EXPLAIN</code>
a list taken from the subquery (e.g. <code>SELECT ... WHERE client_id IN (121,184,501)</code>), the <code>EXPLAIN</code> switches to <code>type:range</code>, and this query gets faster by 50%.</p>
<p>How can I make the query use the index for the data returned by subquery - or, is there a more efficient way of retrieving this data? (Retrieving the id-list to application server, joining it and sending a second query is even more expensive here).</p>
<p>Thanks in advance.</p>
| [
{
"answer_id": 340029,
"author": "cagcowboy",
"author_id": 19629,
"author_profile": "https://Stackoverflow.com/users/19629",
"pm_score": 5,
"selected": true,
"text": "SELECT employees.*\nFROM employees, clients\nWHERE employees.client_id = clients.id\nAND clients.name LIKE 'a%';\n"
},
{
"answer_id": 340031,
"author": "mat",
"author_id": 42083,
"author_profile": "https://Stackoverflow.com/users/42083",
"pm_score": 3,
"selected": false,
"text": "JOIN SELECT employees.* FROM employees, clients WHERE employees.client_id = clients.id AND clients.name LIKE 'a%';\n"
},
{
"answer_id": 340396,
"author": "Thomas Hansen",
"author_id": 29746,
"author_profile": "https://Stackoverflow.com/users/29746",
"pm_score": 0,
"selected": false,
"text": "select * from X as _x where \n exists(select * from Y as _y where _y.someField = _x.someField)\n"
},
{
"answer_id": 340557,
"author": "Rishi Agarwal",
"author_id": 29532,
"author_profile": "https://Stackoverflow.com/users/29532",
"pm_score": 1,
"selected": false,
"text": "SELECT e.* \nFROM employees e \nWHERE EXISTS ( \n SELECT 1 \n FROM clients c \n WHERE c.id = e.client_id \n AND c.name LIKE 'a%'\n)\n"
},
{
"answer_id": 1162849,
"author": "James Healy",
"author_id": 127255,
"author_profile": "https://Stackoverflow.com/users/127255",
"pm_score": 2,
"selected": false,
"text": "SELECT * FROM employees WHERE client_id IN (SELECT id FROM clients WHERE name LIKE 'a%')\n SELECT * FROM employees WHERE client_id IN (1,2,3,4)\n"
}
] | 2008/12/04 | [
"https://Stackoverflow.com/questions/340020",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19746/"
] |
340,030 | <p>Is there a Firefox plugin for manipulating and deleting saved form data?
In the browser there is only the option to delete all data.</p>
| [
{
"answer_id": 340050,
"author": "stesch",
"author_id": 41860,
"author_profile": "https://Stackoverflow.com/users/41860",
"pm_score": 2,
"selected": false,
"text": "formhistory.sqlite"
}
] | 2008/12/04 | [
"https://Stackoverflow.com/questions/340030",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/43144/"
] |
340,043 | <p>I have a problem and i would like to learn the correct way to solve this. </p>
<p>I have a Data Objeckt</p>
<pre><code>class LinkHolder {
public string Text;
public string Link;
}
</code></pre>
<p>I would like to present to the user a RadioButton list that uses the LinkHolder.Text value as descriptive text.
Then on the postback, i would like to do a </p>
<pre><code>Server.Transfer( LinkHolder.Link )
</code></pre>
<p>on the corresponding Link.</p>
<p>I am unsure what is the best/most correct way to do this. Any hints would be appreciated.</p>
| [
{
"answer_id": 340087,
"author": "terjetyl",
"author_id": 29519,
"author_profile": "https://Stackoverflow.com/users/29519",
"pm_score": 0,
"selected": false,
"text": "class LinkHolder {\n public string Text { get; set;}\n public string Link { get; set;}\n}\n List<LinkHolder>"
},
{
"answer_id": 340099,
"author": "Jesper Jensen",
"author_id": 40274,
"author_profile": "https://Stackoverflow.com/users/40274",
"pm_score": 0,
"selected": false,
"text": "List<LinkHolder> List<LinkHolder>"
}
] | 2008/12/04 | [
"https://Stackoverflow.com/questions/340043",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/40274/"
] |
340,046 | <p>We have enableviewstate property for all the server controls in ASP.net.
We know that its going to have the member datas and values in viewstate across postbacks</p>
<p>What is the actual example for this?</p>
| [
{
"answer_id": 340370,
"author": "HTTP 410",
"author_id": 13118,
"author_profile": "https://Stackoverflow.com/users/13118",
"pm_score": 2,
"selected": false,
"text": "<asp:Label runat=\"server\" Font-Name=\"Verdana\" Text=\"Hello, World!\"></asp:Label>\n"
}
] | 2008/12/04 | [
"https://Stackoverflow.com/questions/340046",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/22162/"
] |
340,049 | <p>When I call GetForegroundWindow from c# I am getting the explorer parent process ID (I see this from process explorer) and not the process ID of the app that is in the foreground.</p>
<p>Why is this and how do get the right process ID?</p>
<p>Malcolm</p>
| [
{
"answer_id": 340207,
"author": "Wolf5",
"author_id": 37643,
"author_profile": "https://Stackoverflow.com/users/37643",
"pm_score": 3,
"selected": false,
"text": " [DllImport(\"user32\", SetLastError = true)]\n public static extern int GetForegroundWindow();\n [DllImport(\"user32\", SetLastError = true)]\n public static extern int GetWindowThreadProcessId(int hwnd, ref int lProcessId);\n\n public static int GetProcessThreadFromWindow(int hwnd) {\n int procid = 0;\n int threadid = GetWindowThreadProcessId(hwnd, ref procid);\n return procid;\n }\n"
}
] | 2008/12/04 | [
"https://Stackoverflow.com/questions/340049",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/40568/"
] |
340,090 | <p>I have a C# method that projects the value of a number from an interval to a target interval.<br>
<strong>For example:</strong> we have an interval of -1000 and 9000 and a value of 5000; if we want to project this value to an interval of 0..100 we get 60.</p>
<p>Here is the method: </p>
<pre><code>/// <summary>
/// Projects a value to an interval
/// </summary>
/// <param name="val">The value that needs to be projected</param>
/// <param name="min">The minimum of the interval the value comes from</param>
/// <param name="max">The maximum of the interval the value comes from</param>
/// <param name="intervalTop">The minimum of the interval the value will
/// be projected to</param>
/// <param name="intervalBottom">The maximum of the interval the value will
/// be projected to</param>
/// <returns>Projected value</returns>
public decimal ProjectValueToInterval(decimal val,
decimal min,
decimal max,
decimal intervalBottom,
decimal intervalTop)
{
decimal newMin = Math.Min(0, min);
decimal valueIntervalSize = Math.Abs(max - newMin);
decimal targetIntervalSize = Math.Abs(intervalTop - intervalBottom);
decimal projectionUnit = targetIntervalSize / valueIntervalSize;
return (val * projectionUnit) + Math.Abs((newMin * projectionUnit));
}
</code></pre>
<p>This method needs to be called for thousands of values.<br>
I was wondering if there is a more efficient way to do this in C#? If yes, what changes do you suggest?</p>
| [
{
"answer_id": 340141,
"author": "Skizz",
"author_id": 1898,
"author_profile": "https://Stackoverflow.com/users/1898",
"pm_score": 1,
"selected": false,
"text": "intervalTop + (intervalBottom - intervalTop) * (val - min) / (max - min);\n"
},
{
"answer_id": 340150,
"author": "annakata",
"author_id": 13018,
"author_profile": "https://Stackoverflow.com/users/13018",
"pm_score": 3,
"selected": true,
"text": "returnValue = ((intervalTop-intervalBottom) * (val-min) / (max-min)) + intervalBottom\n"
}
] | 2008/12/04 | [
"https://Stackoverflow.com/questions/340090",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18631/"
] |
340,093 | <p>I'm trying to make a proxy object in IronPython, which should dynamically present underlying structure. The proxy itself shouldn't have any functions and properties, I'm trying to catch all the calls in the runtime. Catching the function calls is easy, I just need to define <strong>getattr</strong>() function for my object, and check does appropriate function exists in the underlying layer, and return some function-like object.</p>
<p>I have problems with properties - I don't know how to distinguish the calling context, is my property called as a lvalue or rvalue:</p>
<p>o = myproxy.myproperty # <em>I need to call underlying.myproperty_get()</em></p>
<p>or</p>
<p>myproxy.myproperty = o # <em>I need to call underlying.myproperty_set(o)</em></p>
<p>I looked at the list of special functions in Python, but I didn't found anything appropriate.</p>
<p>I also tried to make property in the object on the fly, with combination of exec() and builtin property() function, but I found that IronPython 1.1.2 lacks of entire 'new' module (which is present in IronPython 2.x beta, but I'll rather use IP 1.x, because of .NET 2.0 framework).</p>
<p>Any ideas?</p>
| [
{
"answer_id": 340141,
"author": "Skizz",
"author_id": 1898,
"author_profile": "https://Stackoverflow.com/users/1898",
"pm_score": 1,
"selected": false,
"text": "intervalTop + (intervalBottom - intervalTop) * (val - min) / (max - min);\n"
},
{
"answer_id": 340150,
"author": "annakata",
"author_id": 13018,
"author_profile": "https://Stackoverflow.com/users/13018",
"pm_score": 3,
"selected": true,
"text": "returnValue = ((intervalTop-intervalBottom) * (val-min) / (max-min)) + intervalBottom\n"
}
] | 2008/12/04 | [
"https://Stackoverflow.com/questions/340093",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/43152/"
] |
340,095 | <p>I am looking for a .net templating engine - something simple, lightweight, stable with not too many dependencies. All I need it for at the moment is creating templated plain text and html emails. Can anyone give me a good recommendation?</p>
<p>If it helps at all - something like Java's <a href="http://freemarker.sourceforge.net/" rel="noreferrer">Freemarker</a> or <a href="http://velocity.apache.org/" rel="noreferrer">Velocity</a> libraries.</p>
<p>[UPDATE]
Thanks for the answers so far - much appreciated. I am really intested in recommendations or war stories from when you have used these libraries. Seems to be the best way to make a decision without trying each in turn.</p>
| [
{
"answer_id": 33546901,
"author": "Nigrimmist",
"author_id": 1151741,
"author_profile": "https://Stackoverflow.com/users/1151741",
"pm_score": 2,
"selected": false,
"text": "namespace ConsoleApplication4\n{\nclass Program\n{\n static void Main(string[] args)\n {\n\n Stopwatch sw = new Stopwatch();\n\n //RAZOR\n string razorTemplate = @\"@model ConsoleApplication4.Test\n <h1>@Model.Title</h1>\n @if(Model.Condition1)\n {\n <span>condition1 is true</span>\n }\n <div>\n @foreach(var movie in Model.Movies)\n {<span>@movie</span>}\n </div>\";\n\n //burning\n Engine.Razor.RunCompile(razorTemplate, \"templateKey\", typeof(Test), new Test());\n sw.Start();\n var result1 = Engine.Razor.RunCompile(razorTemplate, \"templateKey\", typeof(Test), new Test());\n sw.Stop();\n Console.WriteLine(\"razor : \"+sw.Elapsed);\n\n\n //SHARPTAL\n string sharpTalTemplate = @\"<h1>${Title}</h1> \n <span tal:condition=\"\"Condition1\"\">condition1 is true</span> \n\n <div tal:repeat='movie Movies'>${movie}</div>\";\n\n\n var test = new Test();\n var globals = new Dictionary<string, object>\n {\n { \"Movies\", new List<string> {test.Movies[0],test.Movies[1],test.Movies[2] } },\n { \"Condition1\", test.Condition1 },\n { \"Title\", test.Title },\n };\n\n\n\n var tt = new Template(sharpTalTemplate);\n tt.Render(globals);\n sw.Restart();\n var tt2 = new Template(sharpTalTemplate);\n var result2 = tt2.Render(globals);\n sw.Stop();\n Console.WriteLine(\"sharptal : \" + sw.Elapsed);\n\n\n\n //HANDLEBARS\n string handleBarsTemplate = @\"<h1>{{Title}}</h1>\n {{#if Condition1}} \n <span>condition1 is true</span>\n {{/if}}\n <div>\n {{#each Movies}}\n <span>{{this}}</span>\n {{/each}} \n </div>\";\n var tt3 = Handlebars.Compile(handleBarsTemplate);\n sw.Restart();\n var result3 = tt3(new Test());\n sw.Stop();\n Console.WriteLine(\"handlebars : \" + sw.Elapsed);\n\n Console.WriteLine(\"-----------------------------\");\n Console.WriteLine(result1);\n Console.WriteLine(result2);\n Console.WriteLine(result3);\n\n Console.ReadLine();\n }\n}\n\npublic class Test\n{\n public bool Condition1 { get; set; }\n public List<string> Movies { get; set; }\n public string Title { get; set; }\n\n public Test()\n {\n Condition1 = true;\n Movies = new List<string>() { \"Rocky\", \"The Fifth Element\", \"Intouchables\" };\n Title = \"Hi stackoverflow! Below you can find good movie list! Have a good day.\";\n }\n}\n\n\n}\n"
},
{
"answer_id": 46995817,
"author": "Max Toro",
"author_id": 39923,
"author_profile": "https://Stackoverflow.com/users/39923",
"pm_score": 2,
"selected": false,
"text": "<ul>\n <c:for-each name='n' in='System.Linq.Enumerable.Range(1, 5)' expand-text='yes'>\n <li>{n}</li>\n </c:for-each>\n</ul>\n"
}
] | 2008/12/04 | [
"https://Stackoverflow.com/questions/340095",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1853/"
] |
340,104 | <p>So I've got some scripts I've written which set up a Google map on my page. These scripts are in included in the <code><head></code> of my page, and use jQuery to build the map with markers generated from a list of addresses on the page.</p>
<p>However, I have some exact co-ordinate data for each address which the javascript requires to place the markers correctly. This isn't information I want to be visible on the screen to the user, so what's the "best practice" way to put that data into my document?</p>
| [
{
"answer_id": 340126,
"author": "Rob Stevenson-Leggett",
"author_id": 4950,
"author_profile": "https://Stackoverflow.com/users/4950",
"pm_score": 1,
"selected": false,
"text": " <input id=\"coordinates\" type=\"hidden\" value=\"123.2123.123:123,123,321;.....\" />\n var myCoordsCSV = $(\"#coordinates\").val();\n"
},
{
"answer_id": 340131,
"author": "Stein G. Strindhaug",
"author_id": 26115,
"author_profile": "https://Stackoverflow.com/users/26115",
"pm_score": 2,
"selected": true,
"text": "<form action=\"#\" method=\"get\" id=\"myHiddenValues\">\n <input type=\"text\" name=\"hiddenval1\" id=\"hiddenval1\" value=\"1234\"/>\n <input type=\"text\" name=\"hiddenval2\" id=\"hiddenval2\" value=\"5678\"/>\n</form>\n"
},
{
"answer_id": 340143,
"author": "Vlad Gudim",
"author_id": 22088,
"author_profile": "https://Stackoverflow.com/users/22088",
"pm_score": 1,
"selected": false,
"text": "<div id=\"addr1\" coordinates=\"...\">\n 17 Coldwell Drive<br />\n Blue Mountain<br />\n BA93 1PF<br />\n United Kindom\n</div>\n var myCoordsCSV = $(\"addr1\").coordinates;\n"
},
{
"answer_id": 340208,
"author": "Supernovah",
"author_id": 36076,
"author_profile": "https://Stackoverflow.com/users/36076",
"pm_score": 0,
"selected": false,
"text": "var myArray = new Array(); \nmyArray.push([1.000,1.000,\"test1\"]); \nmyArray.push([2.000,2.000,\"test2\"]); \nmyArray.push([3.000,3.000,\"test3\"]); \nfor(i=0;i<myArray.length;i++){ \n yourGoogleMapsAPICall(myArray[i][0],myArray[i][1],myArray[i][2]); \n} \n"
},
{
"answer_id": 340569,
"author": "mahemoff",
"author_id": 18706,
"author_profile": "https://Stackoverflow.com/users/18706",
"pm_score": 0,
"selected": false,
"text": "document.getElementById(\"geodata\").style.display = \"none\";\n $(\"geodata\").hide()\n"
}
] | 2008/12/04 | [
"https://Stackoverflow.com/questions/340104",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/31582/"
] |
340,111 | <pre><code><document.write("<SCR"+"IPT TYPE='text/javascript' SRC='"+"http"+(window.location.protocol.indexOf('https:')==0?'s':'')+"://"+gDomain+"/"+gDcsId+"/wtid.js"+"'><\/SCR"+"IPT>");
</code></pre>
<p>I need to escape the string above in order to add the whole thing to a StringBuilder but so far I must be missing something because string termination is not correct...</p>
| [
{
"answer_id": 340130,
"author": "Ian G",
"author_id": 31765,
"author_profile": "https://Stackoverflow.com/users/31765",
"pm_score": 0,
"selected": false,
"text": "JavaScript C# window.location.protocol.indexOf('https:') JavaScript gDomain gDcsId C# \"<SCRIPT TYPE='text/javascript' SRC='\"+\"http\"+\"(window.location.protocol.indexOf('https:')==0?'s':'')\"+\"://\" + gDomain + \"/\"+ gDcsId+ \"/wtid.js\"+\"'></SCRIPT>\")\n"
},
{
"answer_id": 340159,
"author": "Stephane",
"author_id": 32891,
"author_profile": "https://Stackoverflow.com/users/32891",
"pm_score": 3,
"selected": false,
"text": "@\"<document.write(\"\"<SCR\"\"+\"\"IPT TYPE='text/javascript' SRC='\"\"+\"\"http\"\"+(window.location.protocol.indexOf('https:')==0?'s':'')+\"\"://\"\"+gDomain+\"\"/\"\"+gDcsId+\"\"/wtid.js\"\"+\"\"'><\\/SCR\"\"+\"\"IPT>\"\");\"\n"
},
{
"answer_id": 340164,
"author": "Daniel Earwicker",
"author_id": 27423,
"author_profile": "https://Stackoverflow.com/users/27423",
"pm_score": 3,
"selected": true,
"text": "string x = @\"<document.write(\"\"<SCR\"\"+\"\"IPT TYPE=\"\"'text/javascript' SRC='\"\"+\"\"http\"\"+(window.location.protocol.indexOf('https:')==0?'s':'')+\"\"://\"\"+gDomain+\"\"/\"\"+gDcsId+\"\"/wtid.js\"\"+\"\"'><\\/SCR\"\"+\"\"IPT>\"\");\";\n var fromCSharp = {0};\n"
}
] | 2008/12/04 | [
"https://Stackoverflow.com/questions/340111",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/42108/"
] |
340,128 | <p>We know that Python provides a lot of productivity over any compiled languages. We have programming in C# & need to write the unit test cases in C# itself. If we see the amount of code we write for unit test is approximately ten times more than the original code. </p>
<p>Is it ideal choice to write unit test cases in IronPython instead of C#? Any body has done like that? I wrote few test cases, they seems to be good. But hairy pointy managers won't accept.</p>
| [
{
"answer_id": 2994724,
"author": "Andy Dent",
"author_id": 53870,
"author_profile": "https://Stackoverflow.com/users/53870",
"pm_score": 1,
"selected": false,
"text": "[TestCase(12, 3, 4)]\n[TestCase(12, 2, 6)]\n[TestCase(12, 4, 3)]\n[TestCase(12, 0, 0, ExpectedException = typeof(System.DivideByZeroException),\n TestName = “DivisionByZeroThrowsExceptionType”)]\n[TestCase(12, 0, 0, ExpectedExceptionName = “System.DivideByZeroException”,\n TestName = “DivisionByZeroThrowsNamedException”)]\npublic void IntegerDivisionWithResultPassedToTest(int n, int d, int q)\n{\n Assert.AreEqual(q, n / d);\n}\n"
}
] | 2008/12/04 | [
"https://Stackoverflow.com/questions/340128",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/43056/"
] |
340,138 | <p>I have the odd problem that I am not able to open the properties of my .NET projects in Visual Studio. If I try to open it by clicking on the Properties tree node in the Solution Explorer I get the following message:</p>
<blockquote>
<p>There is no editor available for '....csproj'. Make sure the application for the file type (.csproj) is installed.</p>
</blockquote>
<p>If I try to open the project properties by the main menu nothing happens at all.</p>
<p>I already tried to reset the Visual Studio settings by command line and a repair installation but nothing helped so far.</p>
<p>I use the Visual Studio 2008 in version 9.0.30729.1 SP including the XNA Game Studio 3.0, ReSharper 4.1 and Visual SVN 1.5.1.</p>
<p>It is occurring on all my projects and seems to be a local issue because my co-workers do not have this kind of problem.</p>
<p>Help is much appreciated!</p>
<p>Thanks,
Michael</p>
| [
{
"answer_id": 413430,
"author": "Mil",
"author_id": 9470,
"author_profile": "https://Stackoverflow.com/users/9470",
"pm_score": 6,
"selected": true,
"text": "devenv /ResetSkipPkgs\n"
},
{
"answer_id": 43673571,
"author": "Anoop",
"author_id": 2123370,
"author_profile": "https://Stackoverflow.com/users/2123370",
"pm_score": 0,
"selected": false,
"text": "<version>"
}
] | 2008/12/04 | [
"https://Stackoverflow.com/questions/340138",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9470/"
] |
340,139 | <p>I have a set of conditions in my where clause like</p>
<pre><code>WHERE
d.attribute3 = 'abcd*'
AND x.STATUS != 'P'
AND x.STATUS != 'J'
AND x.STATUS != 'X'
AND x.STATUS != 'S'
AND x.STATUS != 'D'
AND CURRENT_TIMESTAMP - 1 < x.CREATION_TIMESTAMP
</code></pre>
<p>Which of these conditions will be executed first? I am using oracle.</p>
<p>Will I get these details in my execution plan?
(I do not have the authority to do that in the db here, else I would have tried)</p>
| [
{
"answer_id": 340293,
"author": "Tony Andrews",
"author_id": 18747,
"author_profile": "https://Stackoverflow.com/users/18747",
"pm_score": 6,
"selected": true,
"text": "SQL> set autotrace on\nSQL> select * from emp\n 2 join dept on dept.deptno = emp.deptno\n 3 where emp.ename like 'K%'\n 4 and dept.loc like 'l%'\n 5 /\n\nno rows selected\n\n\nExecution Plan\n----------------------------------------------------------\n\n----------------------------------------------------------------------------------\n| Id | Operation | Name | Rows | Bytes | Cost (%CPU)|\n----------------------------------------------------------------------------------\n| 0 | SELECT STATEMENT | | 1 | 62 | 4 (0)|\n| 1 | NESTED LOOPS | | 1 | 62 | 4 (0)|\n|* 2 | TABLE ACCESS FULL | EMP | 1 | 42 | 3 (0)|\n|* 3 | TABLE ACCESS BY INDEX ROWID| DEPT | 1 | 20 | 1 (0)|\n|* 4 | INDEX UNIQUE SCAN | SYS_C0042912 | 1 | | 0 (0)|\n----------------------------------------------------------------------------------\n\nPredicate Information (identified by operation id):\n---------------------------------------------------\n\n 2 - filter(\"EMP\".\"ENAME\" LIKE 'K%' AND \"EMP\".\"DEPTNO\" IS NOT NULL)\n 3 - filter(\"DEPT\".\"LOC\" LIKE 'l%')\n 4 - access(\"DEPT\".\"DEPTNO\"=\"EMP\".\"DEPTNO\")\n SQL> select * from emp\n 2 join dept on dept.deptno = emp.deptno\n 3 where dept.loc like 'l%'\n 4 and emp.ename like 'K%';\n\nno rows selected\n\n\nExecution Plan\n----------------------------------------------------------\n\n----------------------------------------------------------------------------------\n| Id | Operation | Name | Rows | Bytes | Cost (%CPU)|\n----------------------------------------------------------------------------------\n| 0 | SELECT STATEMENT | | 1 | 62 | 4 (0)|\n| 1 | NESTED LOOPS | | 1 | 62 | 4 (0)|\n|* 2 | TABLE ACCESS FULL | EMP | 1 | 42 | 3 (0)|\n|* 3 | TABLE ACCESS BY INDEX ROWID| DEPT | 1 | 20 | 1 (0)|\n|* 4 | INDEX UNIQUE SCAN | SYS_C0042912 | 1 | | 0 (0)|\n----------------------------------------------------------------------------------\n\nPredicate Information (identified by operation id):\n---------------------------------------------------\n\n 2 - filter(\"EMP\".\"ENAME\" LIKE 'K%' AND \"EMP\".\"DEPTNO\" IS NOT NULL)\n 3 - filter(\"DEPT\".\"LOC\" LIKE 'l%')\n 4 - access(\"DEPT\".\"DEPTNO\"=\"EMP\".\"DEPTNO\")\n"
},
{
"answer_id": 340922,
"author": "Dave Costa",
"author_id": 6568,
"author_profile": "https://Stackoverflow.com/users/6568",
"pm_score": 3,
"selected": false,
"text": "WITH subset AS\n ( SELECT /*+ materialize */\n FROM my_table\n WHERE CURRENT_TIMESTAMP - 1 < x.CREATION_TIMESTAMP\n )\nSELECT *\n FROM subset\n WHERE \n d.attribute3 = 'abcd*' \n AND x.STATUS != 'P' \n AND x.STATUS != 'J' \n AND x.STATUS != 'X' \n AND x.STATUS != 'S' \n AND x.STATUS != 'D'\n"
}
] | 2008/12/04 | [
"https://Stackoverflow.com/questions/340139",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16488/"
] |
340,145 | <p>How can I add the reboot action to a vdproj?</p>
<p>I need an <a href="http://en.wikipedia.org/wiki/Windows_Installer" rel="nofollow noreferrer">MSI</a> file which restart the PC at the end of the installation.</p>
| [
{
"answer_id": 342926,
"author": "saschabeaumont",
"author_id": 592,
"author_profile": "https://Stackoverflow.com/users/592",
"pm_score": 2,
"selected": false,
"text": "ForceReboot ScheduleReboot Dim installer, database, view, result\nSet installer = CreateObject(\"WindowsInstaller.Installer\")\nSet database = installer.OpenDatabase (\"setup.msi\", 1)\nSet view = database.OpenView (\"INSERT INTO Property (Property, Value) VALUES ('REBOOT', 'Force')\")\nview.Execute\ndatabase.Commit\nSet database = nothing\n"
},
{
"answer_id": 6664104,
"author": "angularsen",
"author_id": 134761,
"author_profile": "https://Stackoverflow.com/users/134761",
"pm_score": 2,
"selected": false,
"text": "cscript \"$(ProjectDir)AddRebootPrompt.vbs\" \"$(BuiltOuputPath)\" Dim installer, database, view, result\nDim strPathMsi \n\nIf WScript.Arguments.Count <> 1 Then\n WScript.Echo \"Usage: cscript AddRebootPrompt.vbs <path to MSI>\"\n WScript.Quit -1\nEnd If\n\nstrPathMsi = WScript.Arguments(0)\n\nSet installer = CreateObject(\"WindowsInstaller.Installer\")\nSet database = installer.OpenDatabase (strPathMsi, 1)\nSet view = database.OpenView (\"INSERT INTO Property (Property, Value) VALUES ('REBOOT', 'Force')\")\n\nWScript.Echo \"Adding forced reboot prompt to install sequence.\"\n\nview.Execute\ndatabase.Commit\nWScript.Quit 0\n"
}
] | 2008/12/04 | [
"https://Stackoverflow.com/questions/340145",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15485/"
] |
340,183 | <p>I've been spending some time looking at Phil Haack's article on <a href="http://haacked.com/archive/2008/11/04/areas-in-aspnetmvc.aspx" rel="noreferrer">Grouping Controllers</a> very interesting stuff.</p>
<p>At the moment I'm trying to figure out if it would be possible to use the same ideas to create a plug-in/modular architecture for a project I'm working on.</p>
<p>So my question is: Is it possible to have the Areas in Phil's article split across multiple projects?</p>
<p>I can see that the name spaces will work themselves out, but I'm concerned about the views ending up in the right place. Is it something that can be sorted out with build rules?</p>
<p>Assuming that the above is possible with multiple projects in a single solution, does anyone have any ideas about the best way to make it possible with a separate solution and coding to a predefined set of interfaces? Moving from an Area to a plug-in.</p>
<p>I have some experiences with plug-in architecture but not masses so any guidance in this area would be useful.</p>
| [
{
"answer_id": 340322,
"author": "gius",
"author_id": 19712,
"author_profile": "https://Stackoverflow.com/users/19712",
"pm_score": 2,
"selected": false,
"text": "public IView GetView(string viewName)\n{\n switch (viewName)\n {\n case \"Namespace.View1\":\n return new View1();\n case \"Namespace.View2\":\n return new View2();\n ...\n }\n}\n"
},
{
"answer_id": 353403,
"author": "Simon Farrow",
"author_id": 35047,
"author_profile": "https://Stackoverflow.com/users/35047",
"pm_score": 2,
"selected": false,
"text": "class ResourceVirtualFile : VirtualFile\n{\n string path;\n string assemblyName;\n string resourceName;\n\n public ResourceVirtualFile(\n string virtualPath,\n string AssemblyName,\n string ResourceName)\n : base(virtualPath)\n {\n path = VirtualPathUtility.ToAppRelative(virtualPath);\n assemblyName = AssemblyName;\n resourceName = ResourceName;\n }\n\n public override Stream Open()\n {\n assemblyName = Path.Combine(HttpRuntime.BinDirectory, assemblyName + \".dll\");\n\n Assembly assembly = Assembly.ReflectionOnlyLoadFrom(assemblyName);\n if (assembly != null)\n {\n Stream resourceStream = assembly.GetManifestResourceStream(resourceName);\n if (resourceStream == null)\n throw new ArgumentException(\"Cannot find resource: \" + resourceName);\n return resourceStream;\n }\n throw new ArgumentException(\"Cannot find assembly: \" + assemblyName);\n }\n\n //todo: Neaten this up\n private static string CreateVirtualPath(string AssemblyName, string ResourceName)\n {\n string path = ResourceName.Substring(AssemblyName.Length);\n path = path.Replace(\".aspx\", \"\").Replace(\".\", \"/\");\n return string.Format(\"~{0}.aspx\", path);\n }\n\n public static IDictionary<string, VirtualFile> FindAllResources()\n {\n Dictionary<string, VirtualFile> files = new Dictionary<string, VirtualFile>();\n\n //list all of the bin files\n string[] assemblyFilePaths = Directory.GetFiles(HttpRuntime.BinDirectory, \"*.dll\");\n foreach (string assemblyFilePath in assemblyFilePaths)\n {\n string assemblyName = Path.GetFileNameWithoutExtension(assemblyFilePath);\n Assembly assembly = Assembly.ReflectionOnlyLoadFrom(assemblyFilePath); \n\n //go through each one and get all of the resources that end in aspx\n string[] resourceNames = assembly.GetManifestResourceNames();\n\n foreach (string resourceName in resourceNames)\n {\n if (resourceName.EndsWith(\".aspx\"))\n {\n string virtualPath = CreateVirtualPath(assemblyName, resourceName);\n files.Add(virtualPath, new ResourceVirtualFile(virtualPath, assemblyName, resourceName));\n }\n }\n }\n\n return files;\n }\n}\n private bool IsExtended(string virtualPath)\n {\n String checkPath = VirtualPathUtility.ToAppRelative(virtualPath);\n return resourceVirtualFile.ContainsKey(checkPath);\n }\n\n public override bool FileExists(string virtualPath)\n {\n return (IsExtended(virtualPath) || base.FileExists(virtualPath));\n }\n\n public override VirtualFile GetFile(string virtualPath)\n {\n string withTilda = string.Format(\"~{0}\", virtualPath);\n\n if (resourceVirtualFile.ContainsKey(withTilda))\n return resourceVirtualFile[withTilda];\n\n return base.GetFile(virtualPath);\n }\n"
},
{
"answer_id": 677682,
"author": "Geo",
"author_id": 81903,
"author_profile": "https://Stackoverflow.com/users/81903",
"pm_score": 4,
"selected": false,
"text": "protected void ScanControllersAndRepositoriesFromPath(string path)\n {\n this.Scan(o =>\n {\n o.AssembliesFromPath(path);\n o.AddAllTypesOf<SaasController>().NameBy(type => type.Name.Replace(\"Controller\", \"\"));\n o.AddAllTypesOf<IRepository>().NameBy(type => type.Name.Replace(\"Repository\", \"\"));\n o.AddAllTypesOf<IDomainFactory>().NameBy(type => type.Name.Replace(\"DomainFactory\", \"\"));\n });\n }\n protected void Application_Start()\n {\n ControllerBuilder.Current.SetControllerFactory(\n new ExtensionControllerFactory()\n );\n }\n"
}
] | 2008/12/04 | [
"https://Stackoverflow.com/questions/340183",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/35047/"
] |
340,185 | <p>I am working on an application that involves some gis stuff. There would be some .shp files to be read and plotted onto an opengl screen. The current opengl screen is using the orthographic projection as set from <code>glOrtho()</code> and is already displaying a map using coordinates from a simple text file..</p>
<p>Now the map to be plotted is to be read from a shapefile.</p>
<p>I have the following doubts:</p>
<ol>
<li><p>How to use the WGS84 projection of the .shp file(as read from the .prj file of the shapefile,WKT format) into my existing glOrtho projection..is there any conversion that needs to be done? and how is it different from what the glOrtho() sets up?basically how to use this information?</p></li>
<li><p>My application needs to be setup in such a way that i can know the exact lat/long of a point on the map.for eg. if i am hovering on X city,its correct lat/long could be fetched.I know that this can be done by using opensource utils/apis like GDAL/OGR but i am messed up as the documentation of these apis are not getting into my head.
I tried to find some sample c++ progs but couldnt find one.</p></li>
<li><p>I have already written my own logic to read the coordinates from a shapefile containing either points/polyline/polygon(using C-shapelib) and plotted over my opengl screen.I found a OGR sample code in doc to read a POINTS shapefile but none for POLYGON shapefile.And the problem is that this application has to be so dynamic that upon loading the shapefile,it should correctly setup the projection of the opengl screen depending upon the projection of the .shp file being read..eg WGS84,LCC,EVEREST MODIFIED...etc. how to achieve this from OGR api?</p></li>
</ol>
<p>Kindly give your inputs on this problem.. I am really keen to make this work but im not getting the right start..</p>
| [
{
"answer_id": 24601460,
"author": "msmith81886",
"author_id": 2142228,
"author_profile": "https://Stackoverflow.com/users/2142228",
"pm_score": 0,
"selected": false,
"text": "Guide Books Map Projections"
}
] | 2008/12/04 | [
"https://Stackoverflow.com/questions/340185",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/30868/"
] |
340,192 | <p>I have a problem with a oneway web method that open a moss site (probably because in a oneway webmethod the context is null)</p>
<p>Is possible to rewrite this code to remove the null reference exception? (without the oneway attribute i don't have the exception)</p>
<pre><code>[SoapDocumentMethod(OneWay = true)]
[WebMethod(Description = "TestOneWay")]
public voidTestOneWay(string webUrl)
{
using (SPSite site = new SPSite(webUrl))
{
....
}
}
</code></pre>
<p>the exception is:</p>
<pre><code>[2304] Error:Object reference not set to an instance of an object.
[2304] w3wp.exe Error: 0 :
[2304StackTrace: at System.Web.Hosting.ISAPIWorkerRequestInProc.GetAdditionalServerVar(Int32 index)
[2304] at System.Web.Hosting.ISAPIWorkerRequestInProc.GetServerVariable(String name)
[2304] at System.Web.HttpRequest.AddServerVariableToCollection(String name)
[2304] at System.Web.HttpRequest.FillInServerVariablesCollection()
[2304] at System.Web.HttpServerVarsCollection.Populate()
[2304] at System.Web.HttpServerVarsCollection.Get(String name)
[2304] at System.Collections.Specialized.NameValueCollection.get_Item(String name)
[2304] at Microsoft.SharePoint.SPGlobal.CreateSPRequestAndSetIdentity(Boolean bNotGlobalAdminCode, String strUrl, Boolean bNotAddToContext, Byte[] UserToken, String userName, Boolean bIgnoreTokenTimeout, Boolean bAsAnonymous)
[2304] at Microsoft.SharePoint.SPRequestManager.GetContextRequest(SPRequestAuthenticationMode authenticationMode)
[2304] at Microsoft.SharePoint.Administration.SPFarm.get_RequestNoAuth()
[2304] at Microsoft.SharePoint.SPSite.CopyUserToken(SPUserToken userToken)
[2304] at Microsoft.SharePoint.SPSite.SPSiteConstructor(SPFarm farm, Guid applicationId, Guid contentDatabaseId, Guid siteId, SPUrlZone zone, Uri requestUri, String serverRelativeUrl, Boolean hostHeaderIsSiteName, Uri redirectUri, Pairing pairing, SPUserToken userToken)
[2304] at Microsoft.SharePoint.SPSite..ctor(SPFarm farm, Uri requestUri, Boolean contextSite, SPUserToken userToken)
[2304] at Microsoft.SharePoint.SPSite..ctor(String requestUrl)
[2304] at Reply.Moss2EAI.SPHandler.GetAllFlowConfiguration(String webUrl, String flowConList)
[2304] at Reply.Moss2EAI.EaiMossIntegration.GetMessagesFromEai(String webUrl, String listName, String applicationName)
</code></pre>
| [
{
"answer_id": 355627,
"author": "tartafe",
"author_id": 43162,
"author_profile": "https://Stackoverflow.com/users/43162",
"pm_score": 2,
"selected": true,
"text": "//Call this before call new SPSite()\n private static void ChangeContext(string webUrl)\n {\n Trace.TraceInformation(\"ChangeContext\");\n HttpContext current = HttpContext.Current;\n HttpRequest request = new HttpRequest(\"\", webUrl, \"\");\n HttpContext.Current = new HttpContext(request, new HttpResponse(new StringWriter(CultureInfo.CurrentCulture)));\n HttpContext.Current.User = current.User;\n }\n"
},
{
"answer_id": 1630158,
"author": "Siva",
"author_id": 197254,
"author_profile": "https://Stackoverflow.com/users/197254",
"pm_score": 0,
"selected": false,
"text": "SPWeb web = SPContext.Current.Web\n"
}
] | 2008/12/04 | [
"https://Stackoverflow.com/questions/340192",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/43162/"
] |
340,194 | <p>how to validate letters and whitespaces using Zend Framework ?</p>
| [
{
"answer_id": 341114,
"author": "dcousineau",
"author_id": 20265,
"author_profile": "https://Stackoverflow.com/users/20265",
"pm_score": 2,
"selected": false,
"text": "true $validator = new Zend_Validate_Alpha(true); //will allow whitespace and non number letters\n"
}
] | 2008/12/04 | [
"https://Stackoverflow.com/questions/340194",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
340,204 | <p>Can a macro be written in Scheme (with <code>define-syntax</code>, for example) which will take expressions like this:</p>
<pre><code>(op a b c d e f g h i j)
</code></pre>
<p>And yield expressions like this as output?</p>
<pre><code>(op (op (op (op (op (op (op (op (op a b) c) d) e) f) g) h) i) j)
</code></pre>
<p>Of course, for arbitrary lengths. I can't think of a way to do it, given some template like this:</p>
<pre><code>(define-syntax op
(syntax-rules ()
[(_) 'base-case]
[(v1 v2 ...) 'nested-case??]))
</code></pre>
| [
{
"answer_id": 340294,
"author": "namin",
"author_id": 34596,
"author_profile": "https://Stackoverflow.com/users/34596",
"pm_score": 4,
"selected": true,
"text": "(define bop list)\n\n(define-syntax op\n (syntax-rules ()\n ((op a b) (bop a b))\n ((op a b c ...) (op (bop a b) c ...))))\n (op 1 2 3 4) (bop (bop (bop 1 2) 3) 4) (((1 2) 3) 4)"
},
{
"answer_id": 341675,
"author": "Claudiu",
"author_id": 15055,
"author_profile": "https://Stackoverflow.com/users/15055",
"pm_score": 0,
"selected": false,
"text": "(op 1 2 3 4)\n (op (bop 1 2) 3 4)\n (op (bop (bop 1 2) 3) 4)\n"
},
{
"answer_id": 357487,
"author": "grettke",
"author_id": 121526,
"author_profile": "https://Stackoverflow.com/users/121526",
"pm_score": 1,
"selected": false,
"text": "#!r6rs\n\n(import (rnrs base))\n\n(define-syntax claudiu\n (syntax-rules ()\n ((claudiu fun first second)\n (fun first second))\n ((claudiu fun first second rest ...)\n (claudiu fun (claudiu fun first second) rest ...))))\n"
}
] | 2008/12/04 | [
"https://Stackoverflow.com/questions/340204",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15055/"
] |
340,209 | <p>I'm writing a Java game and I want to implement a power meter for how hard you are going to shoot something. </p>
<p>I need to write a function that takes a int between 0 - 100, and based on how high that number is, it will return a color between Green (0 on the power scale) and Red (100 on the power scale).</p>
<p>Similar to how volume controls work:<br>
<img src="https://i.stack.imgur.com/uErDJ.png" alt="volume control"></p>
<p>What operation do I need to do on the Red, Green, and Blue components of a color to generate the colors between Green and Red?</p>
<p>So, I could run say, <code>getColor(80)</code> and it will return an orangish color (its values in R, G, B) or <code>getColor(10)</code> which will return a more Green/Yellow RGB value.</p>
<p>I know I need to increase components of the R, G, B values for a new color, but I don't know specifically what goes up or down as the colors shift from Green-Red.</p>
<hr>
<p>Progress:</p>
<p>I ended up using HSV/HSB color space because I liked the gradiant better (no dark browns in the middle).</p>
<p>The function I used was:</p>
<pre class="lang-java prettyprint-override"><code>public Color getColor(double power)
{
double H = power * 0.4; // Hue (note 0.4 = Green, see huge chart below)
double S = 0.9; // Saturation
double B = 0.9; // Brightness
return Color.getHSBColor((float)H, (float)S, (float)B);
}
</code></pre>
<p>Where "power" is a number between 0.0 and 1.0. 0.0 will return a bright red, 1.0 will return a bright green.</p>
<p>Java Hue Chart:<br>
<img src="https://i.stack.imgur.com/QphuU.png" alt="Java Hue Chart"></p>
| [
{
"answer_id": 340214,
"author": "Paul Dixon",
"author_id": 6521,
"author_profile": "https://Stackoverflow.com/users/6521",
"pm_score": 9,
"selected": true,
"text": "255 n 0 .. 100 R = (255 * n) / 100\nG = (255 * (100 - n)) / 100 \nB = 0\n 0 degrees 120 degrees"
},
{
"answer_id": 340234,
"author": "efotinis",
"author_id": 12320,
"author_profile": "https://Stackoverflow.com/users/12320",
"pm_score": 2,
"selected": false,
"text": "v = v0 + ratio * (v1 - v0)\n"
},
{
"answer_id": 340245,
"author": "Rafał Dowgird",
"author_id": 12166,
"author_profile": "https://Stackoverflow.com/users/12166",
"pm_score": 5,
"selected": false,
"text": "blue = 0.0\nif 0<=power<0.5: #first, green stays at 100%, red raises to 100%\n green = 1.0\n red = 2 * power\nif 0.5<=power<=1: #then red stays at 100%, green decays\n red = 1.0\n green = 1.0 - 2 * (power-0.5)\n"
},
{
"answer_id": 6583951,
"author": "mawi",
"author_id": 829859,
"author_profile": "https://Stackoverflow.com/users/829859",
"pm_score": 1,
"selected": false,
"text": "import java.awt.Color;\n\npublic class ColorUtils {\n\n public static Color interpolate(Color start, Color end, float p) {\n float[] startHSB = Color.RGBtoHSB(start.getRed(), start.getGreen(), start.getBlue(), null);\n float[] endHSB = Color.RGBtoHSB(end.getRed(), end.getGreen(), end.getBlue(), null);\n\n float brightness = (startHSB[2] + endHSB[2]) / 2;\n float saturation = (startHSB[1] + endHSB[1]) / 2;\n\n float hueMax = 0;\n float hueMin = 0;\n if (startHSB[0] > endHSB[0]) {\n hueMax = startHSB[0];\n hueMin = endHSB[0];\n } else {\n hueMin = startHSB[0];\n hueMax = endHSB[0];\n }\n\n float hue = ((hueMax - hueMin) * p) + hueMin;\n\n return Color.getHSBColor(hue, saturation, brightness);\n }\n}\n"
},
{
"answer_id": 13249391,
"author": "mschmoock",
"author_id": 884474,
"author_profile": "https://Stackoverflow.com/users/884474",
"pm_score": 4,
"selected": false,
"text": "int getTrafficlightColor(double value){\n return java.awt.Color.HSBtoRGB((float)value/3f, 1f, 1f);\n}\n int getTrafficlightColor(double value){\n return android.graphics.Color.HSVToColor(new float[]{(float)value*120f,1f,1f});\n}\n"
},
{
"answer_id": 19796847,
"author": "Nicholas",
"author_id": 1163414,
"author_profile": "https://Stackoverflow.com/users/1163414",
"pm_score": 3,
"selected": false,
"text": "private int getGreenToRedGradientByValue(int currentValue, int maxValue)\n{\n int r = ( (255 * currentValue) / maxValue );\n int g = ( 255 * (maxValue-currentValue) ) / maxValue;\n int b = 0;\n return ((r&0x0ff)<<16)|((g&0x0ff)<<8)|(b&0x0ff);\n}\n"
},
{
"answer_id": 23865972,
"author": "Dawood ibn Kareem",
"author_id": 1081110,
"author_profile": "https://Stackoverflow.com/users/1081110",
"pm_score": 2,
"selected": false,
"text": "power = 0 power = 50 power = 100 blue = 0;\ngreen = 255 * sqrt( cos ( power * PI / 200 ));\nred = 255 * sqrt( sin ( power * PI / 200 )); \n"
},
{
"answer_id": 26204509,
"author": "Christopher Galpin",
"author_id": 879,
"author_profile": "https://Stackoverflow.com/users/879",
"pm_score": 1,
"selected": false,
"text": "import colorsys\n\ndef get_rgb_from_hue_spectrum(percent, start_hue, end_hue):\n # spectrum is red (0.0), orange, yellow, green, blue, indigo, violet (0.9)\n hue = percent * (end_hue - start_hue) + start_hue\n lightness = 0.5\n saturation = 1\n r, g, b = colorsys.hls_to_rgb(hue, lightness, saturation)\n return r * 255, g * 255, b * 255\n\n# from green to red:\nget_rgb_from_hue_spectrum(percent, 0.3, 0.0)\n\n# or red to green:\nget_rgb_from_hue_spectrum(percent, 0.0, 0.3)\n value / max_value (value - min_value) / (max_value - min_value)"
},
{
"answer_id": 28120853,
"author": "lucabelluccini",
"author_id": 1068287,
"author_profile": "https://Stackoverflow.com/users/1068287",
"pm_score": 1,
"selected": false,
"text": "hsl({{ value * 120}}, 50%, 35%)\n"
},
{
"answer_id": 28215440,
"author": "Blowsie",
"author_id": 370286,
"author_profile": "https://Stackoverflow.com/users/370286",
"pm_score": 3,
"selected": false,
"text": "function percentToRGB(percent) {\n if (percent === 100) {\n percent = 99\n }\n var r, g, b;\n\n if (percent < 50) {\n // green to yellow\n r = Math.floor(255 * (percent / 50));\n g = 255;\n\n } else {\n // yellow to red\n r = 255;\n g = Math.floor(255 * ((50 - percent % 50) / 50));\n }\n b = 0;\n\n return \"rgb(\" + r + \",\" + g + \",\" + b + \")\";\n}\n\n\nfunction render(i) {\n var item = \"<li style='background-color:\" + percentToRGB(i) + \"'>\" + i + \"</li>\";\n $(\"ul\").append(item);\n}\n\nfunction repeat(fn, times) {\n for (var i = 0; i < times; i++) fn(i);\n}\n\n\nrepeat(render, 100); li {\n font-size:8px;\n height:10px;\n} <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js\"></script>\n<ul></ul>"
},
{
"answer_id": 30228031,
"author": "Tara",
"author_id": 1907004,
"author_profile": "https://Stackoverflow.com/users/1907004",
"pm_score": 2,
"selected": false,
"text": "const MATH::FLOAT4 color1(0.0f, 1.0f, 0.0f, 1.0f); // Green\nconst MATH::FLOAT4 color2(1.0f, 1.0f, 0.0f, 1.0f); // Yellow\nconst MATH::FLOAT4 color3(1.0f, 0.0f, 0.0f, 1.0f); // Red\n\nMATH::FLOAT4 get_interpolated_color(float interpolation_factor)\n{\n const float factor_color1 = std::max(interpolation_factor - 0.5f, 0.0f);\n const float factor_color2 = 0.5f - fabs(0.5f - interpolation_factor);\n const float factor_color3 = std::max(0.5f - interpolation_factor, 0.0f);\n\n MATH::FLOAT4 color;\n\n color.x = (color1.x * factor_color1 +\n color2.x * factor_color2 +\n color3.x * factor_color3) * 2.0f;\n\n color.y = (color1.y * factor_color1 +\n color2.y * factor_color2 +\n color3.y * factor_color3) * 2.0f;\n\n color.z = (color1.z * factor_color1 +\n color2.z * factor_color2 +\n color3.z * factor_color3) * 2.0f;\n\n color.w = 1.0f;\n\n return(color);\n}\n interpolation_factor 0.0 ... 1.0 0.0 ... 1.0 private readonly Color mColor1 = Color.FromArgb(255, 0, 255, 0);\nprivate readonly Color mColor2 = Color.FromArgb(255, 255, 255, 0);\nprivate readonly Color mColor3 = Color.FromArgb(255, 255, 0, 0);\n\nprivate Color GetInterpolatedColor(double interpolationFactor)\n{\n double interpolationFactor1 = Math.Max(interpolationFactor - 0.5, 0.0);\n double interpolationFactor2 = 0.5 - Math.Abs(0.5 - interpolationFactor);\n double interpolationFactor3 = Math.Max(0.5 - interpolationFactor, 0.0);\n\n return (Color.FromArgb(255,\n (byte)((mColor1.R * interpolationFactor1 +\n mColor2.R * interpolationFactor2 +\n mColor3.R * interpolationFactor3) * 2.0),\n\n (byte)((mColor1.G * interpolationFactor1 +\n mColor2.G * interpolationFactor2 +\n mColor3.G * interpolationFactor3) * 2.0),\n\n (byte)((mColor1.B * interpolationFactor1 +\n mColor2.B * interpolationFactor2 +\n mColor3.B * interpolationFactor3) * 2.0)));\n}\n interpolationFactor 0.0 ... 1.0 0 ... 255"
},
{
"answer_id": 31059379,
"author": "Stanislav Pankevich",
"author_id": 598057,
"author_profile": "https://Stackoverflow.com/users/598057",
"pm_score": 2,
"selected": false,
"text": "let hue: CGFloat = value / 3\nlet saturation: CGFloat = 1 // Or choose any\nlet brightness: CGFloat = 1 // Or choose any\nlet alpha: CGFloat = 1 // Or choose any\n\nlet color = UIColor(hue: hue, saturation: saturation, brightness: brightness, alpha: alpha)\n"
},
{
"answer_id": 32307628,
"author": "S1LENT WARRIOR",
"author_id": 634958,
"author_profile": "https://Stackoverflow.com/users/634958",
"pm_score": 1,
"selected": false,
"text": "Objective-C - (UIColor*) colorForCurrentLevel:(float)level\n{\n double hue = level * 0.4; // Hue (note 0.4 = Green)\n double saturation = 0.9; // Saturation\n double brightness = 0.9; // Brightness\n\n return [UIColor colorWithHue:hue saturation:saturation brightness:brightness alpha:1.0];\n}\n 0.0 1.0"
},
{
"answer_id": 35139576,
"author": "Patrick",
"author_id": 154603,
"author_profile": "https://Stackoverflow.com/users/154603",
"pm_score": 1,
"selected": false,
"text": "function getGreenToRed(percent){\n r = percent<50 ? 255 : Math.floor(255-(percent*2-100)*255/100);\n g = percent>50 ? 255 : Math.floor((percent*2)*255/100);\n return 'rgb('+r+','+g+',0)';\n}\n"
},
{
"answer_id": 35182072,
"author": "Amnon",
"author_id": 1477876,
"author_profile": "https://Stackoverflow.com/users/1477876",
"pm_score": 0,
"selected": false,
"text": "<html>\n<head>\n<script>\n//--------------------------------------------------------------------------\nfunction gradient(left, mid, right)\n{\n var obj = {}\n\n var lt50 = {\"r\":(mid.r-left.r)/50.0,\n \"g\":(mid.g-left.g)/50.0,\n \"b\":(mid.b-left.b)/50.0}\n var gt50 = {\"r\":(right.r-mid.r)/50.0,\n \"g\":(right.g-mid.g)/50.0,\n \"b\":(right.b-mid.b)/50.0}\n\n obj.getColor = function(percent) {\n if (percent == 50.0) {\n return mid;\n }\n if (percent < 50.0) {\n return \"rgb(\"+Math.floor(left.r+lt50.r*percent+0.5)+\",\"+\n Math.floor(left.g+lt50.g*percent+0.5)+\",\"+\n Math.floor(left.b+lt50.b*percent+0.5)+\")\";\n }\n var p2 = percent-50.0;\n return \"rgb(\"+Math.floor(mid.r+gt50.r*p2+0.5)+\",\"+\n Math.floor(mid.g+gt50.g*p2+0.5)+\",\"+\n Math.floor(mid.b+gt50.b*p2+0.5)+\")\";\n }\n\n return obj;\n}\n\n//--------------------------------------------------------------------------\nvar g_gradient = gradient( {\"r\":255, \"g\":20, \"b\":20}, // Left is red\n {\"r\":255, \"g\":255, \"b\":20}, // Middle is yellow\n {\"r\":20, \"g\":255, \"b\":20} ); // right is green\n\n//--------------------------------------------------------------------------\nfunction updateColor()\n{\n var percent = document.getElementById('idtext').value.length;\n var oscore = document.getElementById('idscore');\n\n if (percent > 100.0) {\n percent = 100.0;\n }\n if (percent < 0.0) {\n percent = 0.0;\n }\n var col = g_gradient.getColor(percent)\n oscore.style['background-color'] = col;\n oscore.innerHTML = percent + '%';\n}\n\n</script>\n</head>\n<body onLoad=\"updateColor()\">\n<input size='100' placeholder='type text here' id='idtext' type=\"text\" oninput=\"updateColor()\" />\n<br />\n<br />\n<div id='idscore' style='text-align:center; width:200px; border-style:solid;\n border-color:black; border-width:1px; height:20px;'> </div>\n</body>\n</html>\n"
},
{
"answer_id": 41062484,
"author": "Pavlin Todorov",
"author_id": 5178215,
"author_profile": "https://Stackoverflow.com/users/5178215",
"pm_score": 1,
"selected": false,
"text": "Sub UpdateConditionalFormatting(rng As Range)\n Dim cell As Range\n Dim max As Integer\n\n max = WorksheetFunction.max(rng)\n\n For Each cell In rng.Cells\n\n If cell.Value >= 0 And cell.Value < max / 2 Then\n cell.Interior.Color = RGB(255 * cell.Value / (max / 2), 255, 0)\n ElseIf cell.Value >= max / 2 And cell.Value <= max Then\n cell.Interior.Color = RGB(255, 255 * ((max) - cell.Value) / (max / 2), 0)\n End If\n\n Next cell\nEnd Sub\n"
},
{
"answer_id": 42852764,
"author": "Simon Fernandes",
"author_id": 5737750,
"author_profile": "https://Stackoverflow.com/users/5737750",
"pm_score": 0,
"selected": false,
"text": "-(UIColor*) redToGreenColorWithPosition:(int) value {\n\n double R, G;\n if (value > 50) {\n R = (255 * (100 - value)/ 50) ;\n G = 255;\n }else {\n R = 255;\n G = (255 * (value*2)) / 100;\n }\n\n return [UIColor colorWithRed:R/255.0f green:G/255.0f blue:0.0f alpha:1.0f];\n}\n"
},
{
"answer_id": 43204916,
"author": "MartiniB",
"author_id": 5296694,
"author_profile": "https://Stackoverflow.com/users/5296694",
"pm_score": 1,
"selected": false,
"text": "Public Function GetPercentageColor( _\n ByVal iPercent As Long, Optional _\n ByVal bOpposit As Boolean) As Long\n' 0->100% - Green->Yellow->Red\n' bOpposit - Red->Yellow->Green\n\nIf bOpposit Then iPercent = (100 - iPercent)\n\nSelect Case iPercent\nCase Is < 1: GetPercentageColor = 65280 ' RGB(0, 255, 0)\nCase Is > 99: GetPercentageColor = 255 ' RGB(255, 0, 0)\nCase Is < 50: GetPercentageColor = RGB(255 * iPercent / 50, 255, 0)\nCase Else: GetPercentageColor = RGB(255, (255 * (100 - iPercent)) / 50, 0)\nEnd Select\n\nEnd Function\n"
}
] | 2008/12/04 | [
"https://Stackoverflow.com/questions/340209",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2635/"
] |
340,213 | <p>I work on a program in Delphi that holds a lot of data, and I wonder which method is the best to save it to file. Now we use records and "file of" to save it but I think it should be better methods. I would prefer a system that makes it easy to migrate from the system we use now.</p>
<p>EDIT: The application is a sort of a database application. The user use it to manage data.</p>
| [
{
"answer_id": 340304,
"author": "Miel",
"author_id": 17336,
"author_profile": "https://Stackoverflow.com/users/17336",
"pm_score": 2,
"selected": false,
"text": "procedure TmyThing.PutData(AFile: String);\nvar\n writer: TWriter;\n stream: TFileStream;\nbegin\n stream := TFileStream.Create(AFile, fmCreate);\n try\n writer := TWriter.Create(stream, $ff);\n try\n with writer do\n begin\n WriteSignature; {marker to indicate a Delphi filer object file.}\n WriteListBegin; {outer list marker}\n WriteFloat(cVersion); {write the version for future use}\n WriteString(someProperty);\n {... etc. ...}\n WriteListEnd; {outer list marker}\n end;\n finally\n writer.Free;\n end;\n finally\n stream.Free;\n end;\nend;\n"
},
{
"answer_id": 344065,
"author": "skamradt",
"author_id": 9217,
"author_profile": "https://Stackoverflow.com/users/9217",
"pm_score": 2,
"selected": false,
"text": "TClientDataset midaslib"
},
{
"answer_id": 6247718,
"author": "Rishaan Gupta",
"author_id": 5188428,
"author_profile": "https://Stackoverflow.com/users/5188428",
"pm_score": 1,
"selected": false,
"text": "var\n\n FileStream: TFileStream;\n\n\nprocedure TForm1.Load(Sender: TObject);\n\nBegin\n\nif FileExists ('Thing2.dat') then\n\n Begin \n FileStream := TFileStream.Create('Thing2.dat', fmOpenRead);\n FileStream.ReadComponent( {Thing like Edit1} );\n FileStream.Free;\n End;\nend;\n procedure TForm1.Save(Sender: TObject);\n\nBegin\n\n\n\n FileStream := TFileStream.Create('Thing2.dat', fmcreate);\n\n FileStream.WriteComponent( {Thing like Edit1} );\n\n FileStream.Free;\n\n\n\nend; \n"
}
] | 2008/12/04 | [
"https://Stackoverflow.com/questions/340213",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/36966/"
] |
340,217 | <p>I have two tables with the following columns:</p>
<p>table1:</p>
<pre><code>id, agent_name, ticket_id, category, date_logged
</code></pre>
<p>table2:</p>
<pre><code>id, agent_name, department, admin_status
</code></pre>
<p>What I'm trying to achieve is to Select all rows from table1 where an agents department is equal to that of table2.</p>
<p>I've tried a few different join statements but I'm either getting the syntax wrong or it just won't work with this table setup. I'm a beginner when it comes to MySQL and from what I've read JOIN's are at the complex end of the spectrum!</p>
<p>One other option I've considered is duplicating the column "department" into table1 but that will require a little bit more coding on the frontend and I'm trying to see if I can achieve the desired result without doing that.</p>
<p>Any assistance greatly appreciated. </p>
| [
{
"answer_id": 340231,
"author": "Arvo",
"author_id": 35777,
"author_profile": "https://Stackoverflow.com/users/35777",
"pm_score": 0,
"selected": false,
"text": "select \n a.id, a.agent_name, a.ticket_id, \n a.category, a.date_logged, b.department\nfrom \n table1 a inner join table2 b on b.agent_name=a.agent_name\n"
},
{
"answer_id": 340240,
"author": "Pedrin",
"author_id": 36183,
"author_profile": "https://Stackoverflow.com/users/36183",
"pm_score": 0,
"selected": false,
"text": "Table1: id, agent_id, ticket_id, category, date_logged\nTable2: agent_id, agent_name, department, admin_status\n SELECT t2.agent_name, t1.date_logged FROM table1 t1\nINNER JOIN table2 t2 ON t2.agent_id = t1.agent_id\n"
},
{
"answer_id": 340247,
"author": "Stein G. Strindhaug",
"author_id": 26115,
"author_profile": "https://Stackoverflow.com/users/26115",
"pm_score": 3,
"selected": true,
"text": "SELECT * FROM Table1 \n INNER JOIN Table2 \n ON Table1.agent_name = Table2.agent_name \n WHERE Table2.department = 'somespecific value';\n agent_name agent_id SELECT * FROM Table1 \n INNER JOIN Table2 \n ON Table1.agent_id = Table2.id \n WHERE Table2.department = 'somespecific value';\n"
}
] | 2008/12/04 | [
"https://Stackoverflow.com/questions/340217",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/42428/"
] |
340,223 | <p>I have checked the whole site and googled on the net but was unable to find a simple solution to this problem.</p>
<p>I have a datatable which has about 20 columns and 10K rows. I need to remove the duplicate rows in this datatable based on 4 key columns. Doesn't .Net have a function which does this? The function closest to what I am looking for was datatable.DefaultView.ToTable(true, array of columns to display), But this function does a distinct on <strong>all</strong> the columns.</p>
<p>It would be great if someone could help me with this.</p>
<p>EDIT: I am sorry for not being clear on this. This datatable is being created by reading a CSV file and not from a DB. So using an SQL query is not an option.</p>
| [
{
"answer_id": 340235,
"author": "Samiksha",
"author_id": 29515,
"author_profile": "https://Stackoverflow.com/users/29515",
"pm_score": 0,
"selected": false,
"text": "DELETE FROM table1 AS tb1 INNER JOIN \n(SELECT id, COUNT(id) AS cntr FROM table1 GROUP BY id) AS tb2\nON tb1.id = tb2.id WHERE tb2.cntr > 1\n"
},
{
"answer_id": 340239,
"author": "liggett78",
"author_id": 19762,
"author_profile": "https://Stackoverflow.com/users/19762",
"pm_score": 3,
"selected": false,
"text": "public class MyRowComparer : IEqualityComparer<DataRow>\n{\n\n public bool Equals(DataRow x, DataRow y)\n {\n return (x.Field<int>(\"ID\") == y.Field<int>(\"ID\")) &&\n string.Compare(x.Field<string>(\"Name\"), y.Field<string>(\"Name\"), true) == 0 &&\n ... // extend this to include all your 4 keys...\n }\n\n public int GetHashCode(DataRow obj)\n {\n return obj.Field<int>(\"ID\").GetHashCode() ^ obj.Field<string>(\"Name\").GetHashCode() etc.\n }\n}\n var uniqueRows = myTable.AsEnumerable().Distinct(MyRowComparer);\n"
},
{
"answer_id": 340252,
"author": "Eduardo Campañó",
"author_id": 12091,
"author_profile": "https://Stackoverflow.com/users/12091",
"pm_score": 4,
"selected": true,
"text": "// Fill the DataSet.\nDataSet ds = new DataSet();\nds.Locale = CultureInfo.InvariantCulture;\nFillDataSet(ds);\n\nList<DataRow> rows = new List<DataRow>();\n\nDataTable contact = ds.Tables[\"Contact\"];\n\n// Get 100 rows from the Contact table.\nIEnumerable<DataRow> query = (from c in contact.AsEnumerable()\n select c).Take(100);\n\nDataTable contactsTableWith100Rows = query.CopyToDataTable();\n\n// Add 100 rows to the list.\nforeach (DataRow row in contactsTableWith100Rows.Rows)\n rows.Add(row);\n\n// Create duplicate rows by adding the same 100 rows to the list.\nforeach (DataRow row in contactsTableWith100Rows.Rows)\n rows.Add(row);\n\nDataTable table =\n System.Data.DataTableExtensions.CopyToDataTable<DataRow>(rows);\n\n// Find the unique contacts in the table.\nIEnumerable<DataRow> uniqueContacts =\n table.AsEnumerable().Distinct(DataRowComparer.Default);\n\nConsole.WriteLine(\"Unique contacts:\");\nforeach (DataRow uniqueContact in uniqueContacts)\n{\n Console.WriteLine(uniqueContact.Field<Int32>(\"ContactID\"));\n}\n"
},
{
"answer_id": 340260,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "DELETE TableWithDuplicates\n FROM TableWithDuplicates\n LEFT OUTER JOIN (\n SELECT PK_ID = Min(PK_ID), --Decide your method for deciding which rows to keep\n KeyColumn1,\n KeyColumn2,\n KeyColumn3,\n KeyColumn4\n FROM TableWithDuplicates\n GROUP BY KeyColumn1,\n KeyColumn2,\n KeyColumn3,\n KeyColumn4\n ) AS RowsToKeep\n ON TableWithDuplicates.PK_ID = RowsToKeep.PK_ID\n WHERE RowsToKeep.PK_ID IS NULL\n"
},
{
"answer_id": 2919931,
"author": "Srikanth V M",
"author_id": 128036,
"author_profile": "https://Stackoverflow.com/users/128036",
"pm_score": 0,
"selected": false,
"text": " public DataSet duplicateRemoval(DataSet dSet) \n{\n bool flag;\n int ccount = dSet.Tables[0].Columns.Count;\n string[] colst = new string[ccount];\n int p = 0;\n\n DataSet dsTemp = new DataSet();\n DataTable Tables = new DataTable();\n dsTemp.Tables.Add(Tables);\n\n for (int i = 0; i < ccount; i++)\n {\n dsTemp.Tables[0].Columns.Add(dSet.Tables[0].Columns[i].ColumnName, System.Type.GetType(\"System.String\"));\n }\n\n foreach (System.Data.DataRow row in dSet.Tables[0].Rows)\n {\n flag = false;\n p = 0;\n foreach (System.Data.DataColumn col in dSet.Tables[0].Columns)\n {\n colst[p++] = row[col].ToString();\n if (!string.IsNullOrEmpty(row[col].ToString()))\n { //Display only if any of the data is present in column\n flag = true;\n }\n }\n if (flag == true)\n {\n DataRow myRow = dsTemp.Tables[0].NewRow();\n //Response.Write(\"<tr style=\\\"background:#d2d2d2;\\\">\");\n for (int kk = 0; kk < ccount; kk++)\n {\n myRow[kk] = colst[kk]; \n\n // Response.Write(\"<td class=\\\"table-line\\\" bgcolor=\\\"#D2D2D2\\\">\" + colst[kk] + \"</td>\");\n }\n dsTemp.Tables[0].Rows.Add(myRow);\n }\n } return dsTemp;\n}\n"
},
{
"answer_id": 8531260,
"author": "Suhas Patil",
"author_id": 1101484,
"author_profile": "https://Stackoverflow.com/users/1101484",
"pm_score": 0,
"selected": false,
"text": "DataTable dtFinal = dtInput.DefaultView.ToTable(true, \n new string[ColumnCount] {\"Col1Name\",\"Col2Name\",\"Col3Name\",...,\"ColnName\"});\n"
},
{
"answer_id": 15799672,
"author": "Dave Lucre",
"author_id": 1219999,
"author_profile": "https://Stackoverflow.com/users/1219999",
"pm_score": 0,
"selected": false,
"text": "/// <summary>\n/// Takes a datatable and a column index, and returns a datatable without duplicates\n/// </summary>\n/// <param name=\"dt\">The datatable containing duplicate records</param>\n/// <param name=\"ComparisonFieldIndex\">The column index containing duplicates</param>\n/// <returns>A datatable object without duplicated records</returns>\npublic DataTable duplicateRemoval(DataTable dt, int ComparisonFieldIndex)\n{\n try\n {\n //Build the new datatable that will be returned\n DataTable dtReturn = new DataTable();\n for (int i = 0; i < dt.Columns.Count; i++)\n {\n dtReturn.Columns.Add(dt.Columns[i].ColumnName, System.Type.GetType(\"System.String\"));\n }\n\n //Loop through each record in the datatable we have been passed\n foreach (DataRow dr in dt.Rows)\n {\n bool Found = false;\n //Loop through each record already present in the datatable being returned\n foreach (DataRow dr2 in dtReturn.Rows)\n {\n bool Identical = true;\n //Compare the column specified to see if it matches an existing record\n if (!(dr2[ComparisonFieldIndex].ToString() == dr[ComparisonFieldIndex].ToString()))\n {\n Identical = false;\n }\n //If the record found identically matches one we already have, don't add it again\n if (Identical)\n {\n Found = true;\n break;\n }\n }\n //If we didn't find a matching record, we'll add this one\n if (!Found)\n {\n DataRow drAdd = dtReturn.NewRow();\n for (int i = 0; i < dtReturn.Columns.Count; i++)\n {\n drAdd[i] = dr[i];\n }\n\n dtReturn.Rows.Add(drAdd);\n }\n }\n return dtReturn;\n }\n catch (Exception)\n {\n //Return the original datatable if something failed above\n return dt;\n }\n}\n /// <summary>\n/// Takes a datatable and returns a datatable without duplicates\n/// </summary>\n/// <param name=\"dt\">The datatable containing duplicate records</param>\n/// <returns>A datatable object without duplicated records</returns>\npublic DataTable duplicateRemoval(DataTable dt)\n{\n try\n {\n //Build the new datatable that will be returned\n DataTable dtReturn = new DataTable();\n for (int i = 0; i < dt.Columns.Count; i++)\n {\n dtReturn.Columns.Add(dt.Columns[i].ColumnName, System.Type.GetType(\"System.String\"));\n }\n\n //Loop through each record in the datatable we have been passed\n foreach (DataRow dr in dt.Rows)\n {\n bool Found = false;\n //Loop through each record already present in the datatable being returned\n foreach (DataRow dr2 in dtReturn.Rows)\n {\n bool Identical = true;\n //Compare all columns to see if they match the existing record\n for (int i = 0; i < dt.Columns.Count; i++)\n {\n if (!(dr2[i].ToString() == dr[i].ToString()))\n {\n Identical = false;\n }\n }\n //If the record found identically matches one we already have, don't add it again\n if (Identical)\n {\n Found = true;\n break;\n }\n }\n //If we didn't find a matching record, we'll add this one\n if (!Found)\n {\n DataRow drAdd = dtReturn.NewRow();\n for (int i = 0; i < dtReturn.Columns.Count; i++)\n {\n drAdd[i] = dr[i];\n }\n\n dtReturn.Rows.Add(drAdd);\n }\n }\n return dtReturn;\n }\n catch (Exception)\n {\n //Return the original datatable if something failed above\n return dt;\n }\n}\n"
},
{
"answer_id": 16459635,
"author": "Satinder singh",
"author_id": 1192188,
"author_profile": "https://Stackoverflow.com/users/1192188",
"pm_score": 1,
"selected": false,
"text": "Linq moreLinq RemoveDuplicatesRecords(yourDataTable);\n\n\nprivate DataTable RemoveDuplicatesRecords(DataTable dt)\n{\n var UniqueRows = dt.AsEnumerable().Distinct(DataRowComparer.Default);\n DataTable dt2 = UniqueRows.CopyToDataTable();\n return dt2;\n}\n // Distinctby column name ID \nvar valueDistinctByIdColumn = yourTable.AsEnumerable().DistinctBy(row => new { Id = row[\"Id\"] });\nDataTable dtDistinctByIdColumn = valueDistinctByIdColumn.CopyToDataTable();\n \n moreLinq"
},
{
"answer_id": 70791322,
"author": "molbalga",
"author_id": 1700340,
"author_profile": "https://Stackoverflow.com/users/1700340",
"pm_score": 0,
"selected": false,
"text": "return dt.AsEnumerable()\n .Distinct(DataRowComparer.Default)\n .GroupBy(r => new\n {\n fieldKey1 = r.Field<int>(\"fieldKey1\"), \n fieldKey2 = r.Field<string>(\"fieldKey2\"), \n fieldKeyn = r.Field<DateTime>(\"fieldKeyn\")\n })\n .Select(g => \n g.OrderBy( dr => dr.Field<int>( \"OtherField1\" ) )\n .ThenBy( dr => dr.Field<int>( \"OtherField2\" ) )\n .First())\n .CopyToDataTable();\n"
}
] | 2008/12/04 | [
"https://Stackoverflow.com/questions/340223",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/24105/"
] |
340,232 | <p>With my jquery I'm trying to make the transition from a message to a loading function easy on the eyes by animate the opasity of the message out, inserting the loading.gif and animating the opacity back in. It fails.</p>
<pre><code>$('#powerSearchSubmitButton').click(function(ev) {
startLoad();
return false;
});
function startLoad() {
$('.message').each(function(i) {
$(this).animate({opacity: 0}, 500, function() {
$(this).html("<img src=\"/content/pics/loadingBig.gif\" alt=\"loading\" style=\"opacity:0\"/>");
$(this).animate({opacity: 1},500);
});
};
return true;
};
</code></pre>
<p>When I leave out the <code>.html()</code> call, it works fine (except off course the image is not there; So I think that it is beacuse the html isn't inserted with <code>opacity:0;</code> But when I inserted it with <code>style="opacity:0"</code> it cannot fade back in...</p>
<p>What am I doing wrong?</p>
| [
{
"answer_id": 341339,
"author": "Nathan Long",
"author_id": 4376,
"author_profile": "https://Stackoverflow.com/users/4376",
"pm_score": 2,
"selected": false,
"text": "$(this).fadeOut(500, function() {\n $(this).html(\"<img src='content/pics/loadingBig.gif' alt='loading'/>\");\n });\n$(this).fadeIn(500);\n"
}
] | 2008/12/04 | [
"https://Stackoverflow.com/questions/340232",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11333/"
] |
340,237 | <p>I've cached a value using the ASP.NET Cache, with the following code:</p>
<pre><code>Cache.Insert("TEST_VALUE", 150, null, Cache.NoAbsoluteExpiration, TimeSpan.FromSeconds(120));
</code></pre>
<p>As I understand it, this should mean that if nothing accesses that object for 120 seconds, it will expire and return null.</p>
<p>However, if after 10 minutes I run a page which writes out that value from the cache, it's still there (and indeed still after a whole hour). I know there's nothing else accessing it, because this is all on a local server on my machine.</p>
<p>Can anyone tell me why these values aren't getting purged from the cache?</p>
<hr>
<p>Thanks, I see what you mean, but my HttpModule is checking the type of request before inserting anything into the cache, so it will only occur on form uploads.</p>
<p>I've tried what you suggested anyway, and the breakpoint never gets hit when I am refreshing the page that displays the cached value. </p>
<p>I am assuming that even reading from the cache should extend the lifespan of the object, so I am leaving it 5-10 minutes before refreshing the 'debugging' page, but the value is still there!</p>
| [
{
"answer_id": 341331,
"author": "Mark Bell",
"author_id": 43140,
"author_profile": "https://Stackoverflow.com/users/43140",
"pm_score": 1,
"selected": true,
"text": "Cache[\"TEST_VALUE\"] = counter;\n Cache.Insert(\"TEST_VALUE\", newvalue, null, Cache.NoAbsoluteExpiration, TimeSpan.FromSeconds(120));\n"
},
{
"answer_id": 343273,
"author": "Ben Aston",
"author_id": 38522,
"author_profile": "https://Stackoverflow.com/users/38522",
"pm_score": 0,
"selected": false,
"text": "<cache disableExpiration=\"true\"/> \n"
},
{
"answer_id": 9697534,
"author": "Ron Chong",
"author_id": 1256689,
"author_profile": "https://Stackoverflow.com/users/1256689",
"pm_score": 0,
"selected": false,
"text": "cache(\"Key\") = 10 textbox.text = cache(\"Key\")"
}
] | 2008/12/04 | [
"https://Stackoverflow.com/questions/340237",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/43140/"
] |
340,250 | <p>Hi I'm using <code>System.Net.Mail</code> to send some HTML formatted emails.</p>
<p>What is the correct method for inserting css into the email message?</p>
<p>I know I can apply formatting to each item, but I'ld rather use style sheets..</p>
<p><strong>EDIT</strong>
I should have mentioned that this is for an internal application, and I expect 99% of users to be using Outlook or other client, but never hotmail or gmail etc.</p>
| [
{
"answer_id": 343618,
"author": "Alexander Prokofyev",
"author_id": 11256,
"author_profile": "https://Stackoverflow.com/users/11256",
"pm_score": 2,
"selected": false,
"text": "string letter = File.ReadAllText(Request.PhysicalApplicationPath + \"letter.html\");\nstring style = File.ReadAllText(Request.PhysicalApplicationPath + \"style.css\");\n\nMailMessage message = new MailMessage();\nmessage.Body = letter.Replace(\"{STYLE}\", style);\n <head>\n <title></title>\n <style type=\"text/css\">\n {STYLE}\n </style>\n</head>\n<body>\n"
}
] | 2008/12/04 | [
"https://Stackoverflow.com/questions/340250",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/31765/"
] |
340,270 | <p>I'm doing some really simple math and saving the result to a MS SQL2008 DB.</p>
<p>I'm <em>averaging</em> out the some numbers, which are byte values between 1<->5. I wish to record probably 2 decimal places only. I don't care about rounding for the 2nd decimal place (eg. a 1.155 == 1.5 or 1.6 .. i'm not too phased).</p>
<p>So .. should i store the average result as a float, decimal or double?</p>
<p>When i check what LINQ returns, it can return all three values!</p>
<p>Lastly, what would be the relevant SQL datatype field, also.</p>
<p>cheers!</p>
| [
{
"answer_id": 340301,
"author": "Stein G. Strindhaug",
"author_id": 26115,
"author_profile": "https://Stackoverflow.com/users/26115",
"pm_score": 0,
"selected": false,
"text": "integer = ( sum(all_values) / all_values.count().float ) * 100;\n"
},
{
"answer_id": 341100,
"author": "Jonathan",
"author_id": 6910,
"author_profile": "https://Stackoverflow.com/users/6910",
"pm_score": 3,
"selected": true,
"text": "declare @val decimal(10,2)\nselect @val = 10.155\nselect @val\n select val = round(10.155, 2, 0) -- rounded\nselect val = round(10.155, 2, 1) -- truncated\n"
}
] | 2008/12/04 | [
"https://Stackoverflow.com/questions/340270",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/30674/"
] |
340,271 | <p>The bugzilla (perl-based) system has a feature to login automatically by using a http server environment variable. If you fill in the right ID or username, you are automatically logged in.</p>
<p>My server runs Joomla (PHP-based) and has all the information about who is logged in. It runs bugzilla within a sub-frame.</p>
<p>So, how can I set this enviroment value from a PHP script?</p>
<p>To put it in another way, how does the following script return my own-set variable elsewhere in a session from PHP:</p>
<pre><code>#!/usr/bin/perl -wT
print "Content-type: text/html\n\n";
while (($key, $val) = each %ENV) {
print "$key = $val&lt;BR&gt;\n";
}
</code></pre>
| [
{
"answer_id": 340301,
"author": "Stein G. Strindhaug",
"author_id": 26115,
"author_profile": "https://Stackoverflow.com/users/26115",
"pm_score": 0,
"selected": false,
"text": "integer = ( sum(all_values) / all_values.count().float ) * 100;\n"
},
{
"answer_id": 341100,
"author": "Jonathan",
"author_id": 6910,
"author_profile": "https://Stackoverflow.com/users/6910",
"pm_score": 3,
"selected": true,
"text": "declare @val decimal(10,2)\nselect @val = 10.155\nselect @val\n select val = round(10.155, 2, 0) -- rounded\nselect val = round(10.155, 2, 1) -- truncated\n"
}
] | 2008/12/04 | [
"https://Stackoverflow.com/questions/340271",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/26387/"
] |
340,274 | <p>I'm creating a zip file using the class FastZip from SharpZipLib and once I after I close the program, I cannot delete the file because:</p>
<p>"Cannot delete zip.zip: It is being used by another person or program. Close any programs that might be using the file and try again."</p>
<p>The code that is generating the file is simply this:</p>
<pre><code>fZip.CreateEmptyDirectories = true;
fZip.CreateZip(filesPath + "\\" + this.zipName, filesPath, false, this.zipFilter);
</code></pre>
<p>I tried using:</p>
<pre><code> using (FastZip fZip = new FastZip())
{
try
{
fZip.CreateEmptyDirectories = true;
fZip.CreateZip(filesPath + "\\" + this.zipName, filesPath, false, this.zipFilter);
}
catch (Exception)
{
}
}
</code></pre>
<p>But it doesn't convert to iDisposable</p>
| [
{
"answer_id": 340406,
"author": "Thomas Hansen",
"author_id": 29746,
"author_profile": "https://Stackoverflow.com/users/29746",
"pm_score": 0,
"selected": false,
"text": "using(Stream s = new SharpZipLibStream())\n{\n /*...do stuff, zip stuff.../\n}\n"
},
{
"answer_id": 342470,
"author": "Ryan",
"author_id": 29762,
"author_profile": "https://Stackoverflow.com/users/29762",
"pm_score": 2,
"selected": false,
"text": "CreateZip(File.Create(zipFileName), // ...\n string zipFileName = System.IO.Path.Combine(filesPath, this.zipName);\nusing (Stream stream = File.Create(zipFileName))\n{\n fZip.CreateZip(stream, filesPath, false, this.zipFilter, null);\n stream.Close();\n}\n"
},
{
"answer_id": 74291072,
"author": "RogerMKE",
"author_id": 2166342,
"author_profile": "https://Stackoverflow.com/users/2166342",
"pm_score": 0,
"selected": false,
"text": "GC.Collect()\n"
}
] | 2008/12/04 | [
"https://Stackoverflow.com/questions/340274",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/36532/"
] |
340,277 | <p>I would like to use the JTable row sorter new in Java 6. But also I need it to be compatible in Mac OSX with Java 5. </p>
<p>Is it possible to find out the JVM version during runtime and use different code for the JTable with and without row sorter?</p>
| [
{
"answer_id": 340401,
"author": "Aaron Digulla",
"author_id": 34088,
"author_profile": "https://Stackoverflow.com/users/34088",
"pm_score": 0,
"selected": false,
"text": "sorterClass"
}
] | 2008/12/04 | [
"https://Stackoverflow.com/questions/340277",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9774/"
] |
340,282 | <p>Can someone explain to me why this code prints 14? I was just asked by another student and couldn't figure it out.</p>
<pre><code>int i = 5;
i = ++i + ++i;
cout<<i;
</code></pre>
| [
{
"answer_id": 340299,
"author": "Gonzalo Quero",
"author_id": 40996,
"author_profile": "https://Stackoverflow.com/users/40996",
"pm_score": -1,
"selected": false,
"text": "int i = 5;\ni = i+1; // First ++i, i is now 6\ni = i+1; // Second ++i, i is now 7\ni = i + i // i = 7 + 7\ncout << i // i = 14\n"
},
{
"answer_id": 340305,
"author": "phihag",
"author_id": 35070,
"author_profile": "https://Stackoverflow.com/users/35070",
"pm_score": 6,
"selected": true,
"text": "-Wall /Wall /W4 test-so-side-effects.c: In function 'main':\ntest-so-side-effects.c:5: warning: operation on 'i' may be undefined\ntest-so-side-effects.c:5: warning: operation on 'i' may be undefined\n i = i + 1;\ni = i + 1;\ni = i + i;\n"
},
{
"answer_id": 340306,
"author": "Mr Fooz",
"author_id": 25050,
"author_profile": "https://Stackoverflow.com/users/25050",
"pm_score": 2,
"selected": false,
"text": "int i = 5;\n++i;\n++i;\ni = i + i;\ncout << i;\n"
},
{
"answer_id": 340315,
"author": "bgoncalves",
"author_id": 280,
"author_profile": "https://Stackoverflow.com/users/280",
"pm_score": 2,
"selected": false,
"text": "int j=++i; \nint k=++i;\n\ni = j+k;\n"
},
{
"answer_id": 340464,
"author": "plan9assembler",
"author_id": 1710672,
"author_profile": "https://Stackoverflow.com/users/1710672",
"pm_score": -1,
"selected": false,
"text": " i = i++ + i; //11 \n\n i = i++ + i++; //12\n\n i = i++ + ++i; //13\n\n i = ++i + i++; //13\n\n i = ++i + ++i; //14 \n"
},
{
"answer_id": 341246,
"author": "Michael Burr",
"author_id": 12711,
"author_profile": "https://Stackoverflow.com/users/12711",
"pm_score": 4,
"selected": false,
"text": "i = v[i++]; // the behavior is unspecified\ni = 7, i++, i++; // i becomes 9\ni = ++i + 1; // the behavior is unspecified\ni = i + 1; // the value of i is incremented\n i = 7, i++, i++; static extern"
},
{
"answer_id": 341442,
"author": "Brad Gilbert",
"author_id": 1337,
"author_profile": "https://Stackoverflow.com/users/1337",
"pm_score": 1,
"selected": false,
"text": "14 int i = 5;\ni = ++i + ++i;\ncout<<i;\n\ni = ++i + ++i ;\ni = ++(5) + ++(5) ;\ni = 6 + 6 ;\ni = 12;\n\ni = ++i + ++i ;\ni = ++i + ++(5) ;\ni = ++i + (6) ;\ni = ++(6) + 6 ;\ni = (7) + 6 ;\ni = 13;\n\ni = ++i + ++i ;\ni = ++i + ++(5) ;\ni = ++(6) + (6) ;\ni = (7) + (7) ;\ni = 14;\n 14"
}
] | 2008/12/04 | [
"https://Stackoverflow.com/questions/340282",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2450/"
] |
340,283 | <p>Please consider the following <code>fork()</code>/<code>SIGCHLD</code> pseudo-code.</p>
<pre><code> // main program excerpt
for (;;) {
if ( is_time_to_make_babies ) {
pid = fork();
if (pid == -1) {
/* fail */
} else if (pid == 0) {
/* child stuff */
print "child started"
exit
} else {
/* parent stuff */
print "parent forked new child ", pid
children.add(pid);
}
}
}
// SIGCHLD handler
sigchld_handler(signo) {
while ( (pid = wait(status, WNOHANG)) > 0 ) {
print "parent caught SIGCHLD from ", pid
children.remove(pid);
}
}
</code></pre>
<p>In the above example there's a race-condition. It's possible for "<code>/* child stuff */</code>" to finish before "<code>/* parent stuff */</code>" starts which can result in a child's pid being added to the list of children after it's exited, and never being removed. When the time comes for the app to close down, the parent will wait endlessly for the already-finished child to finish.</p>
<p>One solution I can think of to counter this is to have two lists: <code>started_children</code> and <code>finished_children</code>. I'd add to <code>started_children</code> in the same place I'm adding to <code>children</code> now. But in the signal handler, instead of removing from <code>children</code> I'd <em>add</em> to <code>finished_children</code>. When the app closes down, the parent can simply wait until the difference between <code>started_children</code> and <code>finished_children</code> is zero.</p>
<p>Another possible solution I can think of is using shared-memory, e.g. share the parent's list of children and let the children <code>.add</code> and <code>.remove</code> themselves? But I don't know too much about this.</p>
<p>EDIT: Another possible solution, which was the first thing that came to mind, is to simply add a <code>sleep(1)</code> at the start of <code>/* child stuff */</code> but that smells funny to me, which is why I left it out. I'm also not even sure it's a 100% fix.</p>
<p>So, how would you correct this race-condition? And if there's a well-established recommended pattern for this, please let me know!</p>
<p>Thanks.</p>
| [
{
"answer_id": 340312,
"author": "Darron",
"author_id": 22704,
"author_profile": "https://Stackoverflow.com/users/22704",
"pm_score": -1,
"selected": false,
"text": " // main program excerpt\n for (;;) {\n if ( is_time_to_make_babies ) {\n\n pid = fork();\n if (pid == -1) {\n /* fail */\n } else if (pid == 0) {\n /* child stuff */\n print \"child started\"\n exit\n } else {\n /* parent stuff */\n print \"parent forked new child \", pid\n if (!earlyDeaths.contains(pid)) {\n children.add(pid);\n } else {\n earlyDeaths.remove(pid);\n }\n }\n\n }\n }\n\n // SIGCHLD handler\n sigchld_handler(signo) {\n while ( (pid = wait(status, WNOHANG)) > 0 ) {\n print \"parent caught SIGCHLD from \", pid\n if (children.contains(pid)) {\n children.remove(pid);\n } else {\n earlyDeaths.add(pid);\n }\n }\n }\n"
},
{
"answer_id": 340410,
"author": "qrdl",
"author_id": 28494,
"author_profile": "https://Stackoverflow.com/users/28494",
"pm_score": 5,
"selected": true,
"text": "fork() sigprocmask() fork() children.add()"
}
] | 2008/12/04 | [
"https://Stackoverflow.com/questions/340283",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
340,286 | <p>I keep getting this NPE in my application and I can't seem to get rid of it because it is not showing up in any of my source code. As you can see from the stacktrace it is not happening in my code but in the Swing plaf. Has any of you had this problem and maybe figured out what is happening here?</p>
<pre><code> 11:28:23,273 [AWT-EventQueue-0] ERROR [is.althingi.styran.utlit.styran.StyranImpl]
- uncaughtException
java.lang.NullPointerException
at javax.swing.plaf.basic.BasicTableUI$Handler.setValueIsAdjusting(Unknown Source)
at javax.swing.plaf.basic.BasicTableUI$Handler.mouseReleased(Unknown Source)
at java.awt.AWTEventMulticaster.mouseReleased(Unknown Source)
at java.awt.Component.processMouseEvent(Unknown Source)
at javax.swing.JComponent.processMouseEvent(Unknown Source)
at java.awt.Component.processEvent(Unknown Source)
at java.awt.Container.processEvent(Unknown Source)
at java.awt.Component.dispatchEventImpl(Unknown Source)
at java.awt.Container.dispatchEventImpl(Unknown Source)
at java.awt.Component.dispatchEvent(Unknown Source)
at java.awt.LightweightDispatcher.retargetMouseEvent(Unknown Source)
at java.awt.LightweightDispatcher.processMouseEvent(Unknown Source)
at java.awt.LightweightDispatcher.dispatchEvent(Unknown Source)
at java.awt.Container.dispatchEventImpl(Unknown Source)
at java.awt.Window.dispatchEventImpl(Unknown Source)
at java.awt.Component.dispatchEvent(Unknown Source)
at java.awt.EventQueue.dispatchEvent(Unknown Source)
at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.run(Unknown Source)
</code></pre>
| [
{
"answer_id": 340340,
"author": "bruno conde",
"author_id": 31136,
"author_profile": "https://Stackoverflow.com/users/31136",
"pm_score": 2,
"selected": false,
"text": "private void setValueIsAdjusting(boolean flag) {\n table.getSelectionModel().setValueIsAdjusting(flag);\n table.getColumnModel().getSelectionModel().\n setValueIsAdjusting(flag);\n}\n"
},
{
"answer_id": 463113,
"author": "Alfred B. Thordarson",
"author_id": 3379,
"author_profile": "https://Stackoverflow.com/users/3379",
"pm_score": 4,
"selected": true,
"text": "ListSelectionListener JTable valueChanged scrollRectToVisible updateUI invokeLater updateUI SwingUtilities.invokeLater(new Runnable() {\n public void run() {\n updateUI();\n }\n });\n invokeLater"
}
] | 2008/12/04 | [
"https://Stackoverflow.com/questions/340286",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3379/"
] |
340,341 | <p>When I call the connect function of the Paramiko <code>SSHClient</code> class, it outputs some log data about establishing the connection, which I would like to suppress.</p>
<p>Is there a way to do this either through Paramiko itself, or Python in general?</p>
| [
{
"answer_id": 340815,
"author": "M. Utku ALTINKAYA",
"author_id": 40948,
"author_profile": "https://Stackoverflow.com/users/40948",
"pm_score": 0,
"selected": false,
"text": "import sys\ndev_null = sys.stdout = sys.stderr = open('/dev/null', 'w')\ntry:\n.\n. connect()\n.\nfinally:\n dev_null.close()\n"
},
{
"answer_id": 340896,
"author": "JimB",
"author_id": 32880,
"author_profile": "https://Stackoverflow.com/users/32880",
"pm_score": 4,
"selected": true,
"text": "logger = paramiko.util.logging.getLogger()\n paramiko.util.log_to_file('filename.log')\n"
}
] | 2008/12/04 | [
"https://Stackoverflow.com/questions/340341",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/42820/"
] |
340,344 | <p>I Have created an SSRS Report for retrieving 55000 records using a Stored Procedure. When
executing from the Stored Proc it is taking just 3 seconds but when executing from SSRS report it is taking more than one minute. How can I solve this problem?</p>
| [
{
"answer_id": 21031438,
"author": "Zain",
"author_id": 3179416,
"author_profile": "https://Stackoverflow.com/users/3179416",
"pm_score": 0,
"selected": false,
"text": "declare @reportParamLocal int\nset @reportParamLocal = @reportParam\n\nselect * from Table A where A.field = @reportParam\n"
},
{
"answer_id": 44868479,
"author": "RBL",
"author_id": 1943921,
"author_profile": "https://Stackoverflow.com/users/1943921",
"pm_score": 0,
"selected": false,
"text": "OPTION (RECOMPILE)\n"
},
{
"answer_id": 47658975,
"author": "Andy Evenson",
"author_id": 9056919,
"author_profile": "https://Stackoverflow.com/users/9056919",
"pm_score": 1,
"selected": false,
"text": "SELECT ...\nFROM ...\nWHERE filename IN (@file);\n-- @file is an SSRS multi-value parameter passed directly to the query\n =JOIN(Parameters!file.Value,\",\")\n SELECT ...\nFROM ...\nWHERE ',' + @filelist + ',' LIKE '%,' + FILENAME + ',%';\n-- @filelist is passed to the query as the following expression:\n-- =JOIN(Parameters!file.Value,\",\")\n"
}
] | 2008/12/04 | [
"https://Stackoverflow.com/questions/340344",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
340,345 | <p>I've got a C++ service which provides a named pipe to clients with a NULL SECURITY_ATTRIBUTES as follows:</p>
<p><code>
hPipe = CreateNamedPipe( lpszPipename, PIPE_ACCESS_DUPLEX | FILE_FLAG_OVERLAPPED, PIPE_TYPE_BYTE | PIPE_READMODE_BYTE | PIPE_WAIT,
PIPE_UNLIMITED_INSTANCES, BUFSIZE, BUFSIZE, 0, NULL);
</code></p>
<p>There is a dll which uses this pipe to get services.</p>
<p>There is a c# GUI which uses the dll and works fine.</p>
<p>There is a .net web site which also uses this dll (the exact same one on the same PC) but always gets permission denied when it tries to open the pipe.</p>
<p>Any one know why this might happen and how to fix it?</p>
<p>Also does anyone know of a good tutorial on SECURITY_ATTRIBUTES because I haven't understood the msdn info yet.</p>
<p>Thanks,
Patrick</p>
| [
{
"answer_id": 21031438,
"author": "Zain",
"author_id": 3179416,
"author_profile": "https://Stackoverflow.com/users/3179416",
"pm_score": 0,
"selected": false,
"text": "declare @reportParamLocal int\nset @reportParamLocal = @reportParam\n\nselect * from Table A where A.field = @reportParam\n"
},
{
"answer_id": 44868479,
"author": "RBL",
"author_id": 1943921,
"author_profile": "https://Stackoverflow.com/users/1943921",
"pm_score": 0,
"selected": false,
"text": "OPTION (RECOMPILE)\n"
},
{
"answer_id": 47658975,
"author": "Andy Evenson",
"author_id": 9056919,
"author_profile": "https://Stackoverflow.com/users/9056919",
"pm_score": 1,
"selected": false,
"text": "SELECT ...\nFROM ...\nWHERE filename IN (@file);\n-- @file is an SSRS multi-value parameter passed directly to the query\n =JOIN(Parameters!file.Value,\",\")\n SELECT ...\nFROM ...\nWHERE ',' + @filelist + ',' LIKE '%,' + FILENAME + ',%';\n-- @filelist is passed to the query as the following expression:\n-- =JOIN(Parameters!file.Value,\",\")\n"
}
] | 2008/12/04 | [
"https://Stackoverflow.com/questions/340345",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/38892/"
] |
340,353 | <p>I have a post-compilation step that manipulates the Java bytecode of generated classes. I'd like to make life as painless as possible for library consumers, so I'm looking at ways I can make this process automatic and (if possible) compiler agnostic.</p>
<p>The <a href="http://java.sun.com/javase/6/docs/api/javax/annotation/processing/package-summary.html" rel="nofollow noreferrer">Annotation Processing API</a> provides many of the desired features (automatic service discovery; supported by Eclipse). Unfortunately, this is aimed at code generators and <a href="http://java.sun.com/javase/6/docs/api/javax/annotation/processing/Filer.html" rel="nofollow noreferrer">doesn't support manipulation of existing artefacts</a>:</p>
<blockquote>
<p>The initial inputs to the tool are
considered to be created by the zeroth
round; therefore, attempting to create
a source or class file corresponding
to one of those inputs will result in
a FilerException.</p>
</blockquote>
<p>The Decorator pattern recommended by the API is not an option.</p>
<p>I can see how to perform the step with a runtime agent/instrumentation, but this is a worse option than a manual build step as it would require anyone even peripherally touched by the API to configure their JVMs in a non-obvious manner.</p>
<p>Is there a way to plug into or wrap the <a href="http://java.sun.com/javase/6/docs/api/javax/tools/JavaCompiler.html" rel="nofollow noreferrer">compiler tool</a> as invoked by <a href="http://java.sun.com/javase/6/docs/technotes/tools/" rel="nofollow noreferrer">javac</a>? Has anyone successfully subverted the annotation processors to manipulate bytecode, no matter what the doc says?</p>
| [
{
"answer_id": 340455,
"author": "Aaron Digulla",
"author_id": 34088,
"author_profile": "https://Stackoverflow.com/users/34088",
"pm_score": 3,
"selected": true,
"text": "Example ExampleTpl"
}
] | 2008/12/04 | [
"https://Stackoverflow.com/questions/340353",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/304/"
] |
340,354 | <p>I had two domains for ex. domain1 and domain2, I am opening domain2/index.aspx page as popup from domain1/default.aspx page. While closing domain2 page i need to reload the domain1 page, i had given the javascript code as "Opener.Location.Reload();". I am getting <strong>Permission denied</strong> javascript error. Any ideas about this issue.</p>
| [
{
"answer_id": 340417,
"author": "Timothy Khouri",
"author_id": 11917,
"author_profile": "https://Stackoverflow.com/users/11917",
"pm_score": 2,
"selected": false,
"text": "// On the parent...\nfunction DoTheRefresh()\n{\n location.reload();\n}\n opener.DoTheRefresh();\n"
},
{
"answer_id": 1355689,
"author": "Kosta",
"author_id": 28327,
"author_profile": "https://Stackoverflow.com/users/28327",
"pm_score": 2,
"selected": false,
"text": "var win2;\n\nfunction openWindow()\n{\n win2 = window.open('http://...','childwindow',...);\n checkChild(); \n}\n\nfunction checkChild() {\n if (win2.closed) {\n window.location.reload(true);\n } else setTimeout(\"checkChild()\",1);\n}\n"
},
{
"answer_id": 2586258,
"author": "lau",
"author_id": 97682,
"author_profile": "https://Stackoverflow.com/users/97682",
"pm_score": 3,
"selected": false,
"text": "window.opener.location.href = parentUrl;\n"
}
] | 2008/12/04 | [
"https://Stackoverflow.com/questions/340354",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
340,356 | <p>When I call CreateProcess in Windows, the new process doesn't seem to inherit the console of the calling process. I made a test program that runs "ruby xtest", xtest being a script that writes "hello" to standard output. I ran this test program from Emacs, and get no output. I also tried the following code calling GetStdHandle, but again, no output. Then I tried passing CREATE_NEW_CONSOLE in dwCreationFlags to CreateProcess, which made a whole new window with the Ruby output. Finally, I made a simple fork/exec
test program and compiled it using Cygwin's GCC. This program worked: the Ruby output showed up in Emacs as expected. I tried to decipher the Cygwin source code in <a href="http://cygwin.com/cgi-bin/cvsweb.cgi/src/winsup/cygwin/spawn.cc?rev=1.268&content-type=text/x-cvsweb-markup&cvsroot=src" rel="noreferrer">http://cygwin.com/cgi-bin/cvsweb.cgi/src/winsup/cygwin/spawn.cc?rev=1.268&content-type=text/x-cvsweb-markup&cvsroot=src</a> but failed. So, how do you make the new process inherit the console of the parent process such that the output from the child shows up as expected?</p>
<pre><code>STARTUPINFO si;
PROCESS_INFORMATION pi;
memset(&si, 0, sizeof(si));
memset(&pi, 0, sizeof(pi));
si.dwFlags |= STARTF_USESTDHANDLES;
si.hStdInput = GetStdHandle(STD_INPUT_HANDLE);
si.hStdOutput = GetStdHandle(STD_OUTPUT_HANDLE);
si.hStdError = GetStdHandle(STD_ERROR_HANDLE);
if(!CreateProcess(0, "ruby xtest", 0, 0, 1, 0, 0, 0, &si, &pi)) die("CreateProcess");
</code></pre>
| [
{
"answer_id": 552413,
"author": "MSN",
"author_id": 6210,
"author_profile": "https://Stackoverflow.com/users/6210",
"pm_score": 1,
"selected": false,
"text": "hStdInput hStdOutput hStdError hStdOutput hStdError"
},
{
"answer_id": 640473,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": " STARTUPINFO siStartInfo;\n ZeroMemory( &siStartInfo, sizeof(STARTUPINFO) );\n siStartInfo.cb = sizeof(STARTUPINFO); \n siStartInfo.hStdError = GetStdHandle(STD_OUTPUT_HANDLE); \n siStartInfo.hStdOutput = GetStdHandle(STD_OUTPUT_HANDLE); \n siStartInfo.hStdInput = g_hChildStd_IN_Rd; // my outgoing pipe\n siStartInfo.dwFlags |= STARTF_USESTDHANDLES;\n\n// Create the child process. \n\n bSuccess = CreateProcess(\n NULL, \n szCmdline, \n NULL, \n NULL, \n TRUE, \n 0, \n NULL, \n NULL, \n &siStartInfo, \n &piProcInfo); \n"
},
{
"answer_id": 8999681,
"author": "Thomas Munk",
"author_id": 1168754,
"author_profile": "https://Stackoverflow.com/users/1168754",
"pm_score": 2,
"selected": false,
"text": "FillChar(SI, SizeOf(SI), 0);\nSI.cb:=SizeOf(SI);\nFillChar(PI, SizeOf(PI), 0);\nif CreateProcess(nil, CmdLineVar, nil, nil, False, 0, nil, nil, SI, PI) then ...\n"
}
] | 2008/12/04 | [
"https://Stackoverflow.com/questions/340356",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
340,359 | <p>like whether it is pentium or AMD etc. </p>
| [
{
"answer_id": 340434,
"author": "gimel",
"author_id": 6491,
"author_profile": "https://Stackoverflow.com/users/6491",
"pm_score": 2,
"selected": false,
"text": "Processor family type"
},
{
"answer_id": 340611,
"author": "WACM161",
"author_id": 12255,
"author_profile": "https://Stackoverflow.com/users/12255",
"pm_score": 4,
"selected": false,
"text": "using(ManagementObjectSearcher win32Proc = new ManagementObjectSearcher(\"select * from Win32_Processor\"), \n win32CompSys = new ManagementObjectSearcher(\"select * from Win32_ComputerSystem\"),\n win32Memory = new ManagementObjectSearcher(\"select * from Win32_PhysicalMemory\"))\n {\n foreach (ManagementObject obj in win32Proc.Get())\n {\n clockSpeed = obj[\"CurrentClockSpeed\"].ToString();\n procName = obj[\"Name\"].ToString();\n manufacturer = obj[\"Manufacturer\"].ToString();\n version = obj[\"Version\"].ToString();\n }\n"
},
{
"answer_id": 35340944,
"author": "boubkhaled",
"author_id": 1942732,
"author_profile": "https://Stackoverflow.com/users/1942732",
"pm_score": 0,
"selected": false,
"text": "Imports System.Management\n\n\n\n Private Sub InsertInfo()\n lstView.Items.Clear()\n\n Dim searcher As New ManagementObjectSearcher(\"select * from Win32_Processor\")\n\n Try\n For Each share As ManagementObject In searcher.Get()\n\n Dim grp As ListViewGroup\n Try\n grp = lstView.Groups.Add(share(\"Name\").ToString(), share(\"Name\").ToString())\n Catch\n grp = lstView.Groups.Add(share.ToString(), share.ToString())\n End Try\n\n If share.Properties.Count <= 0 Then\n MessageBox.Show(\"No Information Available\", \"No Info\", MessageBoxButtons.OK, MessageBoxIcon.Information)\n Return\n End If\n\n\n For Each PC As PropertyData In share.Properties\n\n Dim item As New ListViewItem(grp)\n If lstView.Items.Count Mod 2 <> 0 Then\n item.BackColor = Color.White\n Else\n item.BackColor = Color.WhiteSmoke\n End If\n\n item.Text = PC.Name\n\n If PC.Value IsNot Nothing AndAlso PC.Value.ToString().Length > 0 Then\n Select Case PC.Value.GetType().ToString()\n Case \"System.String[]\"\n Dim str As String() = DirectCast(PC.Value, String())\n\n Dim str2 As String = \"\"\n For Each st As String In str\n str2 += st & \" \"\n Next\n\n item.SubItems.Add(str2)\n\n Exit Select\n Case \"System.UInt16[]\"\n Dim shortData As UShort() = DirectCast(PC.Value, UShort())\n\n\n Dim tstr2 As String = \"\"\n For Each st As UShort In shortData\n tstr2 += st.ToString() & \" \"\n Next\n\n item.SubItems.Add(tstr2)\n\n Exit Select\n Case Else\n\n item.SubItems.Add(PC.Value.ToString())\n Exit Select\n End Select\n Else\n Continue For\n End If\n lstView.Items.Add(item)\n Next\n Next\n\n\n Catch exp As Exception\n MessageBox.Show(\"can't get data because of the followeing error \" & vbLf & exp.Message, \"Error\", MessageBoxButtons.OK, MessageBoxIcon.Information)\n End Try\n\n\n End Sub\n"
}
] | 2008/12/04 | [
"https://Stackoverflow.com/questions/340359",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/38807/"
] |
340,366 | <p>I need to update a record in a database with the following fields </p>
<pre><code>[ID] int (AutoIncr. PK)
[ScorerID] int
[Score] int
[DateCreated] smalldatetime
</code></pre>
<p>If a record exists for todays date (only the date portion should be checked, not the time) and a given scorer, I'd like to update the score value for this guy and this day. If the scorer doesn't have a record for today, I'd like to create a new one.</p>
<p>I'm getting grey hair trying to figure how to put this into a single (is this possible?) sql statement. By the way I'm using an MSSQl database and the <code>ExecuteNonQuery()</code> method to issue the query.</p>
| [
{
"answer_id": 340384,
"author": "Timothy Khouri",
"author_id": 11917,
"author_profile": "https://Stackoverflow.com/users/11917",
"pm_score": 5,
"selected": true,
"text": "IF EXISTS (SELECT NULL FROM MyTable WHERE ScorerID = @Blah AND CONVERT(VARCHAR, DateCreated, 101) = CONVERT(VARCHAR, GETDATE(), 101))\n UPDATE MyTable SET blah blah blah\nELSE\n INSERT INTO MyTable blah blah blah\n"
},
{
"answer_id": 340402,
"author": "Tomalak",
"author_id": 18771,
"author_profile": "https://Stackoverflow.com/users/18771",
"pm_score": 1,
"selected": false,
"text": "CREATE PROCEDURE InsertOrUpdateScorer(@ScorerID INT, @Score INT)\nAS\nBEGIN\n IF EXISTS (\n SELECT 1 \n FROM Scorer \n WHERE ScorerID = @ScorerID AND DATEDIFF(dd, GETDATE(), DateCreated) = 0\n )\n BEGIN\n UPDATE\n Scorer\n SET \n Score = @Score\n WHERE\n ScorerID = @ScorerID\n\n RETURN @ScorerID\n END\n ELSE\n BEGIN\n INSERT \n Scorer \n (ScorerID, Score, DateCreated)\n VALUES\n (@ScorerID, @Score, GETDATE())\n\n RETURN SCOPE_IDENTITY()\n END\nEND\n SqlCommand UpdateScorer = New SqlCommand(\"InsertOrUpdateScorer\", DbConn);\nUpdateScorer.CommandType = CommandType.StoredProcedure;\n\nSqlParameter RetValue = UpdateScorer.Parameters.Add(\"RetValue\", SqlDbType.Int);\nRetValue.Direction = ParameterDirection.ReturnValue;\n\nSqlParameter Score = UpdateScorer.Parameters.Add(\"@Score\", SqlDbType.Int);\nScore.Direction = ParameterDirection.Input;\n\nSqlParameter ScorerId = UpdateScorer.Parameters.Add(\"@ScorerID\", SqlDbType.Int);\nScorerId.Direction = ParameterDirection.Input;\n\nScore.Value = 15; // whatever\nScorerId.Value = 15; // whatever\n\nUpdateScorer.ExecuteNonQuery();\nConsole.WriteLine(RetValue.Value);\n"
},
{
"answer_id": 18913792,
"author": "kikea",
"author_id": 2724543,
"author_profile": "https://Stackoverflow.com/users/2724543",
"pm_score": 1,
"selected": false,
"text": "DECLARE @USER_ID AS INT=76;\nDECLARE @TYPE AS NVARCHAR(MAX)='set.global';\nDECLARE @FKEY AS NVARCHAR(MAX)='21';\nDECLARE @DATA AS NVARCHAR(MAX)='test';\n\n begin tran\n MERGE UserData\n USING (SELECT @USER_ID, @TYPE, @FKEY, @DATA) AS Source([UserId], [Type], [FKey], [Data])\n ON (UserData.[UserId] = Source.[UserId] AND UserData.[Type] = Source.[Type] AND (UserData.[FKey] = Source.[FKey] OR (Source.[FKey] IS NULL AND UserData.[FKey] IS NULL)))\n WHEN MATCHED\n THEN\n UPDATE SET [Data] = Source.[Data]\n WHEN NOT MATCHED BY TARGET THEN\n INSERT \n ([UserId]\n ,[Type]\n ,[FKey]\n ,[Data])\n VALUES\n ( Source.[UserId]\n ,Source.[Type]\n ,Source.[FKey]\n ,Source.[Data]);\n\n commit tran\n"
}
] | 2008/12/04 | [
"https://Stackoverflow.com/questions/340366",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16440/"
] |
340,368 | <p>In Visual Studio 2005, is there an easy way to automatically increment the assembly/file build numbers after a successful build?</p>
<p>Emphasis on <strong><em>easy</em></strong>. I would like to track my build version, without having to set up CruiseControl or some similar tool.</p>
| [
{
"answer_id": 340404,
"author": "Dean",
"author_id": 11802,
"author_profile": "https://Stackoverflow.com/users/11802",
"pm_score": 3,
"selected": true,
"text": "<?xml version=\"1.0\" encoding=\"utf-8\"?> <Project DefaultTargets=\"Build\" \n xmlns=\"http://schemas.microsoft.com/developer/msbuild/2003\">\n\n <Import Project=\"$(MSBuildExtensionsPath)\\MSBuildCommunityTasks\\MSBuild.Community.Tasks.Targets\"/> <PropertyGroup>\n <Major>1</Major>\n <Minor>0</Minor>\n <Build>0</Build>\n <Revision>0</Revision> </PropertyGroup> <PropertyGroup>\n <BuildDir>C:\\svn\\Infrastructure</BuildDir> </PropertyGroup>\n\n <ItemGroup>\n <SolutionsToBuild Include=\"Infrastructure.sln\"/> </ItemGroup>\n\n <Target Name=\"Build\" DependsOnTargets=\"ChangeDataAccessAssemblyInfo\">\n <RemoveDir Directories=\"$(BuildDir)\\Builds\" Condition=\"Exists('$(BuildDir)\\Builds')\" />\n <MSBuild Projects=\"@(SolutionsToBuild)\" Properties=\"Configuration=Debug\" Targets=\"Rebuild\" /> </Target>\n\n <ItemGroup>\n <TestAssemblies Include=\"Build\\Logging\\Logging.UnitTests.dll\" /> </ItemGroup>\n\n\n\n <Target Name=\"ChangeDataAccessAssemblyInfo\" >\n <Message Text=\"Writing ChangeDataAccessAssemblyInfo file for 1\"/>\n <Message Text=\"Will update $(BuildDir)\\DataAccess\\My Project\\AssemblyInfo.vb\" />\n <AssemblyInfo CodeLanguage=\"VB\"\n OutputFile=\"$(BuildDir)\\DataAccess\\My Project\\AssemblyInfo_new.vb\" \n\n AssemblyTitle=\"Data Access Layer\"\n AssemblyDescription=\"Message1\"\n AssemblyCompany=\"http://somewebiste\"\n AssemblyProduct=\"the project\"\n AssemblyCopyright=\"Copyright notice\"\n ComVisible=\"true\"\n CLSCompliant=\"true\"\n Guid=\"hjhjhkoi-9898989\"\n AssemblyVersion=\"$(Major).$(Minor).1.1\"\n AssemblyFileVersion=\"$(Major).$(Minor).5.7\"\n Condition=\"$(Revision) != '0' \"\n ContinueOnError=\"false\" />\n\n <Message Text=\"Updated Assembly File Info\" \n ContinueOnError=\"false\"/> </Target> </Project>\n"
}
] | 2008/12/04 | [
"https://Stackoverflow.com/questions/340368",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/22114/"
] |
340,376 | <p>I was wondering if it's possible to calculate the average of some numbers if I have this:</p>
<pre><code>int currentCount = 12;
float currentScore = 6.1123 (this is a range of 1 <-> 10).
</code></pre>
<p>Now, if I receive another score (let's say 4.5), can I recalculate the average so it would be something like:</p>
<pre><code>int currentCount now equals 13
float currentScore now equals ?????
</code></pre>
<p>or is this impossible and I still need to remember the list of scores?</p>
| [
{
"answer_id": 340387,
"author": "John with waffle",
"author_id": 279,
"author_profile": "https://Stackoverflow.com/users/279",
"pm_score": 4,
"selected": false,
"text": "current_sum += input;\ncurrent_count++;\ncurrent_average = current_sum/current_count;\n"
},
{
"answer_id": 340389,
"author": "paxdiablo",
"author_id": 14860,
"author_profile": "https://Stackoverflow.com/users/14860",
"pm_score": 5,
"selected": true,
"text": "currentScore = (currentScore * currentCount + newValue) / (currentCount + 1)\ncurrentCount = currentCount + 1\n {7,9,11,1,12} +--------+-------+----------------------+----------------------+\n| Number | Count | Actual average | Calculated average |\n+--------+-------+----------------------+----------------------+\n| 7 | 1 | (7)/1 = 7 | (0 * 0 + 7) / 1 = 7 |\n| 9 | 2 | (7+9)/2 = 8 | (7 * 1 + 9) / 2 = 8 |\n| 11 | 3 | (7+9+11)/3 = 9 | (8 * 2 + 11) / 3 = 9 |\n| 1 | 4 | (7+9+11+1)/4 = 7 | (9 * 3 + 1) / 4 = 7 |\n| 12 | 5 | (7+9+11+1+12)/5 = 8 | (7 * 4 + 12) / 5 = 8 |\n+--------+-------+----------------------+----------------------+\n"
},
{
"answer_id": 340393,
"author": "Kasprzol",
"author_id": 5957,
"author_profile": "https://Stackoverflow.com/users/5957",
"pm_score": 2,
"selected": false,
"text": "A1 + A2 + ... + AN/N newScore = (currentScore * currentCount + someNewValue)/(currentCount + 1)\n"
},
{
"answer_id": 340469,
"author": "Alterlife",
"author_id": 36848,
"author_profile": "https://Stackoverflow.com/users/36848",
"pm_score": 2,
"selected": false,
"text": " current_average = (current_sum = current_sum + newValue) / ++current_count;\n"
}
] | 2008/12/04 | [
"https://Stackoverflow.com/questions/340376",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/30674/"
] |
340,383 | <pre><code>function a () {
return "foo";
}
a.b = function () {
return "bar";
}
function c () { };
c.prototype = a;
var d = new c();
d.b(); // returns "bar"
d(); // throws exception, d is not a function
</code></pre>
<p>Is there some way for <code>d</code> to be a function, and yet still inherit properties from <code>a</code>?</p>
| [
{
"answer_id": 340838,
"author": "Eugene Lazutkin",
"author_id": 26394,
"author_profile": "https://Stackoverflow.com/users/26394",
"pm_score": 3,
"selected": false,
"text": "var d = new c();\n d c Function c"
},
{
"answer_id": 341050,
"author": "Russell Leggett",
"author_id": 2828,
"author_profile": "https://Stackoverflow.com/users/2828",
"pm_score": 2,
"selected": false,
"text": "function a () {\n return \"foo\";\n}\n\na.b = function () {\n return \"bar\";\n}\n\nfunction c () {\n var f = function(){\n return a();\n };\n\n //mixin all properties on a\n for(var prop in a){\n f[prop] = a[prop];\n }\n\n return f; //just returns the function instead of \"this\"\n};\n\nvar d = new c(); //doesn't need the new keyword, but just for fun it still works\n\nalert(d()); //show \"foo\"\n\nalert(d.b()); //shows \"bar\"\n"
},
{
"answer_id": 346666,
"author": "Daniel Cassidy",
"author_id": 31662,
"author_profile": "https://Stackoverflow.com/users/31662",
"pm_score": 4,
"selected": false,
"text": "__proto__ function a () {\n return \"foo\";\n}\n\na.b = function () {\n return \"bar\";\n}\n\nfunction c () {\n return \"hatstand\";\n}\nc.__proto__ = a;\n\nc(); // returns \"hatstand\"\nc.b(); // returns \"bar\"; inherited from a\n var d = {};\nd.__proto__ = a;\nd.b(); // returns \"bar\"\nd(); // throws exception -- the fact that d is inheriting from a function\n // doesn't make d itself a function.\n"
},
{
"answer_id": 2242465,
"author": "pr1001",
"author_id": 46768,
"author_profile": "https://Stackoverflow.com/users/46768",
"pm_score": 2,
"selected": false,
"text": "__proto__ c a function a () {\n return \"foo\";\n}\n\na.b = function () {\n return \"bar\";\n}\n\nfunction c () {\n var func = function() {\n return \"I am a function\";\n };\n func.__proto__ = a;\n return func;\n}\nc.prototype = a;\n\nvar d = new c();\nd.b(); // returns \"bar\"\nd(); // returns \"I am a function\"\n instanceof d instanceof c // true\nd instanceof a // false\nc instanceof a // false\n"
},
{
"answer_id": 21442571,
"author": "Cody",
"author_id": 1153121,
"author_profile": "https://Stackoverflow.com/users/1153121",
"pm_score": -1,
"selected": false,
"text": "var $omnifarious = (function(Schema){\n\n var fn = function f(){\n console.log('ran f!!!');\n return f;\n };\n\n Schema.prototype = {\n w: function(w){ console.log('w'); return this; },\n x: function(x){ console.log('x'); return this; },\n y: function(y){ console.log('y'); return this; }\n };\n fn.__proto__ = (new Schema()).__proto__;\n\n return fn;\n})(function schema(){ console.log('created new schema', this); });\n\nconsole.log(\n $omnifarious()().w().x().y()()()\n);\n interface Object.freeze() Schema prototype __proto__ fn.__proto__ = Object.freeze(new Schema().__proto__)"
},
{
"answer_id": 46063764,
"author": "Zander Brown",
"author_id": 3975351,
"author_profile": "https://Stackoverflow.com/users/3975351",
"pm_score": 4,
"selected": true,
"text": "Function const obj = Object.create(Function.prototype); // Ensures availability of call, apply ext\n obj const f = function(){\n // Hello, World!\n};\n obj f Object.setPrototypeOf(f,obj);\n const obj = Object.create(Function.prototype);\n\n// Define an 'answer' method on 'obj'\nobj.answer = function() {\n // Call this object\n this.call(); // Logs 'Hello, World'\n console.log('The ultimate answer is 42');\n}\n\nconst f = function() {\n // Standard example\n console.log('Hello, World');\n};\n\nObject.setPrototypeOf(f, obj);\n\n// 'f' is now an object with an 'answer' method\nf.answer();\n// But is still a callable function\nf();"
}
] | 2008/12/04 | [
"https://Stackoverflow.com/questions/340383",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/31662/"
] |
340,413 | <p>How do type casting happen without loss of data inside the compiler?</p>
<p>For example:</p>
<pre><code> int i = 10;
UINT k = (UINT) k;
float fl = 10.123;
UINT ufl = (UINT) fl; // data loss here?
char *p = "Stackoverflow Rocks";
unsigned char *up = (unsigned char *) p;
</code></pre>
<p>How does the compiler handle this type of typecasting? A low-level example showing the bits would be highly appreciated.</p>
| [
{
"answer_id": 340439,
"author": "MSalters",
"author_id": 15416,
"author_profile": "https://Stackoverflow.com/users/15416",
"pm_score": 3,
"selected": false,
"text": "& __stack[4] = float_to_int_bits(& __stack[0])"
},
{
"answer_id": 340466,
"author": "James Hopkin",
"author_id": 11828,
"author_profile": "https://Stackoverflow.com/users/11828",
"pm_score": 3,
"selected": false,
"text": "unsigned int uf1 = static_cast<unsigned int>(fl);\n unsigned char* up = reinterpret_cast<unsigned char*>(p);\n"
},
{
"answer_id": 341330,
"author": "Johannes Schaub - litb",
"author_id": 34509,
"author_profile": "https://Stackoverflow.com/users/34509",
"pm_score": 5,
"selected": true,
"text": "-1 int i = 10; \nunsigned int k = (unsigned int) i; // :1\n\nfloat fl = 10.123;\nunsigned int ufl = (unsigned int) fl; // :2\n\nchar *p = \"Stackoverflow Rocks\"; \nunsigned char *up = (unsigned char *) p; // :3\n unsigned int 10.123 char* char *"
},
{
"answer_id": 341494,
"author": "David Thornley",
"author_id": 14148,
"author_profile": "https://Stackoverflow.com/users/14148",
"pm_score": 1,
"selected": false,
"text": "\nchar * cp; \nfloat * fp; \ncp = malloc(100); \nfp = (float *)(cp + 1);"
}
] | 2008/12/04 | [
"https://Stackoverflow.com/questions/340413",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/38038/"
] |
340,415 | <p>I have a <code>JSP</code> page which contains an <code>HTML</code> <code><select></code> populated with all countries loaded from a database. Say for example, on "create user" all the country values are loaded in the select menu and I select 5 countries. Those 5 values are loaded into database for that particular user.</p>
<p>Now when I click on "modify user" for that userid again there will be a select menu and all the countries will be loaded in the select menu but those 5 countries should be highlighted/selected. </p>
<p>How do I accomplish this using <code>javascript</code>?</p>
| [
{
"answer_id": 340502,
"author": "kgiannakakis",
"author_id": 24054,
"author_profile": "https://Stackoverflow.com/users/24054",
"pm_score": 2,
"selected": false,
"text": "<select multiple=\"multiple\">\n <option value =\"UK\">UK</option>\n <option value =\"France\" selected=\"selected\">France</option>\n <option value =\"Germany\">Germany</option>\n <option value =\"Italy\" selected=\"selected\">Italy</option>\n</select>\n"
},
{
"answer_id": 340503,
"author": "Ken Gentle",
"author_id": 8709,
"author_profile": "https://Stackoverflow.com/users/8709",
"pm_score": 0,
"selected": false,
"text": "javascript JSP HTML <select> selected=\"selected\" <option> javascript option select selected JSP javascript options page load"
}
] | 2008/12/04 | [
"https://Stackoverflow.com/questions/340415",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
340,428 | <p>Is it possible to save a form in VBA as .exe file and then run it.</p>
| [
{
"answer_id": 340490,
"author": "Patrick Cuff",
"author_id": 7903,
"author_profile": "https://Stackoverflow.com/users/7903",
"pm_score": 4,
"selected": true,
"text": "/m"
}
] | 2008/12/04 | [
"https://Stackoverflow.com/questions/340428",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/31132/"
] |
340,431 | <p>I want to create a linked server in one sql server to another using the sp_addlinkedserver procedure. When i access the remote server I would like it to logon as me (i.e. using my windows account). How do I do this?</p>
| [
{
"answer_id": 340450,
"author": "Ed Harper",
"author_id": 27825,
"author_profile": "https://Stackoverflow.com/users/27825",
"pm_score": 2,
"selected": false,
"text": "EXEC master.dbo.sp_addlinkedsrvlogin \n @rmtsrvname=N'<your linked server name>',\n @useself=N'True',\n @locallogin=NULL,\n @rmtuser=NULL,\n @rmtpassword=NULL\n"
}
] | 2008/12/04 | [
"https://Stackoverflow.com/questions/340431",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/36189/"
] |
340,437 | <p>Whilst trawling through some old code I came across something similar to the following:</p>
<pre><code>class Base
{
public:
virtual int Func();
...
};
class Derived : public Base
{
public:
int Func(); // Missing 'virtual' qualifier
...
};
</code></pre>
<p>The code compiles fine (MS VS2008) with no warnings (level 4) and it works as expected - <code>Func</code> is virtual even though the virtual qualifier is missing in the derived class. Now, other than causing some confusion, are there any dangers with this code or should I change it all, adding the <code>virtual</code> qualifier?</p>
| [
{
"answer_id": 340446,
"author": "Blair Conrad",
"author_id": 1199,
"author_profile": "https://Stackoverflow.com/users/1199",
"pm_score": 4,
"selected": true,
"text": "virtual Func"
},
{
"answer_id": 340472,
"author": "James Hopkin",
"author_id": 11828,
"author_profile": "https://Stackoverflow.com/users/11828",
"pm_score": 2,
"selected": false,
"text": "template <typename Base>\nstruct Derived : Base\n{\n void f();\n};\n"
}
] | 2008/12/04 | [
"https://Stackoverflow.com/questions/340437",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9236/"
] |
340,461 | <p>I am wondering how to tell NHibernate to resolve dependencies on my POCO domain objects.</p>
<p>I figured out that methods like CalculateOrderTax should be in the Domain object because they encode domain specific business rules. But once I have two of those I am violating SRP. </p>
<p>It would be no problem to extract those methods to Strategy classes, but I wonder how to make NHibernate load those. </p>
<p>It doesn't seem like a good solution to loop through a list of objects in the repository to do get/set based Dependecy injection before handing the object off to the higher layers.</p>
<p>I am also using Castle Windsor for my Depency injection right now.</p>
| [
{
"answer_id": 341009,
"author": "Cristian Libardo",
"author_id": 16526,
"author_profile": "https://Stackoverflow.com/users/16526",
"pm_score": 4,
"selected": true,
"text": "public class MyInterceptor : EmptyInterceptor\n{\n public override bool OnLoad(object entity, object id, object[] state, string[] propertyNames, IType[] types)\n {\n return InjectDependencies(entity as MyEntity);\n }\n}\n nhSessionFactory.OpenSession(myInterceptor);\n"
}
] | 2008/12/04 | [
"https://Stackoverflow.com/questions/340461",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21699/"
] |
340,471 | <p>Our development process is highly automated via a raft of bash and php scripts (including subversion hook scripts.) These scripts do a number of things to integrate with our Bugzilla 3.0 installation.</p>
<p>But the current integration approach is a bunch of SQL calls which update the bugzilla database directly - which obviously has a number of downsides - including making me nervous about upgrading to 3.2 in case the database schema has changed!</p>
<p>For example, to add a comment to a bug, I'm doing an INSERT into the longdescs table.</p>
<p>So my (slightly long-winded) question is:</p>
<ul>
<li>should I be using Bugzilla WebServices (and if so, is there any good documentation other than the Bugzilla API docs which aren't getting me up to speed quickly)</li>
<li>or, should I be using some other Bugzilla API (direct perl calls?) - and, again, is there any decent doco on this?</li>
<li>or, should I just keep doing what I'm doing (direct SQL calls) because the db doesn't change that much and it "does the job"</li>
</ul>
| [
{
"answer_id": 363507,
"author": "Larry Silverman",
"author_id": 7752,
"author_profile": "https://Stackoverflow.com/users/7752",
"pm_score": 2,
"selected": false,
"text": "contrib/bz_webservice_demo.pl"
}
] | 2008/12/04 | [
"https://Stackoverflow.com/questions/340471",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/24106/"
] |
340,507 | <p>I have a Customer class.</p>
<pre><code>public class Customer
{
private string _id;
private string _name;
// some more properties follow
</code></pre>
<p>I am inheriting the EqualityComparer form MyEqualityComparer(of Customer).<br>
This I am intending to use in LINQ queries.<br>
MyEqualityComparer is intended for partial check between two objects.<br>
If the customer.id and customer.name matches I treat the objects the equal. </p>
<pre><code>public class MyComparer : System.Collections.Generic.EqualityComparer<Customer>
{
public override bool Equals(Customer x, Customer y)
{
if (x.Id == y.Id && x.Name == y.Name)
return true;
else
return false;
}
public override int GetHashCode(Customer obj)
{
return string.Concat(obj.Id,obj.Name).GetHashCode();
}
}
</code></pre>
<p>I referred to <a href="https://stackoverflow.com/questions/16340/how-do-i-generate-a-hashcode-from-a-byte-array-in-c">generating hashcode</a>.<br>
I am little unsure about concatenating strings and using that as a hashcode.<br>
Is this safe and sound what I am trying to do ? </p>
| [
{
"answer_id": 340523,
"author": "liggett78",
"author_id": 19762,
"author_profile": "https://Stackoverflow.com/users/19762",
"pm_score": 2,
"selected": false,
"text": "return obj.Id.GetHashCode() ^ obj.Name.GetHashCode();\n"
},
{
"answer_id": 340526,
"author": "Jon Skeet",
"author_id": 22656,
"author_profile": "https://Stackoverflow.com/users/22656",
"pm_score": 4,
"selected": true,
"text": "EqualityComparer<T> IEqualityComparer<T> EqualityComparer<T> IEqualityComparer return x.Id == y.Id && x.Name == y.Name;\n public override bool Equals(Customer x, Customer y)\n{\n if (object.ReferenceEquals(x, y))\n {\n return true;\n }\n if (x == null || y == null)\n {\n return false;\n }\n return x.Id == y.Id && x.Name == y.Name;\n}\n"
},
{
"answer_id": 340545,
"author": "Mike Two",
"author_id": 23659,
"author_profile": "https://Stackoverflow.com/users/23659",
"pm_score": 1,
"selected": false,
"text": "public override int GetHashCode(Customer obj)\n{\n unchecked\n {\n return ((obj.Id != null ? obj.Id.GetHashCode() : 0) * 397) \n ^ (obj.Name != null ? obj.Name.GetHashCode() : 0);\n }\n}\n"
}
] | 2008/12/04 | [
"https://Stackoverflow.com/questions/340507",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/41968/"
] |
340,520 | <p>A few months ago, I have programmed an ASP.NET GridView with a custom "Delete" LinkButton and Client-Side JavaScript Confirmation according to this msdn article:</p>
<p><a href="http://msdn.microsoft.com/en-us/library/bb428868.aspx" rel="nofollow noreferrer">http://msdn.microsoft.com/en-us/library/bb428868.aspx</a> (published in April 2007)</p>
<p>or e.g. <a href="https://stackoverflow.com/questions/218733/javascript-before-aspbuttonfield-click">Javascript before asp:ButtonField click</a></p>
<p>The code looks like this:</p>
<pre><code><ItemTemplate>
<asp:LinkButton ID="deleteLinkButton" runat="server"
Text="Delete"
OnCommand="deleteLinkButtonButton_Command"
CommandName='<%# Eval("id") %>'
OnClientClick='<%# Eval("id", "return confirm(\"Delete Id {0}?\")") %>'
/>
</ItemTemplate>
</code></pre>
<p>Surprisingly, "Cancel" doesn't work no more with my ie (Version: <code>6.0.2900.2180.xpsp_sp2_qfe.080814-1242</code>) - it always deletes the row. With Opera (Version 9.62) it still works as expeced and described in the msdn article. More surprisingly,
on a fellow worker's machine with the same ie version, it still works ("Cancel" will not delete the row).</p>
<p>The generated code looks like </p>
<pre><code><a onclick="return confirm(...);" href="javascript:__doPostBack('...')">
</code></pre>
<p>As confirm(...) returns false on "Cancel", I expect the __doPostBack event in the href not to be fired. Are there any strange ie settings I accidentally might have changed? What else could be the cause of this weird behaviour? Or is this a "please reinstall WinXP" issue?</p>
| [
{
"answer_id": 340747,
"author": "Samiksha",
"author_id": 29515,
"author_profile": "https://Stackoverflow.com/users/29515",
"pm_score": 1,
"selected": false,
"text": "<asp:LinkButton ID=\"DeleteButton\" runat=\"server\" CausesValidation=\"False\"\n CommandName=\"Delete\" Text=\"Delete\"\n OnClientClick=\"return confirm('Delete Id : '<%# (string)Eval('id')%>')\" >\n\n</asp:LinkButton>\n"
},
{
"answer_id": 343389,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "OnClientClick='<%# Eval(\"id\", \"return confirm(\\\"Delete Id {0}?\\\")\") %>'\n OnClientClick='<%# Eval(\"zahlungid\", \"if(confirm(\\\"Delete Id {0}?\\\")==false){{event.returnValue=false;return false;}}else{{return true;}}\") %>'\n"
}
] | 2008/12/04 | [
"https://Stackoverflow.com/questions/340520",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
340,521 | <p>I'm writing a service that will only get calls from the local host. Performance is important so I thought I'd try the <a href="http://msdn.microsoft.com/en-us/library/system.servicemodel.netnamedpipebinding.aspx" rel="noreferrer">NetNamedPipeBinding</a> instead of <a href="http://msdn.microsoft.com/en-us/library/system.servicemodel.nettcpbinding.aspx" rel="noreferrer">NetTcpBinding</a> and see If I could see any noticeable performance gains.</p>
<p>If a client, after having performed one or more requests to the server, is idle for a longer period of time the next request will fail seemingly due to some idle timeout in the binding. The same thing also happens when the service gets restarted.</p>
<p>I need my clients to be able to keep a connection open for as long as it's allowed in order to avoid the overhead associated with setting up a new connection. I also need to be able to restart the service from time to time and have the clients to automatically retry if they notice that the connection has been terminated.</p>
<p>I know that this is suppported by the reliability stuff in NetTcpBinding but how would one go about getting the same level of re-connect reliability in the NetNamedPipeBinding? Is it even possible?</p>
<p>The question is somewhat academic as it isn't a requirement to use NetNamedPipes, I could just as easily adopt it to use the tcp-binding but It's an itch and I'd really like to scratch it.</p>
| [
{
"answer_id": 340869,
"author": "Chris Porter",
"author_id": 13495,
"author_profile": "https://Stackoverflow.com/users/13495",
"pm_score": 4,
"selected": false,
"text": "<binding name=\"MyBindingName\" sendTimeout=\"00:00:30\" receiveTimeout=\"infinite\">\n <reliableSession enabled=\"true\" inactivityTimeout=\"00:05:00\" ordered=\"true\" />\n <security mode=\"None\" />\n</binding>\n <binding name=\"MyBindingName\" closeTimeout=\"00:00:30\" openTimeout=\"00:00:30\" receiveTimeout=\"infinite\" sendTimeout=\"00:00:30\">\n <reliableSession enabled=\"true\" inactivityTimeout=\"00:01:00\" ordered=\"true\" />\n <security mode=\"None\" />\n</binding>\n [OperationContract(IsOneWay = false, IsInitiating = false, IsTerminating = false)]\nbool KeepAlive();\n\npublic bool KeepAlive()\n{\n return true;\n}\n InstanceContext site = new InstanceContext(this);\n_proxy = new MyServiceChannel(site);\nif (_proxy != null) \n{\n if (_proxy.Login()) \n {\n //Login was successful\n //Add channel event handlers so we can determine if something goes wrong\n foreach (IChannel a in site.OutgoingChannels) \n {\n a.Opened += Channel_Opened;\n a.Faulted += Channel_Faulted;\n a.Closing += Channel_Closing;\n a.Closed += Channel_Closed;\n }\n }\n}\n private void Channel_Faulted(object sender, EventArgs e)\n{\n IChannel channel = sender as IChannel;\n if (channel != null) \n {\n channel.Abort();\n channel.Close();\n }\n\n //Disable the keep alive timer now that the channel is faulted\n _keepAliveTimer.Stop();\n\n //The proxy channel should no longer be used\n AbortProxy();\n\n //Enable the try again timer and attempt to reconnect\n _reconnectTimer.Start();\n}\n\nprivate void _reconnectTimer_Tick(object sender, System.EventArgs e)\n{\n if (_proxy == null) \n {\n InstanceContext site = new InstanceContext(this);\n _proxy = new StateManagerClient(site);\n }\n if (_proxy != null) \n {\n if (_proxy.Login()) \n {\n //The connection is back up\n _reconnectTimer.Stop();\n _keepAliveTimer.Start();\n }\n else \n {\n //The channel has likely faulted and the proxy should be destroyed\n AbortProxy();\n }\n }\n}\n\npublic void AbortProxy()\n{\n if (_proxy != null) \n {\n _proxy.Abort();\n _proxy.Close();\n _proxy = null;\n }\n}\n"
},
{
"answer_id": 4609600,
"author": "Matthew Hess",
"author_id": 393207,
"author_profile": "https://Stackoverflow.com/users/393207",
"pm_score": 5,
"selected": false,
"text": "NetNamedPipeBinding myBinding = new NetNamedPipeBinding(NetNamedPipeSecurityMode.None);\nmyBinding.ReceiveTimeout = TimeSpan.MaxValue;\n <netNamedPipeBinding>\n <binding name=\"myBinding\" receiveTimeout=\"infinite\">\n </binding>\n</netNamedPipeBinding>\n"
}
] | 2008/12/04 | [
"https://Stackoverflow.com/questions/340521",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2114/"
] |
340,525 | <p>I'm trying to learn about Expression trees, and I've created a method that takes an</p>
<pre><code>Expression<Func<bool>>
</code></pre>
<p>and executes it if it satisfies some conditions - see the code below.</p>
<pre><code> private static void TryCommand(Expression<Func<bool>> expression)
{
var methodCallExpression = expression.Body as MethodCallExpression;
if (methodCallExpression == null)
{
throw new ArgumentException("expression must be a MethodCallExpression.");
}
if (methodCallExpression.Object.Type != typeof (MyClass))
{
throw new ArgumentException("expression must be operating on an instanceof MyClass.");
}
var func = expression.Compile();
var success = func.Invoke();
if(!success)
{
Console.WriteLine(methodCallExpression.Method.Name + "() failed with error code " + (func.Target as MyClass).GetError());
}
}
</code></pre>
<p>The problem that</p>
<pre><code>(func.Target as MyClass)
</code></pre>
<p>is null. Clearly I'm doing something wrong! How do I access the instance that the method is operating on?</p>
| [
{
"answer_id": 340566,
"author": "Jon Skeet",
"author_id": 22656,
"author_profile": "https://Stackoverflow.com/users/22656",
"pm_score": 2,
"selected": true,
"text": "Func<int> public static void TryCommand(Expression<Func<MyClass,bool>> command,\n MyClass c)\n{\n // Code as before to find the method name etc.\n\n Func<MyClass, bool> compiled = command.Compile();\n\n if (!compiled(c))\n {\n Console.WriteLine(methodCallExpression.Method.Name\n + \"() failed with error code \" + c.GetError());\n }\n}\n TryCommand(x => x.SomeMethod(), myClass);\n"
},
{
"answer_id": 1422704,
"author": "Ricardo Lacerda Castelo Branco",
"author_id": 173246,
"author_profile": "https://Stackoverflow.com/users/173246",
"pm_score": 2,
"selected": false,
"text": "\nMethodCallExpression methodCallExpression = (MethodCallExpression)expression.Body;\nMemberExpression memberExpression = (MemberExpression)methodCallExpression.Object;\n\nExpression<Func<Object>> getCallerExpression = Expression<Func<Object>>.Lambda<Func<Object>>(memberExpression);\nFunc<Object> getCaller = getCallerExpression.Compile();\nMyClass caller = (MyClass)getCaller();\n"
}
] | 2008/12/04 | [
"https://Stackoverflow.com/questions/340525",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/32413/"
] |
340,528 | <p>If both get and set are compulsory in C# automatic properties, why do I have to bother specifying "get; set;" at all?</p>
| [
{
"answer_id": 340531,
"author": "Brian Genisio",
"author_id": 36687,
"author_profile": "https://Stackoverflow.com/users/36687",
"pm_score": 6,
"selected": false,
"text": "public int Foo { get; private set; }\n public int Foo { private get; set; }\n"
},
{
"answer_id": 340535,
"author": "Cristian Libardo",
"author_id": 16526,
"author_profile": "https://Stackoverflow.com/users/16526",
"pm_score": 4,
"selected": false,
"text": "public int MyProperty { get; private set; }\n"
},
{
"answer_id": 340682,
"author": "Binary Worrier",
"author_id": 18797,
"author_profile": "https://Stackoverflow.com/users/18797",
"pm_score": 7,
"selected": true,
"text": "{get; set;} class Test\n{\n public int n;\n public int i { get; set; }\n public void InitAnInt(out int p)\n {\n p = 100;\n }\n public Test()\n {\n InitAnInt(out n); // This is OK\n InitAnInt(out i); // ERROR: A property or indexer may not be passed \n // as an out or ref parameter\n }\n}\n"
},
{
"answer_id": 341364,
"author": "Ron Todosichuk",
"author_id": 43294,
"author_profile": "https://Stackoverflow.com/users/43294",
"pm_score": 4,
"selected": false,
"text": "public int MyProperty { get; set; }\n private int myProperty;\npublic int MyProperty \n{\n get { return myProperty; }\n set { myProperty = value; } \n}\n public int MyProperty\n{\n [CompilerGenerated]\n get\n {\n return this.<MyProperty>k__BackingField;\n }\n [CompilerGenerated]\n set\n {\n this.<MyProperty>k__BackingField = value;\n }\n}\n [CompilerGenerated]\npublic void set_MyProperty(int value)\n{\n this.<MyProperty>k__BackingField = value;\n}\n[CompilerGenerated]\npublic int get_MyProperty()\n{\n return this.<MyProperty>k__BackingField;\n}\n public int MyProperty { get; private set; }\n public int MyProperty\n{\n [CompilerGenerated]\n get\n {\n return this.<MyProperty>k__BackingField;\n }\n private [CompilerGenerated]\n set\n {\n this.<MyProperty>k__BackingField = value;\n }\n}\n public int myProperty = 0;\npublic int MyProperty\n{\n get { return myProperty; }\n} \n public int Test2\n{\n get\n {\n return this._test;\n }\n}\n\npublic int get_Test2()\n{\n return this._test;\n}\n"
},
{
"answer_id": 342326,
"author": "Robert Rossney",
"author_id": 19403,
"author_profile": "https://Stackoverflow.com/users/19403",
"pm_score": 2,
"selected": false,
"text": "public int Foo;\npublic int Bar { }\n"
},
{
"answer_id": 12657773,
"author": "Zaid Masud",
"author_id": 374420,
"author_profile": "https://Stackoverflow.com/users/374420",
"pm_score": 2,
"selected": false,
"text": "public virtual int Property { get; set; }\n public override int Property { get { return int.MinValue; } }\n"
},
{
"answer_id": 27291579,
"author": "Robert Synoradzki",
"author_id": 2979473,
"author_profile": "https://Stackoverflow.com/users/2979473",
"pm_score": 2,
"selected": false,
"text": "public string Name { get; }\npublic string Name { get; } = \"This won't change even internally\";\n public string Name { get; private set; }\n\npublic Constructor() { Name=\"As initialised\"; }\npublic void Method() { Name=\"This might be changed internally. By mistake. Or not.\"; }\n using System;\n\npublic class Propertier {\n public string ReadOnlyPlease { get; private set; }\n\n public Propertier() { ReadOnlyPlease=\"As initialised\"; }\n public void Method() { ReadOnlyPlease=\"This might be changed internally\"; }\n public override string ToString() { return String.Format(\"[{0}]\",ReadOnlyPlease); }\n}\n\npublic class Program {\n static void Main() {\n Propertier p=new Propertier();\n Console.WriteLine(p);\n\n// p.ReadOnlyPlease=\"Changing externally!\";\n// Console.WriteLine(p);\n\n // error CS0272: The property or indexer `Propertier.ReadOnlyPlease' cannot be used in this context because the set accessor is inaccessible\n // That's good and intended.\n\n // But...\n p.Method();\n Console.WriteLine(p);\n }\n}\n"
}
] | 2008/12/04 | [
"https://Stackoverflow.com/questions/340528",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/38522/"
] |
340,543 | <p>I have a problem creating a regular expression for the following task:</p>
<p>Suppose we have HTML-like text of the kind:</p>
<pre><code><x>...<y>a</y>...<y>b</y>...</x>
</code></pre>
<p>I want to get a collection of values inside <code><y></y></code> tags located inside a given <code><x></code> tag, so the result of the above example would be a collection of two elements ["a","b"].</p>
<p>Additionally, we know that:</p>
<ul>
<li><code><y></code> tags cannot be enclosed in other <code><y></code> tags </li>
<li><code>...</code> can include any text or other tags.</li>
</ul>
<p>How can I achieve this with RegExp?</p>
| [
{
"answer_id": 340603,
"author": "Tomalak",
"author_id": 18771,
"author_profile": "https://Stackoverflow.com/users/18771",
"pm_score": 2,
"selected": false,
"text": "\"y\" tags cannot be enclosed in other \"y\" tags\n\ninput looks like: <x>...<y>a</y>...<y>b</y>...</x>\n <x[^>]*>(.*?)</x>\n <y[^>]*>(.*?)</y>\n input = \"<x>...<y>a</y>...<y>b</y>...</x>\"\nx_re = \"<x[^>]*>(.*?)</x>\"\ny_re = \"<y[^>]*>(.*?)</y>\"\n\nfor each x_match in input.match_all(x_re)\n for each y_match in x_match.group(1).value.match_all(y_re)\n print y_match.group(1).value\n next y_match\nnext x_match\n a\nb\n"
},
{
"answer_id": 342557,
"author": "Alan Moore",
"author_id": 20938,
"author_profile": "https://Stackoverflow.com/users/20938",
"pm_score": 0,
"selected": false,
"text": "String str = \"<y>c</y>...<x>...<y>a</y>...<y>b</y>...</x>...<y>d</y>\";\nString regex = \"<y[^>]*+>(?=(?:[^<]++|<(?!/?+x\\\\b))*+</x>)(.*?)</y>\";\nMatcher m = Pattern.compile(regex).matcher(str);\nwhile (m.find())\n{\n System.out.println(m.group(1));\n}\n <y> </x> <x>"
}
] | 2008/12/04 | [
"https://Stackoverflow.com/questions/340543",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
340,546 | <p>It is advised to use override instead of new key word in C#. Why that rule?</p>
| [
{
"answer_id": 340554,
"author": "Jon Skeet",
"author_id": 22656,
"author_profile": "https://Stackoverflow.com/users/22656",
"pm_score": 5,
"selected": true,
"text": "Base b = new Derived();\nDerived d = new Derived();\nb.MyMethod(); // Calls Base.MyMethod\nd.MyMethod(); // Calls Derived.MyMethod\n"
}
] | 2008/12/04 | [
"https://Stackoverflow.com/questions/340546",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/38807/"
] |
340,548 | <p>I'm writing some tests in Perl which have a fair amount of set up. This setup all lives in a module that the test scripts <code>use</code>. I want to be able to print some diagnostics from the module, and intended to use the <code>diag</code> function from <code>Test::More</code>. Problem is, when you <code>use Test::More</code>, it writes the plan so I get </p>
<blockquote>
<p>You tried to plan twice at lib/MyTest.pm line 15.</p>
</blockquote>
<p>Is there any way I can use <code>diag</code> (or is there an equivalent), or am I stuck with <code>print STDERR</code>?</p>
| [
{
"answer_id": 340554,
"author": "Jon Skeet",
"author_id": 22656,
"author_profile": "https://Stackoverflow.com/users/22656",
"pm_score": 5,
"selected": true,
"text": "Base b = new Derived();\nDerived d = new Derived();\nb.MyMethod(); // Calls Base.MyMethod\nd.MyMethod(); // Calls Derived.MyMethod\n"
}
] | 2008/12/04 | [
"https://Stackoverflow.com/questions/340548",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6402/"
] |
340,553 | <p>What is the best way to send HTTP requests from Windows Powershell?</p>
| [
{
"answer_id": 340570,
"author": "Thomas Bratt",
"author_id": 15985,
"author_profile": "https://Stackoverflow.com/users/15985",
"pm_score": 6,
"selected": true,
"text": "$page = (New-Object System.Net.WebClient).DownloadString(\"http://localhost/\")\n"
},
{
"answer_id": 21857868,
"author": "Kamarey",
"author_id": 86296,
"author_profile": "https://Stackoverflow.com/users/86296",
"pm_score": 4,
"selected": false,
"text": "$page = Invoke-WebRequest \"http://localhost/\"\n"
}
] | 2008/12/04 | [
"https://Stackoverflow.com/questions/340553",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15985/"
] |
340,562 | <p>In Java (And in general) is there a way to make a class so public that it's methods etc... are accessible from little classes all around that don't even instantiate it? Ha, what I mean is... If I have a daddy class that has a method <code>draw()</code> and it instantiates a baby class called Hand and one called Deck, and then deck instantiates a babier class called Card that has a method <code>play()</code>, is there a way for <code>Play()</code> to then call <code>Draw()</code> from the daddy class?</p>
<p>The idea here is that... the daddy class says "Deck! play(card)!" and then deck says "Card! play()!" and then play turns around and says "Hey daddy! Draw()!"</p>
<p>PS the idea is that... in a CCG every card has a "play()" method that is different but they are all essentially called in the same way. The opportunity to play the card comes around, and you call play on it. But the card doesn't do anything internal to itself: no no, it calls a number of methods from the rules of the game, which is has visibility to. So, like, a card in MTG that says "draw one card. Deal one damage to target player." is calling draw(player, 1) and dealDamage(player, 1) which are presumably not in the card itself... since they effect variables presumably instantiated by the players when they started the game and agreed on life totals and rules such as what "draw" means?</p>
<p>(meta-question: as usual, could someone please rename this question so that it reflects what I am asking... being a beginner is so frustrating!)</p>
| [
{
"answer_id": 340590,
"author": "Bill the Lizard",
"author_id": 1288,
"author_profile": "https://Stackoverflow.com/users/1288",
"pm_score": 3,
"selected": true,
"text": "class Daddy {\n public foo(){...}\n public createBaby(){\n Baby baby = new Baby(this);\n // baby now has a reference to Daddy\n }\n}\n\n\nclass Baby {\n Daddy daddy;\n public Baby(Daddy daddy){\n this.daddy = daddy;\n }\n ...\n public callDaddy(){\n daddy.foo();\n }\n}\n"
},
{
"answer_id": 340654,
"author": "James",
"author_id": 41039,
"author_profile": "https://Stackoverflow.com/users/41039",
"pm_score": 0,
"selected": false,
"text": "public class OuterClass{\n int x\n private class InnerClass{\n InnerClass(){\n x = 10;\n }\n }\n}\n"
}
] | 2008/12/04 | [
"https://Stackoverflow.com/questions/340562",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/29182/"
] |
340,568 | <p>I'm trying to find an zip compression and encryption component with <a href="http://www.networkworld.com/careers/2004/0315manonline.html" rel="noreferrer">encryption suitable for use by the US Federal Government</a>, so I can't use Zip 2.0 encryption, it has to be AES or the like. I've already found <a href="http://www.icsharpcode.net/OpenSource/SharpZipLib/" rel="noreferrer">SharpZipLib</a> (can't do AES encyrption), and <a href="http://www.chilkatsoft.com/downloads.asp" rel="noreferrer">Chilkat</a> (can do AES encryption, but costs money). Am I missing any other options?</p>
| [
{
"answer_id": 410446,
"author": "Cheeso",
"author_id": 48082,
"author_profile": "https://Stackoverflow.com/users/48082",
"pm_score": 5,
"selected": true,
"text": " using (ZipFile zip = new ZipFile())\n {\n zip.AddFile(\"ReadMe.txt\"); // no password for this entry\n\n // use a password for subsequent entries\n zip.Password= \"This.Encryption.is.FIPS.197.Compliant!\";\n zip.Encryption= EncryptionAlgorithm.WinZipAes256;\n zip.AddFile(\"Rawdata-2008-12-18.csv\");\n zip.Save(\"Backup-AES-Encrypted.zip\");\n }\n"
}
] | 2008/12/04 | [
"https://Stackoverflow.com/questions/340568",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/33264/"
] |
340,608 | <p>So I was thinking about creating a dynamic sql question, meaning that i want the amount of parameters to be dynamic.</p>
<p>Having looked at this: <a href="https://stackoverflow.com/questions/337704/parameterizing-a-sql-in-clause#337725">Parameterize an SQL IN clause</a> i was thinking that using like '%x%' is SLOW and not good.</p>
<p>What i actually would like to do is using the IN keyword and have it somewhat like this:</p>
<p>select UserId from NameTable where Name IN (@List_of_names)</p>
<p>Where the @List_of_names could contain i.e. </p>
<ul>
<li>Filip Ekberg</li>
<li>Filip</li>
<li>Ekberg Filip</li>
<li>Ekberg</li>
<li>Johan Ekberg</li>
<li>Johan</li>
</ul>
<p>( my second name is johan, thats why it's in there ,) )</p>
<p>So all these should match up with Johan Filip Ekberg.</p>
<p>I want to be using either LINQ to SQL or LINQ to SQL ( Stored Procedure ) using C#.</p>
<p>Suggestions and thoughts please!</p>
<p>----------------- Clearification of scenario and tables -------------------------</p>
<p>Imagine i have the following: A table with Users, A table with Names and a Table that connects the Names to a certain user.</p>
<p>So by having</p>
<pre><code>[User Table]
User ID Full Name
1 Johan Filip Ekberg
2 Anders Ekberg
[Names]
Name ID Name
1 Filip
2 Ekberg
3 Johan
4 Anders
[Connect Names]
Name ID User ID
1 1
2 1
3 1
2 4
2 2
</code></pre>
<p>So if i want to look for: Ekberg</p>
<p>The return should be:</p>
<ul>
<li>Johan Filip Ekberg</li>
<li>Anders Ekberg</li>
</ul>
<p>If i want to search for Johan Ekberg</p>
<ul>
<li>Johan Filip Ekberg</li>
</ul>
<p>If i want to search for Anders</p>
<ul>
<li>Anders Ekberg</li>
</ul>
<p>The amount of "search names" can be infinite, if i have the name: Johan Anders Carl Filip Ekberg ( This is just 1 person with many names ) and i just pass "Carl Filip" in, i want to find that User.</p>
<p>Does this make everything clearer?</p>
| [
{
"answer_id": 340630,
"author": "Sergiu Damian",
"author_id": 41345,
"author_profile": "https://Stackoverflow.com/users/41345",
"pm_score": 1,
"selected": false,
"text": "SELECT UserId FROM NameTable WHERE CHARINDEX( '|' + Name + '|', '|Filip Ekberg|Filip|Ekberg Filip|') > 0\n"
},
{
"answer_id": 341003,
"author": "Tom H",
"author_id": 5696608,
"author_profile": "https://Stackoverflow.com/users/5696608",
"pm_score": 3,
"selected": true,
"text": "SELECT DISTINCT\n CN.user_id\nFROM\n dbo.Names N\nINNER JOIN dbo.Connect_Names CN ON CN.name_id = N.name_id\nINNER JOIN dbo.GetTableFromNameList(@names) T ON T.name = N.name\n SELECT\n CN.user_id\nFROM\n dbo.Names N\nINNER JOIN dbo.Connect_Names CN ON CN.name_id = N.name_id\nINNER JOIN dbo.GetTableFromNameList(@names) T ON T.name = N.name\nGROUP BY CN.user_id\nHAVING COUNT(*) = (SELECT COUNT(*) FROM dbo.GetTableFromNameList(@names))\n"
},
{
"answer_id": 341226,
"author": "Amy B",
"author_id": 8155,
"author_profile": "https://Stackoverflow.com/users/8155",
"pm_score": 1,
"selected": false,
"text": "List<string> targets = new List<string>() {\"Johan\", \"Ekberg\"};\nint targetCount = targets.Count;\n//\nList<Users> result = \n dc.Names\n .Where(n => targets.Contains(n.Name))\n .SelectMany(n =>\n dc.ConnectNames.Where(cn => cn.NameId == n.NameId)\n )\n .GroupBy(cn => cn.UserId)\n .Where(g => g.Count() == targetCount)\n .SelectMany(g =>\n dc.Users.Where(u => u.UserId == g.Key)\n )\n .ToList();\n"
}
] | 2008/12/04 | [
"https://Stackoverflow.com/questions/340608",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/39106/"
] |
340,610 | <p>It is not possible to fire an event in C# that has no handlers attached to it. So before each call it is necessary to check if the event is null.</p>
<pre><code>if ( MyEvent != null ) {
MyEvent( param1, param2 );
}
</code></pre>
<p>I would like to keep my code as clean as possible and get rid of those null checks. I don't think it will affect performance very much, at least not in my case.</p>
<pre><code>MyEvent( param1, param2 );
</code></pre>
<p>Right now I solve this by adding an empty inline handler to each event manually. This is error prone, since I need to remember to do that etc.</p>
<pre><code>void Initialize() {
MyEvent += new MyEvent( (p1,p2) => { } );
}
</code></pre>
<p>Is there a way to generate empty handlers for all events of a given class automatically using reflection and some CLR magic?</p>
| [
{
"answer_id": 340618,
"author": "Dinah",
"author_id": 356,
"author_profile": "https://Stackoverflow.com/users/356",
"pm_score": 8,
"selected": true,
"text": "public delegate void MyClickHandler(object sender, string myValue);\npublic event MyClickHandler Click = delegate {}; // add empty delegate!\n\n//Let you do this:\npublic void DoSomething() {\n Click(this, \"foo\");\n}\n\n//Instead of this:\npublic void DoSomething() {\n if (Click != null) // Unnecessary!\n Click(this, \"foo\");\n}\n"
},
{
"answer_id": 340620,
"author": "leppie",
"author_id": 15541,
"author_profile": "https://Stackoverflow.com/users/15541",
"pm_score": 3,
"selected": false,
"text": "MyEvent += delegate { };\n"
},
{
"answer_id": 340638,
"author": "TcKs",
"author_id": 20382,
"author_profile": "https://Stackoverflow.com/users/20382",
"pm_score": 6,
"selected": false,
"text": "if ( MyEvent != null ) {\n MyEvent( param1, param2 );\n}\n EventHandler handler = this.MyEvent;\nif ( null != handler ) { handler( param1, param2 ); }\n static void RaiseEvent( EventHandler handler, object sender, EventArgs e ) {\n if ( null != handler ) { handler( sender, e ); }\n}\n RaiseEvent( MyEvent, param1, param2 );\n static void Raise( this EventHandler handler, object sender, EventArgs e ) {\n if ( null != handler ) { handler( sender, e ); }\n}\n MyEvent.Raise( param1, param2 );\n static void Raise<TEventArgs>( this EventHandler<TEventArgs> handler,\n object sender, TEventArgs e ) where TEventArgs : EventArgs\n{\n if ( null != handler ) { handler( sender, e ); }\n}\n"
},
{
"answer_id": 701495,
"author": "vkelman",
"author_id": 236391,
"author_profile": "https://Stackoverflow.com/users/236391",
"pm_score": 3,
"selected": false,
"text": "public static class EventHandlerExtensions {\n public static void Raise<T>(this EventHandler<T> handler, object sender, T args) where T : EventArgs {\n if (handler != null) handler(sender, args);\n }\n}\n"
},
{
"answer_id": 4824099,
"author": "naasking",
"author_id": 144873,
"author_profile": "https://Stackoverflow.com/users/144873",
"pm_score": 1,
"selected": false,
"text": "if (someDelegate != null) someDelegate(x, y, z);\n someDelegate.Raise(x, y, z);\n event Action fooEvent;\n...\nlock (someDummyObject) fooEvent += newHandler;\n Action fooEvent;\n...\nEvents.Add(ref fooEvent, newHandler);\n"
},
{
"answer_id": 44452771,
"author": "gandaliter",
"author_id": 1669475,
"author_profile": "https://Stackoverflow.com/users/1669475",
"pm_score": 3,
"selected": false,
"text": "?. MyEvent?.Invoke(...) Invoke Invoke public delegate void MyClickHandler(object sender, string myValue);\npublic event MyClickHandler Click;\n\npublic void DoSomething() {\n Click?.Invoke(this, \"foo\");\n}\n"
}
] | 2008/12/04 | [
"https://Stackoverflow.com/questions/340610",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/35440/"
] |
340,622 | <p>Is there a shortcut key to bring up the call hierarchy of a method inline with the code, in the quick menu format, rather than bringing up the call hierarchy panel?</p>
| [
{
"answer_id": 49383362,
"author": "mani_drinks_coffee",
"author_id": 1315254,
"author_profile": "https://Stackoverflow.com/users/1315254",
"pm_score": 2,
"selected": false,
"text": "alt"
}
] | 2008/12/04 | [
"https://Stackoverflow.com/questions/340622",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/42491/"
] |
340,623 | <p>I understand that programming to interfaces helps with loose coupling. However, is there a guideline that explains when its most effective?</p>
<p>For example, I have a simple web application that collects data on employees, their training plans, expenses and computes their expense for the year etc. This is a fairly simple application and I can of course use an interface but wonder if there would be any use. I will be using it for the sake of using it.</p>
<p>It can always be argued that as the application grows in complexity and I pass around objects it would make more sense to pass the type (interface) than an implementation. So, should I wait for the application to become complex or use it right away? I'm wondering the best practice might turn out to be "this guy is over doing things".</p>
| [
{
"answer_id": 340665,
"author": "terjetyl",
"author_id": 29519,
"author_profile": "https://Stackoverflow.com/users/29519",
"pm_score": 2,
"selected": false,
"text": "class SimpleClass\n{\n public int A { get; set; }\n public int B { get; set; }\n public int C { get; set; }\n}\n\nList<SimpleClass> Calc(IEnumerable<SimpleClass> list)\n{\n foreach(SimpleClass item in list)\n {\n item.C = item.A * item.C:\n }\n return list.ToList();\n}\n List<SimpleClass>, SimpleClass[], Collection<SimpleClass>"
},
{
"answer_id": 345299,
"author": "snogfish",
"author_id": 13863,
"author_profile": "https://Stackoverflow.com/users/13863",
"pm_score": 1,
"selected": false,
"text": "public class Employee {\n private IExpenseCalculator expenses;\n\n public ExpenseSheet GetExpenses() {\n return expenses.CalcExpenses();\n }\n}\n"
}
] | 2008/12/04 | [
"https://Stackoverflow.com/questions/340623",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/40070/"
] |
340,627 | <p>I need to parse Visual Studio automatically generated XML documentation to create a report. I decided to use XSLT but I'm very new to it and need help.
Common template is:</p>
<pre><code><doc>
<members>
<member name="F:MyNamespace">
<summary>Some text</summary>
</member>
</members>
</doc>
</code></pre>
<p>I want to isolate members with name which begins on some word, for example, P:Interfaces.Core. I decided to use RegExp in select statement.</p>
<pre><code><?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:fn="http://www.w3.org/TR/xpath-functions/">
<xsl:template match="/" >
<html xmlns="http://www.w3.org/1999/xhtml">
<body style="font-family:Tahoma">
<p>Interfaces list:</p>
<table>
<xsl:for-each select="doc/members/member">
<xsl:sort order="ascending" />
<xsl:value-of select="fn:matches(., 'P\..+')" />
<br />
</xsl:for-each>
</table>
</body>
</html>
</xsl:template>
</xsl:stylesheet>
</code></pre>
<p>Why does I'm getting error:</p>
<blockquote>
<p>Namespace <a href="http://www.w3.org/TR/xpath-functions" rel="nofollow noreferrer">http://www.w3.org/TR/xpath-functions</a> does not contain any functions ></p>
</blockquote>
<p>Where am I wrong? I found such code in examples, including w3c.org!</p>
| [
{
"answer_id": 340865,
"author": "Dimitre Novatchev",
"author_id": 36305,
"author_profile": "https://Stackoverflow.com/users/36305",
"pm_score": 4,
"selected": true,
"text": "XslCompiledTransform XslTransform starts-with() starts-with(., 'P:Interfaces') true() false() contains() ends-with() ends-with(s1, s2) substring string-length string-length === substring() string-length()"
}
] | 2008/12/04 | [
"https://Stackoverflow.com/questions/340627",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/41956/"
] |
340,645 | <p>Let's say I have a simple chunck of XML:-</p>
<pre><code><root>
<item forename="Fred" surname="Flintstone" />
<item forename="Barney" surname="Rubble" />
</root>
</code></pre>
<p>Having fetched this XML in Silverlight I would like to bind it with <a href="http://en.wikipedia.org/wiki/Extensible_Application_Markup_Language" rel="nofollow noreferrer">XAML</a> of this ilke:-</p>
<pre><code><ListBox x:Name="ItemList" Style="{StaticResource Items}">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<TextBox Text="{Binding Forename}" />
<TextBox Text="{Binding Surname}" />
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</code></pre>
<p>Now I can bind simply enough with LINQ to XML and a nominal class:-</p>
<pre><code>public class Person {
public string Forename {get; set;}
public string Surname {get; set;}
}
</code></pre>
<p>Can it be done without this class?</p>
<p>In other words, coupling between the Silverlight code and the input XML is limited to the XAML only, other source code is agnostic to the set of attributes on the item element.</p>
<p><strong>Edit</strong>: The use of XSD is suggested but ultimately it amounts the same thing. XSD->Generated class.</p>
<p><strong>Edit</strong>: An anonymous class doesn't work, Silverlight can't bind them.</p>
<p><strong>Edit</strong>: This needs to be two way, the user needs to be able to edit the values and these values end up in the XML. (Changed original TextBlock to TextBox in sample above.)</p>
| [
{
"answer_id": 341358,
"author": "Bryant",
"author_id": 10893,
"author_profile": "https://Stackoverflow.com/users/10893",
"pm_score": 2,
"selected": false,
"text": "public class XAttributeConverter : IValueConverter\n{\n public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)\n {\n var xml = value as XElement;\n var name = parameter as string;\n return xml.Attribute(name).Value;\n }\n}\n <ListBox x:Name=\"ItemList\">\n <ListBox.Resources>\n <local:XAttributeConverter x:Name=\"xcvt\" />\n </ListBox.Resources>\n <ListBox.ItemTemplate>\n <DataTemplate>\n <StackPanel Orientation=\"Horizontal\">\n <TextBlock Text=\"{Binding Converter={StaticResource xcvt}, ConverterParameter=forename}\" />\n <TextBlock Text=\"{Binding Converter={StaticResource xcvt}, ConverterParameter=surname}\" />\n </StackPanel>\n </DataTemplate>\n </ListBox.ItemTemplate>\n</ListBox>\n XElement xml = XElement.Parse(\"<root><item forename='Fred' surname='Flintstone' /><item forename='Barney' surname='Rubble' /></root>\");\n\nItemList.ItemsSource = xml.Descendants(\"item\");\n"
},
{
"answer_id": 341551,
"author": "MojoFilter",
"author_id": 93,
"author_profile": "https://Stackoverflow.com/users/93",
"pm_score": 0,
"selected": false,
"text": "var data = from c in xml.Descendants(\"item\")\n select new { Forename = c.Attribute(\"forename\").Value, \n Surname = c.Attribute(\"surname\").Value };\nItemList.ItemsSource = data\n"
}
] | 2008/12/04 | [
"https://Stackoverflow.com/questions/340645",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17516/"
] |
340,657 | <p>Is there a way to just tell the compiler, that I want my objects to be serializable by default?</p>
| [
{
"answer_id": 342178,
"author": "Marc Gravell",
"author_id": 23354,
"author_profile": "https://Stackoverflow.com/users/23354",
"pm_score": 3,
"selected": true,
"text": "[Serializable] ISerializable BinaryFormatter SoapFormatter [Serializable] IXmlSerializable public XmlSerializer [DataContract] [MessageContract] DataContractSerializer"
}
] | 2008/12/04 | [
"https://Stackoverflow.com/questions/340657",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1220/"
] |
340,696 | <p>Does cygwin allow a statically compiled binary? This would prevent the need for cygwin1.dll being on the PATH of target machines.</p>
| [
{
"answer_id": 27370738,
"author": "chenwj",
"author_id": 577251,
"author_profile": "https://Stackoverflow.com/users/577251",
"pm_score": 4,
"selected": false,
"text": "-mno-cygwin x86_64-w64-mingw32-gcc"
},
{
"answer_id": 44076504,
"author": "Peter Schultz",
"author_id": 2480447,
"author_profile": "https://Stackoverflow.com/users/2480447",
"pm_score": 2,
"selected": false,
"text": "x86_64-w64-mingw32-gcc.exe main.c -o main.exe\n"
}
] | 2008/12/04 | [
"https://Stackoverflow.com/questions/340696",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5823/"
] |
340,708 | <p>I want to use jQuery with a GridView which contains textboxes, but I'm stuck on how to get event listeners registered for every textbox on the selected row. I was thinking I could do something with a StingBuilder in the Unload event of the GridView but I can't get it working.</p>
| [
{
"answer_id": 340795,
"author": "BigJump",
"author_id": 8542,
"author_profile": "https://Stackoverflow.com/users/8542",
"pm_score": 2,
"selected": true,
"text": "<asp:GridView runat=\"server\">\n <Columns>\n <asp:BoundField ControlStyle-CssClass=\"someclass\" DataField=\"xxx\" />\n </Columns>\n</asp:GridView>\n $().ready(function() {\n $(\".someclass\").function() {\n //do something interesting\n }\n});\n"
}
] | 2008/12/04 | [
"https://Stackoverflow.com/questions/340708",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/30512/"
] |
340,717 | <p>Seeing this: <a href="http://www.suckless.org/wiki.html" rel="nofollow noreferrer">http://www.suckless.org/wiki.html</a>. A wiki based on Mercurial. Are there any other non-code related use to version control? Is there any other projects that uses version control tools inside instead of programming their own specific solution?</p>
| [
{
"answer_id": 340731,
"author": "Joachim Sauer",
"author_id": 40342,
"author_profile": "https://Stackoverflow.com/users/40342",
"pm_score": 3,
"selected": false,
"text": "/etc"
},
{
"answer_id": 7585122,
"author": "Félix Saparelli",
"author_id": 231788,
"author_profile": "https://Stackoverflow.com/users/231788",
"pm_score": 0,
"selected": false,
"text": "git tree"
}
] | 2008/12/04 | [
"https://Stackoverflow.com/questions/340717",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/39057/"
] |
340,748 | <p>I was writing some code, and I notice a pattern in the exception handling that got me thinking:</p>
<pre><code>try{
// do stuff... throws JMS, Create and NamingException
} catch (NamingException e) {
log1(e);
rollback();
doSomething(e)
} catch (CreateException e) {
log1(e);
rollback();
doSomething(e)
}
</code></pre>
<p>Where JMSException would be handle some where up in the stack.</p>
<p>Would it be to just write:</p>
<pre><code>try{
// do stuff... throws JMS, Create and NamingException
} catch Exception[NamingException, CreateException] e) {
log1(e);
rollback();
doSomething(e)
}
</code></pre>
<p>instead of putting it in tu a helper method:</p>
<pre><code>try{
// do stuff... throws JMS, Create and NamingException
} catch (NamingException e) {
helper_handleError1(e)
} catch (CreateException e) {
helper_handleError1(e)
}
</code></pre>
<p>Notice that I want to propagate stacktrace of the original JMSException, and I don't "feel like" creating an new JMSException with a third catch clause :)</p>
<p>Any toughs? Is this an extreme situation that would only pollute the syntax of Java, or just a cool thing to add?</p>
| [
{
"answer_id": 340785,
"author": "defnull",
"author_id": 407880,
"author_profile": "https://Stackoverflow.com/users/407880",
"pm_score": 0,
"selected": false,
"text": "try {\n ...\n} catch ( Exception e) {\n if typeof(e) not in ('MyException', 'SpecialException') {\n throw e\n }\n doSomething()\n}\n"
},
{
"answer_id": 340791,
"author": "luiscubal",
"author_id": 32775,
"author_profile": "https://Stackoverflow.com/users/32775",
"pm_score": 0,
"selected": false,
"text": "} catch Exception[NamingException, CreateException] e) {\n void doYellow(NamingException e);\nvoid doYellow(CreateException e);\n"
},
{
"answer_id": 340807,
"author": "Dennis C",
"author_id": 40214,
"author_profile": "https://Stackoverflow.com/users/40214",
"pm_score": 0,
"selected": false,
"text": "try{\n try{\n // do stuff... throws JMS, Create and NamingException\n } catch (NamingException e) {\n throw new MyException(e);\n } catch (CreateException e) {\n throw new MyException(e);\n }\n} catch (MyException e) {\n // something on e or e.getCause();\n}\n"
},
{
"answer_id": 340809,
"author": "Paul Tomblin",
"author_id": 3333,
"author_profile": "https://Stackoverflow.com/users/3333",
"pm_score": 0,
"selected": false,
"text": "try\n{\n // do stuff... throws JMS, Create and NamingException\n} catch (JMSException e) \n{ \n if (e instanceof CreateException || e instanceof NamingExcption)\n { \n log1(e);\n rollback();\n doSomething(e);\n }\n else\n throw e;\n}\n"
},
{
"answer_id": 340834,
"author": "Joel Coehoorn",
"author_id": 3043,
"author_profile": "https://Stackoverflow.com/users/3043",
"pm_score": 2,
"selected": false,
"text": "try\n{\n // do stuff ...\n}\ncatch (NamingException e)\ncatch (CreateException e)\n{\n log1(e);\n rollback();\n doSoemthing(e);\n}\n using"
}
] | 2008/12/04 | [
"https://Stackoverflow.com/questions/340748",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/35323/"
] |
340,787 | <p>I have a XML with a structure similar to this:</p>
<pre><code><category>
<subCategoryList>
<category>
</category>
<category>
<!--and so on -->
</category>
</subCategoryList>
</category>
</code></pre>
<p>I have a Category class that has a <code>subcategory</code> list (<code>List<Category></code>). I'm trying to parse this XML file with XPath, but I can't get the child categories of a category. </p>
<p>How can I do this with XPath? Is there a better way to do this?</p>
| [
{
"answer_id": 340831,
"author": "sblundy",
"author_id": 4893,
"author_profile": "https://Stackoverflow.com/users/4893",
"pm_score": 2,
"selected": false,
"text": "//category/subCategoryList/category category /category/subCategoryList/category"
},
{
"answer_id": 340832,
"author": "kgiannakakis",
"author_id": 24054,
"author_profile": "https://Stackoverflow.com/users/24054",
"pm_score": 0,
"selected": false,
"text": "NodeList nodes = (NodeList) xpath.evaluate(\"//category//subCategoryList/category\",\ninputSource, XPathConstants.NODESET);\n"
},
{
"answer_id": 2818246,
"author": "ripper234",
"author_id": 11236,
"author_profile": "https://Stackoverflow.com/users/11236",
"pm_score": 5,
"selected": true,
"text": " public static void main(String[] args) \n throws ParserConfigurationException, SAXException, \n IOException, XPathExpressionException {\n\n DocumentBuilderFactory domFactory = \n DocumentBuilderFactory.newInstance();\n domFactory.setNamespaceAware(true); \n DocumentBuilder builder = domFactory.newDocumentBuilder();\n Document doc = builder.parse(\"persons.xml\");\n XPath xpath = XPathFactory.newInstance().newXPath();\n // XPath Query for showing all nodes value\n XPathExpression expr = xpath.compile(\"//person/*/text()\");\n\n Object result = expr.evaluate(doc, XPathConstants.NODESET);\n NodeList nodes = (NodeList) result;\n for (int i = 0; i < nodes.getLength(); i++) {\n System.out.println(nodes.item(i).getNodeValue()); \n }\n }\n"
}
] | 2008/12/04 | [
"https://Stackoverflow.com/questions/340787",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/314728/"
] |
340,790 | <p>I have the following problem: Multithreaded WPF application, Model View Presenter Implementation. Presenters and Views that belong together are created on a separate thread and get a separate Dispatcher. Now someone calls from another thread a method on the Presenter. I am intercepting the call, and now begins the problem: if the call comes from the same thread as the presenter, i want to proceed with the call, else invoke the call on the Dispatcherthread, so that i don't need to care about UI calls.
I have already read about the use of SynchronizationContext, but that doesnt seem to work for me because if the calling thread is no UI thread i can't compare the 2 contexts. Whats a possible, working and elegant solution ?</p>
| [
{
"answer_id": 340968,
"author": "jyoung",
"author_id": 14841,
"author_profile": "https://Stackoverflow.com/users/14841",
"pm_score": 2,
"selected": false,
"text": "if( presenterDispatcherObject.CheckAccess() )\n Doit();\nelse\n presenterDispatcherObject.BeginInvoke( DispatcherPriority.Normal, () => DoIt() ); \n"
},
{
"answer_id": 342754,
"author": "John Z",
"author_id": 43430,
"author_profile": "https://Stackoverflow.com/users/43430",
"pm_score": 0,
"selected": false,
"text": "public delegate bool MyFuncHandler(object arg);\n\nbool ThreadedMyFunc(object arg)\n{\n //...\n\n bool result;\n\n //...\n\n // use dispatcher passed in, I would pass into the contructor of your class\n if (dispatcher.CheckAccess())\n {\n result = MyFunc(arg);\n }\n else\n {\n result = dispatcher.Invoke(new MyFuncHandler(MyFunc), arg);\n }\n\n return result;\n}\n\nbool MyFunc(object arg)\n{\n //...\n}\n"
}
] | 2008/12/04 | [
"https://Stackoverflow.com/questions/340790",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
340,816 | <p>How can I send keyboard input messages to either the currently selected window or the previously selected window? </p>
<p>I have a program which I use to type some characters which are not present on my keyboard and I would like it if I could just send the input directly rather than me having to copy and paste all the time.</p>
<p>EDIT:</p>
<p>The application of this is typing the German Umlauts. I'm an American and I work in Germany. I'm working on an American keyboard and from time to time I have to type in the umlauts / the euro symbol / the sharp S. Currently I have a simple WinForms application with a textfield and some buttons with the extra characters on it. I type into the textfield and I can press the buttons to append text to the textfield. I then copy the text and paste it where ever. What would be nice though if I could just just hit one of the buttons and it would send the text where ever I'm typing / was typing. The current program works fairly well but I could make it better.</p>
| [
{
"answer_id": 340883,
"author": "Patrick Desjardins",
"author_id": 13913,
"author_profile": "https://Stackoverflow.com/users/13913",
"pm_score": 0,
"selected": false,
"text": "myField.Text += \"®\"; //This is a char that I do not have on my keyboard\n"
}
] | 2008/12/04 | [
"https://Stackoverflow.com/questions/340816",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/26566/"
] |
340,827 | <p>I am attempting to mock a call to an indexed property. I.e. I would like to moq the following:</p>
<pre><code>object result = myDictionaryCollection["SomeKeyValue"];
</code></pre>
<p>and also the setter value</p>
<pre><code>myDictionaryCollection["SomeKeyValue"] = myNewValue;
</code></pre>
<p>I am doing this because I need to mock the functionality of a class my app uses. </p>
<p>Does anyone know how to do this with MOQ? I've tried variations on the following:</p>
<pre><code>Dictionary<string, object> MyContainer = new Dictionary<string, object>();
mock.ExpectGet<object>( p => p[It.IsAny<string>()]).Returns(MyContainer[(string s)]);
</code></pre>
<p>But that doesn't compile.</p>
<p>Is what I am trying to achieve possible with MOQ, does anyone have any examples of how I can do this?</p>
| [
{
"answer_id": 359123,
"author": "Mike Scott",
"author_id": 43649,
"author_profile": "https://Stackoverflow.com/users/43649",
"pm_score": 7,
"selected": false,
"text": "MyContainer[(string s)] var mock = new Mock<IDictionary>();\nmock.SetupGet( p => p[It.IsAny<string>()]).Returns(\"foo\");\n"
},
{
"answer_id": 861282,
"author": "wasker",
"author_id": 21952,
"author_profile": "https://Stackoverflow.com/users/21952",
"pm_score": 4,
"selected": false,
"text": "/// <summary>\n/// HTTP session mockup.\n/// </summary>\ninternal sealed class HttpSessionMock : HttpSessionStateBase\n{\n private readonly Dictionary<string, object> objects = new Dictionary<string, object>();\n\n public override object this[string name]\n {\n get { return (objects.ContainsKey(name)) ? objects[name] : null; }\n set { objects[name] = value; }\n }\n}\n\n/// <summary>\n/// Base class for all controller tests.\n/// </summary>\npublic class ControllerTestSuiteBase : TestSuiteBase\n{\n private readonly HttpSessionMock sessionMock = new HttpSessionMock();\n\n protected readonly Mock<HttpContextBase> Context = new Mock<HttpContextBase>();\n protected readonly Mock<HttpSessionStateBase> Session = new Mock<HttpSessionStateBase>();\n\n public ControllerTestSuiteBase()\n : base()\n {\n Context.Expect(ctx => ctx.Session).Returns(sessionMock);\n }\n}\n"
},
{
"answer_id": 30086584,
"author": "JustEngland",
"author_id": 57263,
"author_profile": "https://Stackoverflow.com/users/57263",
"pm_score": 4,
"selected": false,
"text": "var request = new Moq.Mock<HttpRequestBase>();\nrequest.SetupGet(r => r[\"foo\"]).Returns(\"bar\");\n"
},
{
"answer_id": 37609853,
"author": "Vitaliy Ulantikov",
"author_id": 63867,
"author_profile": "https://Stackoverflow.com/users/63867",
"pm_score": 4,
"selected": false,
"text": "SetupGet SetupSet SetupGet SetupGet Setup internal static MethodCallReturn<T, TProperty> SetupGet<T, TProperty>(Mock<T> mock, Expression<Func<T, TProperty>> expression, Condition condition) where T : class\n{\n return PexProtector.Invoke<MethodCallReturn<T, TProperty>>((Func<MethodCallReturn<T, TProperty>>) (() =>\n {\n if (ExpressionExtensions.IsPropertyIndexer((LambdaExpression) expression))\n return Mock.Setup<T, TProperty>(mock, expression, condition);\n ...\n }\n ...\n}\n Dictionary var dictionary = new Dictionary<string, object>();\n\nvar applicationSettingsBaseMock = new Mock<SettingsBase>();\napplicationSettingsBaseMock\n .Setup(sb => sb[It.IsAny<string>()])\n .Returns((string key) => dictionary[key]);\napplicationSettingsBaseMock\n .SetupSet(sb => sb[\"Expected Key\"] = It.IsAny<object>())\n .Callback((string key, object value) => dictionary[key] = value);\n"
}
] | 2008/12/04 | [
"https://Stackoverflow.com/questions/340827",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/31128/"
] |
340,842 | <p>This works:</p>
<pre><code>constructor TMyObj.Create;
begin
inherited;
end;
</code></pre>
<p>Why this is not working also?</p>
<pre><code>function TMyObjEx.Import(CONST FileName: string; CONST x, y, z: Integer): string;
begin
result:= inherited; // Import(FileName, x, y, z); <--- Compiler says: "incompatible types"
//do other stuff here
end;
</code></pre>
<p>Declaration of TMyObjEx is like this:</p>
<pre><code>TYPE
TMyObj = class(TChObj)
private
protected
public
function Import (CONST FileName: string; CONST x, y, z: Integer): string; virtual;
end;
TMyObjEx= class(TMyObj)
private
protected
public
function Import(CONST FileName: string; CONST x, y, z: Integer): string; override;
end;
</code></pre>
| [
{
"answer_id": 340893,
"author": "Rob Kennedy",
"author_id": 33732,
"author_profile": "https://Stackoverflow.com/users/33732",
"pm_score": 1,
"selected": false,
"text": "inherited"
},
{
"answer_id": 342063,
"author": "Nick Hodges",
"author_id": 2044,
"author_profile": "https://Stackoverflow.com/users/2044",
"pm_score": 3,
"selected": false,
"text": "function TMyObjEx.Import(CONST FileName: string; CONST x, y, z: Integer): string;\nbegin\n result:= inherited Import(FileName, x, y, z); \n //do other stuff here\nend;\n"
}
] | 2008/12/04 | [
"https://Stackoverflow.com/questions/340842",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
340,850 | <blockquote>
<p><code>dict</code> methods <code>dict.keys()</code>, <code>dict.items()</code> and <code>dict.values()</code>
return “views” instead of lists.</p>
</blockquote>
<p><a href="https://docs.python.org/3/whatsnew/3.0.html#views-and-iterators-instead-of-lists" rel="nofollow noreferrer">Source</a></p>
<p>First of all, how is a view different from an iterator? Secondly, what is the benefit of this change? Is it just for performance reasons?</p>
<p>It doesn't seem intuitive to me, i.e., I'm asking for a list of things (give me all your keys) and I'm getting something else back. Will this confuse people?</p>
| [
{
"answer_id": 9023627,
"author": "max",
"author_id": 336527,
"author_profile": "https://Stackoverflow.com/users/336527",
"pm_score": 3,
"selected": false,
"text": "list iteritems elem in cont view in in def f():\n for i in range(10):\n yield i\n\n5 in f() # True\n in n O(n) in in O(1) >>> d = dict(zip(range(50000000), range(50000000)))\n>>> 49999999 in d\nTrue\n>>> 49999999 in iter(d) # kinda how generator function would work\nTrue\n>>>\n in in"
},
{
"answer_id": 26553373,
"author": "Antony Hatchkins",
"author_id": 237105,
"author_profile": "https://Stackoverflow.com/users/237105",
"pm_score": 0,
"selected": false,
"text": "len()"
}
] | 2008/12/04 | [
"https://Stackoverflow.com/questions/340850",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13009/"
] |
340,878 | <p>I'm having trouble setting up a scheduled task (now called Task Scheduler) under the actions tab to run on windows 2007 server. It also has exchange server 2007. </p>
<p>I've tried setting </p>
<p>Program/script : C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe
Add arguments (optional): -psconsolefile exshell.psc1 -command "& {c:\mes-detail\emsbilling08.ps1}"
Start in (optional): "C:\Program Files\Microsoft\Exchange Server\Bin\</p>
<p>I realize the exshell.psc1 probably also needs an explicit path so I've also tried:</p>
<p>-psconsolefile C:\Program Files\Microsoft\Exchange Server\Bin\exshell.psc1 -command "& {c:\mes-detail\mailall3.ps1}" as well but that doesn't work either</p>
<p>Any ideas? </p>
| [
{
"answer_id": 33798161,
"author": "uz-it",
"author_id": 3382897,
"author_profile": "https://Stackoverflow.com/users/3382897",
"pm_score": 0,
"selected": false,
"text": "Add-PSSnapin Microsoft.Exchange.Management.PowerShell.Admin\nAdd-PSSnapin Microsoft.Exchange.Management.PowerShell.Support\n"
}
] | 2008/12/04 | [
"https://Stackoverflow.com/questions/340878",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18853/"
] |
340,888 | <p>I've just done my first little webapp in django and I love it. I'm about to start on converting an old production PHP site into django and as part its template, there is a navigation bar.</p>
<p>In PHP, I check each nav option's URL against the current URL, in the template code and apply a CSS class if they line up. It's horrendously messy.</p>
<p>Is there something better for django or a good way of handling the code in the template?</p>
<p>To start, how would I go about getting the current URL?</p>
| [
{
"answer_id": 341713,
"author": "Michael Warkentin",
"author_id": 422277,
"author_profile": "https://Stackoverflow.com/users/422277",
"pm_score": 3,
"selected": false,
"text": "<body class=\"{{ nav_class }}\">\n body.home #nav_home,\nbody.about #nav_about { */ Current nav styles */ }\n"
},
{
"answer_id": 341748,
"author": "jpwatts",
"author_id": 21279,
"author_profile": "https://Stackoverflow.com/users/21279",
"pm_score": 7,
"selected": true,
"text": "<html>\n <head>...</head>\n <body>\n ...\n {% block nav %}\n <ul id=\"nav\">\n <li>{% block nav-home %}<a href=\"{% url 'home' %}\">Home</a>{% endblock %}</li>\n <li>{% block nav-about %}<a href=\"{% url 'about' %}\">About</a>{% endblock %}</li>\n <li>{% block nav-contact %}<a href=\"{% url 'contact' %}\">Contact</a>{% endblock %}</li>\n </ul>\n {% endblock %}\n ...\n </body>\n</html>\n {% extends \"base.html\" %}\n\n{% block nav-about %}<strong class=\"nav-active\">About</strong>{% endblock %}\n"
},
{
"answer_id": 343297,
"author": "Oli",
"author_id": 12870,
"author_profile": "https://Stackoverflow.com/users/12870",
"pm_score": 2,
"selected": false,
"text": "<li{{ link1_active }}>...link...</li>\n<li{{ link2_active }}>...link...</li>\n<li{{ link3_active }}>...link...</li>\n<li{{ link4_active }}>...link...</li>\n class=\"selected\" {'link1_active':' class=\"selected\"'} <li{% if link1_active %} class=\"selected\"{% endif %}>...link...</li>\n<li{% if link2_active %} class=\"selected\"{% endif %}>...link...</li>\n...\n"
},
{
"answer_id": 346759,
"author": "muhuk",
"author_id": 42188,
"author_profile": "https://Stackoverflow.com/users/42188",
"pm_score": 3,
"selected": false,
"text": "<a class=\"tab {% ifequal active_tab \"statistics\" %}active{% endifequal %}\" href=\"{% url Member.Statistics %}\">Statistics</a>\n {'active_tab': 'statistics'} RequestContext {{ request.path }}\n from django.template import RequestContext\n\ndef my_view(request):\n # do something awesome here\n return template.render(RequestContext(request, context_dict))\n"
},
{
"answer_id": 477719,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 7,
"selected": false,
"text": "@register.simple_tag\ndef active(request, pattern):\n import re\n if re.search(pattern, request.path):\n return 'active'\n return ''\n urlpatterns += patterns('',\n (r'/$', view_home_method, 'home_url_name'),\n (r'/services/$', view_services_method, 'services_url_name'),\n (r'/contact/$', view_contact_method, 'contact_url_name'),\n)\n {% load tags %}\n\n{% url 'home_url_name' as home %}\n{% url 'services_url_name' as services %}\n{% url 'contact_url_name' as contact %}\n\n<div id=\"navigation\">\n <a class=\"{% active request home %}\" href=\"{{ home }}\">Home</a>\n <a class=\"{% active request services %}\" href=\"{{ services }}\">Services</a>\n <a class=\"{% active request contact %}\" href=\"{{ contact }}\">Contact</a>\n</div>\n"
},
{
"answer_id": 656328,
"author": "nivhab",
"author_id": 79024,
"author_profile": "https://Stackoverflow.com/users/79024",
"pm_score": 5,
"selected": false,
"text": "from django import template\n\nregister = template.Library()\n\n@register.tag\ndef active(parser, token):\n args = token.split_contents()\n template_tag = args[0]\n if len(args) < 2:\n raise template.TemplateSyntaxError, \"%r tag requires at least one argument\" % template_tag\n return NavSelectedNode(args[1:])\n\nclass NavSelectedNode(template.Node):\n def __init__(self, patterns):\n self.patterns = patterns\n def render(self, context):\n path = context['request'].path\n for p in self.patterns:\n pValue = template.Variable(p).resolve(context)\n if path == pValue:\n return \"active\" # change this if needed for other bootstrap version (compatible with 3.2)\n return \"\"\n urlpatterns += patterns('',\n url(r'/$', view_home_method, {}, name='home_url_name'),\n url(r'/services/$', view_services_method, {}, name='services_url_name'),\n url(r'/contact/$', view_contact_method, {}, name='contact_url_name'),\n url(r'/contact/$', view_contact2_method, {}, name='contact2_url_name'),\n)\n {% load tags %}\n\n{% url home_url_name as home %}\n{% url services_url_name as services %}\n{% url contact_url_name as contact %}\n{% url contact2_url_name as contact2 %}\n\n<div id=\"navigation\">\n <a class=\"{% active request home %}\" href=\"home\">Home</a>\n <a class=\"{% active request services %}\" href=\"services\">Services</a>\n <a class=\"{% active request contact contact2 %}\" href=\"contact\">Contact</a>\n</div>\n"
},
{
"answer_id": 770912,
"author": "Thomas Schreiber",
"author_id": 93559,
"author_profile": "https://Stackoverflow.com/users/93559",
"pm_score": 2,
"selected": false,
"text": "def project_list(request, catslug):\n \"render the category detail page\"\n category = get_object_or_404(Category, slug=catslug, site__id__exact=settings.SITE_ID)\n context = {\n 'active_category': \n category,\n 'category': \n category,\n 'category_list': \n Category.objects.filter(site__id__exact=settings.SITE_ID),\n\n }\n <ul>\n {% for category in category_list %}\n <li class=\"tab{% ifequal active_category category %}-active{% endifequal %}\">\n <a href=\"{{ category.get_absolute_url }}\">{{ category.cat }}</a>\n </li>\n {% endfor %}\n</ul>\n"
},
{
"answer_id": 899993,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "def navigation(request):\n\"\"\"\nCustom context processor to set the navigation menu pointer.\n\"\"\"\nnav_pointer = ''\nif request.path == '/':\n nav_pointer = 'main'\nelif request.path.startswith('/services/'):\n nav_pointer = 'services'\nelif request.path.startswith('/other_stuff/'):\n nav_pointer = 'other_stuff'\nreturn {'nav_pointer': nav_pointer}\n"
},
{
"answer_id": 1401077,
"author": "Nino",
"author_id": 154268,
"author_profile": "https://Stackoverflow.com/users/154268",
"pm_score": 2,
"selected": false,
"text": "from django import template\nregister = template.Library()\n\n@register.tag\ndef ifnaviactive(parser, token):\n nodelist = parser.parse(('endifnaviactive',))\n parser.delete_first_token()\n\n import re\n args = token.split_contents()\n template_tag = args[0]\n if len(args) < 2:\n raise template.TemplateSyntaxError, \"%r tag requires at least one argument\" % template_tag\n return NavSelectedNode(args[1:], nodelist)\n\nclass NavSelectedNode(template.Node):\n def __init__(self, patterns, nodelist):\n self.patterns = patterns\n self.nodelist = nodelist\n\n def render(self, context):\n path = context['request'].path\n for p in self.patterns:\n pValue = template.Variable(p).resolve(context)\n if path == pValue:\n return self.nodelist.render(context)\n return \"\"\n {% url product_url as product %}\n\n{% ifnaviactive request product %}\n <ul class=\"subnavi\">\n <li>Subnavi item for product 1</li>\n ...\n </ul>\n{% endifnaviactive %}\n"
},
{
"answer_id": 1800535,
"author": "Andreas",
"author_id": 219001,
"author_profile": "https://Stackoverflow.com/users/219001",
"pm_score": 3,
"selected": false,
"text": "#current_nav.py\nfrom django import template\n\nregister = template.Library()\n\n@register.tag\ndef current_nav(parser, token):\n import re\n args = token.split_contents()\n template_tag = args[0]\n if len(args) < 2:\n raise template.TemplateSyntaxError, \"%r tag requires at least one argument\" % template_tag\n return NavSelectedNode(args[1])\n\nclass NavSelectedNode(template.Node):\n def __init__(self, url):\n self.url = url\n\n def render(self, context):\n path = context['request'].path\n pValue = template.Variable(self.url).resolve(context)\n if (pValue == '/' or pValue == '') and not (path == '/' or path == ''):\n return \"\"\n if path.startswith(pValue):\n return ' class=\"current\"'\n return \"\"\n\n\n\n#template.html\n{% block nav %}\n{% load current_nav %}\n{% url home as home_url %}\n{% url signup as signup_url %}\n{% url auth_login as auth_login_url %}\n<ul class=\"container\">\n <li><a href=\"{{ home_url }}\"{% current_nav home_url %} title=\"Home\">Home</a></li>\n <li><a href=\"{{ auth_login_url }}\"{% current_nav auth_login_url %} title=\"Login\">Login</a></li>\n <li><a href=\"{{ signup_url }}\"{% current_nav signup_url %} title=\"Signup\">Signup</a></li>\n</ul>\n{% endblock %}\n"
},
{
"answer_id": 1860598,
"author": "dtt101",
"author_id": 184354,
"author_profile": "https://Stackoverflow.com/users/184354",
"pm_score": 3,
"selected": false,
"text": "<body id=\"section-{% block section %}home{% endblock %}\">\n {% block section %}show{% endblock %}\n #section-home a#nav-home{\n font-weight:bold;\n}\n"
},
{
"answer_id": 9249759,
"author": "xaralis",
"author_id": 303184,
"author_profile": "https://Stackoverflow.com/users/303184",
"pm_score": 2,
"selected": false,
"text": "{% url admin:clients_client_changelist as clients %}\n{% url admin:clients_town_changelist as towns %}\n{% url admin:clients_district_changelist as districts %}\n\n<li class=\"{% active \"/\" %}\"><a href=\"/\">Home</a></li>\n<li class=\"{% active clients %}\"><a href=\"{{ clients }}\">Clients</a></li>\n{% if request.user.is_superuser %}\n<li class=\"{% active towns districts %}\">\n <a href=\"#\">Settings</a>\n <ul>\n <li><a href=\"{{ towns }}\">Towns</a></li>\n <li><a href=\"{{ districts }}\">Districts</a></li>\n </ul>\n</li>\n{% endif %}\n from django import template\n\nregister = template.Library()\n\n@register.tag\ndef active(parser, token):\n args = token.split_contents()\n template_tag = args[0]\n if len(args) < 2:\n raise template.TemplateSyntaxError, \"%r tag requires at least one argument\" % template_tag\n return NavSelectedNode(args[1:])\n\nclass NavSelectedNode(template.Node):\n def __init__(self, urls):\n self.urls = urls\n\n def render(self, context):\n path = context['request'].path\n\n for url in self.urls:\n if '\"' not in url:\n cpath = template.Variable(url).resolve(context)\n else:\n cpath = url.strip('\"')\n\n if (cpath == '/' or cpath == '') and not (path == '/' or path == ''):\n return \"\"\n if path.startswith(cpath):\n return 'active'\n return \"\"\n"
},
{
"answer_id": 9697665,
"author": "Juho Vepsäläinen",
"author_id": 228885,
"author_profile": "https://Stackoverflow.com/users/228885",
"pm_score": 0,
"selected": false,
"text": "from django.utils.translation import get_language, ugettext as _\n\n\nclass Navi(list):\n items = (_('Events'), _('Users'), )\n\n def __init__(self, cur_path):\n lang = get_language()\n first_part = '/' + cur_path.lstrip('/').split('/')[0]\n\n def set_status(n):\n if n['url'] == first_part:\n n['status'] == 'active'\n\n for i in self.items:\n o = {'name': i, 'url': '/' + slugify(i)}\n set_status(o)\n self.append(o)\n\n# remember to attach Navi() to your template context!\n# ie. 'navi': Navi(request.path)\n {% include \"includes/navigation.html\" with items=navi %}\n <ul class=\"nav\">\n {% for item in items %}\n <li class=\"{{ item.status }}\">\n <a href=\"{{ item.url }}\">{{ item.name }}</a>\n </li>\n {% endfor %}\n </ul>\n"
},
{
"answer_id": 10861672,
"author": "errkk",
"author_id": 267757,
"author_profile": "https://Stackoverflow.com/users/267757",
"pm_score": 1,
"selected": false,
"text": "my_tasks from django import template\nfrom django.core.urlresolvers import reverse\n\nregister = template.Library()\n\n@register.tag\ndef active(parser, token):\n args = token.split_contents()\n template_tag = args[0]\n if len(args) < 2:\n raise template.TemplateSyntaxError, \"%r tag requires at least one argument\" % template_tag\n return NavSelectedNode(args[1:])\n\nclass NavSelectedNode(template.Node):\n def __init__(self, name):\n self.name = name\n\n def render(self, context):\n\n if context['request'].path == reverse(self.name[1]):\n return 'active'\n else:\n return ''\n url(r'^tasks/my', my_tasks, name = 'my_tasks' ),\n <li class=\"{% active request all_tasks %}\"><a href=\"{% url all_tasks %}\">Everyone</a></li>\n"
},
{
"answer_id": 12673624,
"author": "Per",
"author_id": 1214181,
"author_profile": "https://Stackoverflow.com/users/1214181",
"pm_score": 0,
"selected": false,
"text": "{% load url from future %}\n\n{% url view as view_url %}\n<li class=\"nav-item{% ifequal view_url request.path %} current{% endifequal %}\">\n <a href=\"{{ view_url }}\">{{ title }}</a>\n</li>\n <ul>\n {% include \"intranet/nav_item.html\" with view='intranet.views.home' title='Home' %}\n {% include \"intranet/nav_item.html\" with view='crm.views.clients' title='Clients' %}\n</ul>\n from django.conf import global_settings\nTEMPLATE_CONTEXT_PROCESSORS = global_settings.TEMPLATE_CONTEXT_PROCESSORS + (\n 'django.core.context_processors.request',\n)\n"
},
{
"answer_id": 13335433,
"author": "matts1",
"author_id": 1503619,
"author_profile": "https://Stackoverflow.com/users/1503619",
"pm_score": 2,
"selected": false,
"text": "<script type=\"text/javascript\" src=\"/static/js/jquery.js\"></script>\n<script>\n $(document).ready(function(){\n var path = location.pathname;\n $('ul.navbar a.nav[href$=\"' + path + '\"]').addClass(\"active\");\n });\n</script>\n"
},
{
"answer_id": 15954946,
"author": "Marcus Whybrow",
"author_id": 166938,
"author_profile": "https://Stackoverflow.com/users/166938",
"pm_score": 4,
"selected": false,
"text": "{% load lineage %}\n<div id=\"navigation\">\n <a class=\"{% ancestor '/home/' %}\" href=\"/home/\">Home</a>\n <a class=\"{% ancestor '/services/' %}\" href=\"/services/\">Services</a>\n <a class=\"{% ancestor '/contact/' %}\" href=\"/contact/\">Contact</a>\n</div>\n ancestor {% url %}"
},
{
"answer_id": 19023893,
"author": "Konrad Hałas",
"author_id": 991546,
"author_profile": "https://Stackoverflow.com/users/991546",
"pm_score": 4,
"selected": false,
"text": "breadcrumbs class YourDetailView(DetailView):\n breadcrumbs = ['detail']\n (...)\n <a href=\"/detail/\" {% if 'detail' in view.breadcrumbs %}class=\"active\"{% endif %}>Detail</a>\n breadcrumbs class YourDetailView(DetailView):\n breadcrumbs = ['dashboard', 'list', 'detail']\n (...)\n <a href=\"/dashboard/\" {% if 'dashboard' in view.breadcrumbs %}class=\"active\"{% endif %}>Dashboard</a>\n<a href=\"/list/\" {% if 'list' in view.breadcrumbs %}class=\"active\"{% endif %}>List</a>\n<a href=\"/detail/\" {% if 'detail' in view.breadcrumbs %}class=\"active\"{% endif %}>Detail</a>\n"
},
{
"answer_id": 19636510,
"author": "suhailvs",
"author_id": 2351696,
"author_profile": "https://Stackoverflow.com/users/2351696",
"pm_score": 0,
"selected": false,
"text": "{% url 'some_urlpattern_name' as url %}\n<a href=\"{{url}}\"{% if request.path == url %} class=\"active\"{% endif %}>Link</a>\n"
},
{
"answer_id": 20161408,
"author": "tback",
"author_id": 246241,
"author_profile": "https://Stackoverflow.com/users/246241",
"pm_score": 1,
"selected": false,
"text": "True {% if %} {% load navigation %}\n<li{% if request|active:\"home\" %} class=\"active\"{% endif %}><a href=\"{% url \"home\" %}\">Home</a></li>\n @register.filter(name=\"active\")\ndef active(request, url_name):\n return resolve(request.path_info).url_name == url_name\n RequestContext settings.py TEMPLATE_CONTEXT_PROCESSORS = (\n ...\n 'django.core.context_processors.request',\n)\n"
},
{
"answer_id": 20204948,
"author": "user193130",
"author_id": 2891365,
"author_profile": "https://Stackoverflow.com/users/2891365",
"pm_score": 0,
"selected": false,
"text": "<li> // DOM Ready\n$(function() {\n // Highlight current page in nav bar\n $('.nav, .navbar-nav li').each(function() {\n // Count the number of links to the current page in the <li>\n var matched_links = $(this).find('a[href]').filter(function() {\n return $(this).attr('href') == window.location.pathname; \n }).length;\n // If there's at least one, mark the <li> as active\n if (matched_links)\n $(this).addClass('active');\n });\n});\n click return false href # var matched_links = $(this).find('a[href]').filter(function() {\n var matched = $(this).attr('href') == window.location.pathname;\n if (matched)\n $(this).click(function() { return false; });\n return matched;\n }).length;\n"
},
{
"answer_id": 23584728,
"author": "Brian Faherty",
"author_id": 766482,
"author_profile": "https://Stackoverflow.com/users/766482",
"pm_score": 0,
"selected": false,
"text": "class SetActiveViewMixin(object):\n def get_context_data(self, **kwargs):\n context = super(SetActiveViewMixin, self).get_context_data(**kwargs)\n context['active_nav_menu'] = {\n self.request.resolver_match.view_name: ' class=\"pure-menu-selected\"'\n }\n return context\n <ul>\n <li{{active_nav_menu.node_explorer }}><a href=\"{% url 'node_explorer' '' %}\">Explore</a></li>\n <li{{active_nav_menu.node_create }}><a href=\"{% url 'node_create' path %}\">Create</a></li>\n <li{{active_nav_menu.node_edit }}><a href=\"{% url 'node_edit' path %}\">Edit</a></li>\n <li{{active_nav_menu.node_delete }}><a href=\"{% url 'node_delete' path %}\">Delete</a></li>\n</ul>\n"
},
{
"answer_id": 26933116,
"author": "Logik Sounds",
"author_id": 3991187,
"author_profile": "https://Stackoverflow.com/users/3991187",
"pm_score": 0,
"selected": false,
"text": "<div class=\"pure-u-1 pure-menu pure-menu-open pure-menu-horizontal header\" >\n <ul class=\"\">\n <li id=\"home\"><a href=\"{% url 'article:index' %}\">Home</a></li>\n <li id=\"news\"><a href=\"{% url 'article:index' %}\">News</a></li>\n <li id=\"analysis\"><a href=\"{% url 'article:index' %}\">Analysis</a></li>\n <li id=\"opinion\"><a href=\"{% url 'article:index' %}\">Opinion</a></li>\n <li id=\"data\"><a href=\"{% url 'article:index' %}\">Data</a></li>\n <li id=\"events\"><a href=\"{% url 'article:index' %}\">Events</a></li>\n <li id=\"forum\"><a href=\"{% url 'article:index' %}\">Forum</a></li>\n <li id=\"subscribe\"><a href=\"{% url 'article:index' %}\">Subscribe</a></li>\n </ul>\n <script type=\"text/javascript\">\n (function(){\n loc=/\\w+/.exec(window.location.pathname)[0];\n el=document.getElementById(loc).className='pure-menu-selected'; \n })(); \n </script>\n</div>\n"
},
{
"answer_id": 28525952,
"author": "MadeOfAir",
"author_id": 1433559,
"author_profile": "https://Stackoverflow.com/users/1433559",
"pm_score": 2,
"selected": false,
"text": "%if% # navigation.py\nfrom django import template\nfrom django.core.urlresolvers import resolve\n\nregister = template.Library()\n\n@register.filter(name=\"activate_if_active\", is_safe=True)\ndef activate_if_active(request, urlname):\n if resolve(request.get_full_path()).url_name == urlname:\n return \"active\"\n return ''\n {% load navigation %}\n<li class=\"{{ request|activate_if_active:'url_name' }}\">\n <a href=\"{% url 'url_name' %}\">My View</a>\n</li>\n \"django.core.context_processors.request\" TEMPLATE_CONTEXT_PROCESSORS"
},
{
"answer_id": 30851283,
"author": "DestyNova",
"author_id": 1528682,
"author_profile": "https://Stackoverflow.com/users/1528682",
"pm_score": 1,
"selected": false,
"text": "## myapp_tags.py\n\n@register.simple_tag\ndef nav_css_class(page_class):\n if not page_class:\n return \"\"\n else:\n return page_class\n ## views.py\n\ndef ping(request):\n context={}\n context[\"nav_ping\"] = \"active\"\n return render(request, 'myapp/ping.html',context)\n <!-- sidebar.html -->\n\n{% load myapp_tags %}\n...\n\n<a class=\"{% nav_css_class nav_home %}\" href=\"{% url 'index' %}\">\n Accueil\n</a>\n<a class=\"{% nav_css_class nav_candidats %}\" href=\"{% url 'candidats' %}\">\n Candidats\n</a>\n<a class=\"{% nav_css_class nav_ping %}\" href=\"{% url 'ping' %}\">\n Ping\n</a>\n<a class=\"{% nav_css_class nav_stat %}\" href=\"{% url 'statistiques' %}\">\n Statistiques\n</a>\n...\n nav_css_class request"
},
{
"answer_id": 48078227,
"author": "Evgeny Bobkin",
"author_id": 5739875,
"author_profile": "https://Stackoverflow.com/users/5739875",
"pm_score": 1,
"selected": false,
"text": "**Placed in templates as base.html**\n\n{% block tab_menu %}\n<ul class=\"tab-menu\">\n <li class=\"{% if active_tab == 'tab1' %} active{% endif %}\"><a href=\"#\">Tab 1</a></li>\n <li class=\"{% if active_tab == 'tab2' %} active{% endif %}\"><a href=\"#\">Tab 2</a></li>\n <li class=\"{% if active_tab == 'tab3' %} active{% endif %}\"><a href=\"#\">Tab 3</a></li>\n</ul>\n{% endblock tab_menu %}\n\n**Placed in your page template**\n\n{% extends \"base.html\" %}\n\n{% block tab_menu %}\n {% with active_tab=\"tab1\" %} {{ block.super }} {% endwith %}\n{% endblock tab_menu %}\n"
},
{
"answer_id": 55293060,
"author": "Tjorriemorrie",
"author_id": 184379,
"author_profile": "https://Stackoverflow.com/users/184379",
"pm_score": 2,
"selected": false,
"text": "templates/fnf/nav_item.html <li class=\"nav-item\">\n <a class=\"nav-link {% if is_active %}active{% endif %}\" href=\"{% url url_name %}\">{{ link_name }}</a>\n</li>\n is_active templatetags/nav.py from django import template\n\nregister = template.Library()\n\n\n@register.inclusion_tag('fnf/nav_item.html', takes_context=True)\ndef nav_item(context, url_name, link_name=None):\n return {\n 'url_name': url_name,\n 'link_name': link_name or url_name.title(),\n 'is_active': context.request.resolver_match.url_name == url_name,\n }\n templates/fnf/nav.html {% load nav %}\n<nav class=\"navbar navbar-expand-lg navbar-light bg-light\">\n <ul class=\"navbar-nav mr-auto\">\n {% nav_item 'dashboard' %}\n </ul>\n"
},
{
"answer_id": 64192897,
"author": "Daksh Patel",
"author_id": 7997600,
"author_profile": "https://Stackoverflow.com/users/7997600",
"pm_score": 0,
"selected": false,
"text": " <ul class=\"nav navbar-nav\">\n <li>\n <a href=\"{% url 'index' %}\">Cities</a>\n </li>\n <li>\n <a href=\"{% url 'all_cafes' %}\">Cafes</a>\n </li>\n </ul>\n"
}
] | 2008/12/04 | [
"https://Stackoverflow.com/questions/340888",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12870/"
] |
340,911 | <p>Are there any VS.NET plugins that will format a selection of code for printing or emailing and is also free?</p>
| [
{
"answer_id": 341079,
"author": "Stein G. Strindhaug",
"author_id": 26115,
"author_profile": "https://Stackoverflow.com/users/26115",
"pm_score": 0,
"selected": false,
"text": "monospaced :set expandtab\n:%retab\n :set noexpandtab\n:%retab\n"
},
{
"answer_id": 341576,
"author": "configurator",
"author_id": 9536,
"author_profile": "https://Stackoverflow.com/users/9536",
"pm_score": 0,
"selected": false,
"text": "Editor -> Advanced -> Untabify Selected Lines"
}
] | 2008/12/04 | [
"https://Stackoverflow.com/questions/340911",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/40106/"
] |
340,915 | <p>I have form that displays several keywords (standard set of choice lists that changes rarely). There are about 4 such fields and each have about 20 choices or so.</p>
<p>I'm thinking if caching the keywords will be helpful for performance / best practice? Is there a strategy for determining when to cache?</p>
| [
{
"answer_id": 341125,
"author": "user35559",
"author_id": 35559,
"author_profile": "https://Stackoverflow.com/users/35559",
"pm_score": 0,
"selected": false,
"text": "\"IDictionary<string, IList<string>\"\n \"IDIctionary<string, IDictionary<string, string>\"\n"
},
{
"answer_id": 341151,
"author": "Shawn",
"author_id": 26,
"author_profile": "https://Stackoverflow.com/users/26",
"pm_score": 1,
"selected": false,
"text": " <%@ OutputCache Duration=\"60\" VaryByParam=\"Keyword\" %>\n my-page.aspx?Keyword=Cards my-page.aspx?Keyword=Books"
}
] | 2008/12/04 | [
"https://Stackoverflow.com/questions/340915",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/40070/"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.