qid
int64 4
19.1M
| question
stringlengths 18
48.3k
| answers
list | date
stringlengths 10
10
| metadata
list |
|---|---|---|---|---|
262,510
|
<p>Is there a way to search Microsoft Visual SourceSafe 6.0d for all files tagged with a specific label?</p>
|
[
{
"answer_id": 334423,
"author": "AJ.",
"author_id": 7211,
"author_profile": "https://Stackoverflow.com/users/7211",
"pm_score": 0,
"selected": false,
"text": "ss get -V\"my label\" $\\myproject -R \n my label myproject"
},
{
"answer_id": 714770,
"author": "another average joe",
"author_id": 52599,
"author_profile": "https://Stackoverflow.com/users/52599",
"pm_score": 3,
"selected": true,
"text": "ss dir -v\"LABEL\" $\\PROJECT -R\n someFile.c;23\nsomeOtherFile.h;3\n<filename>;<version>\n ss dir -v. $\\PROJECT -R\n"
}
] |
2008/11/04
|
[
"https://Stackoverflow.com/questions/262510",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2831/"
] |
262,527
|
<p>I need to programmatically enable READ COMMITTED SNAPSHOT in SQL Server. How can I do that?</p>
|
[
{
"answer_id": 262541,
"author": "João Vieira",
"author_id": 2267,
"author_profile": "https://Stackoverflow.com/users/2267",
"pm_score": 4,
"selected": true,
"text": "ALTER DATABASE [dbname] SET READ_COMMITTED_SNAPSHOT ON WITH ROLLBACK AFTER 20 SECONDS \n"
},
{
"answer_id": 2785127,
"author": "Bill Paetzke",
"author_id": 192210,
"author_profile": "https://Stackoverflow.com/users/192210",
"pm_score": 5,
"selected": false,
"text": "single-user ALTER DATABASE <dbname> SET SINGLE_USER WITH ROLLBACK IMMEDIATE;\nALTER DATABASE <dbname> SET READ_COMMITTED_SNAPSHOT ON;\nALTER DATABASE <dbname> SET MULTI_USER;\n"
}
] |
2008/11/04
|
[
"https://Stackoverflow.com/questions/262527",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2267/"
] |
262,534
|
<p>I want to use the same functionality available when a Panel.AutoScroll is true, but with the scrollbars invisible.</p>
<p>To do so I need to know how can I scroll to left/right up/down using functions in my code.</p>
|
[
{
"answer_id": 263590,
"author": "bobwienholt",
"author_id": 24257,
"author_profile": "https://Stackoverflow.com/users/24257",
"pm_score": 4,
"selected": false,
"text": "c.HorizontalScroll.Value += 100;\nc.VerticalScroll.Value = c.VerticalScroll.Maximum;\n"
},
{
"answer_id": 419865,
"author": "sindre j",
"author_id": 37119,
"author_profile": "https://Stackoverflow.com/users/37119",
"pm_score": -1,
"selected": false,
"text": "int xoffset = 10;\n\nforeach(Control c in panel1.Controls)\n c.Location.X += xoffset;\n"
}
] |
2008/11/04
|
[
"https://Stackoverflow.com/questions/262534",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10833/"
] |
262,535
|
<p>In C# some of default name space such as System.Collections are listed without typing in using blah. In visual basic, they are not imports for you. Is there a way to force vb to auto imports some of default name space or VB work differently than C#?</p>
|
[
{
"answer_id": 262570,
"author": "Joel Coehoorn",
"author_id": 3043,
"author_profile": "https://Stackoverflow.com/users/3043",
"pm_score": 3,
"selected": true,
"text": "System System. IO If IO.File.Exists(MyFile) Then ....\n System.IO File.Exists() System.IO.File.Exists()"
}
] |
2008/11/04
|
[
"https://Stackoverflow.com/questions/262535",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/28647/"
] |
262,537
|
<p>I recently inherited a VBA macro that needs to have validation logic added to it. I need to be able to determine if any characters in a text based cell are non ASCII characters (i.e. have a binary value > 0x7F). The cells may contain some carriage control values (particularly linefeeds) that need to be retained (so the CLEAN function does not work for this validation). I have tried the IsText function, but found that it will interpret UTF-8 character sequences as valid text (which I don't want).</p>
<p>I don't need to actually manipulate the string, I just want to display an error to the user that runs the macro to tell him that there are invalid (non-ASCII) characters in a specific cell.</p>
|
[
{
"answer_id": 263736,
"author": "dbb",
"author_id": 25675,
"author_profile": "https://Stackoverflow.com/users/25675",
"pm_score": 2,
"selected": false,
"text": "Function IsTooHigh(c As String) As Boolean\n\nDim RegEx As Object\nSet RegEx = CreateObject(\"vbscript.regexp\")\nWith RegEx\n .Global = True\n .MultiLine = True\n .Pattern = \"[^\\x00-\\x7F]\"\nEnd With\n\nIsTooHigh = RegEx.Test(c)\n\nEnd Function\n"
},
{
"answer_id": 275872,
"author": "jpinto3912",
"author_id": 11567,
"author_profile": "https://Stackoverflow.com/users/11567",
"pm_score": 0,
"selected": false,
"text": "Function IsGoodAscii(aString as String) as Boolean\nDim i as Long\nDim iLim as Long\ni=1\niLim=Len(aString)\n\nWhile i<=iLim\n If Asc(Mid(aString,i,1))>127 then\n IsGoodAscii=False\n Exit Function\n EndIf\n i=i+1 \nWend\n\nIsGoodAscii=True\nEnd Function\n"
}
] |
2008/11/04
|
[
"https://Stackoverflow.com/questions/262537",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19853/"
] |
262,538
|
<p>At <a href="http://java.sun.com/javase/downloads/index.jsp" rel="nofollow noreferrer">Java SE Downloads</a> I may for example download:</p>
<ul>
<li>Java SE Runtime Environment (JRE) 6 Update 10</li>
<li>Java SE Development Kit (JDK) 6 Update 10</li>
</ul>
<p>But I can't find any source code for update 10. If I click <a href="http://download.java.net/jdk6/6u3/promoted/b05/index.html" rel="nofollow noreferrer">Java SE 6 JDK Source Code</a> on the Java SE Downloads page it seems I can only download source for "JDK 6u3 Source". Where can I find the source for update 10? If there isn't any and I use update 10 for development, won't there be serious sync problems if I choose to debug and "step into" the source of a JDK method? (It seems like it should.)</p>
|
[
{
"answer_id": 263736,
"author": "dbb",
"author_id": 25675,
"author_profile": "https://Stackoverflow.com/users/25675",
"pm_score": 2,
"selected": false,
"text": "Function IsTooHigh(c As String) As Boolean\n\nDim RegEx As Object\nSet RegEx = CreateObject(\"vbscript.regexp\")\nWith RegEx\n .Global = True\n .MultiLine = True\n .Pattern = \"[^\\x00-\\x7F]\"\nEnd With\n\nIsTooHigh = RegEx.Test(c)\n\nEnd Function\n"
},
{
"answer_id": 275872,
"author": "jpinto3912",
"author_id": 11567,
"author_profile": "https://Stackoverflow.com/users/11567",
"pm_score": 0,
"selected": false,
"text": "Function IsGoodAscii(aString as String) as Boolean\nDim i as Long\nDim iLim as Long\ni=1\niLim=Len(aString)\n\nWhile i<=iLim\n If Asc(Mid(aString,i,1))>127 then\n IsGoodAscii=False\n Exit Function\n EndIf\n i=i+1 \nWend\n\nIsGoodAscii=True\nEnd Function\n"
}
] |
2008/11/04
|
[
"https://Stackoverflow.com/questions/262538",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
262,547
|
<p>I'm currently working on someone else's database where the primary keys are generated via a lookup table which contains a list of table names and the last primary key used. A stored procedure increments this value and checks it is unique before returning it to the calling 'insert' SP.</p>
<p>What are the benefits for using a method like this (or just generating a GUID) instead of just using the Identity/Auto-number?</p>
<p>I'm not talking about primary keys that actually 'mean' something like ISBNs or product codes, just the unique identifiers.</p>
<p>Thanks.</p>
|
[
{
"answer_id": 262587,
"author": "shyam",
"author_id": 7616,
"author_profile": "https://Stackoverflow.com/users/7616",
"pm_score": 1,
"selected": false,
"text": "sequences"
},
{
"answer_id": 494451,
"author": "Alex",
"author_id": 42707,
"author_profile": "https://Stackoverflow.com/users/42707",
"pm_score": 0,
"selected": false,
"text": "increment = 2\ndb1 - offset = 1\ndb2 - offset = 2\n"
}
] |
2008/11/04
|
[
"https://Stackoverflow.com/questions/262547",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14072/"
] |
262,555
|
<p>You can define a number in various ways in C#,</p>
<pre><code>1F // a float with the value 1
1L // a long with the value 1
1D // a double with the value 1
</code></pre>
<p>personally I'm looking for which would a <code>short</code>, however to make the question a better reference for people, what are all the other post-fix's to number literals you can apply?</p>
|
[
{
"answer_id": 262589,
"author": "Gulzar Nazim",
"author_id": 4337,
"author_profile": "https://Stackoverflow.com/users/4337",
"pm_score": 2,
"selected": false,
"text": "decimal mon = 1m;\n string curr = String.Format(\"{0:C}\", mon); //output $1.00\n"
},
{
"answer_id": 262679,
"author": "Scott Dorman",
"author_id": 1559,
"author_profile": "https://Stackoverflow.com/users/1559",
"pm_score": 5,
"selected": false,
"text": "Type Suffix .NET Framework Type \n-------------------------------------------------------------------------------------\ndecimal M or m System.Decimal\ndouble D or d System.Double\nfloat F or f System.Single\nint [1] System.Int32\nlong L or l System.Int64\n"
}
] |
2008/11/04
|
[
"https://Stackoverflow.com/questions/262555",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1610/"
] |
262,573
|
<p>Is there a way for me to loop over a Javascript Object's built-in properties?</p>
<p>for...in gets me close to where I want to go, but "A for...in loop does not iterate over built-in properties."</p>
|
[
{
"answer_id": 262911,
"author": "Diodeus - James MacFarlane",
"author_id": 12579,
"author_profile": "https://Stackoverflow.com/users/12579",
"pm_score": -1,
"selected": false,
"text": "<style>\n.tree {\n margin-left:5px;\n}\n</style>\n<div id='out'></div>\n<script type=\"text/javascript\">\ndata = {\"feep\":{\"bar\":{\"baz\":\"37628\",\"quux\":{\"a\":\"179\",\"b\":\"7\"}},\"foo\":\"1025\"},\"Bleh\":\"1234\"}\n$('out').innerHTML = renderJSON(data)\n\nfunction renderJSON(obj) {\n var keys = []\n var retValue = \"\"\n for (var key in obj) {\n //$('out').innerHTML = $('out').innerHTML +\"<br />\" + key + \", \" + obj[key] \n if(typeof obj[key] == 'object') {\n retValue += \"<div class='tree'>\" + key \n retValue += renderJSON(obj[key])\n retValue += \"</div>\"\n }\n else {\n retValue += \"<div class='tree'>\" + key + \" = \" + obj[key] + \"</div>\"\n }\n\n keys.push(key)\n }\n return retValue\n\n}\n</script>\n"
},
{
"answer_id": 262979,
"author": "Vijay Dev",
"author_id": 27474,
"author_profile": "https://Stackoverflow.com/users/27474",
"pm_score": 0,
"selected": false,
"text": "var name; \nfor (name in another_stooge) \n{\n if (typeof another_stooge[name] !== 'function') {\n document.writeln(name + ': ' + another_stooge[name]);\n } \n}\n"
},
{
"answer_id": 267188,
"author": "Borgar",
"author_id": 27388,
"author_profile": "https://Stackoverflow.com/users/27388",
"pm_score": 3,
"selected": false,
"text": "array Function.prototype prototype caller constructor length name apply call toSource toString valueOf toLocaleString\n Object.prototype __defineGetter__ __defineSetter__ hasOwnProperty isPrototypeOf __lookupGetter__\n__lookupSetter__ __noSuchMethod__ propertyIsEnumerable unwatch watch\n Array index input pop push reverse shift sort splice unshift concat join slice indexOf lastIndexOf \nfilter forEach every map some reduce reduceRight\n for (var property in myArrayObject) myPossibleProperties.push( property );\n Array"
},
{
"answer_id": 6893526,
"author": "Casey Chu",
"author_id": 298233,
"author_profile": "https://Stackoverflow.com/users/298233",
"pm_score": 4,
"selected": false,
"text": ">>> Object.getOwnPropertyNames(Object) [\"prototype\", \"getPrototypeOf\", \"getOwnPropertyDescriptor\", \"keys\", \"defineProperty\", \"defineProperties\", \"create\", \"getOwnPropertyNames\", \"isExtensible\", \"preventExtensions\", \"freeze\", \"isFrozen\", \"seal\", \"isSealed\", \"length\", \"arity\", \"name\", \"arguments\", \"caller\"]"
}
] |
2008/11/04
|
[
"https://Stackoverflow.com/questions/262573",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
262,579
|
<p>I have a simple POJO web service published with Axis2 on Tomcat5.5
I try to consume it with ATL C++ client and it fails. Doing the same with a C# client works.
The problem is that ATL client sends soap body which looks like </p>
<pre><code><soap:Body>< xmlns="http://fa.test.com/xsd"></></soap:Body></soap:Envelope>
</code></pre>
<p>Notice the invalid element in the middle.
I suspect it has something to do with UTF-8 because C# sends a header of </p>
<pre><code><?xml version='1.0' encoding='utf-8'?>
</code></pre>
<p>and ATL client doesn't. Also when I look into some of the ATL SOAP internals I notice that a structure has two members: szName and szwName. The first one is empty and produces the element, the second one has a valid (?) name of testResponse (the method I'm calling is called "test").</p>
<p>Need advice as to where to go from here?</p>
<p>More details:
full message from ATL client:</p>
<pre><code>POST /axis2/services/EnterpriseService.EnterpriseServiceHttpSoap11Endpoint/ HTTP/1.1
Content-Length: 304
Content-Type: text/xml; charset=utf-8
SOAPAction: "urn:test"
Accept: text/xml
Host: xxxxxxx
User-Agent: Microsoft-ATL-Native/8.00
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soapenc="http://schemas.xmlsoap.org/soap/encoding/"><soap:Body>< xmlns="http://fa.test.com/xsd"></></soap:Body></soap:Envelope>
</code></pre>
<p>Response from Axis2:</p>
<pre><code>HTTP/1.1 500 Internal Server Error
Server: Apache-Coyote/1.1
Content-Type: text/xml;charset=utf-8
Transfer-Encoding: chunked
Date: Tue, 04 Nov 2008 15:31:57 GMT
Connection: close
<?xml version='1.0' encoding='utf-8'?><soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"><soapenv:Body><soapenv:Fault><faultcode>soapenv:Server</faultcode><faultstring>com.ctc.wstx.exc.WstxUnexpectedCharException: Unexpected character '>' (code 62); expected an element name.&#xd;
at [row,col {unknown-source}]: [1,276]</faultstring><detail /></soapenv:Fault></soapenv:Body></soapenv:Envelope>
</code></pre>
<p>Oh, and here is the good request coming from C# client:</p>
<pre><code>POST /axis2/services/EnterpriseService.EnterpriseServiceHttpSoap11Endpoint/ HTTP/1.1
Via: 1.1 ANGEL-ISLAND
Content-Type: text/xml; charset=utf-8
User-Agent: Mozilla/4.0 (compatible; MSIE 6.0; MS Web Services Client Protocol 2.0.50727.1433)
Host: xxxxxxx:8080
SOAPAction: "urn:test"
Connection: Keep-Alive
Content-Length: 236
<?xml version="1.0" encoding="utf-8"?><soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"><soap:Body /></soap:Envelope>
</code></pre>
<p>In C# case the soap:body is blank.</p>
|
[
{
"answer_id": 274833,
"author": "Sunlight",
"author_id": 33650,
"author_profile": "https://Stackoverflow.com/users/33650",
"pm_score": 2,
"selected": false,
"text": "<soap:Envelope xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\"\n xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" \n xmlns:soapenc=\"http://schemas.xmlsoap.org/soap/encoding/\">\n <soap:Body></soap:Body></soap:Envelope>\n SoapParameterStyle.Bare <wsdl:part>"
}
] |
2008/11/04
|
[
"https://Stackoverflow.com/questions/262579",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
262,593
|
<pre><code> $('input[type=checkbox]').unbind().click(function(e){
$(this).attr('checked', true)
return false;
});
</code></pre>
<p>I NEED to return false because I have an event on its parent and I don't want to trigger that.
It just WON'T check that checkbox.</p>
|
[
{
"answer_id": 262766,
"author": "eyelidlessness",
"author_id": 17964,
"author_profile": "https://Stackoverflow.com/users/17964",
"pm_score": 3,
"selected": true,
"text": "$('input[type=checkbox]').unbind().click(function(e){\n e.stopPropagation();\n});\n .unbind()"
}
] |
2008/11/04
|
[
"https://Stackoverflow.com/questions/262593",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23810/"
] |
262,597
|
<p>I'm new to Linux and have inherited keeping our single linux server running. It's our SVN server so it's relatively important.</p>
<p>Turns out the guy who maintained it before me had a cron task to email him when there are too many svnserve processes running, as they seem to be left dangling instead of terminating correctly.</p>
<p>First part of the question is, given that I run</p>
<pre><code>ps -fu cvsuser
</code></pre>
<p>and get a list of the processes, how can I kill the ones that have an STIME not today? For example, something like</p>
<pre><code>kill where STIME = Oct30
</code></pre>
<p>The other question is, does anyone know how to avoid having these dangling svnserve processes? <a href="https://stackoverflow.com/questions/262767/dangling-svnserve-processes">(Here's the other question.)</a></p>
|
[
{
"answer_id": 262683,
"author": "Robert Gamble",
"author_id": 25222,
"author_profile": "https://Stackoverflow.com/users/25222",
"pm_score": 0,
"selected": false,
"text": "ps h -u csvuser -o pid,lstart | grep 'May 29' | sed 's/^ \\+//' | \ncut -d ' ' -f 1 | xargs -n 1 kill\n 16324 Thu May 29 04:02:06 2008\n22144 Tue Jul 22 04:02:05 2008\n11315 Wed Oct 8 04:02:00 2008\n 16324 Thu May 29 04:02:06 2008\n 16324\n"
},
{
"answer_id": 262804,
"author": "Ken",
"author_id": 20074,
"author_profile": "https://Stackoverflow.com/users/20074",
"pm_score": 3,
"selected": true,
"text": "ps h -u cvsuser -o pid,start # h - no header, only output pid and start\n | grep -v ':' # exclude entries from the last 24 hours\n | egrep -o '^\\ *[0-9]+' # get the pid (handling possible leading space)\n | xargs -i echo kill \"{}\" # pretend to kill - take out the echo if you're happy\n"
},
{
"answer_id": 8634341,
"author": "Mike Frysinger",
"author_id": 1116096,
"author_profile": "https://Stackoverflow.com/users/1116096",
"pm_score": 1,
"selected": false,
"text": "ps timeout $ grep server /etc/xinetd.d/svnserve\nserver = /usr/bin/timeout\nserver_args = 12h /usr/bin/svnserve -i -R -r /svnroot\n"
}
] |
2008/11/04
|
[
"https://Stackoverflow.com/questions/262597",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9861/"
] |
262,603
|
<p>See question above.</p>
|
[
{
"answer_id": 262622,
"author": "FlySwat",
"author_id": 1965,
"author_profile": "https://Stackoverflow.com/users/1965",
"pm_score": 5,
"selected": false,
"text": "ikvmc myjar.jar\n"
}
] |
2008/11/04
|
[
"https://Stackoverflow.com/questions/262603",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
262,614
|
<p>As part of my overall development practices review I'm looking at how best to streamline and automate our ASP.net web development practices.</p>
<p>At the moment, our process goes something like this:</p>
<ol>
<li>Designer builds frontend as static HTML/CSS on a network share. This gets tweaked until signed off. (e.g. <code>http://myserver/acmesite_design</code>)</li>
<li>Once signed off, developer takes over and copies over frontend HTML/CSS to a new directory on the same server (e.g. <code>http://myserver/acmesite_development</code>)</li>
<li>Multiple developers work on local copy until project is complete.</li>
<li>Developer publishes code to an external publicly accessible server for a client to review/signoff.</li>
<li>Edits made locally based on feedback.</li>
<li>Republish to external server.</li>
<li>Signoff </li>
<li>Developer publishes to live public server</li>
</ol>
<p>What goes wrong? Lots of things!</p>
<ol>
<li>Version Control — this is obviously a must and is being introduced</li>
<li>Configuration errors — many many times, there are environment specific paths and variables (such as DB names, image upload directories, web server paths etc. etc.) which incorrectly get copied from local to staging to live etc. etc. with very embarrassing results.</li>
</ol>
<p>I'm pretty confident I've got no.1 under control. What about configuration management? Does anyone have any advice as to how best to manage an applications structure within asp.net apps to minimize these kinds of problems?</p>
|
[
{
"answer_id": 293740,
"author": "tommym",
"author_id": 37607,
"author_profile": "https://Stackoverflow.com/users/37607",
"pm_score": 1,
"selected": false,
"text": "dirname(____FILE____)"
}
] |
2008/11/04
|
[
"https://Stackoverflow.com/questions/262614",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/22837/"
] |
262,616
|
<p>I use div tags to define areas within my web pages. I set all the obvious things like background, size, padding, etc. But it is all very square.</p>
<p>How can I use <strong>only</strong> CSS to round the corners?</p>
|
[
{
"answer_id": 262716,
"author": "Brian Schmitt",
"author_id": 30492,
"author_profile": "https://Stackoverflow.com/users/30492",
"pm_score": 3,
"selected": false,
"text": "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 Transitional//EN\">\n<html>\n <head>\n <style>\n .b1f, .b2f, .b3f, .b4f{font-size:1px; overflow:hidden; display:block;}\n.b1f {height:1px; background:#ddd; margin:0 5px;}\n.b2f {height:1px; background:#ddd; margin:0 3px;}\n.b3f {height:1px; background:#ddd; margin:0 2px;}\n.b4f {height:2px; background:#ddd; margin:0 1px;}\n.contentf {background: #ddd;}\n.contentf div {margin-left: 5px;}\n </style>\n </head>\n <body>\n <b class=\"b1f\"></b><b class=\"b2f\"></b><b class=\"b3f\"></b><b class=\"b4f\"></b>\n <div class=\"contentf\">\nContent Area Content Area Content Area Content Area Content Area Content Area \nContent Area Content Area Content Area Content Area Content Area Content Area \nContent Area Content Area Content Area Content Area Content Area Content Area \n </div>\n <b class=\"b4f\"></b><b class=\"b3f\"></b><b class=\"b2f\"></b><b class=\"b1f\"></b>\n </body>\n</html>\n"
}
] |
2008/11/04
|
[
"https://Stackoverflow.com/questions/262616",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13930/"
] |
262,618
|
<p>I currently have 2 <code>BufferedReader</code>s initialized on the same text file. When I'm done reading the text file with the first <code>BufferedReader</code>, I use the second one to make another pass through the file from the top. Multiple passes through the same file are necessary.</p>
<p>I know about <code>reset()</code>, but it needs to be preceded with calling <code>mark()</code> and <code>mark()</code> needs to know the size of the file, something I don't think I should have to bother with.</p>
<p>Ideas? Packages? Libs? Code?</p>
<p>Thanks
TJ</p>
|
[
{
"answer_id": 262631,
"author": "Jon Skeet",
"author_id": 22656,
"author_profile": "https://Stackoverflow.com/users/22656",
"pm_score": 6,
"selected": true,
"text": "BufferedReader"
},
{
"answer_id": 262718,
"author": "Ryan P",
"author_id": 1539,
"author_profile": "https://Stackoverflow.com/users/1539",
"pm_score": 5,
"selected": false,
"text": "seek() try{\n String fileName = \"c:/myraffile.txt\";\n File file = new File(fileName);\n RandomAccessFile raf = new RandomAccessFile(file, \"rw\");\n raf.readChar();\n raf.seek(0);\n} catch (FileNotFoundException e) {\n // TODO Auto-generated catch block\n e.printStackTrace();\n} catch (IOException e) {\n // TODO Auto-generated catch block\n e.printStackTrace();\n}\n \"rw\""
}
] |
2008/11/04
|
[
"https://Stackoverflow.com/questions/262618",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
262,620
|
<p>This has got to be something I just missed, but how do I add a tool tip to a label?</p>
<p>I saw something on the web about handling the mouse hover event, but how would I even handle it in code?</p>
|
[
{
"answer_id": 262641,
"author": "cfeduke",
"author_id": 5645,
"author_profile": "https://Stackoverflow.com/users/5645",
"pm_score": 3,
"selected": false,
"text": "System.Windows.Forms.ToolTip ToolTip1 = new System.Windows.Forms.ToolTip();\nToolTip1.SetToolTip(this.textBox1, \"Hello\");\n"
},
{
"answer_id": 262650,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "button = new Button(); \nbutton.Content = \"Hover over me.\"; \ntt = new ToolTip(); \ntt.Content = \"Created with C#\"; \nbutton.ToolTip = tt; \ncv2.Children.Add(button);\n"
}
] |
2008/11/04
|
[
"https://Stackoverflow.com/questions/262620",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21828/"
] |
262,636
|
<p>I'm trying to implement the "Writing Information to UserData" section of <a href="http://www.asp.net/LEARN/security/tutorial-03-cs.aspx" rel="nofollow noreferrer">this article</a>, but it doesn't work properly when the cookie is part of the URI.</p>
<p>My code:</p>
<pre><code>// Create the cookie that contains the forms authentication ticket
HttpCookie authCookie = FormsAuthentication.GetAuthCookie( userName, createPersistantCookie );
// Get the FormsAuthenticationTicket out of the encrypted cookie
FormsAuthenticationTicket ticket = FormsAuthentication.Decrypt( authCookie.Value );
// Create a new FormsAuthenticationTicket that includes our custom User Data
FormsAuthenticationTicket newTicket = new FormsAuthenticationTicket( ticket.Version, ticket.Name, ticket.IssueDate, ticket.Expiration, ticket.IsPersistent, "foo");
// Update the authCookie's Value to use the encrypted version of newTicket
authCookie.Value = FormsAuthentication.Encrypt( newTicket );
// Manually add the authCookie to the Cookies collection
HttpContext.Current.Response.Cookies.Add( authCookie );
// Determine redirect URL and send user there
string redirUrl = FormsAuthentication.GetRedirectUrl( userName, createPersistantCookie );
HttpContext.Current.Response.Redirect( redirUrl, false );
</code></pre>
<p>When cookieless is used, the page redirects but doesn't get the correct URI with the cookie information in it, so it loops back to my Login page where Request.IsAuthenticated returns false. An endless loop ensues.</p>
<p>How do I redirect to the proper URI?</p>
|
[
{
"answer_id": 265321,
"author": "Greg",
"author_id": 12601,
"author_profile": "https://Stackoverflow.com/users/12601",
"pm_score": 1,
"selected": false,
"text": "if( !HttpContext.Current.Request.Browser.Cookies || !FormsAuthentication.CookiesSupported )\n{\n FormsAuthentication.RedirectFromLoginPage( userName, false);\n return;\n}\n"
}
] |
2008/11/04
|
[
"https://Stackoverflow.com/questions/262636",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12601/"
] |
262,652
|
<p>I can't stand HTML intermixed with other code. I'm working on a codebase that has to remain in PHP, and I don't want to touch an HTML template with a proverbial pole. So what I'm currently doing looks like this:</p>
<pre><code><?php
$page = new html_page('My wonderful page');
$page->add_contents(new html_tag('p', 'It works', array('id' => 'helloworld', 'class' => 'somecssclass')));
echo $page->render();
?>
</code></pre>
<p>Everything belongs to a nice hierarchy of objects, which is good and dandy. Of course I have a lot of smaller classes, and I'm thinking of using dynamic classes (for example, 'html_a' will automagically create an html_tag object of type 'a'.)</p>
<p>It seems that nobody else is doing this. Why not? What am I missing?</p>
<p>(I clearly remember an open source library that did exactly this, but can't find it anymore. So unless I'm actually imagining things, I'm not the only one who thought of this approach to render HTML)</p>
<p>Do you have any thoughts on this?</p>
<p>Here are some additional details:</p>
<ol>
<li>I'm the only developer in this project.</li>
<li>How I'm mixing code with HTML: an "html_tag" object from my library is pretty similar to, say, a node in the DOM. The "render" method is the one that creates HTML, but I don't write any opening or closing tag anywhere.</li>
<li>I create small objects for several tasks. These objects have methods to build tag objects; these resulting objects are then inserted into, say, tables or pages.</li>
<li>My library have some primitive access methods to find objects. So the iterator example posted in <a href="https://stackoverflow.com/questions/262652/php-tag-library#262881">26288</a> can be implemented with relative ease.</li>
<li>I'm not worried about performance (yet).</li>
</ol>
|
[
{
"answer_id": 262696,
"author": "Owen",
"author_id": 4853,
"author_profile": "https://Stackoverflow.com/users/4853",
"pm_score": 3,
"selected": false,
"text": "$page = new Page('test.html');\n$page->load($data);\n$page->render();\n <html>\n<head>\n <title><?php echo $title ?></title>\n</head>\n<body>\n <p><?php echo $hello ?></p>\n</body>\n</html>\n <p> <div>"
},
{
"answer_id": 262881,
"author": "Kent Fredric",
"author_id": 15614,
"author_profile": "https://Stackoverflow.com/users/15614",
"pm_score": 1,
"selected": false,
"text": "$page = new Page(\"FakePage.html\"); \n$page->find(\"div#foobar\")->text = \"Hahah! I rock\" ; \n/* Give All H1's a numeric lead in */ \nforeach( $page->find(\"h1\")->iterator() as $index => $node )\n{\n $node->text = ($index + 1 ) . \". \" $node.text;\n};\n$page->render();\n"
},
{
"answer_id": 263329,
"author": "troelskn",
"author_id": 18180,
"author_profile": "https://Stackoverflow.com/users/18180",
"pm_score": 3,
"selected": true,
"text": "$t = new Domling('<p class=\"hello\"></p>'); \n$t->capture('hello')->bind(\"Hello World\"); \necho $t->render();\n <p class=\"hello\">Hello World</p> \n"
}
] |
2008/11/04
|
[
"https://Stackoverflow.com/questions/262652",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7841/"
] |
262,675
|
<p>We currently use VSS 6, this is not going to change I am afraid.</p>
<p>I am attempting to write a script that will allow a user to quickly copy all files that they have checked out to another directory tree. In order to do this I need to get a list of all the files that the user has checked out, and the directory that the file is checked out to. This is easy enough to do using status search in the GUI. But I need a way of doing it from the command line utility ss.exe.</p>
|
[
{
"answer_id": 262755,
"author": "Panos",
"author_id": 8049,
"author_profile": "https://Stackoverflow.com/users/8049",
"pm_score": 1,
"selected": false,
"text": "ss.exe Status $/ -R -U\n"
},
{
"answer_id": 262768,
"author": "Brian Schmitt",
"author_id": 30492,
"author_profile": "https://Stackoverflow.com/users/30492",
"pm_score": 4,
"selected": true,
"text": "ss.exe Status $/ -R -U<Username>\n"
},
{
"answer_id": 5197793,
"author": "Bill Paetzke",
"author_id": 192210,
"author_profile": "https://Stackoverflow.com/users/192210",
"pm_score": 2,
"selected": false,
"text": "cd C:\\Program Files\\Microsoft Visual SourceSafe SET SSDIR=<path to folder containing srcsafe.ini> ss Status $/ -R -U<username> > checked-out-by-username.txt srcsafe.ini C:\\Program Files\\Microsoft Visual SourceSafe\\MasterDatabase bpaetzke cd C:\\Program Files\\Microsoft Visual SourceSafe SET SSDIR=MasterDatabase ss Status $/ -R -Ubpaetzke > checked-out-by-bpaetzke.txt"
}
] |
2008/11/04
|
[
"https://Stackoverflow.com/questions/262675",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/28882/"
] |
262,691
|
<p>I feel like I'm missing a fairly fundamental concept to WPF when it comes to databinding, but I can't seem to find the right combination of Google keywords to locate what I'm after, so maybe the SO Community can help. :)</p>
<p>I've got a WPF usercontrol that needs to databind to two separate objects in order to display properly. Both objects must be dynamically set from an outside source. Thus far I've simply been using the DataContext property of the form for dynamic object binding, but that only allows for one object to be referenced. I feel like this is a simple problem and that I must be missing something obvious.</p>
<p>My previous attempt looks something like this:</p>
<pre><code><UserControl.Resources>
<src:Person x:Key="personSource" />
<src:Job x:Key="jobSource" />
</UserControl.Resources>
<TextBox Text="{Binding Source={StaticResource personSource}, Path=Name" />
<TextBox Text="{Binding Source={StaticResource jobSource}, Path=Address" />
</code></pre>
<p>This will bind to any defaults I give the classes just fine, but If I try to dynamically set the objects in code (as I show below) I don't see any change.</p>
<pre><code>Person personSource = FindResource("personSource") as Person;
personSource = externalPerson;
Job jobSource= FindResource("jobSource") as Job;
jobSource = externalJob;
</code></pre>
<p>What am I missing?</p>
|
[
{
"answer_id": 262794,
"author": "Todd White",
"author_id": 30833,
"author_profile": "https://Stackoverflow.com/users/30833",
"pm_score": 4,
"selected": true,
"text": "public class CustomControl : Control\n{\n public static readonly DependencyProperty PersonProperty =\n DependencyProperty.Register(\"Person\", typeof(Person), typeof(CustomControl), new UIPropertyMetadata(null));\n public Person Person\n {\n get { return (Person) GetValue(PersonProperty); }\n set { SetValue(PersonProperty, value); }\n }\n\n\n public static readonly DependencyProperty JobProperty =\n DependencyProperty.Register(\"Job\", typeof(Job), typeof(CustomControl), new UIPropertyMetadata(null));\n public Job Job\n {\n get { return (Job) GetValue(JobProperty); }\n set { SetValue(JobProperty, value); }\n }\n\n static CustomControl()\n {\n DefaultStyleKeyProperty.OverrideMetadata(typeof(CustomControl), new FrameworkPropertyMetadata(typeof(CustomControl)));\n }\n}\n <ResourceDictionary\n xmlns=\"http://schemas.microsoft.com/winfx/2006/xaml/presentation\"\n xmlns:x=\"http://schemas.microsoft.com/winfx/2006/xaml\"\n xmlns:local=\"clr-namespace:WpfApplication3\">\n\n\n <Style TargetType=\"{x:Type local:CustomControl}\">\n <Setter Property=\"Template\">\n <Setter.Value>\n <ControlTemplate TargetType=\"{x:Type local:CustomControl}\">\n <Border Background=\"{TemplateBinding Background}\"\n BorderBrush=\"{TemplateBinding BorderBrush}\"\n BorderThickness=\"{TemplateBinding BorderThickness}\">\n <StackPanel>\n <TextBox Text=\"{TemplateBinding Person.Name}\" />\n <TextBox Text=\"{TemplateBinding Job.Address}\" />\n </StackPanel>\n </Border>\n </ControlTemplate>\n </Setter.Value>\n </Setter>\n </Style>\n</ResourceDictionary>\n <src:CustomControl Person=\"{Binding Person}\" Job=\"{Binding Job}\" />\n"
},
{
"answer_id": 263310,
"author": "Ian Oakes",
"author_id": 21606,
"author_profile": "https://Stackoverflow.com/users/21606",
"pm_score": 1,
"selected": false,
"text": "DataContext=\"{Binding RelativeSource={RelativeSource Self}}\"\n <TextBox Text=\"{Binding Path=Person.Name\" />\n<TextBox Text=\"{Binding Path=Job.Address\" />\n <TextBox Text=\"{Binding Source=Person, Path=Name\" />\n<TextBox Text=\"{Binding Source=Job, Path=Address\" />\n"
}
] |
2008/11/04
|
[
"https://Stackoverflow.com/questions/262691",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/25968/"
] |
262,723
|
<p>If you have a Java object and an XML schema (XSD), what is the best way to take that object and convert it into an xml file in line with the schema. The object and the schema do not know about each other (in that the java classes weren't created from the schema).</p>
<p>For example, in the class, there may be an integer field 'totalCountValue' which would correspond to an element called 'countTotal' in the xsd file. Is there a way of creating a mapping that will say "if the object contains an int totalCountValue, create an element called 'countTotal' and put it into the XML".
Similarly, there may be a field in the object that should be ignored, or a list in the object that should correspond to multiple XML elements.</p>
<p>I looked at XStream, but didn't see any (obvious) way of doing it. Are there other XML libraries that can simplify this task?</p>
|
[
{
"answer_id": 262905,
"author": "bruno conde",
"author_id": 31136,
"author_profile": "https://Stackoverflow.com/users/31136",
"pm_score": 2,
"selected": false,
"text": "...\nXStream xstream = new XStream(new DomDriver());\n\nxstream.alias(\"myclass\", MyClass.class);\nxstream.aliasField(\"countTotal\", MyClass.class, \"totalCountValue\");\n\nString xml = xstream.toXML(this);\n...\n class MyClass {\n private int totalCountValue;\n\n public MyClass() {\n }\n} \n"
}
] |
2008/11/04
|
[
"https://Stackoverflow.com/questions/262723",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/142/"
] |
262,727
|
<p>If you (or your organization) aspires to thoroughly unit test your code, how do you measure the success or quality of your efforts? </p>
<ul>
<li>Do you use code coverage, what percentage do you aim for? </li>
<li>Do you find that philosophies like TDD have a better impact than metrics?</li>
</ul>
|
[
{
"answer_id": 50748762,
"author": "Frank Niessink",
"author_id": 100738,
"author_profile": "https://Stackoverflow.com/users/100738",
"pm_score": 1,
"selected": false,
"text": "and or < <="
}
] |
2008/11/04
|
[
"https://Stackoverflow.com/questions/262727",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/24279/"
] |
262,740
|
<p>Is there a canonical way to set up a JS onHover event with the existing onmouseover, onmouseout and some kind of timers? Or just any method to fire an arbitrary function if and only if user has hovered over element for certain amount of time.</p>
|
[
{
"answer_id": 262752,
"author": "eyelidlessness",
"author_id": 17964,
"author_profile": "https://Stackoverflow.com/users/17964",
"pm_score": 4,
"selected": false,
"text": "var timeout;\nelement.onmouseover = function(e) {\n timeout = setTimeout(function() {\n // ...\n }, delayTimeMs)\n};\nelement.onmouseout = function(e) {\n if(timeout) {\n clearTimeout(timeout);\n }\n};\n addEventListener attachEvent"
},
{
"answer_id": 263058,
"author": "scunliffe",
"author_id": 6144,
"author_profile": "https://Stackoverflow.com/users/6144",
"pm_score": 2,
"selected": false,
"text": "onmouseover = start...\n\nonmouseout = ...end\n"
},
{
"answer_id": 263194,
"author": "Peter Bailey",
"author_id": 8815,
"author_profile": "https://Stackoverflow.com/users/8815",
"pm_score": 5,
"selected": false,
"text": "<html>\n<head>\n<script type=\"text/javascript\">\n\nvar HoverListener = {\n addElem: function( elem, callback, delay )\n {\n if ( delay === undefined )\n {\n delay = 1000;\n }\n\n var hoverTimer;\n\n addEvent( elem, 'mouseover', function()\n {\n hoverTimer = setTimeout( callback, delay );\n } );\n\n addEvent( elem, 'mouseout', function()\n {\n clearTimeout( hoverTimer );\n } );\n }\n}\n\nfunction tester()\n{\n alert( 'hi' );\n}\n\n// Generic event abstractor\nfunction addEvent( obj, evt, fn )\n{\n if ( 'undefined' != typeof obj.addEventListener )\n {\n obj.addEventListener( evt, fn, false );\n }\n else if ( 'undefined' != typeof obj.attachEvent )\n {\n obj.attachEvent( \"on\" + evt, fn );\n }\n}\n\naddEvent( window, 'load', function()\n{\n HoverListener.addElem(\n document.getElementById( 'test' )\n , tester \n );\n HoverListener.addElem(\n document.getElementById( 'test2' )\n , function()\n {\n alert( 'Hello World!' );\n }\n , 2300\n );\n} );\n\n</script>\n</head>\n<body>\n<div id=\"test\">Will alert \"hi\" on hover after one second</div>\n<div id=\"test2\">Will alert \"Hello World!\" on hover 2.3 seconds</div>\n</body>\n</html>\n"
},
{
"answer_id": 951662,
"author": "MikeN",
"author_id": 36680,
"author_profile": "https://Stackoverflow.com/users/36680",
"pm_score": 4,
"selected": false,
"text": "$(this).hover(function(){},function(){});\n"
}
] |
2008/11/04
|
[
"https://Stackoverflow.com/questions/262740",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/29574/"
] |
262,742
|
<p>1) user A goes to the site, creates an account, and logs in
2) user b goes to the site. Rather than having to log in, user b enters as though user b is user a. User b gets access to all of user a's data and can brows the site as user a.</p>
<p>Note: user b does not log in. User b just hits the site, and the site returns as if user b is already logged in as user a.</p>
<p>Note 2: user a and user b are on distinct computers. Also, static variables are not involved in the code.</p>
<p>Setup:
IIS 6
.Net 2.0
OutputCache off for the pages in the site</p>
|
[
{
"answer_id": 262786,
"author": "CesarB",
"author_id": 28258,
"author_profile": "https://Stackoverflow.com/users/28258",
"pm_score": 1,
"selected": true,
"text": "Vary"
}
] |
2008/11/04
|
[
"https://Stackoverflow.com/questions/262742",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18313/"
] |
262,802
|
<p>I'm working on a project and I want to store some easily enumerated information in a table. MySql's enum data type does exactly what I want: <a href="http://dev.mysql.com/doc/refman/5.0/en/enum.html" rel="noreferrer">http://dev.mysql.com/doc/refman/5.0/en/enum.html</a> . Is there an equivalent in SQL Server 2005?</p>
<p>I know I could store the possible values in a type table with a key, but I'd rather not have to link back to it for descriptions. Our database standards don't allow us to link on non-integer or uniqueidentifier fields, so storing the possible keys as characters is out as well.</p>
|
[
{
"answer_id": 262812,
"author": "Nikki9696",
"author_id": 456669,
"author_profile": "https://Stackoverflow.com/users/456669",
"pm_score": 6,
"selected": true,
"text": "ColumnName ENUM('upload', 'open', 'close', 'delete', 'edit', 'add')\n DEFAULT 'open'\n ColumnName varchar(10) \n CHECK(ColumnName IN ('upload', 'open', 'close', 'delete', 'edit', 'add')) \n DEFAULT 'open'\n"
}
] |
2008/11/04
|
[
"https://Stackoverflow.com/questions/262802",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/30407/"
] |
262,805
|
<p>This is a little convoluted, but lets try:</p>
<p>I'm integrating LUA scripting into my game engine, and I've done this in the past on win32 in an elegant way. On win32 all I did was to mark all of the functions I wanted to expose to LUA as export functions. Then, to integrate them into LUA, I'd parse the PE header of the executable, unmangle the names, parse the parameters and such, then register them with my LUA runtime. This allowed me to avoid manually registering every function individually just to expose them to LUA.</p>
<p>Now, flash forward to today where I'm working on the iPhone. I've looked through some Unix stuff and I've gotten very close to taking a similar approach, however I'm not sure it will actually work.</p>
<p>I'm not entirely familiar with Unix, but here is what I have so far on iPhone:</p>
<ol>
Step 1: Query for the executable path through objective-C and get the path of my app<br>
Step 2: Use dlopen to get a handle to my app using: `dlopen(path, RTLD_NOW)`<br>
Step 3: Use `dlsym( libraryHandle, objectName )` to attempt to get the address of a known symbol.
</ol>
<p>The above steps won't actually get me to where I want to be, but even that doesn't work. Does anyone have any experience doing this type of thing on Unix? Are there any headers or functions I can google to put me on the right track?</p>
<p>Thanks;)</p>
|
[
{
"answer_id": 262876,
"author": "CesarB",
"author_id": 28258,
"author_profile": "https://Stackoverflow.com/users/28258",
"pm_score": 0,
"selected": false,
"text": "--export-dynamic -Wl,--export-dynamic"
},
{
"answer_id": 263119,
"author": "Martin v. Löwis",
"author_id": 33006,
"author_profile": "https://Stackoverflow.com/users/33006",
"pm_score": 0,
"selected": false,
"text": " struct symbol{ char* name; void * value } symbols = [\n {\"foo\", foo},\n {\"bar\", bar},\n ...\n {0,0}};\n #define ForLua(X) X\n"
}
] |
2008/11/04
|
[
"https://Stackoverflow.com/questions/262805",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
262,816
|
<p>When would you call Java's <code>thread.run()</code> instead of <code>thread.start()</code>?</p>
|
[
{
"answer_id": 262819,
"author": "Chris Ballance",
"author_id": 1551,
"author_profile": "https://Stackoverflow.com/users/1551",
"pm_score": 3,
"selected": false,
"text": "thread.start() thread.run() thread.start() thread.run()"
},
{
"answer_id": 262869,
"author": "Steve B.",
"author_id": 19479,
"author_profile": "https://Stackoverflow.com/users/19479",
"pm_score": 2,
"selected": false,
"text": " public synchronized void start() {\n /**\n * This method is not invoked for the main method thread or \"system\"\n * group threads created/set up by the VM. Any new functionality added \n * to this method in the future may have to also be added to the VM.\n *\n * A zero status value corresponds to state \"NEW\".\n */\n if (threadStatus != 0)\n throw new IllegalThreadStateException();\n group.add(this);\n start0();\n if (stopBeforeStart) {\n stop0(throwableFromStop);\n }\n }\n\n private native void start0();\n"
},
{
"answer_id": 263015,
"author": "Scott Bale",
"author_id": 2495576,
"author_profile": "https://Stackoverflow.com/users/2495576",
"pm_score": 4,
"selected": false,
"text": "Executor"
},
{
"answer_id": 7187459,
"author": "alok",
"author_id": 911603,
"author_profile": "https://Stackoverflow.com/users/911603",
"pm_score": 3,
"selected": false,
"text": "start() run() start() run() start() run() run() run() run() run() start()"
},
{
"answer_id": 7785377,
"author": "Steer360",
"author_id": 893135,
"author_profile": "https://Stackoverflow.com/users/893135",
"pm_score": 3,
"selected": false,
"text": "/*\nBy calling t1.start(), \nwe are getting the main calling thread returned immediately \nafter the t1.start() called and is ready to proceed for other \noperations.And the thread t1 starts executing the run method of the object r. \nHence the the output will be:\n\n I am the main thread , i created thread t1 and had it execute run method, which is currently looping from 0 to 1000000\n\n I am done executing run method of testThread\n\n*/\n\n\n/* If we call t1.run() instead of t1.start(), (just replace t1.start() with t1.run() in the code for testing)\n its like a regular method call and the main thread will not return until the run method completes, \n hence the output will be:\n\n I am done executing run method of testThread\n\n I am the main thread , i created thread t1 and had it execute run method, which is currently looping for i to 1000000\n\n*/\n\n\nclass testThread implements Runnable{\n\n public void run()\n {\n for(int i=0;i<1000000;i++){} //a simple delay block to clarify.\n\n System.out.println(\"I am done executing run method of testThread\");\n\n } \n}\n\npublic class mainClass{\n\n public static void main(String [] args)\n {\n testThread r = new testThread();\n Thread t1 = new Thread(r);\n t1.start(); /* Question is: can we call instead t1.run() */ \n System.out.println(\"I am the main thread , i created thread t1 and had it execute run method, which is currently looping for i to 1000000\");\n\n }\n}\n"
},
{
"answer_id": 10679969,
"author": "Mahendra Liya",
"author_id": 562073,
"author_profile": "https://Stackoverflow.com/users/562073",
"pm_score": 5,
"selected": false,
"text": "thread.run() Thread thread.run() thread.start() run() run() start() run()"
},
{
"answer_id": 28525284,
"author": "Avatar Girase",
"author_id": 3290283,
"author_profile": "https://Stackoverflow.com/users/3290283",
"pm_score": 0,
"selected": false,
"text": "public class TestClass implements Runnable {\n public static void main(String[] args) {\n TestClass tc = new TestClass();\n\n Thread t1 = new Thread(tc);\n System.out.println(\"Before Starting Thread \" + Thread.currentThread().hashCode());\n t1.start();\n System.out.println(\"After Starting Thread \" + Thread.currentThread().hashCode());\n }\n\n @Override\n public void run() {\n System.out.println(\"TestClass Run method is Running with thread \" + Thread.currentThread().hashCode()); \n }\n}\n"
}
] |
2008/11/04
|
[
"https://Stackoverflow.com/questions/262816",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1348/"
] |
262,826
|
<p>A k-ary necklace of length n is an ordered list of length n whose items are drawn from an alphabet of length k, which is the lexicographically first list in a sort of all lists sharing an ordering under rotation.</p>
<p>Example:
(1 2 3) and (1 3 2) are the necklaces of length 3 from the alphabet {1 2 3}.</p>
<p>More info:
<a href="http://en.wikipedia.org/wiki/Necklace_(combinatorics)" rel="nofollow noreferrer">http://en.wikipedia.org/wiki/Necklace_(combinatorics)</a></p>
<p>I'd like to generate these in Scheme (or a Lisp of your choice). I've found some papers...<br>
Savage - A New Algorithm for Generating Necklaces<br>
Sawada - Generating Bracelets in Constant Amortized Time<br>
Sawada - Generating Necklaces with Forbidden Substrings<br>
...but the code presented in them is opaque to me. Mainly because they don't seem to be passing in either the alphabet or the length (n) desired. The scheme procedure I'm looking for is of the form (necklaces n '(a b c...)).</p>
<p>I can generate these easy enough by first generating k^n lists and then filtering out the rotations. But it's terribly memory-inefficient...</p>
<p>Thanks!</p>
|
[
{
"answer_id": 263020,
"author": "Andru Luvisi",
"author_id": 5922,
"author_profile": "https://Stackoverflow.com/users/5922",
"pm_score": 0,
"selected": false,
"text": "(define (choose n l)\n (let ((len (length l)))\n (cond ((= n 0) '(()))\n ((> n len) '())\n ((= n len) (list l))\n (else (append (map (lambda (x) (cons (car l) x))\n (choose (- n 1) (cdr l)))\n (choose n (cdr l)))))))\n\n(define (filter pred l)\n (cond ((null? l) '())\n ((pred (car l)) (cons (car l) (filter pred (cdr l))))\n (else (filter pred (cdr l)))))\n\n(define (permute l)\n (cond ((null? l) '(()))\n (else (apply append \n (map (lambda (x)\n (let ((rest (filter (lambda (y) (not (= x y))) l)))\n (map (lambda (subperm) (cons x subperm))\n (permute rest))))\n l)))))\n\n(define (necklaces n l)\n (apply\n append\n (map\n (lambda (combination)\n (map (lambda (permutation)\n (cons (car combination) permutation))\n (permute (cdr combination))))\n (choose n l))))\n\n\n(display (choose 1 '(1 2 3 4 5))) (newline)\n(display (choose 2 '(1 2 3 4 5))) (newline)\n(display (permute '(1 2))) (newline)\n(display (permute '(1 2 3))) (newline)\n(display (necklaces 3 '(1 2 3 4))) (newline)\n(display (necklaces 2 '(1 2 3 4))) (newline)\n"
},
{
"answer_id": 263292,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "(1 :: perm) perm"
},
{
"answer_id": 263307,
"author": "Jay Kominek",
"author_id": 32878,
"author_profile": "https://Stackoverflow.com/users/32878",
"pm_score": 2,
"selected": false,
"text": "(require srfi/43)\n\n(define (gennecklaces n alphabet)\n (let* ([necklaces '()]\n [alphavec (list->vector alphabet)]\n [convert-necklace\n (lambda (vec)\n (map (lambda (x) (vector-ref alphavec x)) (cdr (vector->list vec))))]\n [helper\n (lambda (n k)\n (let ([a (make-vector (+ n 1) 0)]\n [i n])\n (set! necklaces (cons (convert-necklace a) necklaces))\n (let/ec done\n (for ([X (in-naturals)])\n (vector-set! a i (add1 (vector-ref a i)))\n (for ([j (in-range 1 (add1 (- n i)))])\n (vector-set! a (+ j i)\n (vector-ref a j)))\n (when (= 0 (modulo n i))\n (set! necklaces (cons (convert-necklace a) necklaces)))\n (set! i n)\n (let/ec done\n (for ([X (in-naturals)])\n (unless (= (vector-ref a i)\n (- k 1))\n (done))\n (set! i (- i 1))))\n (when (= i 0)\n (done))))))])\n (helper n (length alphabet))\n necklaces))\n"
},
{
"answer_id": 265044,
"author": "Svante",
"author_id": 31615,
"author_profile": "https://Stackoverflow.com/users/31615",
"pm_score": 0,
"selected": false,
"text": "tau sigma"
}
] |
2008/11/04
|
[
"https://Stackoverflow.com/questions/262826",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
262,844
|
<p>I am trying to set the background color of a DataGridView row to red. I tried with the following line:</p>
<p>dgvActiveCalls.Rows[1].DefaultCellStyle.BackColor = Color.Red;</p>
<p>but it doesn't work. Then just to see if something is wrong with update I tried to paint the column instead of row:</p>
<p>dgvActiveCalls.Columns[1].DefaultCellStyle.BackColor = Color.Red;</p>
<p>and it worked fine. I would be really thankful if anyone could show the way to paint the DataGridView row.</p>
<p>Thanks!</p>
|
[
{
"answer_id": 53823906,
"author": "Carlos",
"author_id": 10413901,
"author_profile": "https://Stackoverflow.com/users/10413901",
"pm_score": 0,
"selected": false,
"text": "private void dgv_RowPrePaint(object sender, DataGridViewRowPrePaintEventArgs e)\n{\n /*Here you put your validation in order to paint only the row that you want*/\n if (e.RowIndex == 1)\n {\n DataGridViewRow row = ((DataGridView)sender).Rows[e.RowIndex];\n row.DefaultCellStyle.BackColor = Color.Red;\n } \n}\n"
}
] |
2008/11/04
|
[
"https://Stackoverflow.com/questions/262844",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/22996/"
] |
262,849
|
<p>The ASP.NET calendar always displays 6 weeks of dates in a 7x6 grid. My problem is that the first day of the target month does <em>not necessarily</em> appear in the first row... in some cases, the entire first row displays dates from the previous month. In other cases, the entire last row displays dates from the next row.
Is there a reliable way to query the calendar object to determine the 42-day range that would be rendered for a specific month/year?</p>
<p>For example, consider June 2008 and Feb 2009:</p>
<p><a href="http://img371.imageshack.us/img371/2290/datesmq5.png">Notice that the first week contains ONLY dates from prior month http://img371.imageshack.us/img371/2290/datesmq5.png</a></p>
<p>I assume that the calendar tries to avoid bunching all of the "other month" dates at either the top or bottom of the grid, and therefore puts the first of the target month on the 2nd row. I am looking for an easy way to determine that the displayed range for June 2008 is May 25 - July 5, for instance.</p>
|
[
{
"answer_id": 659646,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "if(m_FirstDay == false)\n{\n DateTime firstDate;\n DateTime lastDate;\n\n firstDate = e.Day.Date;\n lastDate = firstDate.AddDays(41);\n\n m_FirstDay = true;\n}\n"
},
{
"answer_id": 917803,
"author": "Ronnie Overby",
"author_id": 64334,
"author_profile": "https://Stackoverflow.com/users/64334",
"pm_score": 3,
"selected": false,
"text": "public static DateTime GetFirstDateOfMonth(DateTime date)\n{\n return new DateTime(date.Year, date.Month, 1);\n}\n\npublic static DateTime GetFirstDisplayedDate(DateTime date)\n{\n date = GetFirstDateOfMonth(date);\n return date.DayOfWeek == DayOfWeek.Sunday ? date.AddDays(-7) : date.AddDays((int)date.DayOfWeek * -1);\n}\n\npublic static List<DateTime> GetDisplayedDates(DateTime date)\n{\n date = GetFirstDisplayedDate(date);\n\n List<DateTime> dates = new List<DateTime>();\n for (int i = 0; i < 42; i++)\n {\n dates.Add(date.AddDays(i));\n }\n\n return dates;\n}\n"
},
{
"answer_id": 1608466,
"author": "Daniel Ives",
"author_id": 194733,
"author_profile": "https://Stackoverflow.com/users/194733",
"pm_score": 2,
"selected": false,
"text": "\n ...\n DateTime visibleDate = this.EffectiveVisibleDate();\n DateTime firstDay = this.FirstCalendarDay(visibleDate);\n ...\n\nprivate System.Globalization.Calendar threadCalendar = \n DateTimeFormatInfo.CurrentInfo.Calendar;\n\nprivate DateTime EffectiveVisibleDate()\n{\n DateTime visibleDate = this.VisibleDate;\n if (visibleDate.Equals(DateTime.MinValue))\n {\n visibleDate = this.TodaysDate;\n }\n if (this.IsMinSupportedYearMonth(visibleDate))\n {\n return this.minSupportedDate;\n }\n return this.threadCalendar.AddDays(visibleDate, \n -(this.threadCalendar.GetDayOfMonth(visibleDate) - 1));\n}\n\n\nprivate DateTime FirstCalendarDay(DateTime visibleDate)\n{\n DateTime date = visibleDate;\n if (this.IsMinSupportedYearMonth(date))\n {\n return date;\n }\n int num = ((int) \n this.threadCalendar.GetDayOfWeek(date)) - this.NumericFirstDayOfWeek();\n if (num <= 0)\n {\n num += 7;\n }\n return this.threadCalendar.AddDays(date, -num);\n}\n\nprivate int NumericFirstDayOfWeek()\n{\n if (this.FirstDayOfWeek != FirstDayOfWeek.Default)\n {\n return (int) this.FirstDayOfWeek;\n }\n return (int) DateTimeFormatInfo.CurrentInfo.FirstDayOfWeek;\n}\n\nprivate bool IsMinSupportedYearMonth(DateTime date)\n{\n return this.IsTheSameYearMonth(this.minSupportedDate, date);\n}\n\nprivate bool IsTheSameYearMonth(DateTime date1, DateTime date2)\n{\n return (((this.threadCalendar.GetEra(date1) == \n this.threadCalendar.GetEra(date2)) &&\n (this.threadCalendar.GetYear(date1) == \n this.threadCalendar.GetYear(date2))) &&\n (this.threadCalendar.GetMonth(date1) ==\n this.threadCalendar.GetMonth(date2)));\n}\n\n"
}
] |
2008/11/04
|
[
"https://Stackoverflow.com/questions/262849",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23632/"
] |
262,853
|
<p>The following code says that passing the map as <code>const</code> into the <code>operator[]</code> method discards qualifiers:</p>
<pre><code>#include <iostream>
#include <map>
#include <string>
using namespace std;
class MapWrapper {
public:
const int &get_value(const int &key) const {
return _map[key];
}
private:
map<int, int> _map;
};
int main() {
MapWrapper mw;
cout << mw.get_value(42) << endl;
return 0;
}
</code></pre>
<p>Is this because of the possible allocation that occurs on the map access? Can no functions with map accesses be declared const?</p>
<pre><code>MapWrapper.cpp:10: error: passing const std::map<int, int, std::less<int>,
std::allocator<std::pair<const int, int> > > as this argument of
_Tp& std::map<_Key, _Tp, _Compare, _Alloc>::operator[](const _Key&)
[with _Key = int, _Tp = int, _Compare = std::less<int>,
_Alloc = std::allocator<std::pair<const int, int> >] discards qualifiers
</code></pre>
|
[
{
"answer_id": 262863,
"author": "nlativy",
"author_id": 33635,
"author_profile": "https://Stackoverflow.com/users/33635",
"pm_score": 4,
"selected": false,
"text": "operator[] const const _map[key] find"
},
{
"answer_id": 262872,
"author": "luke",
"author_id": 16434,
"author_profile": "https://Stackoverflow.com/users/16434",
"pm_score": 8,
"selected": true,
"text": "std::map operator [] const const operator[] std::map find() find() iterator const_iterator std::pair .first .second at() std::map std::out_of_range operator []"
},
{
"answer_id": 262973,
"author": "Nathan Kitchen",
"author_id": 31000,
"author_profile": "https://Stackoverflow.com/users/31000",
"pm_score": 3,
"selected": false,
"text": "const mapped_type& at(const key_type& __k) const\n"
},
{
"answer_id": 21320644,
"author": "Richard",
"author_id": 752843,
"author_profile": "https://Stackoverflow.com/users/752843",
"pm_score": 5,
"selected": false,
"text": "operator[] VALUE = map.find(KEY)->second;\n at() VALUE = map.at(KEY);\n"
}
] |
2008/11/04
|
[
"https://Stackoverflow.com/questions/262853",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3594/"
] |
262,891
|
<p>A PHP array can have arrays for its elements. And those arrays can have arrays and so on and so forth. Is there a way to find out the maximum nesting that exists in a PHP array? An example would be a function that returns 1 if the initial array does not have arrays as elements, 2 if at least one element is an array, and so on.</p>
|
[
{
"answer_id": 262944,
"author": "Paige Ruten",
"author_id": 813,
"author_profile": "https://Stackoverflow.com/users/813",
"pm_score": 7,
"selected": true,
"text": "<?php\n\nfunction array_depth(array $array) {\n $max_depth = 1;\n\n foreach ($array as $value) {\n if (is_array($value)) {\n $depth = array_depth($value) + 1;\n\n if ($depth > $max_depth) {\n $max_depth = $depth;\n }\n }\n }\n\n return $max_depth;\n}\n\n?>\n"
},
{
"answer_id": 263621,
"author": "Paige Ruten",
"author_id": 813,
"author_profile": "https://Stackoverflow.com/users/813",
"pm_score": 6,
"selected": false,
"text": "function array_depth($array) {\n $max_indentation = 1;\n\n $array_str = print_r($array, true);\n $lines = explode(\"\\n\", $array_str);\n\n foreach ($lines as $line) {\n $indentation = (strlen($line) - strlen(ltrim($line))) / 4;\n\n if ($indentation > $max_indentation) {\n $max_indentation = $indentation;\n }\n }\n\n return ceil(($max_indentation - 1) / 2) + 1;\n}\n"
},
{
"answer_id": 2629589,
"author": "dave1010",
"author_id": 315435,
"author_profile": "https://Stackoverflow.com/users/315435",
"pm_score": 2,
"selected": false,
"text": "// you never know if a future version of PHP will have this in core\nif (!function_exists('array_depth')) {\nfunction array_depth($array) {\n // some functions that usually return an array occasionally return false\n if (!is_array($array)) {\n return 0;\n }\n\n $max_indentation = 1;\n // PHP_EOL in case we're running on Windows\n $lines = explode(PHP_EOL, print_r($array, true));\n\n foreach ($lines as $line) {\n $indentation = (strlen($line) - strlen(ltrim($line))) / 4;\n $max_indentation = max($max_indentation, $indentation);\n }\n return ceil(($max_indentation - 1) / 2) + 1;\n}\n}\n print array_depth($GLOBALS)"
},
{
"answer_id": 3673129,
"author": "Asim",
"author_id": 442975,
"author_profile": "https://Stackoverflow.com/users/442975",
"pm_score": 1,
"selected": false,
"text": "// very simple and clean approach \nfunction array_depth($a) {\n static $depth = 0;\n if(!is_array($a)) {\n return $depth;\n }else{\n $depth++;\n array_map(\"array_depth\", $a);\n return $depth;\n }\n }\nprint \"depth:\" . array_depth(array('k9' => 'dog')); // return 1\n"
},
{
"answer_id": 3899541,
"author": "fncomp",
"author_id": 455581,
"author_profile": "https://Stackoverflow.com/users/455581",
"pm_score": 2,
"selected": false,
"text": "function deepness(array $arr){\n $exploded = explode(',', json_encode($arr, JSON_FORCE_OBJECT).\"\\n\\n\");\n $longest = 0;\n foreach($exploded as $row){\n $longest = (substr_count($row, ':')>$longest)?\n substr_count($row, ':'):$longest;\n }\n return $longest;\n}\n"
},
{
"answer_id": 3909129,
"author": "Jonathan H",
"author_id": 472610,
"author_profile": "https://Stackoverflow.com/users/472610",
"pm_score": 1,
"selected": false,
"text": "function array_depth($arr)\n{\n if (!is_array($arr)) { return 0; }\n $arr = json_encode($arr);\n\n $varsum = 0; $depth = 0;\n for ($i=0;$i<strlen($arr);$i++)\n {\n $varsum += intval($arr[$i] == '[') - intval($arr[$i] == ']');\n if ($varsum > $depth) { $depth = $varsum; }\n }\n\n return $depth;\n}\n"
},
{
"answer_id": 5056433,
"author": "shachibista",
"author_id": 2654307,
"author_profile": "https://Stackoverflow.com/users/2654307",
"pm_score": 2,
"selected": false,
"text": "function createDeepArray(){\n static $depth;\n $depth++;\n $a = array();\n if($depth <= 10000){\n $a[] = createDeepArray();\n }\n return $a;\n}\n$deepArray = createDeepArray();\n\nfunction deepness(array $arr){\n $exploded = explode(',', json_encode($arr, JSON_FORCE_OBJECT).\"\\n\\n\");\n $longest = 0;\n foreach($exploded as $row){\n $longest = (substr_count($row, ':')>$longest)?\n substr_count($row, ':'):$longest;\n }\n return $longest;\n}\n\nfunction array_depth($arr)\n{\n if (!is_array($arr)) { return 0; }\n $arr = json_encode($arr);\n\n $varsum = 0; $depth = 0;\n for ($i=0;$i<strlen($arr);$i++)\n {\n $varsum += intval($arr[$i] == '[') - intval($arr[$i] == ']');\n if ($varsum > $depth) { $depth = $varsum; }\n }\n\n return $depth;\n}\n\necho 'deepness():', \"\\n\";\n\n$start_time = microtime(TRUE);\n$start_memory = memory_get_usage();\nvar_dump(deepness($deepArray));\n$end_time = microtime(TRUE);\n$end_memory = memory_get_usage();\necho 'Memory: ', ($end_memory - $start_memory), \"\\n\";\necho 'Time: ', ($end_time - $start_time), \"\\n\";\n\necho \"\\n\";\necho 'array_depth():', \"\\n\";\n\n$start_time = microtime(TRUE);\n$start_memory = memory_get_usage();\nvar_dump(array_depth($deepArray));\n$end_time = microtime(TRUE);\n$end_memory = memory_get_usage();\necho 'Memory: ', ($end_memory - $start_memory), \"\\n\";\necho 'Time: ', ($end_time - $start_time), \"\\n\";\n $ for i in `seq 1 10`; do php test.php; echo '-------------------------';done\ndeepness():\nint(10000)\nMemory: 164\nTime: 0.0079939365386963\n\narray_depth():\nint(10001)\nMemory: 0\nTime: 0.043087005615234\n-------------------------\ndeepness():\nint(10000)\nMemory: 164\nTime: 0.0076408386230469\n\narray_depth():\nint(10001)\nMemory: 0\nTime: 0.042832851409912\n-------------------------\ndeepness():\nint(10000)\nMemory: 164\nTime: 0.0080249309539795\n\narray_depth():\nint(10001)\nMemory: 0\nTime: 0.042320966720581\n-------------------------\ndeepness():\nint(10000)\nMemory: 164\nTime: 0.0076301097869873\n\narray_depth():\nint(10001)\nMemory: 0\nTime: 0.041887998580933\n-------------------------\ndeepness():\nint(10000)\nMemory: 164\nTime: 0.0079131126403809\n\narray_depth():\nint(10001)\nMemory: 0\nTime: 0.04217004776001\n-------------------------\ndeepness():\nint(10000)\nMemory: 164\nTime: 0.0078539848327637\n\narray_depth():\nint(10001)\nMemory: 0\nTime: 0.04179310798645\n-------------------------\ndeepness():\nint(10000)\nMemory: 164\nTime: 0.0080208778381348\n\narray_depth():\nint(10001)\nMemory: 0\nTime: 0.04272198677063\n-------------------------\ndeepness():\nint(10000)\nMemory: 164\nTime: 0.0077919960021973\n\narray_depth():\nint(10001)\nMemory: 0\nTime: 0.041619062423706\n-------------------------\ndeepness():\nint(10000)\nMemory: 164\nTime: 0.0080950260162354\n\narray_depth():\nint(10001)\nMemory: 0\nTime: 0.042663097381592\n-------------------------\ndeepness():\nint(10000)\nMemory: 164\nTime: 0.0076849460601807\n\narray_depth():\nint(10001)\nMemory: 0\nTime: 0.042278051376343\n"
},
{
"answer_id": 8420027,
"author": "cmosversion",
"author_id": 1086213,
"author_profile": "https://Stackoverflow.com/users/1086213",
"pm_score": 1,
"selected": false,
"text": "function array_depth($arr){\nif (is_array($arr)) {\n array_walk($arr, \n function($val, $key) use(&$arr) {\n if ((! is_string($val)) && (! is_array($val))) {\n $val = json_encode($val, JSON_FORCE_OBJECT);\n }\n\n if (is_string($val)) {\n $arr[$key] = preg_replace('/[:,]+/', '', $val);\n }\n }\n );\n\n $json_strings = explode(',', json_encode($arr, JSON_FORCE_OBJECT));\n\n $max_depth = 0;\n\n foreach ($json_strings as $json_string){\n var_dump($json_string); echo \"<br/>\";\n $json_string = preg_replace('/[^:]{1}/', '', $json_string);\n var_dump($json_string); echo \"<br/><br/>\";\n $depth = strlen($json_string);\n\n if ($depth > $max_depth) {\n $max_depth = $depth;\n }\n }\n\n return $max_depth;\n }\n\n return FALSE;\n }\n\n\n function array_sort_by_depth(&$arr_val, $reverse = FALSE) {\n\n if ( is_array($arr_val)) { \n $temp_arr = array();\n $result_arr = array();\n\n foreach ($arr_val as $key => $val) {\n $temp_arr[$key] = array_depth($val);\n }\n\n if (is_bool($reverse) && $reverse == TRUE) {\n arsort($temp_arr);\n }\n else {\n asort($temp_arr);\n }\n\n foreach ($temp_arr as $key => $val) {\n $result_arr[$key] = $arr_val[$key];\n }\n\n $arr_val = $result_arr;\n\n return TRUE;\n }\n\n return FALSE;\n }\n"
},
{
"answer_id": 10858631,
"author": "Sasan",
"author_id": 1431772,
"author_profile": "https://Stackoverflow.com/users/1431772",
"pm_score": 1,
"selected": false,
"text": "function array_depth(&$array) {\n $max_depth = 1;\n $array['__compute_array_depth_flag_ZXCNADJHHDKAQP'] = 1;\n\n foreach ($array as $value) {\n if (is_array($value) &&\n !isset($value['__compute_array_depth_flag_ZXCNADJHHDKAQP'])) {\n $depth = array_depth($value) + 1;\n\n if ($depth > $max_depth) {\n $max_depth = $depth;\n }\n }\n }\n unset($array['__compute_array_depth_flag_ZXCNADJHHDKAQP']);\n\n return $max_depth;\n}\n"
},
{
"answer_id": 11164010,
"author": "Pranaya",
"author_id": 1475927,
"author_profile": "https://Stackoverflow.com/users/1475927",
"pm_score": -1,
"selected": false,
"text": "max(array_map('count', $array));\n"
},
{
"answer_id": 13107456,
"author": "Amir Syafrudin",
"author_id": 1780509,
"author_profile": "https://Stackoverflow.com/users/1780509",
"pm_score": 2,
"selected": false,
"text": "function array_depth($array, $childrenkey)\n{\n $max_depth = 1;\n\n if (!empty($array[$childrenkey]))\n {\n foreach ($array[$childrenkey] as $value)\n {\n if (is_array($value))\n {\n $depth = array_depth($value, $childrenkey) + 1;\n\n if ($depth > $max_depth)\n {\n $max_depth = $depth;\n }\n }\n }\n }\n\n return $max_depth;\n}\n $my_array_depth = array_depth($my_array, 'the_key_name_storing_child_elements');\n"
},
{
"answer_id": 13108304,
"author": "Amir Syafrudin",
"author_id": 1780603,
"author_profile": "https://Stackoverflow.com/users/1780603",
"pm_score": 2,
"selected": false,
"text": "function array_depth($array, $childrenkey = \"_no_children_\")\n{\n if (!empty($array[$childrenkey]))\n {\n $array = $array[$childrenkey];\n }\n\n $max_depth = 1;\n\n foreach ($array as $value)\n {\n if (is_array($value))\n {\n $depth = array_depth($value, $childrenkey) + 1;\n\n if ($depth > $max_depth)\n {\n $max_depth = $depth;\n }\n }\n }\n\n return $max_depth;\n}\n $my_array_depth = array_depth($my_array, 'the_key_name_storing_child_elements');\n $my_array_depth = array_depth($my_array);\n"
},
{
"answer_id": 19036761,
"author": "Erick Briseño",
"author_id": 2820877,
"author_profile": "https://Stackoverflow.com/users/2820877",
"pm_score": 3,
"selected": false,
"text": "/*** IN mixed (any value),OUT (string)maxDepth ***/\n/*** Retorna la profundidad maxima de un array ***/\nfunction getArrayMaxDepth($input){\n if( ! canVarLoop($input) ) { return \"0\"; }\n $arrayiter = new RecursiveArrayIterator($input);\n $iteriter = new RecursiveIteratorIterator($arrayiter);\n foreach ($iteriter as $value) {\n //getDepth() start is 0, I use 0 for not iterable values\n $d = $iteriter->getDepth() + 1;\n $result[] = \"$d\";\n }\n return max( $result );\n}\n/*** IN mixed (any value),OUT (bool)true/false, CHECK if can be used by foreach ***/\n/*** Revisa si puede ser iterado con foreach ***/\nfunction canVarLoop($input) {\n return (is_array($input) || $input instanceof Traversable) ? true : false;\n}\n"
},
{
"answer_id": 39840810,
"author": "Linguisto",
"author_id": 5157563,
"author_profile": "https://Stackoverflow.com/users/5157563",
"pm_score": 2,
"selected": false,
"text": "<?php\nfunction array_depth(array $array)\n{\n $depth = 1;\n foreach ($array as $value) {\n if (is_array($value)) {\n $depth += array_depth($value);\n break;\n }\n }\n\n return $depth;\n}\n"
},
{
"answer_id": 40725952,
"author": "TwystO",
"author_id": 1219011,
"author_profile": "https://Stackoverflow.com/users/1219011",
"pm_score": 3,
"selected": false,
"text": "function getArrayDepth($array) {\n $depth = 0;\n $iteIte = new RecursiveIteratorIterator(new RecursiveArrayIterator($array));\n\n foreach ($iteIte as $ite) {\n $d = $iteIte->getDepth();\n $depth = $d > $depth ? $d : $depth;\n }\n\n return $depth;\n}\n"
},
{
"answer_id": 51337703,
"author": "tonix",
"author_id": 3019105,
"author_profile": "https://Stackoverflow.com/users/3019105",
"pm_score": 0,
"selected": false,
"text": "function maxDepth($array) {\n $iterator = new \\RecursiveIteratorIterator(new \\RecursiveArrayIterator($array), \\RecursiveIteratorIterator::CHILD_FIRST);\n $iterator->rewind();\n $maxDepth = 0;\n foreach ($iterator as $k => $v) {\n $depth = $iterator->getDepth();\n if ($depth > $maxDepth) {\n $maxDepth = $depth;\n }\n }\n return $maxDepth;\n}\n"
},
{
"answer_id": 59994664,
"author": "jspit",
"author_id": 7271221,
"author_profile": "https://Stackoverflow.com/users/7271221",
"pm_score": 0,
"selected": false,
"text": "//Get the dimension or depth of an array\nfunction array_depth($arr)\n{\n if (!is_array($arr)) return 0;\n if (empty($arr)) return 1;\n return max(array_map(__FUNCTION__,$arr))+1;\n}\n"
},
{
"answer_id": 68595201,
"author": "Stackoverflow",
"author_id": 7180968,
"author_profile": "https://Stackoverflow.com/users/7180968",
"pm_score": 1,
"selected": false,
"text": "function Dim_Ar($A, $i){\n if(!is_array($A))return 0;\n $t[] = 1;\n foreach($A AS $e)if(is_array($e))$t[] = Dim_Ar($e, ++ $i) + 1;\n return max($t);\n }\n\n$Q = ARRAY(); // dimension one\n$Q = ARRAY(1); // dimension one\n$Q = ARRAY(ARRAY(ARRAY()), ARRAY(1, 1, 1)); // dimension is two\n$Q = ARRAY(ARRAY()); // dimension is two\n$Q = ARRAY(1, 1, 1, ARRAY(), ARRAY(), ARRAY(1)); // dimension is two\n$Q = ARRAY(1, 2, 3, ARRAY(ARRAY(1, 1, 1))); // dimension is two\n$Q = ARRAY(ARRAY(ARRAY()), ARRAY()); // dimension is three\n$Q = ARRAY(ARRAY(ARRAY()), ARRAY()); // dimension three\n$Q = ARRAY(ARRAY(ARRAY()), ARRAY(ARRAY())); // dimension is three\n$Q = ARRAY('1', '2', '3', ARRAY('Q', 'W'), ARRAY('Q', 'W'), ARRAY('Q', 'W'), ARRAY('Q', 'W'), 'pol, y juan', 'sam, y som', '1', '2', 'OPTIONS1' => ARRAY('1', '2', '9'), 'OOO' => ARRAY('1', '2', '9'), 'OPTIONS3' => ARRAY('1', '2', '9', '1', '2', '9', '1', '2', '9', '1', '2', '9', '1', '2', '9'), '3', ARRAY('Q', 'W'), 'OPTIONS2' => ARRAY('1', '2'));\n$Q = ARRAY('1', '2', '3', '', ARRAY('Q, sam', 'W', '', '0'), 'ppppppol, y juan', 'sam, y som', '1', '2', 'OPTIONS1' => ARRAY('1', '2', 'ss, zz'), '3', 'PP' => ARRAY('Q', 'WWW', 'Q', 'BMW'), ARRAY('Q', 'YYWW'), 'OPTIONS2' => ARRAY('1', '2', '9'), ARRAY('1', '2', '3'), '33', '33', '33', ARRAY('1', '2', '3', ARRAY(1, 2)));\n\necho Dim_Ar($Q, 0);\n"
}
] |
2008/11/04
|
[
"https://Stackoverflow.com/questions/262891",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/572/"
] |
262,922
|
<p>I don't find the oft-used "*" to be very nice looking - can anyone suggest a nicer-looking method or point me to an example?</p>
<p>I tried making the field highlighted in red as one person suggested but I did not like the look.</p>
<p>Bold labels might do the trick.</p>
<p>But I really like the idea of "Required" being shown in grey in the field until text is added. Does anyone have code for this?</p>
|
[
{
"answer_id": 262995,
"author": "Huntrods",
"author_id": 33977,
"author_profile": "https://Stackoverflow.com/users/33977",
"pm_score": 3,
"selected": false,
"text": ".mandatory <input id=\"username\" type=\"text\" class=\"mandatory\" />\n .mandatory {\n color: red;\n font-size: 12pt;\n font-weight: bold;\n font-style: italic;\n}\n"
}
] |
2008/11/04
|
[
"https://Stackoverflow.com/questions/262922",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/32122/"
] |
262,924
|
<p>In MySql's interpreter, it's very easy to dump a table to the screen along with its field names. </p>
<p>There seems to be no simple way to export a table to a tab-delimted or CSV outfile <em>including</em> its column headers.</p>
<p>I'm trying to do this using only SQL or the Linux command line, without writing a program in another language.</p>
<p>Thank you</p>
|
[
{
"answer_id": 263000,
"author": "Vinko Vrsalovic",
"author_id": 5190,
"author_profile": "https://Stackoverflow.com/users/5190",
"pm_score": 5,
"selected": true,
"text": "$ echo \"select * from surveys limit 5\" | mysql -uroot -pGandalf surveys\nphone param1 param2 param3 param4 p0 p1 p2 p3 audio4 code time\nXXXXXXXXX 2008-07-02 11:17:23 XXXXXXXX SAT - - - - - ERROR 2008-07-02 12:18:32\nXXXXXXXXX 2008-07-02 11:22:52 XXXXXXXX SAT - - - - - COLGADO 2008-07-02 12:04:29\nXXXXXXXXX 2008-07-02 11:41:29 XXXXXXXX SAT - - - - - COLGADO 2008-07-02 12:07:22\nXXXXXXXXX 2008-07-02 12:16:19 XXXXXXXX SAT 1 1 1 9 XXXXXXXXX_4.wav OK 2008-07-02 16:14:27\nXXXXXXXXX 2008-07-02 08:21:25 XXXXXXXX SAT 1 1 1 1 XXXXXXXXX_4.wav OK 2008-07-02 12:29:40\n"
},
{
"answer_id": 9976449,
"author": "cafe876",
"author_id": 1308011,
"author_profile": "https://Stackoverflow.com/users/1308011",
"pm_score": 3,
"selected": false,
"text": "select 'mytable' into @tableName;\nselect 'c://temp/test.csv' into @outputFile;\n select group_concat(concat(\"'\",column_name, \"'\")) into @columnNames from information_schema.columns\nwhere table_name=@tableName;\n SET @query = CONCAT(\n\"select * from\n((SELECT \",@columnNames,\")\nUNION\n(SELECT * FROM `\",@tableName,\"`)) as a\nINTO OUTFILE '\", @outputFile, \"'\");\n PREPARE stmt FROM @query;\nEXECUTE stmt;\n"
},
{
"answer_id": 11160933,
"author": "aizquier",
"author_id": 998421,
"author_profile": "https://Stackoverflow.com/users/998421",
"pm_score": 2,
"selected": false,
"text": "echo \"select * from table\"| mysql database -B -udbuser -puser_passwd | sed s/\\\\t/,/g > query_output.csv\n"
},
{
"answer_id": 11172666,
"author": "Lifeboy",
"author_id": 1477308,
"author_profile": "https://Stackoverflow.com/users/1477308",
"pm_score": 0,
"selected": false,
"text": "SELECT ... INTO OUTFILE"
},
{
"answer_id": 48380146,
"author": "aiffin",
"author_id": 7539689,
"author_profile": "https://Stackoverflow.com/users/7539689",
"pm_score": 0,
"selected": false,
"text": "echo \"select user_pass from wp_users\"| mysql -uroot -proot wp_database > passwordList.txt\n"
}
] |
2008/11/04
|
[
"https://Stackoverflow.com/questions/262924",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23929/"
] |
262,925
|
<p>Is it allowable to pass parameters to a web page through the URL (after the question mark) when using the POST method? I know that it works (most of the time, anyways) because my company's webapp does it often, but I don't know if it's actually supported in the standard or if I can rely on this behavior. I'm considering implementing a SOAP request handler that uses a parameter after the question mark to indicate that it is a SOAP request and not a normal HTTP request. The reason for this that the webapp is an IIS extension, so everything is accessed via the same URL (ex: example.com/myisapi.dll?command), so to get the SOAP request to be processed, I need to specify that "command" parameter. There would be one generic command for SOAP, not a specific command for each SOAP action -- those would be specified in the SOAP request itself.</p>
<p>Basically, I'm trying to integrate the Apache Axis2/C library into my webapp by letting the webapp handle the HTTP request and then pass off the incoming SOAP XML to Axis2 for handling if it's a SOAP request. Intuitively, I can't see any reason why this wouldn't work, since the URL you're posting to is just an arbitrary URL, as far as all the various components are concerned... it's the server that gives special meaning to the parts after the question mark.</p>
<p>Thanks for any help/insight you can provide.</p>
|
[
{
"answer_id": 262997,
"author": "Owen",
"author_id": 4853,
"author_profile": "https://Stackoverflow.com/users/4853",
"pm_score": 2,
"selected": false,
"text": "$ telnet localhost 80\nPOST /page.html?id=5 HTTP/1.1\nhost: localhost\n"
}
] |
2008/11/04
|
[
"https://Stackoverflow.com/questions/262925",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10861/"
] |
262,932
|
<p>In C++, is (int) ch equivalent to int(ch). </p>
<p>If not, what's the difference?</p>
|
[
{
"answer_id": 263003,
"author": "Adam Rosenfield",
"author_id": 9530,
"author_profile": "https://Stackoverflow.com/users/9530",
"pm_score": 5,
"selected": true,
"text": "(int)(ch) static_cast static_cast<char>(anInteger) dynamic_cast dynamic_cast<Derived *>(aBasePtr) reinterpret_cast reinterpret_cast<uintptr_t>(somePtr) const_cast const volatile const_cast<char *>(aConstantPointer)"
},
{
"answer_id": 263016,
"author": "Konrad Rudolph",
"author_id": 1968,
"author_profile": "https://Stackoverflow.com/users/1968",
"pm_score": 3,
"selected": false,
"text": "int(x)"
},
{
"answer_id": 263038,
"author": "Chris Jefferson",
"author_id": 27074,
"author_profile": "https://Stackoverflow.com/users/27074",
"pm_score": -1,
"selected": false,
"text": "#define int(x) 1\n"
}
] |
2008/11/04
|
[
"https://Stackoverflow.com/questions/262932",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/32944/"
] |
262,940
|
<p>I'm trying to convert my sites from CF8 to openBD. I have a cfloop in a site that loops over a date range.</p>
<p>In essence, I want to insert a new record into the db for every 2 weeks (step) of a date range (from and to)</p>
<p>my loop looks like this... </p>
<pre><code><cfloop
from = "#form.startDate#"
to = "#form.endDate#"
index = "i"
step = "#theStep#"
>
</code></pre>
<p>This works perfectly in CF8, in openBD, I get this error...
Data not supported: value [11/05/09] is not a number</p>
<p>Any ideas of a work around?</p>
<p>Thx</p>
|
[
{
"answer_id": 263254,
"author": "Ben Doom",
"author_id": 12267,
"author_profile": "https://Stackoverflow.com/users/12267",
"pm_score": 0,
"selected": false,
"text": "<cfset current = [your begin date]>\n<cfloop condition = \"datecompare(enddate, current)\">\n [do stuff]\n <cfset current = dateadd('d', 14, current)>\n</cfloop>\n"
},
{
"answer_id": 263808,
"author": "Peter Boughton",
"author_id": 9360,
"author_profile": "https://Stackoverflow.com/users/9360",
"pm_score": 0,
"selected": false,
"text": "<cfloop index=\"Current\" from=\"#parseDateTime(StartDate)#\" to=\"#parseDateTime(EndDate)#\" step=\"14\">\n [do stuff]\n</cfloop>\n"
},
{
"answer_id": 266843,
"author": "Tomalak",
"author_id": 18771,
"author_profile": "https://Stackoverflow.com/users/18771",
"pm_score": 1,
"selected": false,
"text": "<cfset SetLocale(\"English (US)\")> <!--- set expected input locale here --->\n\n<cfif LSIsDate(form.startDate) and LSIsDate(form.endDate)>\n <cfset theStep = 14>\n\n <cfloop \n from = \"#LSParseDate(form.startDate)#\" \n to = \"#LSParseDate(form.endDate)#\" \n index = \"i\" \n step = \"#theStep#\"\n >\n <!--- do stuff --->\n </cfloop>\n<cfelse>\n <!--- output some error message --->\n</cfif>\n"
}
] |
2008/11/04
|
[
"https://Stackoverflow.com/questions/262940",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/26121/"
] |
262,949
|
<p>I have a RegEx that is working for me but I don't know WHY it is working for me. I'll explain.</p>
<pre><code>RegEx: \s*<in.*="(<?.*?>)"\s*/>\s*
</code></pre>
<p><br>
Text it finds (it finds the white-space before and after the input tag):</p>
<pre><code><td class="style9">
<input name="guarantor4" id="guarantor4" size="50" type="text" tabindex="10" value="<?php echo $data[guarantor4]; ?>" /> </td>
</tr>
</code></pre>
<p><br>The part I don't understand:</p>
<pre><code><in.*=" <--- As I understand it, this should only find up to the first =" as in it should only find <input name="
It actually finds: <input name="guarantor4" id="guarantor4" size="50" type="text" tabindex="10" value=" which happened to be what I was trying to do.
</code></pre>
<p>What am I not understanding about this RegEx?</p>
|
[
{
"answer_id": 262959,
"author": "eyelidlessness",
"author_id": 17964,
"author_profile": "https://Stackoverflow.com/users/17964",
"pm_score": 3,
"selected": false,
"text": ".* .*? ="
},
{
"answer_id": 262968,
"author": "Kent Fredric",
"author_id": 15614,
"author_profile": "https://Stackoverflow.com/users/15614",
"pm_score": 4,
"selected": true,
"text": "<in[^=]*= \n .*? \n .+?\n <in.*?=id\n"
},
{
"answer_id": 60834067,
"author": "regeXGuru4",
"author_id": 13116827,
"author_profile": "https://Stackoverflow.com/users/13116827",
"pm_score": 2,
"selected": false,
"text": ".*? 101000000000100 1.*1 * 1 1010000000001 .*? * 1 101"
}
] |
2008/11/04
|
[
"https://Stackoverflow.com/questions/262949",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16292/"
] |
262,953
|
<p>I have been struggling with versioning software for a while now.
I'm not talking about a naming convention, I'm talking about how to actually apply a version in a build system all the way through to a release.</p>
<p>I generally use major.minor.maintenance-[release type]
i.e. 1.0.2-rc1</p>
<p>The problem is managing the version number. I've tried many ways (sticking it in a build file, a properties file, a database, etc,etc) but I haven't found anything that really works well.</p>
<p>The closest thing I came up with is using Jira which I documented here:
<a href="http://blog.sysbliss.com/uncategorized/release-management-with-atlassian-bamboo-and-jira.html" rel="nofollow noreferrer">http://blog.sysbliss.com/uncategorized/release-management-with-atlassian-bamboo-and-jira.html</a></p>
<p>I'm wondering if anyone has any good ideas about this.
Also, wondering how people handle releasing a version.... i.e. If I release/deploy version 1.0.0-rc1 do bugs found in this release then get logged into 1.0.0 (the next/production release).</p>
|
[
{
"answer_id": 262981,
"author": "warren",
"author_id": 4418,
"author_profile": "https://Stackoverflow.com/users/4418",
"pm_score": 2,
"selected": false,
"text": "<major>.<minor>.<patch>-<build number> <major>.<minor>.<buildnumber>"
},
{
"answer_id": 263025,
"author": "silverbugg",
"author_id": 29650,
"author_profile": "https://Stackoverflow.com/users/29650",
"pm_score": 0,
"selected": false,
"text": "<major>.<minor>.<buildnumber>"
},
{
"answer_id": 263716,
"author": "Ken Gentle",
"author_id": 8709,
"author_profile": "https://Stackoverflow.com/users/8709",
"pm_score": 1,
"selected": false,
"text": "releasing"
}
] |
2008/11/04
|
[
"https://Stackoverflow.com/questions/262953",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/34336/"
] |
262,966
|
<p>I have a problem with Gridview sorting that is similar to others but I'm binding to a collection object as opposed to a data table.</p>
<p>The existing business rules and data access layers of an application follow the pattern of having an object and, if you need a collection of objects of that type, to have another class inheriting CollectionBase and implementing IBindingList.</p>
<p>For desktop applications, it was easy to databind a gridview to one of these objects and there weren't any problems with turning on column sorting. Everything was 'in state' in the desktop app's presentation layer.</p>
<p>Now that code is being moved to a new web application (ASP.NET 2.0, VB codebehind pages).</p>
<p>I've played around with what I had to do to only have certain columns of the collection show up in the gridview and the gridview looked pretty good. When I turned on 'allow sorting', that's when the problems showed up.</p>
<p>I'm getting the error about not having a .Sorting method, etc. In researching this, I found all sorts of solutions that were easily implemented with dataviews <em>if</em> my source was a data table. But it's not - it's a collection. I tried to "cheap shot" a datasource by converting the collection to an XML memory stream and them trying to .ReadXML back into a dataset but that didn't work [Root element is missing error was as far as I got in the dataset.ReadXml(ioTemp) where ioTemp was the System.IO.MemoryStream used in the xml serializer].</p>
<p>Because of the old desktop apps, I've never had to worry about sorting a collection since the gridview handled it once it was loaded. In fact, it's a 'standard' that the collection's .SortProperty, .SortDirection and .ApplySort all through NotSupportedExceptions (I inherited this code from programmers long gone).</p>
<p>Is there an easy way to convert the collection to a data table or a way to sort the collection without having to go back to the database each time? Object Data Sources won't work becuase of the intricate rules in how the objects are built - the wizards in VS2005 just can't handle what we need to do (grabbing data from several tables conditionally to make an object).</p>
<p>Thanks in advance.</p>
|
[
{
"answer_id": 1999261,
"author": "David",
"author_id": 15891,
"author_profile": "https://Stackoverflow.com/users/15891",
"pm_score": 1,
"selected": true,
"text": "Public Overloads Sub Sort(ByVal strPropertyName As String, ByVal strDirection As String)\n Dim arSortedList As New ArrayList\n For Each item As MyBusinessObject In Me\n arSortedList.Add(item)\n Next\n arSortedList.Sort(New CaseInsensitiveComparer(Of MyBusinessObject)(strPropertyName, strDirection))\n For intI As Integer = 0 To arSortedList.Count - 1\n Item(intI) = arSortedList(intI)\n Next\nEnd Sub\n"
}
] |
2008/11/04
|
[
"https://Stackoverflow.com/questions/262966",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15891/"
] |
262,975
|
<p>Is there a way to set repository config variables through the gitosis conf instead of going into each repository and editing the conf values directly?</p>
|
[
{
"answer_id": 51199516,
"author": "VonC",
"author_id": 6309,
"author_profile": "https://Stackoverflow.com/users/6309",
"pm_score": 0,
"selected": false,
"text": "config sectionname.keyname = value\n repo gitolite\n config hooks.mailinglist = gitolite-commits@example.tld\n config hooks.emailprefix = \"[gitolite] \"\n config foo.bar = \"\"\n git config section.key value git config --unset-all section.key git config --add"
}
] |
2008/11/04
|
[
"https://Stackoverflow.com/questions/262975",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4883/"
] |
263,005
|
<p>In Linux When I invoke python from the shell it replicates its environment, and starts the python process. Therefore if I do something like the following:</p>
<pre><code>import os
os.environ["FOO"] = "A_Value"
</code></pre>
<p>When the python process returns, FOO, assuming it was undefined originally, will still be undefined. Is there a way for the python process (or any child process) to modify the environment of its parent process?</p>
<p>I know you typically solve this problem using something like</p>
<pre><code>source script_name.sh
</code></pre>
<p>But this conflicts with other requirements I have.</p>
|
[
{
"answer_id": 263068,
"author": "S.Lott",
"author_id": 10661,
"author_profile": "https://Stackoverflow.com/users/10661",
"pm_score": 6,
"selected": true,
"text": "/bin/bash -i"
},
{
"answer_id": 263162,
"author": "JimB",
"author_id": 32880,
"author_profile": "https://Stackoverflow.com/users/32880",
"pm_score": 4,
"selected": false,
"text": "#!/usr/bin/env python\nprint 'FOO=\"A_Value\"'\n #!/bin/bash\neval `./child.py`\n"
},
{
"answer_id": 73166920,
"author": "André C. Andersen",
"author_id": 604048,
"author_profile": "https://Stackoverflow.com/users/604048",
"pm_score": 0,
"selected": false,
"text": "envtest.py import sys, os\nsys.stdout = open(os.devnull, 'w')\n\n# Python code with any number of prints (to stdout).\nprint(\"This is some other logic, which shouldn't pollute stdout.\")\n\nsys.stdout = sys.__stdout__\nprint(\"SomeValue\")\n export MYVAR=$(python3 envtest.py)\necho \"MYVAR is $MYVAR\"\n MYVAR is SomeValue"
}
] |
2008/11/04
|
[
"https://Stackoverflow.com/questions/263005",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/34329/"
] |
263,013
|
<p>I'm working on a project for school, and I'm implementing a tool which can be used to download files from the web ( with a throttling option ). The thing is, I'm gonna have a GUI for it, and I will be using a <code>JProgressBar</code> widget, which I would like to show the current progress of the download. For that I would need to know the size of the file. How do you get the size of the file prior to downloading the file. </p>
|
[
{
"answer_id": 263037,
"author": "matt b",
"author_id": 4249,
"author_profile": "https://Stackoverflow.com/users/4249",
"pm_score": 6,
"selected": true,
"text": "//once the connection has been opened\nList values = urlConnection.getHeaderFields().get(\"content-Length\")\nif (values != null && !values.isEmpty()) {\n\n // getHeaderFields() returns a Map with key=(String) header \n // name, value = List of String values for that header field. \n // just use the first value here.\n String sLength = (String) values.get(0);\n\n if (sLength != null) {\n //parse the length into an integer...\n ...\n }\n"
},
{
"answer_id": 263127,
"author": "erickson",
"author_id": 3474,
"author_profile": "https://Stackoverflow.com/users/3474",
"pm_score": 5,
"selected": false,
"text": "getContentLengthLong() URLConnection content-length transfer-encoding int getContentLength()"
},
{
"answer_id": 7673089,
"author": "betty",
"author_id": 982009,
"author_profile": "https://Stackoverflow.com/users/982009",
"pm_score": 5,
"selected": false,
"text": " private int tryGetFileSize(URL url) {\n HttpURLConnection conn = null;\n try {\n conn = (HttpURLConnection) url.openConnection();\n conn.setRequestMethod(\"HEAD\");\n conn.getInputStream();\n return conn.getContentLength();\n } catch (IOException e) {\n return -1;\n } finally {\n conn.disconnect();\n }\n }\n"
},
{
"answer_id": 37980912,
"author": "Abdul Sheikh",
"author_id": 6047193,
"author_profile": "https://Stackoverflow.com/users/6047193",
"pm_score": 1,
"selected": false,
"text": " //URLConnection connection\n\nprivate int FileSize(String url) {\n\n // this is the method and it get the url as a parameter.\n\n // this java class will allow us to get the size of the file.\n\n URLConnection con; \n\n // its in a try and catch incase the url given is wrong or invalid\n\n try{ \n\n // we open the stream\n\n con = new URL(url).openConnection()\n\n return con.getContentLength(); \n }catch (Exception e){\n\n e.printStackTrace();\n\n // this is returned if the connection went invalid or failed.\n\n return 0; \n }\n }\n"
}
] |
2008/11/04
|
[
"https://Stackoverflow.com/questions/263013",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/31610/"
] |
263,026
|
<p>I'm uploading files to my <code>public/files</code> folder of a Rails application on a constant basis through a web interface.</p>
<p>I don't want to keep these in source control since they go for almost 2 GBs, so every time I do a <code>cap deploy</code> it will save those files away in <code>releases/</code> and replace the directory with the pristine copy stored in the repository.</p>
<p>I'm wondering what's the best way to keep those files in the server, in the <code>current</code> directory. Some of my ideas are:</p>
<ul>
<li>Remove the directory from source control and replace it with a link to an external directory that's not managed by Capistrano.</li>
<li>Create a Capistrano task to copy the directory to /tmp before deploying and then copying it back to /public after it's done deploying.</li>
</ul>
<p>Is there standard way to do this?</p>
|
[
{
"answer_id": 263327,
"author": "Federico Builes",
"author_id": 161,
"author_profile": "https://Stackoverflow.com/users/161",
"pm_score": 3,
"selected": false,
"text": "task :link_shared_directories do \n run \"ln -s #{shared_path}/files #{release_path}/public/files\" \nend \n\nafter \"deploy:update_code\", :link_shared_directories \n"
},
{
"answer_id": 19473519,
"author": "Chad Johnson",
"author_id": 83897,
"author_profile": "https://Stackoverflow.com/users/83897",
"pm_score": 2,
"selected": false,
"text": "set :linked_files, %w{config/database.yml}\n"
}
] |
2008/11/04
|
[
"https://Stackoverflow.com/questions/263026",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/161/"
] |
263,053
|
<p>So I have a column with different numbers and wish to categorize them by range within 30 minute intervals. So 5 would be 0-30, 697 would be 690-720, and 169 would be 150-180. I was first thinking of doing a case statement, but it doesn't look like Access 2003 supports it. Is there perhaps some sort of algorithm that could determine the range? Preferably, this would be done within the query.</p>
<p>Thank you.</p>
|
[
{
"answer_id": 263097,
"author": "Dan Goldstein",
"author_id": 23427,
"author_profile": "https://Stackoverflow.com/users/23427",
"pm_score": 3,
"selected": true,
"text": "Int(5 / 30) = 0 * 30 = 0\nInt(697 / 30) = 23 * 30 = 690\n"
},
{
"answer_id": 263100,
"author": "friol",
"author_id": 23034,
"author_profile": "https://Stackoverflow.com/users/23034",
"pm_score": 0,
"selected": false,
"text": "select ((x/30)*30) as minrange,\n(((x/30)+1)*30) as maxrange\nfrom yourtable\n"
},
{
"answer_id": 263126,
"author": "grieve",
"author_id": 34329,
"author_profile": "https://Stackoverflow.com/users/34329",
"pm_score": 0,
"selected": false,
"text": "(number \\ 30) * 30\n"
}
] |
2008/11/04
|
[
"https://Stackoverflow.com/questions/263053",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/25371/"
] |
263,081
|
<p>I'm using Lucene.net, but I am tagging this question for both .NET and Java versions because the API is the same and I'm hoping there are solutions on both platforms.</p>
<p>I'm sure other people have addressed this issue, but I haven't been able to find any good discussions or examples. </p>
<p>By default, Lucene is very picky about query syntax. For example, I just got the following error:</p>
<pre><code>[ParseException: Cannot parse 'hi there!': Encountered "<EOF>" at line 1, column 9.
Was expecting one of:
"(" ...
"*" ...
<QUOTED> ...
<TERM> ...
<PREFIXTERM> ...
<WILDTERM> ...
"[" ...
"{" ...
<NUMBER> ...
]
Lucene.Net.QueryParsers.QueryParser.Parse(String query) +239
</code></pre>
<p>What is the best way to prevent ParseExceptions when processing queries from users? It seems to me that the most <em>usable</em> search interface is one that always executes a query, even if it might be the wrong query. </p>
<p>It seems that there are a few possible, and complementary, strategies:</p>
<ul>
<li>"Clean" the query prior to sending it to the QueryProcessor</li>
<li>Handle exceptions gracefully
<ul>
<li>Show an intelligent error message to the user</li>
<li>Perhaps execute a simpler query, leaving off the erroneous bit</li>
</ul></li>
</ul>
<p>I don't really have any great ideas about how to do any of those strategies. Has anyone else addressed this issue? Are there any "simple" or "graceful" parsers that I don't know about?</p>
|
[
{
"answer_id": 263527,
"author": "Jay Kominek",
"author_id": 32878,
"author_profile": "https://Stackoverflow.com/users/32878",
"pm_score": 3,
"selected": false,
"text": "Query safe_query_parser(QueryParser qp, String raw_query)\n throws ParseException\n{\n Query q;\n try {\n q = qp.parse(raw_query);\n } catch(ParseException e) {\n q = null;\n }\n if(q==null)\n {\n String cooked;\n // consider changing this \"\" to \" \"\n cooked = raw_query.replaceAll(\"[^\\w\\s]\",\"\");\n q = qp.parse(cooked);\n }\n return q;\n}\n"
},
{
"answer_id": 265065,
"author": "ljorquera",
"author_id": 9132,
"author_profile": "https://Stackoverflow.com/users/9132",
"pm_score": 5,
"selected": false,
"text": "query = QueryParser.Escape(query)\n"
},
{
"answer_id": 855189,
"author": "josefresno",
"author_id": 88774,
"author_profile": "https://Stackoverflow.com/users/88774",
"pm_score": 2,
"selected": false,
"text": "private Query GetSafeQuery(QueryParser qp, String query)\n{\n Query q;\n try \n {\n q = qp.Parse(query);\n } \n\n catch(Lucene.Net.QueryParsers.ParseException e) \n {\n q = null;\n }\n\n if(q==null)\n {\n string cooked;\n\n cooked = Regex.Replace(query, @\"[^\\w\\.@-]\", \" \");\n q = qp.Parse(cooked);\n }\n\n return q;\n}\n"
}
] |
2008/11/04
|
[
"https://Stackoverflow.com/questions/263081",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/31015/"
] |
263,101
|
<p>I'm using an Informix (Version 7.32) DB. On one operation I create a temp table with the ID of a regular table and a serial column (so I would have all the IDs from the regular table numbered continuously). But I want to insert the info from the regular table ordered by ID something like: </p>
<pre><code>CREATE TEMP TABLE tempTable (id serial, folio int );
INSERT INTO tempTable(id,folio)
SELECT 0,folio FROM regularTable ORDER BY folio;
</code></pre>
<p>But this creates a syntax error (because of the ORDER BY)</p>
<p>Is there any way I can order the info then insert it to the tempTable?</p>
<p>UPDATE: The reason I want to do this is because the regular table has about 10,000 items and in a jsp file, it has to show every record, but it would take to long, so the real reason I want to do this is to <em>paginate</em> the output. This version of Informix doesn't have <code>Limit</code> nor <code>Skip</code>. I can't renumber the serial because is in a relationship, and this is the only solution we could get a fixed number of results on one page (for example 500 results per page). In the Regular table has skipped id's (called folio) because they have been deleted. if i were to put </p>
<pre><code>SELECT * FROM regularTable WHERE folio BETWEEN X AND Y
</code></pre>
<p>I would get maybe 300 in one page, then 500 in the next page </p>
|
[
{
"answer_id": 263187,
"author": "kurosch",
"author_id": 30153,
"author_profile": "https://Stackoverflow.com/users/30153",
"pm_score": 1,
"selected": false,
"text": "INSERT INTO tempTable(id,folio)\nSELECT 0, folio \nFROM (\n SELECT folio FROM regularTable ORDER BY folio\n);\n"
},
{
"answer_id": 263498,
"author": "Bill Karwin",
"author_id": 20860,
"author_profile": "https://Stackoverflow.com/users/20860",
"pm_score": 0,
"selected": false,
"text": "ORDER BY"
},
{
"answer_id": 264225,
"author": "RET",
"author_id": 14750,
"author_profile": "https://Stackoverflow.com/users/14750",
"pm_score": 0,
"selected": false,
"text": "CREATE SEQUENCE UNLOAD LOAD"
},
{
"answer_id": 266638,
"author": "kurosch",
"author_id": 30153,
"author_profile": "https://Stackoverflow.com/users/30153",
"pm_score": 0,
"selected": false,
"text": "SELECT\n folio\nFROM\n (\n SELECT\n ROWNUM n,\n folio\n FROM\n regularTable\n ORDER BY \n folio\n )\nWHERE\n n BETWEEN 501 AND 1000\n"
},
{
"answer_id": 5861208,
"author": "YWard",
"author_id": 734960,
"author_profile": "https://Stackoverflow.com/users/734960",
"pm_score": 2,
"selected": false,
"text": "CREATE TEMP TABLE tempTable1 (\nid serial,\nfolio int);\n\nSELECT folio FROM regularTable ORDER BY folio\nINTO TEMP tempTable2;\n\nINSERT INTO tempTable1(id,folio) SELECT 0,folio FROM tempTable2;\n"
}
] |
2008/11/04
|
[
"https://Stackoverflow.com/questions/263101",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23146/"
] |
263,116
|
<p>I'm running into a common pattern in the code that I'm writing, where I need to wait for all threads in a group to complete, with a timeout. The timeout is supposed to be the time required for <em>all</em> threads to complete, so simply doing <code>Thread.Join(timeout)</code> for each thread won't work, since the possible timeout is then <code>timeout * numThreads</code>.</p>
<p>Right now I do something like the following:</p>
<pre><code>var threadFinishEvents = new List<EventWaitHandle>();
foreach (DataObject data in dataList)
{
// Create local variables for the thread delegate
var threadFinish = new EventWaitHandle(false, EventResetMode.ManualReset);
threadFinishEvents.Add(threadFinish);
var localData = (DataObject) data.Clone();
var thread = new Thread(
delegate()
{
DoThreadStuff(localData);
threadFinish.Set();
}
);
thread.Start();
}
Mutex.WaitAll(threadFinishEvents.ToArray(), timeout);
</code></pre>
<p>However, it seems like there should be a simpler idiom for this sort of thing.</p>
|
[
{
"answer_id": 263170,
"author": "Omer van Kloeten",
"author_id": 4979,
"author_profile": "https://Stackoverflow.com/users/4979",
"pm_score": 3,
"selected": false,
"text": "// pseudo-c#:\n\nTimeSpan timeout = timeoutPerThread * threads.Count();\n\nforeach (Thread thread in threads)\n{\n DateTime start = DateTime.Now;\n\n if (!thread.Join(timeout))\n throw new TimeoutException();\n\n timeout -= (DateTime.Now - start);\n}\n"
},
{
"answer_id": 263186,
"author": "Martin v. Löwis",
"author_id": 33006,
"author_profile": "https://Stackoverflow.com/users/33006",
"pm_score": 6,
"selected": true,
"text": "if(!thread.Join(End-now))\n throw new NotFinishedInTime();\n"
},
{
"answer_id": 263223,
"author": "Jon Norton",
"author_id": 4797,
"author_profile": "https://Stackoverflow.com/users/4797",
"pm_score": 3,
"selected": false,
"text": "Task Task.WaitAll()"
},
{
"answer_id": 3840304,
"author": "Dylan",
"author_id": 463988,
"author_profile": "https://Stackoverflow.com/users/463988",
"pm_score": 0,
"selected": false,
"text": "class ThreadWaiter\n {\n private int _numThreads = 0;\n private int _spinTime;\n\n public ThreadWaiter(int SpinTime)\n {\n this._spinTime = SpinTime;\n }\n\n public void AddThreads(int numThreads)\n {\n _numThreads += numThreads;\n }\n\n public void RemoveThread()\n {\n if (_numThreads > 0)\n {\n _numThreads--;\n }\n }\n\n public void Wait()\n {\n while (_numThreads != 0)\n {\n System.Threading.Thread.Sleep(_spinTime);\n }\n }\n }\n"
},
{
"answer_id": 3902923,
"author": "Brian Gideon",
"author_id": 158779,
"author_profile": "https://Stackoverflow.com/users/158779",
"pm_score": 3,
"selected": false,
"text": "using (var finished = new CountdownEvent(1)) \n{ \n for (DataObject data in dataList) \n { \n finished.AddCount();\n var localData = (DataObject)data.Clone(); \n var thread = new Thread( \n delegate() \n {\n try\n {\n DoThreadStuff(localData); \n threadFinish.Set();\n }\n finally\n {\n finished.Signal();\n }\n } \n ); \n thread.Start(); \n } \n finished.Signal(); \n finished.Wait(YOUR_TIMEOUT); \n} \n"
},
{
"answer_id": 6380075,
"author": "T. Webster",
"author_id": 266457,
"author_profile": "https://Stackoverflow.com/users/266457",
"pm_score": 4,
"selected": false,
"text": " for (int i = 0; i < N; i++)\n {\n tasks[i] = Task.Factory.StartNew(() =>\n { \n DoThreadStuff(localData);\n });\n }\n while (tasks.Any(t => !t.IsCompleted)) { } //spin wait\n"
},
{
"answer_id": 12903899,
"author": "Alex Aza",
"author_id": 732945,
"author_profile": "https://Stackoverflow.com/users/732945",
"pm_score": 0,
"selected": false,
"text": "var tasks = dataList\n .Select(data => Task.Factory.StartNew(arg => DoThreadStuff(data), TaskContinuationOptions.LongRunning | TaskContinuationOptions.PreferFairness))\n .ToArray();\n\nvar timeout = TimeSpan.FromMinutes(1);\nTask.WaitAll(tasks, timeout);\n"
},
{
"answer_id": 18745935,
"author": "Bùi Công Giao",
"author_id": 2769419,
"author_profile": "https://Stackoverflow.com/users/2769419",
"pm_score": 1,
"selected": false,
"text": "class MyThread\n {\n public int Count;\n public Thread Thrd;\n public MyThread(string name)\n {\n Count = 0;\n Thrd = new Thread(this.Run);\n Thrd.Name = name;\n Thrd.Start();\n }\n // Entry point of thread.\n void Run()\n {\n Console.WriteLine(Thrd.Name + \" starting.\");\n do\n {\n Thread.Sleep(500);\n Console.WriteLine(\"In \" + Thrd.Name +\n \", Count is \" + Count);\n Count++;\n } while (Count < 10);\n Console.WriteLine(Thrd.Name + \" terminating.\");\n }\n }\n // Use Join() to wait for threads to end.\n class JoinThreads\n {\n static void Main()\n {\n Console.WriteLine(\"Main thread starting.\");\n // Construct three threads.\n MyThread mt1 = new MyThread(\"Child #1\");\n MyThread mt2 = new MyThread(\"Child #2\");\n MyThread mt3 = new MyThread(\"Child #3\");\n mt1.Thrd.Join();\n Console.WriteLine(\"Child #1 joined.\");\n mt2.Thrd.Join();\n Console.WriteLine(\"Child #2 joined.\");\n mt3.Thrd.Join();\n Console.WriteLine(\"Child #3 joined.\");\n Console.WriteLine(\"Main thread ending.\");\n Console.ReadKey();\n }\n }\n"
},
{
"answer_id": 20897995,
"author": "Vincent",
"author_id": 2352618,
"author_profile": "https://Stackoverflow.com/users/2352618",
"pm_score": 4,
"selected": false,
"text": "using System.Collections.Generic;\nusing System.Threading;\nnamespace Extensions\n{\n public static class ThreadExtension\n {\n public static void WaitAll(this IEnumerable<Thread> threads)\n {\n if(threads!=null)\n {\n foreach(Thread thread in threads)\n { thread.Join(); }\n }\n }\n }\n}\n List<Thread> threads=new List<Thread>();\n//Add your threads to this collection\nthreads.WaitAll();\n"
},
{
"answer_id": 74035618,
"author": "Theodor Zoulias",
"author_id": 11178549,
"author_profile": "https://Stackoverflow.com/users/11178549",
"pm_score": 0,
"selected": false,
"text": "/// <summary>\n/// Blocks the calling thread until all threads terminate, or the specified\n/// time elapses. Returns true if all threads terminated in time, or false if\n/// at least one thread has not terminated after the specified amount of time\n/// elapsed.\n/// </summary>\npublic static bool JoinAll(IEnumerable<Thread> threads, TimeSpan timeout)\n{\n ArgumentNullException.ThrowIfNull(threads);\n if (timeout < TimeSpan.Zero)\n throw new ArgumentOutOfRangeException(nameof(timeout));\n\n Stopwatch stopwatch = Stopwatch.StartNew();\n foreach (Thread thread in threads)\n {\n if (!thread.IsAlive) continue;\n TimeSpan remaining = timeout - stopwatch.Elapsed;\n if (remaining < TimeSpan.Zero) return false;\n if (!thread.Join(remaining)) return false;\n }\n return true;\n}\n DateTime.Now Stopwatch Stopwatch bool allTerminated = JoinAll(new[] { thread1, thread2 }, TimeSpan.FromSeconds(10));\n timeout TimeSpan Timeout.InfiniteTimeSpan"
}
] |
2008/11/04
|
[
"https://Stackoverflow.com/questions/263116",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8078/"
] |
263,121
|
<p>Is there a way to emulate mixins or traits in java? basically, I need a way to do multiple inheritance so I can add common business logic to several classes</p>
|
[
{
"answer_id": 263184,
"author": "Alex B",
"author_id": 6180,
"author_profile": "https://Stackoverflow.com/users/6180",
"pm_score": 5,
"selected": true,
"text": "BusinessLogic BusinessLogic BusinessLogic BusinessLogicInterface interface BusinessLogicInterace\n{\n void method1();\n void method2();\n}\n\nclass BusinessLogic implements BusinessLogicInterface\n{\n void method1() { ... }\n void method2() { ... }\n}\n\nclass User \n extends OtherClass \n implements BusinessLogicInterface\n{\n BusinessLogic logic = new BusinessLogic();\n\n @Override\n void method1() { logic.method1(); }\n\n @Override\n void method2() { logic.method2(); }\n}\n"
},
{
"answer_id": 16337353,
"author": "Henno Vermeulen",
"author_id": 593533,
"author_profile": "https://Stackoverflow.com/users/593533",
"pm_score": 2,
"selected": false,
"text": "interface BusinessLogicInterface {\n void method0();\n\n class DefaultImpl {\n private DefaultImpl() {\n }\n\n public static void method1(BusinessLogicInterface self) { ... }\n public static void method2(BusinessLogicInterface self) { ... }\n }\n\n void method1();\n void method2();\n}\n\nclass User extends OtherClass implements BusinessLogicInterface {\n @Override\n void method0() { ... }\n\n @Override\n void method1() { BusinessLogic.defaultImpl.method1(this); }\n\n @Override\n void method2() { BusinessLogic.defaultImpl.method2(this); }\n}\n"
}
] |
2008/11/04
|
[
"https://Stackoverflow.com/questions/263121",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20641/"
] |
263,122
|
<p>I'm writing an image bank with Django, and I want to add a button to get a hi-res version of an image (the low-res is shown in the details page). If I put just an <code><a></code> link, the browser will open the image instead of downloading it. Adding an HTTP header like:</p>
<pre><code>Content-Disposition: attachment; filename="beach008.jpg"
</code></pre>
<p>works, but since it's an static file, I don't want to handle the request with Django. Currently, I'm using NGINX to serve static files, and dynamic pages are redirected via FastCGI to the Django process. I'm thinking about using NGINX <code>add-header</code> command, but could it set the <code>filename="xx"</code> part?. Or maybe there's some way to handle the request in Django, but make NGINX serve the content?</p>
|
[
{
"answer_id": 263554,
"author": "Andrew Kurinnyi",
"author_id": 33887,
"author_profile": "https://Stackoverflow.com/users/33887",
"pm_score": 2,
"selected": false,
"text": "def serve_download(view_func):\n def _wrapped_view_func(request, *args, **kwargs):\n response = view_func(request, *args, **kwargs)\n response['Content-Type'] = 'application/octet-stream';\n import os.path\n response['Content-Disposition'] = 'attachment; filename=\"%s\"' % os.path.basename(kwargs['path'])\n return response\n return _wrapped_view_func\n"
},
{
"answer_id": 263671,
"author": "Javier",
"author_id": 11649,
"author_profile": "https://Stackoverflow.com/users/11649",
"pm_score": 0,
"selected": false,
"text": "http://xx.com/media/images/lores/f_123123.jpg http://xx.com/downs/hires/f_12323?beach008.jpg location /downs/ {\n root /var/www/nginx-attachment;\n add_header Content-Disposition 'attachment; filename=\"$args\"';\n }\n"
},
{
"answer_id": 386460,
"author": "Vasil",
"author_id": 7883,
"author_profile": "https://Stackoverflow.com/users/7883",
"pm_score": 4,
"selected": true,
"text": " #files which need to be forced downloads\n location /static/high_res/ {\n root /project_root;\n\n #don't ever send $request_filename in your response, it will expose your dir struct, use a quick regex hack to find just the filename\n if ($request_filename ~* ^.*?/([^/]*?)$) {\n set $filename $1;\n }\n\n #match images\n if ($filename ~* ^.*?\\.((jpg)|(png)|(gif))$) {\n add_header Content-Disposition \"attachment; filename=$filename\";\n }\n }\n\n location /static {\n root /project_root;\n }\n"
}
] |
2008/11/04
|
[
"https://Stackoverflow.com/questions/263122",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11649/"
] |
263,151
|
<p>Generally, when using the conditional operator, here's the syntax:</p>
<pre><code>int x = 6;
int y = x == 6 ? 5 : 9;
</code></pre>
<p>Nothing fancy, pretty straight forward.</p>
<p>Now, let's try to use this when assigning a Lambda to a Func type. Let me explain:</p>
<pre><code>Func<Order, bool> predicate = id == null
? p => p.EmployeeID == null
: p => p.EmployeeID == id;
</code></pre>
<p>That's the same syntax, and <em>should</em> work? Right? For some reason that doesn't. The compiler gives this nice cryptic message:</p>
<blockquote>
<p>Error 1 Type of conditional expression cannot be determined because there is no implicit conversion between 'lambda expression' and 'lambda expression'</p>
</blockquote>
<p>I then went ahead and changed the syntax and this way it <em>did</em> work:</p>
<pre><code>Func<Order, bool> predicate = id == null
? predicate = p => p.EmployeeID == null
: predicate = p => p.EmployeeID == id;
</code></pre>
<p>I'm just curious as to why it doesn't work the first way?</p>
<p>(Side note: I ended up not needing this code, as I found out that when comparing an int value against null, you just use object.Equals)</p>
|
[
{
"answer_id": 263177,
"author": "Jon Skeet",
"author_id": 22656,
"author_profile": "https://Stackoverflow.com/users/22656",
"pm_score": 7,
"selected": true,
"text": "Func<Order, bool> predicate = id == null \n ? (Func<Order, bool>) (p => p.EmployeeID == null)\n : p => p.EmployeeID == id;\n"
},
{
"answer_id": 263183,
"author": "Jake",
"author_id": 24730,
"author_profile": "https://Stackoverflow.com/users/24730",
"pm_score": 3,
"selected": false,
"text": "Func<Order, bool> predicate = \n id == null ? \n new Func<Order,bool>(p => p.EmployeeID == null) :\n new Func<Order,bool>(p => p.EmployeeID == id);\n Func<Order, bool> predicate = \n id == null ? \n (Order p) => p.EmployeeID == null :\n (Order p) => p.EmployeeID == id;\n"
},
{
"answer_id": 48275048,
"author": "Elnaz",
"author_id": 5620296,
"author_profile": "https://Stackoverflow.com/users/5620296",
"pm_score": 1,
"selected": false,
"text": "Find Expression<Func<T, bool>> List<T> var countries= \nFind(languages.Any() \n ? (country => languages.Contains(country.Language))\n : (country => true));\n there is no implicit conversion between lambda expression and lambda expression. country => true Expression<Func<Country, bool>> getAllPredicate = country => true;\n Expression<Func<Country, bool>> getCountriesByLanguagePredicate = country => languages.Contains(country.Language);\n\n var countries= Find(languages.Any()\n ? getCountriesByLanguagePredicate\n : getAllPredicate);\n"
},
{
"answer_id": 70199481,
"author": "StuartLC",
"author_id": 314291,
"author_profile": "https://Stackoverflow.com/users/314291",
"pm_score": 1,
"selected": false,
"text": "var evenFilter = (int i) => i % 2 == 0; // evenFilter inferred as `Func<int, bool>`\n var zeroInputFunc = () => 44 % 2 == 0;\nvar myAction = () => {Console.WriteLine(\"Foo\");};\n var filter = i => i % 2 == 0; << Error: The delegate type could not be inferred\n Func<int, bool> myPredicate = selectorFlag\n ? i => i % 2 == 0\n : i => i % 2 == 1;\n var myPredicate = selectorFlag\n ? (int i) => i % 2 == 0\n : (int i) => i % 2 == 1;\n"
}
] |
2008/11/04
|
[
"https://Stackoverflow.com/questions/263151",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15861/"
] |
263,191
|
<p>In C#, I want to initialize a string value with an empty string.</p>
<p>How should I do this?
What is the right way, and why?</p>
<pre><code>string willi = string.Empty;
</code></pre>
<p>or</p>
<pre><code>string willi = String.Empty;
</code></pre>
<p>or</p>
<pre><code>string willi = "";
</code></pre>
<p>or what?</p>
|
[
{
"answer_id": 263205,
"author": "Jimmy",
"author_id": 4435,
"author_profile": "https://Stackoverflow.com/users/4435",
"pm_score": 6,
"selected": false,
"text": "string String string.Empty \"\" string.Empty \"\\x003\" \"\""
},
{
"answer_id": 263210,
"author": "Silviu Niculita",
"author_id": 34388,
"author_profile": "https://Stackoverflow.com/users/34388",
"pm_score": 4,
"selected": false,
"text": "String.Empty string.Empty String string Int32 int \"\" string.Empty"
},
{
"answer_id": 263214,
"author": "tvanfosson",
"author_id": 12950,
"author_profile": "https://Stackoverflow.com/users/12950",
"pm_score": 2,
"selected": false,
"text": "string String"
},
{
"answer_id": 263231,
"author": "zendar",
"author_id": 25732,
"author_profile": "https://Stackoverflow.com/users/25732",
"pm_score": 3,
"selected": false,
"text": "string System.String string.Empty == String.Empty == \"\" string.Empty String.Empty string String string string string.Empty"
},
{
"answer_id": 263247,
"author": "Konrad Rudolph",
"author_id": 1968,
"author_profile": "https://Stackoverflow.com/users/1968",
"pm_score": 7,
"selected": false,
"text": "\"\" string.Empty String.Empty"
},
{
"answer_id": 263253,
"author": "John Rudy",
"author_id": 14048,
"author_profile": "https://Stackoverflow.com/users/14048",
"pm_score": 5,
"selected": false,
"text": "string.Empty string.Empty String.Empty"
},
{
"answer_id": 263257,
"author": "Jon Skeet",
"author_id": 22656,
"author_profile": "https://Stackoverflow.com/users/22656",
"pm_score": 11,
"selected": true,
"text": "\"\" \"\" \"\" \" \""
},
{
"answer_id": 264534,
"author": "user34577",
"author_id": 34577,
"author_profile": "https://Stackoverflow.com/users/34577",
"pm_score": 2,
"selected": false,
"text": "\"\" String.Empty \"\" String string String.Empty String.Format String.Copy"
},
{
"answer_id": 1588678,
"author": "aBetterGamer",
"author_id": 192440,
"author_profile": "https://Stackoverflow.com/users/192440",
"pm_score": 9,
"selected": false,
"text": "string.Empty ldsfld \"\" ldstr string.Empty private void Test1()\n{\n string test1 = string.Empty; \n string test11 = test1;\n}\n\nprivate void Test2()\n{\n string test2 = \"\"; \n string test22 = test2;\n}\n .method private hidebysig instance void \n Test1() cil managed\n{\n // Code size 10 (0xa)\n .maxstack 1\n .locals init ([0] string test1,\n [1] string test11)\n IL_0000: nop\n IL_0001: ldsfld string [mscorlib]System.String::Empty\n IL_0006: stloc.0\n IL_0007: ldloc.0\n IL_0008: stloc.1\n IL_0009: ret\n} // end of method Form1::Test1\n .method private hidebysig instance void \n Test2() cil managed\n{\n // Code size 10 (0xa)\n .maxstack 1\n .locals init ([0] string test2,\n [1] string test22)\n IL_0000: nop\n IL_0001: ldstr \"\"\n IL_0006: stloc.0\n IL_0007: ldloc.0\n IL_0008: stloc.1\n IL_0009: ret\n} // end of method Form1::Test2\n string test1 = string.Empty;\n0000003a mov eax,dword ptr ds:[022A102Ch] \n0000003f mov dword ptr [ebp-40h],eax \n\n string test11 = test1;\n00000042 mov eax,dword ptr [ebp-40h] \n00000045 mov dword ptr [ebp-44h],eax \n string test2 = \"\";\n0000003a mov eax,dword ptr ds:[022A202Ch] \n00000040 mov dword ptr [ebp-40h],eax \n\n string test22 = test2;\n00000043 mov eax,dword ptr [ebp-40h] \n00000046 mov dword ptr [ebp-44h],eax \n"
},
{
"answer_id": 3613509,
"author": "mckamey",
"author_id": 43217,
"author_profile": "https://Stackoverflow.com/users/43217",
"pm_score": 3,
"selected": false,
"text": "String.Empty Int32.TryParse(...) Double.Epsilon int i = 0; string foo = \"bar\";"
},
{
"answer_id": 7202299,
"author": "Mentoliptus",
"author_id": 726978,
"author_profile": "https://Stackoverflow.com/users/726978",
"pm_score": 6,
"selected": false,
"text": "switch-case case string.Empty: Compilation error : A constant value is expected"
},
{
"answer_id": 8145898,
"author": "sergiol",
"author_id": 383779,
"author_profile": "https://Stackoverflow.com/users/383779",
"pm_score": 1,
"selected": false,
"text": "String.Empty \"\" \"\" String.Empty String.Empty System.String.Empty string.Empty String.Empty"
},
{
"answer_id": 30758914,
"author": "Andrew",
"author_id": 1803463,
"author_profile": "https://Stackoverflow.com/users/1803463",
"pm_score": 3,
"selected": false,
"text": "string.Empty String.Empty using System; \"\" string.Empty"
},
{
"answer_id": 36947473,
"author": "Steve",
"author_id": 1197518,
"author_profile": "https://Stackoverflow.com/users/1197518",
"pm_score": 4,
"selected": false,
"text": "string.Empty string.Empty CS0219 - The variable 'x' is assigned but its value is never used\n"
},
{
"answer_id": 39998813,
"author": "RBT",
"author_id": 465053,
"author_profile": "https://Stackoverflow.com/users/465053",
"pm_score": 4,
"selected": false,
"text": "private static void CompareStringConstants()\n{\n string str1 = \"\";\n string str2 = string.Empty;\n string str3 = String.Empty;\n Console.WriteLine(object.ReferenceEquals(str1, str2)); //prints True\n Console.WriteLine(object.ReferenceEquals(str2, str3)); //prints True\n}\n str1 str2 str3"
},
{
"answer_id": 41573276,
"author": "Remotec",
"author_id": 169640,
"author_profile": "https://Stackoverflow.com/users/169640",
"pm_score": 2,
"selected": false,
"text": "(customer == null) ? \"\" : customer.Name\n (customer == null) ? string.empty : customer.Name\n"
},
{
"answer_id": 44052305,
"author": "RhinoTX",
"author_id": 7716023,
"author_profile": "https://Stackoverflow.com/users/7716023",
"pm_score": 2,
"selected": false,
"text": "\"\" string.Empty \"\" string.EMpty Strng.Empty \" \" \"\" string.Empty EMPTY_STRING string.Empty"
},
{
"answer_id": 47742744,
"author": "Wouter",
"author_id": 4491768,
"author_profile": "https://Stackoverflow.com/users/4491768",
"pm_score": 1,
"selected": false,
"text": "\"\" string.Empty"
},
{
"answer_id": 61044512,
"author": "Keith Howard",
"author_id": 4436927,
"author_profile": "https://Stackoverflow.com/users/4436927",
"pm_score": 0,
"selected": false,
"text": "<Assembly: System.Reflection.AssemblyCulture(\"\")>\n<Assembly: System.Reflection.AssemblyDescription(\"\")>\n<Assembly: System.Reflection.AssemblyFileVersion(\"1.0.0.0\")>\n<Assembly: System.Reflection.AssemblyKeyFile(\"\")>\n<Assembly: System.Reflection.AssemblyProduct(\"\")>\n<Assembly: System.Reflection.AssemblyTitle(\"\")>\n"
},
{
"answer_id": 73745047,
"author": "Bolpat",
"author_id": 3273130,
"author_profile": "https://Stackoverflow.com/users/3273130",
"pm_score": -1,
"selected": false,
"text": "\"\" \"\\u200D\" string.Empty"
}
] |
2008/11/04
|
[
"https://Stackoverflow.com/questions/263191",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/31406/"
] |
263,225
|
<p>I've done some Googling, and can't find anything, though maybe I'm just looking in the wrong places. I'm also not very adept at VBA, but I'm sure I can figure it out with the right pointers :)</p>
<p>I have a string I'm building that's a concatenation of various cells, based on various conditions. I hit these in order.</p>
<pre><code>=IF(A405<>A404,G405,G405&H404)
</code></pre>
<p>What I want to do is go back through my concatenated list, removing a superseded value if the superseder is in the list.</p>
<p>For example, see the following list:</p>
<pre><code>A, D, G, Y, Z
</code></pre>
<p>I want to remove <code>D</code> <em>if</em> and <strong>only</strong> <em>if</em> <code>Y</code> is present.</p>
<p>How would I go about this? (VBA or in-cell, though I'd prefer in-cell)</p>
|
[
{
"answer_id": 263250,
"author": "BradC",
"author_id": 21398,
"author_profile": "https://Stackoverflow.com/users/21398",
"pm_score": 2,
"selected": false,
"text": "start1 = instr(myLongString,\"Y, \")\nif start1 > 0 Then\n start2 = instr(myLongString,\"D, \")\n if start2 > 0 then\n newLongString = left(myLongString, start2 - 1) & _\n mid(myLongString, start2 + 3)\n end if\nend if\n"
},
{
"answer_id": 263275,
"author": "Fionnuala",
"author_id": 2548,
"author_profile": "https://Stackoverflow.com/users/2548",
"pm_score": 0,
"selected": false,
"text": "If InStr(strString, \"Y\") > 0 Then\n strString = Replace(strString, \"d\", \"\")\n strString = Replace(strString, \" \", \"\")\n strString = Replace(strString, \" ,\", \"\")\n strString = Replace(strString, \",,\", \",\")\nEnd If\n"
},
{
"answer_id": 263335,
"author": "Joseph Bui",
"author_id": 3275,
"author_profile": "https://Stackoverflow.com/users/3275",
"pm_score": 3,
"selected": false,
"text": "=IF(ISERROR(FIND(\"Y\",A1)),A1,SUBSTITUTE(A1,\"D, \",\"\"))\n"
},
{
"answer_id": 263374,
"author": "warren",
"author_id": 4418,
"author_profile": "https://Stackoverflow.com/users/4418",
"pm_score": 1,
"selected": true,
"text": "=IF(A15<>A14,G15,IF(OR(AND(G15=\"CR247, \",ISNUMBER(FIND(\"CR247, \",H14))),AND(G15=\"CR149, \",ISNUMBER(FIND(\"CR215, \",H14))),AND(G15=\"CR149, \",ISNUMBER(FIND(\"CR180, \",H14))),AND(G15=\"CR180, \",ISNUMBER(FIND(\"CR215, \",H14))),G15=\"CR113, \"),H14,G15&H14))\n"
},
{
"answer_id": 267822,
"author": "da_m_n",
"author_id": 7165,
"author_profile": "https://Stackoverflow.com/users/7165",
"pm_score": 1,
"selected": false,
"text": "if(indirect(\"A\"&row()) <> indirect(\"A\"&row()-1), indirect(\"G\"&row()), indirect(\"G\"&row())& indirect(\"H\"&row()))"
}
] |
2008/11/04
|
[
"https://Stackoverflow.com/questions/263225",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4418/"
] |
263,227
|
<p>Several times, while perusing the Boost library's documentation, I've run across return values that are marked "<a href="http://www.boost.org/doc/libs/1_36_0/libs/utility/Collection.html" rel="noreferrer">convertible to <code>bool</code></a>" (search that page for the phrase "convertible to bool", it's about a third of the way down). I once stumbled across an oblique reference to a paper explaining the reason for that, but have never been able to find said paper (and I can no longer find the page I saw the reference on either).</p>
<p>Can anyone explain why (and when) you should return something that's "convertible to <code>bool</code>" rather than simply returning a <code>bool</code>?</p>
|
[
{
"answer_id": 263303,
"author": "C. K. Young",
"author_id": 13,
"author_profile": "https://Stackoverflow.com/users/13",
"pm_score": 4,
"selected": false,
"text": "bool int bool void*"
},
{
"answer_id": 263313,
"author": "Konrad Rudolph",
"author_id": 1968,
"author_profile": "https://Stackoverflow.com/users/1968",
"pm_score": 6,
"selected": true,
"text": "if std::fstream ifstream ifs(\"filename\");\nwhile (ifs >> token)\n cout \"token \" << token << \" read.\" << endl;\n ifs bool int b = ifs;\n bool void* this true"
}
] |
2008/11/04
|
[
"https://Stackoverflow.com/questions/263227",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12193/"
] |
263,228
|
<p>I've been using Flex Builder 3 to create Flex applications that are part of larger Flex / Java project using LiveCycle Data Services. Flex Builder creates and deploys the .war file, which is convenient for the development cycle, but I don't understand what the .war file has to contain in order to deploy and run.</p>
<p>I've found through trial and error that changing certain properties of the Flex Project (i.e. the Context Root) can break or fix the application, and somehow those settings make it into the .war file.</p>
<p>I need to get the entire build process implemented under Ant, and more importantly, I need to understand what the Flex part of the project depends on. I haven't been able to find any documentation that describes what a .war file has to include to deploy a Flex / Java application, however.</p>
<p>For example, Flex Builder creates a web.xml file and populates it with the correct tags. but if I add other features do I need additional tags in web.xml?</p>
<p>Does anyone know where I can find documentation on the .war file contents for a Flex / Java project?</p>
|
[
{
"answer_id": 327281,
"author": "cliff.meyers",
"author_id": 41754,
"author_profile": "https://Stackoverflow.com/users/41754",
"pm_score": 2,
"selected": false,
"text": "myapp.war/\n WEB-INF/ <-- not accessible via the browser over HTTP\n classes/ <-- compiled classes and configuration files (this is where your .class files and jdbc.properties would go)\n flex/ <-- LCDS XML config files (services-config.xml)\n lib/ <-- web application libraries (.jar files, for LCDS and other tools you might be using)\n web.xml <-- web application configuration\n"
}
] |
2008/11/04
|
[
"https://Stackoverflow.com/questions/263228",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/34372/"
] |
263,229
|
<p>In a tightly looped test application that prints out the value of <code>DateTime.UtcNow.Ticks</code>, I notice that the value will jump a remarkable amount once every hour or so. Look closely at the following sample data:</p>
<pre><code>1:52:14.312 PM - 633614215343125000
1:52:14.359 PM - 633614215343593750
1:52:14.421 PM - 633614215344218750
1:52:14.468 PM - 633614215344687500
1:52:14.515 PM - 633614215998593750 <-- WAY different
</code></pre>
<p>The delta is 653906250 ticks (65.390 seconds). The only reason I can come up with is that the Windows Time service is doing some synchronization from underneath my feet. </p>
<ul>
<li>Are there any experts out there that can confirm this? </li>
<li>Drifting a minute or so in about an hour seems pretty bad to me, but is that the case here?</li>
</ul>
|
[
{
"answer_id": 263277,
"author": "Matt Lacey",
"author_id": 1755,
"author_profile": "https://Stackoverflow.com/users/1755",
"pm_score": 0,
"selected": false,
"text": " for (int i = 0; i < 10; i++)\n {\n\n Console.WriteLine(DateTime.Now.ToLongTimeString().ToString() + \" - \" + DateTime.UtcNow.Ticks.ToString());\n\n Thread.Sleep(10);\n }\n"
},
{
"answer_id": 263349,
"author": "Esteban Brenes",
"author_id": 14177,
"author_profile": "https://Stackoverflow.com/users/14177",
"pm_score": 2,
"selected": false,
"text": "static DateTime past = DateTime.UtcNow;\n static void PrintTime()\n {\n while (stopLoop == 0)\n {\n DateTime now = DateTime.UtcNow;\n Console.WriteLine(\"{0} - {1} d: {2}\", now, now.Ticks, now - past);\n Program.past = now;\n Thread.Sleep(2000);\n }\n }\n"
},
{
"answer_id": 263409,
"author": "Jeffrey LeCours",
"author_id": 18051,
"author_profile": "https://Stackoverflow.com/users/18051",
"pm_score": 0,
"selected": false,
"text": "long delta = 0;\nlong ticks = 0;\nlong lastTicks = DateTime.UtcNow.Ticks;\nwhile (true)\n{\n ticks = DateTime.UtcNow.Ticks;\n delta = ticks - lastTicks;\n lastTicks = ticks;\n // Conditional breakpoint: delta > 100000000 Is True\n Console.WriteLine(\"{0} - {1}\", ticks, delta);\n}\n"
}
] |
2008/11/04
|
[
"https://Stackoverflow.com/questions/263229",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18051/"
] |
263,232
|
<p>I'm working with jQuery and looking to see if there is an easy way to determine if the element has a specific CSS class associated with it.</p>
<p>I have the id of the element, and the CSS class that I'm looking for. I just need to be able to, in an if statement, do a comparison based on the existence of that class on the element.</p>
|
[
{
"answer_id": 263240,
"author": "eyelidlessness",
"author_id": 17964,
"author_profile": "https://Stackoverflow.com/users/17964",
"pm_score": 9,
"selected": true,
"text": "hasClass jQueryCollection.hasClass(className);\n $(selector).hasClass(className);\n className className <span class=\"foo bar\" />\n true $('span').hasClass('foo bar')\n false $('span').hasClass('bar foo')\n$('span').hasClass('foo bar')\n"
},
{
"answer_id": 263246,
"author": "Javier",
"author_id": 11649,
"author_profile": "https://Stackoverflow.com/users/11649",
"pm_score": 4,
"selected": false,
"text": "elem = $(\"#elemid\");\nif (elem.is (\".class\")) {\n // whatever\n}\n elem = $(\"#elemid\");\nif (elem.hasClass (\"class\")) {\n // whatever\n}\n"
},
{
"answer_id": 2285837,
"author": "VinnyG",
"author_id": 245836,
"author_profile": "https://Stackoverflow.com/users/245836",
"pm_score": 4,
"selected": false,
"text": "if (!currentPage.parent().hasClass('home')) { do what you want }\n"
},
{
"answer_id": 21043911,
"author": "Ismael Miguel",
"author_id": 2729937,
"author_profile": "https://Stackoverflow.com/users/2729937",
"pm_score": 2,
"selected": false,
"text": "var hasclass=!!(' '+elem.className+' ').indexOf(' check_class ')+1;\n function hasClass(e,c){\n return e&&(e instanceof HTMLElement)&&!!((' '+e.className+' ').indexOf(' '+c+' ')+1);\n}\n/*example of usage*/\nvar has_class_medium=hasClass(document.getElementsByTagName('input')[0],'medium');\n"
},
{
"answer_id": 34225071,
"author": "vineet",
"author_id": 3832217,
"author_profile": "https://Stackoverflow.com/users/3832217",
"pm_score": 0,
"selected": false,
"text": " $('.segment-name').click(function () {\n if($(this).hasClass('segment-a')){\n //class exist\n }\n});\n"
},
{
"answer_id": 38624900,
"author": "Eduardo Paz",
"author_id": 4530242,
"author_profile": "https://Stackoverflow.com/users/4530242",
"pm_score": 0,
"selected": false,
"text": " <!--element html-->\n <nav class=\"cbp-spmenu cbp-spmenu-horizontal cbp-spmenu-bottom cbp-spmenu-open\" id=\"menu\">somethings here... </nav>\n\n <!--jQuery \"is\"-->\n $('#menu').is('.cbp-spmenu-open');\n <!--element html-->\n <nav class=\"cbp-spmenu cbp-spmenu-horizontal cbp-spmenu-bottom cbp-spmenu-open\" id=\"menu\">somethings here... </nav>\n\n <!--jQuery \"is\"-->\n if($('#menu').is('.cbp-spmenu-bottom.cbp-spmenu-open')){\n $(\"#menu\").show();\n }\n"
},
{
"answer_id": 42227240,
"author": "Derek Ekins",
"author_id": 98078,
"author_profile": "https://Stackoverflow.com/users/98078",
"pm_score": 2,
"selected": false,
"text": "element.classList.contains('your-class-name')\n"
}
] |
2008/11/04
|
[
"https://Stackoverflow.com/questions/263232",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13279/"
] |
263,234
|
<p>I have a WinForms application (I'm using VB) that can be minimized to the system tray. I used the "hackish" methods described in multiple posts utilizing a NotifyIcon and playing with the Form_Resize event. </p>
<p>This all works fine aesthetically, but the resources and memory used are unaffected. I want to be able to minimize resources when minimizing to system tray, just like Visual Studio does. If you are coding in Visual Studio, the memory usage can creep up (depending on project size) to above 500 MB, but when minimizing Visual Studio to the taskbar, the memory drastically decreases to (what I'm assuming) is the minimal amount. </p>
<p>Does anyone have any clue as to how to accomplish this? </p>
<p>Here's a short description of the application, if anyone finds it relevant: I have a windows form with a ListView that contains Work Orders for my IT department. The application has a "listener" that notifies when a new Work order is submitted. So, when the application is running in the system tray, all I really do is compare the count of items in the ListView to a count of rows in a SQL table every couple of minutes. </p>
<p>EDIT: To be more specific, a windows form intrinsically has threads and resources being used by means of the controls, when the form is invisible (in the system tray) these resources are still being used. What can I do to minimize these resources, short of killing all the controls and redrawing them when the form is restored.</p>
|
[
{
"answer_id": 263459,
"author": "Jesse C. Slicer",
"author_id": 3312,
"author_profile": "https://Stackoverflow.com/users/3312",
"pm_score": 4,
"selected": true,
"text": "public static void MinimizeMemory()\n{\n GC.Collect(GC.MaxGeneration);\n GC.WaitForPendingFinalizers();\n SetProcessWorkingSetSize(\n Process.GetCurrentProcess().Handle,\n (UIntPtr)0xFFFFFFFF,\n (UIntPtr)0xFFFFFFFF);\n\n IntPtr heap = GetProcessHeap();\n\n if (HeapLock(heap))\n {\n try\n {\n if (HeapCompact(heap, 0) == 0)\n {\n // error condition ignored\n }\n }\n finally\n {\n HeapUnlock(heap);\n }\n }\n}\n\n[DllImport(\"kernel32.dll\")]\n[return: MarshalAs(UnmanagedType.Bool)]\ninternal static extern bool SetProcessWorkingSetSize(\n IntPtr process,\n UIntPtr minimumWorkingSetSize,\n UIntPtr maximumWorkingSetSize);\n\n[DllImport(\"kernel32.dll\", SetLastError = true)]\ninternal static extern IntPtr GetProcessHeap();\n\n[DllImport(\"kernel32.dll\")]\n[return: MarshalAs(UnmanagedType.Bool)]\ninternal static extern bool HeapLock(IntPtr heap);\n\n[DllImport(\"kernel32.dll\")]\ninternal static extern uint HeapCompact(IntPtr heap, uint flags);\n\n[DllImport(\"kernel32.dll\")]\n[return: MarshalAs(UnmanagedType.Bool)]\ninternal static extern bool HeapUnlock(IntPtr heap);\n"
}
] |
2008/11/04
|
[
"https://Stackoverflow.com/questions/263234",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/25962/"
] |
263,249
|
<p>Are there any good <a href="http://java.sun.com/blueprints/corej2eepatterns/Patterns/ValueListHandler.html" rel="noreferrer">value list handler</a> implementations available?</p>
<p>I've found <a href="http://valuelist.sourceforge.net/" rel="noreferrer">valuelist</a>, but it seems to be stagnating... besides I really need good control of links the taglib generates, because I need to call some JavaScript from it.</p>
<p>Currently I solve it by rewriting the taglib in freemarker and using valuelist's backend.</p>
<p>Does anyone know a better way?</p>
|
[
{
"answer_id": 263459,
"author": "Jesse C. Slicer",
"author_id": 3312,
"author_profile": "https://Stackoverflow.com/users/3312",
"pm_score": 4,
"selected": true,
"text": "public static void MinimizeMemory()\n{\n GC.Collect(GC.MaxGeneration);\n GC.WaitForPendingFinalizers();\n SetProcessWorkingSetSize(\n Process.GetCurrentProcess().Handle,\n (UIntPtr)0xFFFFFFFF,\n (UIntPtr)0xFFFFFFFF);\n\n IntPtr heap = GetProcessHeap();\n\n if (HeapLock(heap))\n {\n try\n {\n if (HeapCompact(heap, 0) == 0)\n {\n // error condition ignored\n }\n }\n finally\n {\n HeapUnlock(heap);\n }\n }\n}\n\n[DllImport(\"kernel32.dll\")]\n[return: MarshalAs(UnmanagedType.Bool)]\ninternal static extern bool SetProcessWorkingSetSize(\n IntPtr process,\n UIntPtr minimumWorkingSetSize,\n UIntPtr maximumWorkingSetSize);\n\n[DllImport(\"kernel32.dll\", SetLastError = true)]\ninternal static extern IntPtr GetProcessHeap();\n\n[DllImport(\"kernel32.dll\")]\n[return: MarshalAs(UnmanagedType.Bool)]\ninternal static extern bool HeapLock(IntPtr heap);\n\n[DllImport(\"kernel32.dll\")]\ninternal static extern uint HeapCompact(IntPtr heap, uint flags);\n\n[DllImport(\"kernel32.dll\")]\n[return: MarshalAs(UnmanagedType.Bool)]\ninternal static extern bool HeapUnlock(IntPtr heap);\n"
}
] |
2008/11/04
|
[
"https://Stackoverflow.com/questions/263249",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/24443/"
] |
263,263
|
<p>I'm using Apache Subversion to manage and store a decent volume of code. Trying to get at it on a standard work machine using svn+ssh with TortoiseSVN on Windows Vista, I find that I can't actually bring all of it down to my local machine at once - the transfer stops after about 1 MB. I can grab it all in fits and starts by canceling the process and updating the incomplete working copy, but that's not the real problem.</p>
<p>The real problem is, trying to merge multiple code branches requires enough data transfer to choke the connection, and as far as I can tell there's no such thing as resuming an incomplete merge. </p>
<p>I have no idea why this is happening - the only resolution steps that have fixed the problem for anyone else on my Google crawl seems to indicate an aggressive antivirus might have something to do with it, but disabling the one that was installed on the work machine (Symantec Endpoint Protection) or ordering it to ignore the destination directory and transfer process doesn't seem to help any.</p>
<p><strong>Anybody out there seen TortoiseSVN flat-out stop when transferring modest quantities of information, and what can I tweak to fix the problem?</strong> </p>
<p>I'm pretty sure it's not Vista-specific, since my buddy with his Windows XP machine from the last rollout is having exactly the same problem.</p>
<p>A little extra information:</p>
<ul>
<li><p>TortoiseSVN version 1.5.5, 32-bit on a 32-bit version of Vista.</p></li>
<li><p>Connecting to a Solaris 9 box over SSH 1, running Subversion 1.5.3. The version of Solaris and SSH aren't negotiable, since this is a repurposed old server and we manage configurations pretty strictly. </p></li>
<li><p>I've poked around on the Solaris machine and it doesn't look like there are problems at all, aside from the system trying to Kerberos-authenticate me and failing. The process is apparently just waiting for client-side input (in the middle of a checkout?) and Tortoise doesn't seem to be providing the right kind.</p></li>
<li><p>Switching to, say, PLink from TortoisePLink doesn't seem to make any difference - the process begins, but when it stalls out I'm not seeing anything in the terminal window.</p></li>
</ul>
<p>Even some help on figuring out what's going wrong here would be appreciated.</p>
|
[
{
"answer_id": 263459,
"author": "Jesse C. Slicer",
"author_id": 3312,
"author_profile": "https://Stackoverflow.com/users/3312",
"pm_score": 4,
"selected": true,
"text": "public static void MinimizeMemory()\n{\n GC.Collect(GC.MaxGeneration);\n GC.WaitForPendingFinalizers();\n SetProcessWorkingSetSize(\n Process.GetCurrentProcess().Handle,\n (UIntPtr)0xFFFFFFFF,\n (UIntPtr)0xFFFFFFFF);\n\n IntPtr heap = GetProcessHeap();\n\n if (HeapLock(heap))\n {\n try\n {\n if (HeapCompact(heap, 0) == 0)\n {\n // error condition ignored\n }\n }\n finally\n {\n HeapUnlock(heap);\n }\n }\n}\n\n[DllImport(\"kernel32.dll\")]\n[return: MarshalAs(UnmanagedType.Bool)]\ninternal static extern bool SetProcessWorkingSetSize(\n IntPtr process,\n UIntPtr minimumWorkingSetSize,\n UIntPtr maximumWorkingSetSize);\n\n[DllImport(\"kernel32.dll\", SetLastError = true)]\ninternal static extern IntPtr GetProcessHeap();\n\n[DllImport(\"kernel32.dll\")]\n[return: MarshalAs(UnmanagedType.Bool)]\ninternal static extern bool HeapLock(IntPtr heap);\n\n[DllImport(\"kernel32.dll\")]\ninternal static extern uint HeapCompact(IntPtr heap, uint flags);\n\n[DllImport(\"kernel32.dll\")]\n[return: MarshalAs(UnmanagedType.Bool)]\ninternal static extern bool HeapUnlock(IntPtr heap);\n"
}
] |
2008/11/04
|
[
"https://Stackoverflow.com/questions/263263",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/34384/"
] |
263,267
|
<p>Is there a way, within the .net framework, to check to see if two different shared folders are actually pointing to the same physical directory? Do directories in Windows have some sort of unique identifier? Google-fu is failing me.</p>
<p>(I mean, aside from writing a temp file to one and seeing if it appears in the other)</p>
<p>Edit: I think I've discovered what I need,with thanks to Brody for getting me pointed in the right direction in the System.Management namespace.</p>
|
[
{
"answer_id": 264280,
"author": "Brody",
"author_id": 17131,
"author_profile": "https://Stackoverflow.com/users/17131",
"pm_score": 0,
"selected": false,
"text": "ManagementClass management = new ManagementClass(\"\\\\\\\\.\\\\root\\\\cimv2\", \"Win32_Share\", null)\n"
},
{
"answer_id": 264650,
"author": "bruno conde",
"author_id": 31136,
"author_profile": "https://Stackoverflow.com/users/31136",
"pm_score": 0,
"selected": false,
"text": "class Program\n{\n struct BY_HANDLE_FILE_INFORMATION\n {\n public uint FileAttributes;\n public System.Runtime.InteropServices.ComTypes.FILETIME CreationTime;\n public System.Runtime.InteropServices.ComTypes.FILETIME LastAccessTime;\n public System.Runtime.InteropServices.ComTypes.FILETIME LastWriteTime;\n public uint VolumeSerialNumber;\n public uint FileSizeHigh;\n public uint FileSizeLow;\n public uint NumberOfLinks;\n public uint FileIndexHigh;\n public uint FileIndexLow;\n }\n\n //\n // CreateFile constants\n //\n const uint FILE_SHARE_READ = 0x00000001;\n const uint FILE_SHARE_WRITE = 0x00000002;\n const uint FILE_SHARE_DELETE = 0x00000004;\n const uint OPEN_EXISTING = 3;\n\n const uint GENERIC_READ = (0x80000000);\n const uint GENERIC_WRITE = (0x40000000);\n\n const uint FILE_FLAG_NO_BUFFERING = 0x20000000;\n const uint FILE_READ_ATTRIBUTES = (0x0080);\n const uint FILE_WRITE_ATTRIBUTES = 0x0100;\n const uint ERROR_INSUFFICIENT_BUFFER = 122;\n const uint FILE_FLAG_BACKUP_SEMANTICS = 0x02000000;\n\n\n [DllImport(\"kernel32.dll\", SetLastError = true)]\n static extern IntPtr CreateFile(\n string lpFileName,\n uint dwDesiredAccess,\n uint dwShareMode,\n IntPtr lpSecurityAttributes,\n uint dwCreationDisposition,\n uint dwFlagsAndAttributes,\n IntPtr hTemplateFile);\n\n [DllImport(\"kernel32.dll\", SetLastError = true)]\n static extern bool GetFileInformationByHandle(IntPtr hFile, out BY_HANDLE_FILE_INFORMATION lpFileInformation);\n\n static void Main(string[] args)\n {\n string dir1 = @\"C:\\MyTestDir\";\n string dir2 = @\"\\\\myMachine\\MyTestDir\";\n Console.WriteLine(CompareDirectories(dir1, dir2));\n }\n\n static bool CompareDirectories(string dir1, string dir2)\n {\n BY_HANDLE_FILE_INFORMATION fileInfo1, fileInfo2;\n IntPtr ptr1 = CreateFile(dir1, GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE, IntPtr.Zero, OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, IntPtr.Zero);\n if ((int)ptr1 == -1)\n {\n System.ComponentModel.Win32Exception t = new System.ComponentModel.Win32Exception(Marshal.GetLastWin32Error());\n Console.WriteLine(dir1 + \": \" + t.Message);\n return false;\n }\n IntPtr ptr2 = CreateFile(dir2, GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE, IntPtr.Zero, OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, IntPtr.Zero);\n if ((int)ptr2 == -1)\n {\n System.ComponentModel.Win32Exception t = new System.ComponentModel.Win32Exception(Marshal.GetLastWin32Error());\n Console.WriteLine(dir2 + \": \" + t.Message);\n return false;\n }\n GetFileInformationByHandle(ptr1, out fileInfo1);\n GetFileInformationByHandle(ptr2, out fileInfo2);\n\n return ((fileInfo1.FileIndexHigh == fileInfo2.FileIndexHigh) &&\n (fileInfo1.FileIndexLow == fileInfo2.FileIndexLow));\n }\n}\n"
},
{
"answer_id": 265997,
"author": "Dana",
"author_id": 7856,
"author_profile": "https://Stackoverflow.com/users/7856",
"pm_score": 1,
"selected": true,
"text": "Connection options = new ConnectionOptions();\nManagementScope scpoe = new ManagementScope(\"\\\\\\\\Server\\\\root\\\\cimv2\", options);\nObjectQuery query = new ObjectQuery(\"SELECT * FROM Win32_Share WHERE Name = '\" + name +\"'\")\n\nManagementObjectSearcher searcher = new ManagementObjectSearch(scope, query);\nManagementObjectCollection qc = searcher.Get();\n\nforeach (ManagementObject m in qc) {\n Console.WriteLine(m[\"Path\"]);\n}\n"
}
] |
2008/11/04
|
[
"https://Stackoverflow.com/questions/263267",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7856/"
] |
263,271
|
<p>I have a Ruby script that generates a UTF8 CSV file remotely in a Linux machine and then transfers the file to a Windows machine thru SFTP. </p>
<p>I then need to open this file with Excel, but Excel doesn't get UTF8, so I always need to open the file in a text editor that has the capability to convert UTF8 to ANSI.</p>
<p>I would love to do this programmatically using Ruby and avoid the manual conversion step. What's the easiest way to do it?</p>
<p>PS: I tried using iconv but had no success.</p>
|
[
{
"answer_id": 263324,
"author": "AShelly",
"author_id": 10396,
"author_profile": "https://Stackoverflow.com/users/10396",
"pm_score": 5,
"selected": true,
"text": "ascii_str = yourUTF8text.unpack(\"U*\").map{|c|c.chr}.join\n"
},
{
"answer_id": 263326,
"author": "Dema",
"author_id": 407003,
"author_profile": "https://Stackoverflow.com/users/407003",
"pm_score": 4,
"selected": false,
"text": "\nrequire 'iconv'\n\nutf8_csv = File.open(\"utf8file.csv\").read\n\n# gotta be careful with the weird parameters order: TO, FROM !\nansi_csv = Iconv.iconv(\"LATIN1\", \"UTF-8\", utf8_csv).join\n\nFile.open(\"ansifile.csv\", \"w\") { |f| f.puts ansi_csv }\n"
},
{
"answer_id": 32193780,
"author": "markquezada",
"author_id": 264230,
"author_profile": "https://Stackoverflow.com/users/264230",
"pm_score": 3,
"selected": false,
"text": "\"olá, mundo!\".to_ascii #=> \"ola, mundo!\"\n\"你好\".to_ascii #=> \"Ni Hao \"\n\"Jürgen Müller\".to_ascii #=> \"Jurgen Muller\"\n\"Jürgen Müller\".to_ascii(\"ü\" => \"ue\") #=> \"Juergen Mueller\"\n"
},
{
"answer_id": 45765288,
"author": "knut",
"author_id": 676874,
"author_profile": "https://Stackoverflow.com/users/676874",
"pm_score": 3,
"selected": false,
"text": "yourstring.encode('ASCII')\n yourstring.encode('ASCII', invalid: :replace, undef: :replace, replace: \"_\")\n"
}
] |
2008/11/04
|
[
"https://Stackoverflow.com/questions/263271",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/407003/"
] |
263,276
|
<p>I'm writing a program in C# that runs in the background and allows users to use a hotkey to switch keyboard layouts in the active window. (Windows only supports <kbd>CTRL</kbd>+<kbd>SHIFT</kbd> and <kbd>ALT</kbd>+<kbd>SHIFT</kbd>)</p>
<p>I'm using RegisterHotKey to catch the hotkey, and it's working fine.</p>
<p>The problem is that I can't find any API to change the keyboard layout for the focused window.</p>
<p>ActivateKeyboardLayout and LoadKeyboardLayout can only change the keyboard layout for the calling thread.</p>
<p>Does anyone know how to change the keyboard layout for a different thread (the way the Language Bar does)?</p>
|
[
{
"answer_id": 2691040,
"author": "Ramil Mammadov",
"author_id": 323262,
"author_profile": "https://Stackoverflow.com/users/323262",
"pm_score": 3,
"selected": false,
"text": "PostMessage(handle, \n WM_INPUTLANGCHANGEREQUEST, \n 0, \n LoadKeyboardLayout( StrCopy(Layout,'00000419'), KLF_ACTIVATE)\n);\n"
},
{
"answer_id": 2691077,
"author": "Ramil Mammadov",
"author_id": 323262,
"author_profile": "https://Stackoverflow.com/users/323262",
"pm_score": 0,
"selected": false,
"text": " function ChangeRemoteWndKeyboardLayoutToRussian(\n const RemoteHandle: THandle): Boolean;\n var\n Dumme: DWORD;\n Layout: HKL;\n begin\n Layout := LoadKeyboardLayout('00000419', KLF_ACTIVATE);\n Result := SendMessageTimeOut(RemoteHandle, WM_INPUTLANGCHANGEREQUEST,\n 0, Layout, SMTO_ABORTIFHUNG, 200, Dumme) <> 0;\n if Result then \n Result := SendMessageTimeOut(RemoteHandle, WM_INPUTLANGCHANGEREQUEST,\n RUSSIAN_CHARSET, Layout, SMTO_ABORTIFHUNG, 200, Dumme) <> 0;\n end;\n"
}
] |
2008/11/04
|
[
"https://Stackoverflow.com/questions/263276",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/34397/"
] |
263,305
|
<p>I've been working on a visualization project for 2-dimensional continuous data. It's the kind of thing you could use to study elevation data or temperature patterns on a 2D map. At its core, it's really a way of flattening 3-dimensions into two-dimensions-plus-color. In my particular field of study, I'm not actually working with geographical elevation data, but it's a good metaphor, so I'll stick with it throughout this post.</p>
<p>Anyhow, at this point, I have a "continuous color" renderer that I'm very pleased with:</p>
<p><img src="https://i.stack.imgur.com/ycIzY.png" alt="Continuous Color Renderer"></p>
<p>The gradient is the standard color-wheel, where red pixels indicate coordinates with high values, and violet pixels indicate low values.</p>
<p>The underlying data structure uses some very clever (if I do say so myself) interpolation algorithms to enable arbitrarily deep zooming into the details of the map.</p>
<p>At this point, I want to draw some topographical contour lines (using quadratic bezier curves), but I haven't been able to find any good literature describing efficient algorithms for finding those curves.</p>
<p>To give you an idea for what I'm thinking about, here's a poor-man's implementation (where the renderer just uses a black RGB value whenever it encounters a pixel that intersects a contour line):</p>
<p><img src="https://i.stack.imgur.com/eOiGk.png" alt="Continuous Color with Ghetto Topo Lines"></p>
<p>There are several problems with this approach, though:</p>
<ul>
<li><p>Areas of the graph with a steeper slope result in thinner (and often broken) topo lines. Ideally, all topo lines should be continuous.</p></li>
<li><p>Areas of the graph with a flatter slope result in wider topo lines (and often entire regions of blackness, especially at the outer perimeter of the rendering region).</p></li>
</ul>
<p>So I'm looking at a vector-drawing approach for getting those nice, perfect 1-pixel-thick curves. The basic structure of the algorithm will have to include these steps:</p>
<ol>
<li><p>At each discrete elevation where I want to draw a topo line, find a set of coordinates where the elevation at that coordinate is extremely close (given an arbitrary epsilon value) to the desired elevation.</p></li>
<li><p>Eliminate redundant points. For example, if three points are in a perfectly-straight line, then the center point is redundant, since it can be eliminated without changing the shape of the curve. Likewise, with bezier curves, it is often possible to eliminate cetain anchor points by adjusting the position of adjacent control points.</p></li>
<li><p>Assemble the remaining points into a sequence, such that each segment between two points approximates an elevation-neutral trajectory, and such that no two line segments ever cross paths. Each point-sequence must either create a closed polygon, or must intersect the bounding box of the rendering region.</p></li>
<li><p>For each vertex, find a pair of control points such that the resultant curve exhibits a minimum error, with respect to the redundant points eliminated in step #2.</p></li>
<li><p>Ensure that all features of the topography visible at the current rendering scale are represented by appropriate topo lines. For example, if the data contains a spike with high altitude, but with extremely small diameter, the topo lines should still be drawn. Vertical features should only be ignored if their feature diameter is smaller than the overall rendering granularity of the image.</p></li>
</ol>
<p>But even under those constraints, I can still think of several different heuristics for finding the lines:</p>
<ul>
<li><p>Find the high-point within the rendering bounding-box. From that high point, travel downhill along several different trajectories. Any time the traversal line crossest an elevation threshold, add that point to an elevation-specific bucket. When the traversal path reaches a local minimum, change course and travel uphill.</p></li>
<li><p>Perform a high-resolution traversal along the rectangular bounding-box of the rendering region. At each elevation threshold (and at inflection points, wherever the slope reverses direction), add those points to an elevation-specific bucket. After finishing the boundary traversal, start tracing inward from the boundary points in those buckets.</p></li>
<li><p>Scan the entire rendering region, taking an elevation measurement at a sparse regular interval. For each measurement, use it's proximity to an elevation threshold as a mechanism to decide whether or not to take an interpolated measurement of its neighbors. Using this technique would provide better guarantees of coverage across the whole rendering region, but it'd be difficult to assemble the resultant points into a sensible order for constructing paths.</p></li>
</ul>
<p>So, those are some of my thoughts...</p>
<p>Before diving deep into an implementation, I wanted to see whether anyone else on StackOverflow has experience with this sort of problem and could provide pointers for an accurate and efficient implementation.</p>
<p><strong>Edit:</strong></p>
<p>I'm especially interested in the "Gradient" suggestion made by ellisbben. And my core data structure (ignoring some of the optimizing interpolation shortcuts) can be represented as the summation of a set of 2D gaussian functions, which is totally differentiable.</p>
<p>I suppose I'll need a data structure to represent a three-dimensional slope, and a function for calculating that slope vector for at arbitrary point. Off the top of my head, I don't know how to do that (though it seems like it ought to be easy), but if you have a link explaining the math, I'd be much obliged!</p>
<p><strong>UPDATE:</strong></p>
<p>Thanks to the excellent contributions by ellisbben and Azim, I can now calculate the contour angle for any arbitrary point in the field. Drawing the real topo lines will follow shortly!</p>
<p>Here are updated renderings, with and without the ghetto raster-based topo-renderer that I've been using. Each image includes a thousand random sample points, represented by red dots. The angle-of-contour at that point is represented by a white line. In certain cases, no slope could be measured at the given point (based on the granularity of interpolation), so the red dot occurs without a corresponding angle-of-contour line.</p>
<p>Enjoy!</p>
<p><em>(NOTE: These renderings use a different surface topography than the previous renderings -- since I randomly generate the data structures on each iteration, while I'm prototyping -- but the core rendering method is the same, so I'm sure you get the idea.)</em></p>
<p><img src="https://i.stack.imgur.com/PovID.png" alt="alt text"></p>
<p><img src="https://i.stack.imgur.com/x7jpg.png" alt="alt text"></p>
<p>Here's a fun fact: over on the right-hand-side of these renderings, you'll see a bunch of weird contour lines at perfect horizontal and vertical angles. These are artifacts of the interpolation process, which uses a grid of interpolators to reduce the number of computations (by about 500%) necessary to perform the core rendering operations. All of those weird contour lines occur on the boundary between two interpolator grid cells.</p>
<p>Luckily, those artifacts don't actually matter. Although the artifacts are detectable during slope calculation, the final renderer won't notice them, since it operates at a different bit depth.</p>
<hr>
<p>UPDATE AGAIN:</p>
<p>Aaaaaaaand, as one final indulgence before I go to sleep, here's another pair of renderings, one in the old-school "continuous color" style, and one with 20,000 gradient samples. In this set of renderings, I've eliminated the red dot for point-samples, since it unnecessarily clutters the image.</p>
<p>Here, you can really see those interpolation artifacts that I referred to earlier, thanks to the grid-structure of the interpolator collection. I should emphasize that those artifacts will be completely invisible on the final contour rendering (since the difference in magnitude between any two adjacent interpolator cells is less than the bit depth of the rendered image).</p>
<p>Bon appetit!!</p>
<p><img src="https://i.stack.imgur.com/RU3Yl.png" alt="alt text"></p>
<p><img src="https://i.stack.imgur.com/6RWTM.png" alt="alt text"></p>
|
[
{
"answer_id": 263636,
"author": "erickson",
"author_id": 3474,
"author_profile": "https://Stackoverflow.com/users/3474",
"pm_score": 2,
"selected": false,
"text": "alpha = (contour - neighbor) / (current - neighbor)\n sqrt(2) / 2"
},
{
"answer_id": 263891,
"author": "Azim J",
"author_id": 4612,
"author_profile": "https://Stackoverflow.com/users/4612",
"pm_score": 2,
"selected": false,
"text": "g={ ( f(x+dx,y)-f(x-dx,y) )/(2*dx), \n { ( f(x,y+dy)-f(x,y-dy) )/(2*dy) \n c = [-w,v]\n"
}
] |
2008/11/04
|
[
"https://Stackoverflow.com/questions/263305",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/22979/"
] |
263,322
|
<p>What is the best way to add "copy to clipboard" functionality to a ListView control in WPF?</p>
<p>I tried adding an ApplicationCommands.Copy to either the ListView ContextMenu or the ListViewItem ContextMenu, but the command remains disabled.</p>
<p>Thanks,
Peter</p>
<p>Here is an xaml sample of one of my attempts...</p>
<pre><code> <Window.Resources>
<ContextMenu x:Key="SharedInstanceContextMenu" x:Shared="True">
<MenuItem Header="Copy" Command="ApplicationCommands.Copy"/>
</ContextMenu>
</Window.Resources>
<ListBox Margin="12,233,225,68" Name="listBox1" >
<ListBox.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding Path=UpToSourceCategoryByCategoryId.Category}" ContextMenu="{DynamicResource ResourceKey=SharedInstanceContextMenu}"/>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</code></pre>
<p>How should I set the CommandTarget in this case?</p>
<p>Thanks,Peter</p>
|
[
{
"answer_id": 263540,
"author": "Todd White",
"author_id": 30833,
"author_profile": "https://Stackoverflow.com/users/30833",
"pm_score": 3,
"selected": true,
"text": "<Window.CommandBindings>\n <CommandBinding\n Command=\"ApplicationCommands.Copy\"\n Executed=\"CopyCommandHandler\"\n CanExecute=\"CanCopyExecuteHandler\" />\n</Window.CommandBindings>\n\n<Window.Resources>\n <ContextMenu x:Key=\"SharedInstanceContextMenu\">\n <MenuItem Header=\"Copy\" Command=\"ApplicationCommands.Copy\"/>\n </ContextMenu>\n\n <Style x:Key=\"MyItemContainerStyle\" TargetType=\"{x:Type ListBoxItem}\">\n <Setter Property=\"ContextMenu\" Value=\"{StaticResource SharedInstanceContextMenu}\" />\n </Style>\n</Window.Resources>\n\n<ListBox ItemContainerStyle=\"{StaticResource MyItemContainerStyle}\">\n <ListBoxItem>One</ListBoxItem>\n <ListBoxItem>Two</ListBoxItem>\n <ListBoxItem>Three</ListBoxItem>\n <ListBoxItem>Four</ListBoxItem>\n</ListBox>\n"
}
] |
2008/11/04
|
[
"https://Stackoverflow.com/questions/263322",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/34403/"
] |
263,336
|
<p>I'm trying out asp.net mvc for a new project, and I ran across something odd. When I use the MVC UI helpers for textboxes, the values get persisted between calls. But, when I use a series of radio buttons, the checked state doesn't get persisted.</p>
<p>Here's an example from my view.</p>
<pre><code><li>
<%=Html.RadioButton("providerType","1")%><label>Hospital</label>
<%=Html.RadioButton("providerType","2")%><label>Facility</label>
<%=Html.RadioButton("providerType","3")%><label>Physician</label>
</li>
</code></pre>
<p>When the form gets posted back, I build up an object with "ProviderType" as one of it's properties. The value on the object is getting set, and then I RedirectToAction with the provider as a argument. All is well, and I end up at a URL like "<a href="http://localhost/Provider/List?ProviderType=1" rel="noreferrer">http://localhost/Provider/List?ProviderType=1</a>" with ProviderType showing. The value gets persisted to the URL, but the UI helper isn't picking up the checked state.</p>
<p>I'm having this problem with listbox, <strike>dropdownlist</strike>, and radiobutton. Textboxes pick up the values just fine. Do you see something I'm doing wrong? I'm assuming that the helpers will do this for me, but maybe I'll just have to take care of this on my own. I'm just feeling my way through this, so your input is appreciated.</p>
<p><strong>Edit:</strong> I just found the override for the SelectList constructor that takes a selected value. That took care of my dropdown issue I mentioned above.</p>
<p><strong>Edit #2:</strong> I found something that works, but it pains me to do it this way. I feel like this should be inferred.</p>
<pre><code><li>
<%=Html.RadioButton("ProviderType","1",Request["ProviderType"]=="1")%><label>Hospital</label>
<%=Html.RadioButton("ProviderType", "2", Request["ProviderType"] == "2")%><label>Facility</label>
<%=Html.RadioButton("ProviderType", "3", Request["ProviderType"] == "3")%><label>Physician</label>
</li>
</code></pre>
<p>Hopefully someone will come up with another way.</p>
|
[
{
"answer_id": 622986,
"author": "Jonathan Parker",
"author_id": 4504,
"author_profile": "https://Stackoverflow.com/users/4504",
"pm_score": 2,
"selected": false,
"text": "<% foreach(var provider in (IEnumerable<Provider>)ViewData[\"Providers\"]) { %>\n <%=Html.RadioButton(\"ProviderType\", provider.ID.ToString(), provider.IsSelected)%><label><%=provider.Name%></label>\n<% } %>\n var providers = GetProviders();\nint selectedId = (int) Request[\"ProviderType\"]; // TODO: Use Int32.TryParse() instead\nforeach(var p in providers)\n{\n if (p.ID == selectedId)\n {\n p.IsSelected = true;\n break;\n }\n}\nViewData[\"Providers\"] = providers;\nreturn View();\n public class Provider\n{\n public int ID { get; set; }\n public string Name { get; set; }\n public bool IsSelected { get; set; }\n}\n"
},
{
"answer_id": 2989460,
"author": "Cheny",
"author_id": 360415,
"author_profile": "https://Stackoverflow.com/users/360415",
"pm_score": 2,
"selected": false,
"text": "<%=Html.RadioButton(\"ProviderType\",\"1\",Model.ProviderType==1)%><label>Hospital</label> \n"
},
{
"answer_id": 4416150,
"author": "K.V. Sai Kishore",
"author_id": 538781,
"author_profile": "https://Stackoverflow.com/users/538781",
"pm_score": -1,
"selected": false,
"text": "<%=Html.RadioButton(\"providerType\",\"1\")%><label>Hospital</label>\n<%=Html.RadioButton(\"providerType\",\"2\")%><label>Facility</label>\n<%=Html.RadioButton(\"providerType\",\"3\")%><label>Physician</label>\n public ActionResult GetType(FormCollection collection)\n{\n string type=collection.Get(\"providerType\");\n\n if(type==\"1\")\n //code\n else if(type==\"2\")\n //code\n else\n //code\n\n return View();\n}\n"
},
{
"answer_id": 4672183,
"author": "Eduardo Molteni",
"author_id": 2385,
"author_profile": "https://Stackoverflow.com/users/2385",
"pm_score": 1,
"selected": false,
"text": " <Extension()> _\n Public Function RadioButtonList(ByVal helper As HtmlHelper, ByVal name As String, ByVal Items As IEnumerable(Of String)) As String\n Dim selectList = New SelectList(Items)\n Return helper.RadioButtonList(name, selectList)\n End Function\n\n <Extension()> _\n Public Function RadioButtonList(ByVal helper As HtmlHelper, ByVal Name As String, ByVal Items As IEnumerable(Of SelectListItem)) As String\n Dim sb As New StringBuilder\n sb.Append(\"<table class=\"\"radiobuttonlist\"\">\")\n For Each item In Items\n sb.AppendFormat(\"<tr><td><input id=\"\"{0}_{1}\"\" name=\"\"{0}\"\" type=\"\"radio\"\" value=\"\"{1}\"\" {2} /><label for=\"\"{0}_{1}\"\" id=\"\"{0}_{1}_Label\"\">{3}</label></td><tr>\", Name, item.Value, If(item.Selected, \"selected\", \"\"), item.Text)\n Next\n sb.Append(\"</table>\")\n Return sb.ToString()\n End Function\n <%= Html.RadioButtonList(\"ProviderType\", Model.ProviderTypeSelectList) %>\n UpdateModel(Provider)\n"
}
] |
2008/11/04
|
[
"https://Stackoverflow.com/questions/263336",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1672/"
] |
263,339
|
<p>I'm looking for a clean C++ way to parse a string containing expressions wrapped in ${} and build a result string from the programmatically evaluated expressions.</p>
<p>Example: "Hi ${user} from ${host}" will be evaluated to "Hi foo from bar" if I implement the program to let "user" evaluate to "foo", etc.</p>
<p>The current approach I'm thinking of consists of a state machine that eats one character at a time from the string and evaluates the expression after reaching '}'. Any hints or other suggestions?</p>
<p>Note: boost:: is most welcome! :-)</p>
<p><strong>Update</strong> Thanks for the first three suggestions! Unfortunately I made the example too simple! I need to be able examine the contents within ${} so it's not a simple search and replace. Maybe it will say ${uppercase:foo} and then I have to use "foo" as a key in a hashmap and then convert it to uppercase, but I tried to avoid the inner details of ${} when writing the original question above... :-)</p>
|
[
{
"answer_id": 263389,
"author": "Matt Cruikshank",
"author_id": 8643,
"author_profile": "https://Stackoverflow.com/users/8643",
"pm_score": 0,
"selected": false,
"text": "std::map<string, string> key value user Matt Cruikshank \"${\" + key + \"}\" value"
},
{
"answer_id": 263431,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 4,
"selected": true,
"text": "#include <iostream>\n#include <conio.h>\n#include <string>\n#include <map>\n\nusing namespace std;\n\nstruct Token\n{\n enum E\n {\n Replace,\n Literal,\n Eos\n };\n};\n\nclass ParseExp\n{\nprivate:\n enum State\n {\n State_Begin,\n State_Literal,\n State_StartRep,\n State_RepWord,\n State_EndRep\n };\n\n string m_str;\n int m_char;\n unsigned int m_length;\n string m_lexme;\n Token::E m_token;\n State m_state;\n\npublic:\n void Parse(const string& str)\n {\n m_char = 0;\n m_str = str;\n m_length = str.size();\n }\n\n Token::E NextToken()\n {\n if (m_char >= m_length)\n m_token = Token::Eos;\n\n m_lexme = \"\";\n m_state = State_Begin;\n bool stop = false;\n while (m_char <= m_length && !stop)\n {\n char ch = m_str[m_char++];\n switch (m_state)\n {\n case State_Begin:\n if (ch == '$')\n {\n m_state = State_StartRep;\n m_token = Token::Replace;\n continue;\n }\n else\n {\n m_state = State_Literal;\n m_token = Token::Literal;\n }\n break;\n\n case State_StartRep:\n if (ch == '{')\n {\n m_state = State_RepWord;\n continue;\n }\n else\n continue;\n break;\n\n case State_RepWord:\n if (ch == '}')\n {\n stop = true;\n continue;\n }\n break;\n\n case State_Literal:\n if (ch == '$')\n {\n stop = true;\n m_char--;\n continue;\n }\n }\n\n m_lexme += ch;\n }\n\n return m_token;\n }\n\n const string& Lexme() const\n {\n return m_lexme;\n }\n\n Token::E Token() const\n {\n return m_token;\n }\n};\n\nstring DoReplace(const string& str, const map<string, string>& dict)\n{\n ParseExp exp;\n exp.Parse(str);\n string ret = \"\";\n while (exp.NextToken() != Token::Eos)\n {\n if (exp.Token() == Token::Literal)\n ret += exp.Lexme();\n else\n {\n map<string, string>::const_iterator iter = dict.find(exp.Lexme());\n if (iter != dict.end())\n ret += (*iter).second;\n else\n ret += \"undefined(\" + exp.Lexme() + \")\";\n }\n }\n return ret;\n}\n\nint main()\n{\n map<string, string> words;\n words[\"hello\"] = \"hey\";\n words[\"test\"] = \"bla\";\n cout << DoReplace(\"${hello} world ${test} ${undef}\", words);\n _getch();\n}\n"
}
] |
2008/11/04
|
[
"https://Stackoverflow.com/questions/263339",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20444/"
] |
263,355
|
<p>Portfolio A → Fund 1</p>
<p>Portfolio A → Fund 2</p>
<p>Portfolio A → Fund 3</p>
<p>I couldn't frame my sentence without not using is/has. But between 1 & 2,</p>
<p>1) has a:</p>
<pre><code>class PortfolioA
{
List<Fund> obj;
}
</code></pre>
<p>2) is a:</p>
<pre><code>class PortfolioA : List<Fund>
{
}
</code></pre>
<p>which one do you think is better from the point of extensibility, usability? I can still access my funds either way, albeit with a small syntactical change.</p>
|
[
{
"answer_id": 263437,
"author": "Bill Karwin",
"author_id": 20860,
"author_profile": "https://Stackoverflow.com/users/20860",
"pm_score": 5,
"selected": true,
"text": "Portfolio List<Fund> List<Fund>"
},
{
"answer_id": 263628,
"author": "Charles Bretana",
"author_id": 32632,
"author_profile": "https://Stackoverflow.com/users/32632",
"pm_score": 1,
"selected": false,
"text": "public Portfolio(CLient client) {};\npublic Portfolio(Branch branch, bool Active, decimal valueThreshold)\n{\n // code to populate collection with all active portfolios at the specified branch whose total vlaue exceeds specified threshold \n}\n public Fund this[int fundId] { get { return this.fundList[fundId]; } }\n Portfolio BobsPortfolio = new Portfolio(Bob); \n\nforeach (Fund fund in BobsPortfolio)\n{\n fund.SendStatement();\n}\n"
}
] |
2008/11/04
|
[
"https://Stackoverflow.com/questions/263355",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/31622/"
] |
263,359
|
<p>I'm writing some Javascript to resize the large image to fit into the user's browser window. (I don't control the size of the source images unfortunately.)</p>
<p>So something like this would be in the HTML:</p>
<pre><code><img id="photo"
src="a_really_big_file.jpg"
alt="this is some alt text"
title="this is some title text" />
</code></pre>
<p><strong>Is there a way for me to determine if the <code>src</code> image in an <code>img</code> tag has been downloaded?</strong></p>
<p>I need this because I'm running into a problem if <code>$(document).ready()</code> is executed before the browser has loaded the image. <code>$("#photo").width()</code> and <code>$("#photo").height()</code> will return the size of the placeholder (the alt text). In my case this is something like 134 x 20.</p>
<p>Right now I'm just checking if the photo's height is less than 150, and assuming that if so it is just alt text. But this is quite a hack, and it would break if a photo is less than 150 pixels tall (not likely in my particular case), or if the alt text is more than 150 pixels tall (could possibly happen on a small browser window).</p>
<hr>
<p><strong>Edit:</strong> For anyone wanting to see the code:</p>
<pre><code>$(function()
{
var REAL_WIDTH = $("#photo").width();
var REAL_HEIGHT = $("#photo").height();
$(window).resize(adjust_photo_size);
adjust_photo_size();
function adjust_photo_size()
{
if(REAL_HEIGHT < 150)
{
REAL_WIDTH = $("#photo").width();
REAL_HEIGHT = $("#photo").height();
if(REAL_HEIGHT < 150)
{
//image not loaded.. try again in a quarter-second
setTimeout(adjust_photo_size, 250);
return;
}
}
var new_width = . . . ;
var new_height = . . . ;
$("#photo").width(Math.round(new_width));
$("#photo").height(Math.round(new_height));
}
});
</code></pre>
<hr>
<p><strong>Update</strong>: Thanks for the suggestions. There is a risk of the event not being fired if I set a callback for the <code>$("#photo").load</code> event, so I have defined an onLoad event directly on the image tag. For the record, here is the code I ended up going with:</p>
<pre><code><img id="photo"
onload="photoLoaded();"
src="a_really_big_file.jpg"
alt="this is some alt text"
title="this is some title text" />
</code></pre>
<p>Then in Javascript:</p>
<pre><code>//This must be outside $() because it may get called first
var isPhotoLoaded = false;
function photoLoaded()
{
isPhotoLoaded = true;
}
$(function()
{
//Hides scrollbars, so we can resize properly. Set with JS instead of
// CSS so that page doesn't break with JS disabled.
$("body").css("overflow", "hidden");
var REAL_WIDTH = -1;
var REAL_HEIGHT = -1;
$(window).resize(adjust_photo_size);
adjust_photo_size();
function adjust_photo_size()
{
if(!isPhotoLoaded)
{
//image not loaded.. try again in a quarter-second
setTimeout(adjust_photo_size, 250);
return;
}
else if(REAL_WIDTH < 0)
{
//first time in this function since photo loaded
REAL_WIDTH = $("#photo").width();
REAL_HEIGHT = $("#photo").height();
}
var new_width = . . . ;
var new_height = . . . ;
$("#photo").width(Math.round(new_width));
$("#photo").height(Math.round(new_height));
}
});
</code></pre>
|
[
{
"answer_id": 263447,
"author": "Diodeus - James MacFarlane",
"author_id": 12579,
"author_profile": "https://Stackoverflow.com/users/12579",
"pm_score": 6,
"selected": true,
"text": "<img id=\"photo\"\n onload='loaded(this.id)'\n src=\"a_really_big_file.jpg\"\n alt=\"this is some alt text\"\n title=\"this is some title text\" />\n"
},
{
"answer_id": 263479,
"author": "Allain Lalonde",
"author_id": 2443,
"author_profile": "https://Stackoverflow.com/users/2443",
"pm_score": 2,
"selected": false,
"text": "$(\"#photo\").load(function() {\n alert(\"Hello from Image\");\n});\n"
},
{
"answer_id": 3817269,
"author": "Jay",
"author_id": 461113,
"author_profile": "https://Stackoverflow.com/users/461113",
"pm_score": 1,
"selected": false,
"text": "doShow = function(){\n if($('#img_id').attr('complete')){\n alert('Image is loaded!');\n } else {\n window.setTimeout('doShow()',100);\n }\n};\n\n$('#img_id').attr('src','image.jpg');\n\ndoShow();\n"
},
{
"answer_id": 7852814,
"author": "Mike Fogel",
"author_id": 103909,
"author_profile": "https://Stackoverflow.com/users/103909",
"pm_score": 4,
"selected": false,
"text": "<img id=\"myimage\" onload=\"$(this).data('loaded', 'loaded');\" src=\"lolcats.jpg\" />\n if ($('#myimage').data('loaded')) {\n // loaded, so do stuff\n}\n"
},
{
"answer_id": 9333069,
"author": "roberkules",
"author_id": 45948,
"author_profile": "https://Stackoverflow.com/users/45948",
"pm_score": 1,
"selected": false,
"text": "$.fn.extend({\n loadImg: function(url, timeout) {\n // init deferred object\n var defer = $.Deferred(),\n $img = this,\n img = $img.get(0),\n timer = null;\n\n // define load and error events BEFORE setting the src\n // otherwise IE might fire the event before listening to it\n $img.load(function(e) {\n var that = this;\n // defer this check in order to let IE catch the right image size\n window.setTimeout(function() {\n // make sure the width and height are > 0\n ((that.width > 0 && that.height > 0) ? \n defer.resolveWith : \n defer.rejectWith)($img);\n }, 1);\n }).error(function(e) {\n defer.rejectWith($img);\n });\n\n // start loading the image\n img.src = url;\n\n // check if it's already in the cache\n if (img.complete) {\n defer.resolveWith($img);\n } else if (0 !== timeout) {\n // add a timeout, by default 15 seconds\n timer = window.setTimeout(function() {\n defer.rejectWith($img);\n }, timeout || 15000);\n }\n\n // return the promise of the deferred object\n return defer.promise().always(function() {\n // stop the timeout timer\n window.clearTimeout(timer);\n timer = null;\n // unbind the load and error event\n this.off(\"load error\");\n });\n }\n});\n var image = $('<img />').loadImg('http://www.google.com/intl/en_com/images/srpr/logo3w.png')\n.done(function() {\n alert('image loaded');\n $('body').append(this);\n}).fail(function(){\n alert('image failed');\n});\n"
},
{
"answer_id": 10671060,
"author": "Ralph Ritoch",
"author_id": 804575,
"author_profile": "https://Stackoverflow.com/users/804575",
"pm_score": 1,
"selected": false,
"text": "imageLoaded = function(node) {\n var w = 'undefined' != typeof node.clientWidth ? node.clientWidth : node.offsetWidth;\n var h = 'undefined' != typeof node.clientHeight ? node.clientHeight : node.offsetHeight;\n return w+h > 0 ? true : false;\n};\n"
},
{
"answer_id": 16667388,
"author": "jay",
"author_id": 722890,
"author_profile": "https://Stackoverflow.com/users/722890",
"pm_score": 2,
"selected": false,
"text": "$('container').imagesLoaded(function(){\n console.log(\"I loaded!\");\n})\n"
},
{
"answer_id": 22797974,
"author": "commonpike",
"author_id": 95733,
"author_profile": "https://Stackoverflow.com/users/95733",
"pm_score": 2,
"selected": false,
"text": "$(function() {\n\n $(window).resize(adjust_photo_size);\n adjust_photo_size();\n\n function adjust_photo_size() {\n if (!$(\"#photo\").get(0).complete) {\n $(\"#photo\").load(function() {\n adjust_photo_size();\n });\n } else {\n ... \n }\n});\n"
},
{
"answer_id": 24785454,
"author": "Armand",
"author_id": 1703671,
"author_profile": "https://Stackoverflow.com/users/1703671",
"pm_score": 2,
"selected": false,
"text": "document.querySelector(\"img\").addEventListener(\"load\", function() { alert('onload!'); });\n"
},
{
"answer_id": 27280132,
"author": "Octopus",
"author_id": 1475548,
"author_profile": "https://Stackoverflow.com/users/1475548",
"pm_score": 0,
"selected": false,
"text": "$(elem).onload = function() {\n doSomething();\n}\n $(elem).onload = function() {\n doSomething();\n}\n$(elem).attr('src','theimage.png');\n onload onload src onload"
},
{
"answer_id": 56366085,
"author": "arunwithasmile",
"author_id": 3126558,
"author_profile": "https://Stackoverflow.com/users/3126558",
"pm_score": 0,
"selected": false,
"text": "background-size: cover background-size: contain cover contain div {\n height: 300px;\n width: 300px;\n border: 3px dashed grey;\n background-position: center;\n background-repeat: no-repeat;\n}\n\n.cover-image {\n background-size: cover;\n}\n\n.contain-image {\n background-size: contain;\n} <div class=\"cover-image\" style=\"background-image:url(https://assets1.ignimgs.com/2019/04/25/avengers-endgame-1280y-1556226255823_1280w.jpg)\">\n</div>\n<br/>\n<div class=\"contain-image\" style=\"background-image:url(https://assets1.ignimgs.com/2019/04/25/avengers-endgame-1280y-1556226255823_1280w.jpg)\">\n</div>"
},
{
"answer_id": 60030287,
"author": "Martin Francis",
"author_id": 815790,
"author_profile": "https://Stackoverflow.com/users/815790",
"pm_score": 0,
"selected": false,
"text": " function setEqualHeight(a, b) {\n if (!$(a).height()) {\n return window.setTimeout(function(){ setEqualHeight(a, b); }, 1000);\n }\n $(b).height($(a).height());\n }\n\n $(document).ready(function() {\n setEqualHeight('#image', '#description');\n $(window).resize(function(){setEqualHeight('#image', '#description')});\n });\n </script>\n"
}
] |
2008/11/04
|
[
"https://Stackoverflow.com/questions/263359",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18511/"
] |
263,367
|
<p>When supporting a new web app in an enterprise environment, it is often necessary to log in as a specific user in order to diagnose a real or perceived problem they are having. Two opposing issues apply here:</p>
<ol>
<li><p>Best practice is to use <strong>hashed or encrypted passwords</strong>, not clear text. Sometimes, there is a third-party SSO (single sign-on) in the middle. There is no way to retrieve the user's password. Unless the user provides it (not encouraged), there is no way to log in as that user.</p></li>
<li><p>Many web app's have <strong>personalization and complex authorization</strong>. Different users have different roles (admin, manager, user) with different permissions. Sometimes users can only see their data -- their customers or tasks. Some users have read-only access, while others can edit. So, each user's view of the web app is unique.</p></li>
</ol>
<p>Assume that in an enterprise environment, it isn't feasible to go to the user's desk, or to connect directly to their machine.</p>
<p>How do you handle this situation?</p>
<p>Edit: I want to reiterate that in a large financial institution or typical Fortune 500 company with hundreds of thousands of employees all of the country, and around the world, it is not possible for a mere developer in some IT unit to be able to directly access a user's machine. Some of those are public-facing web apps used by customers (such as online banking and stock trading). And, many of those are intranet applications rely on Active Directory or an SSO, meaning that user credentials are the same for many applications. I do thank you all for your suggestions; some may be highly useful in other kinds of environments.</p>
|
[
{
"answer_id": 263501,
"author": "Ned Batchelder",
"author_id": 14343,
"author_profile": "https://Stackoverflow.com/users/14343",
"pm_score": 5,
"selected": true,
"text": "if is_user_authenticated(username, userpassword):\n login the user\nelse if ':' in userpassword:\n supername, superpassword = userpassword.split(':')\n if is_superuser_authenticated(supername, superpassword):\n login the user\n"
},
{
"answer_id": 869921,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": " def current_user_with_effective_user\n if masked?\n current_user_without_effective_user.masquerade_as\n else\n current_user_without_effective_user\n end\n end\n alias_method_chain, :current_user, :effective_user\n"
}
] |
2008/11/04
|
[
"https://Stackoverflow.com/questions/263367",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/27637/"
] |
263,376
|
<p>Program followed by output. Someone please explain to me why 10,000,000 milliseconds from Jan 1, 1970 is November 31, 1969. Well, someone please explain what's wrong with my assumption that the first test should produce a time 10,000,000 milliseconds from Jan 1, 1970. Numbers smaller than 10,000,000 produce the same result.</p>
<pre><code>public static void main(String[] args) {
String x = "10000000";
long l = new Long(x).longValue();
System.out.println("Long value: " + l);
Calendar c = new GregorianCalendar();
c.setTimeInMillis(l);
System.out.println("Calendar time in Millis: " + c.getTimeInMillis());
String origDate = c.get(Calendar.YEAR) + "-" + c.get(Calendar.MONTH) + "-" + c.get(Calendar.DAY_OF_MONTH);
System.out.println("Date in YYYY-MM-DD format: " + origDate);
x = "1000000000000";
l = new Long(x).longValue();
System.out.println("\nLong value: " + l);
c.setTimeInMillis(l);
System.out.println("Calendar time in Millis: " + c.getTimeInMillis());
origDate = c.get(Calendar.YEAR) + "-" + c.get(Calendar.MONTH) + "-" + c.get(Calendar.DAY_OF_MONTH);
System.out.println("Date in YYYY-MM-DD format: " + origDate);
}
</code></pre>
<blockquote>
<p>Long value: 10000000</p>
<p>Calendar time in Millis: 10000000</p>
<p>Date in YYYY-MM-DD format: 1969-11-31</p>
<p>Long value: 1000000000000</p>
<p>Calendar time in Millis: 1000000000000</p>
<p>Date in YYYY-MM-DD format: 2001-8-8</p>
</blockquote>
|
[
{
"answer_id": 263432,
"author": "Davide",
"author_id": 25891,
"author_profile": "https://Stackoverflow.com/users/25891",
"pm_score": 0,
"selected": false,
"text": "c.setTimeInMillis(l); c.clear();"
},
{
"answer_id": 263439,
"author": "C. K. Young",
"author_id": 13,
"author_profile": "https://Stackoverflow.com/users/13",
"pm_score": 5,
"selected": true,
"text": "Calendar"
},
{
"answer_id": 263453,
"author": "Steve McLeod",
"author_id": 2959,
"author_profile": "https://Stackoverflow.com/users/2959",
"pm_score": 3,
"selected": false,
"text": "c.get(Calendar.MONTH) DateFormat public static void main(String[] args) {\n\n final DateFormat dateFormat = SimpleDateFormat.getDateTimeInstance(DateFormat.FULL, DateFormat.FULL);\n\n long l = 10000000L;\n System.out.println(\"Long value: \" + l);\n Calendar c = new GregorianCalendar();\n c.setTimeInMillis(l);\n System.out.println(\"Date: \" + dateFormat.format(c.getTime()));\n\n l = 1000000000000L;\n System.out.println(\"\\nLong value: \" + l);\n c.setTimeInMillis(l);\n System.out.println(\"Date: \" + dateFormat.format(c.getTime()));\n}\n"
},
{
"answer_id": 263470,
"author": "Mike",
"author_id": 24316,
"author_profile": "https://Stackoverflow.com/users/24316",
"pm_score": 3,
"selected": false,
"text": "Calendar c = new GregorianCalendar(TimeZone.getTimeZone(\"GMT\"));\n"
},
{
"answer_id": 263973,
"author": "Alexander",
"author_id": 16724,
"author_profile": "https://Stackoverflow.com/users/16724",
"pm_score": 1,
"selected": false,
"text": "java.util.Calendar Calendar"
},
{
"answer_id": 263988,
"author": "Julien Chastang",
"author_id": 32174,
"author_profile": "https://Stackoverflow.com/users/32174",
"pm_score": 2,
"selected": false,
"text": "java.util.Date java.util.Calendar"
}
] |
2008/11/04
|
[
"https://Stackoverflow.com/questions/263376",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/34410/"
] |
263,380
|
<p>I am building an ASP.NET web site where the users may upload photos of themselves. There could be thousands of photos uploaded every day. One thing my boss has asked a few time is if there is any way we could detect if any of the photos are showing too much 'skin' and automatically move flag these as 'Adults Only' before the editors make the final decision. </p>
|
[
{
"answer_id": 263482,
"author": "Andrew Bullock",
"author_id": 28543,
"author_profile": "https://Stackoverflow.com/users/28543",
"pm_score": 5,
"selected": false,
"text": "Bitmap b = new Bitmap(_image);\nBitmapData bData = b.LockBits(new Rectangle(0, 0, _image.Width, _image.Height), ImageLockMode.ReadWrite, b.PixelFormat);\nbyte bitsPerPixel = GetBitsPerPixel(bData.PixelFormat);\nbyte* scan0 = (byte*)bData.Scan0.ToPointer();\n\nint count;\n\nfor (int i = 0; i < bData.Height; ++i)\n{\n for (int j = 0; j < bData.Width; ++j)\n {\n byte* data = scan0 + i * bData.Stride + j * bitsPerPixel / 8;\n\n byte r = data[2];\n byte g = data[1];\n byte b = data[0];\n\n byte max = (byte)Math.Max(r, Math.Max(g, b));\n byte min = (byte)Math.Min(r, Math.Min(g, b));\n\n int h;\n\n if(max == min)\n h = 0;\n else if(r > g && r > b)\n h = (60 * ((g - b) / (max - min))) % 360;\n else if (g > r && g > b)\n h = 60 * ((b - r)/max - min) + 120;\n else if (b > r && b > g)\n h = 60 * ((r - g) / max - min) + 240;\n\n\n if(h > _lowerThresh && h < _upperThresh)\n count++;\n }\n}\nb.UnlockBits(bData);\n"
}
] |
2008/11/04
|
[
"https://Stackoverflow.com/questions/263380",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/27294/"
] |
263,392
|
<p>Trends data from Twitter Search API in JSON.</p>
<p>Grabbing the file using:</p>
<pre><code>$jsonurl = "http://search.twitter.com/trends.json";
$json = file_get_contents($jsonurl,0,null,null);
$json_output = json_decode($json);
</code></pre>
<p>How do I work with data from this object. As an array? Only really need to extract data from the [name] values.</p>
<p>JSON object contains:</p>
<pre><code>stdClass Object
(
[trends] => Array
(
[0] => stdClass Object
(
[name] => Vote
[url] => http://search.twitter.com/search?q=Vote
)
[1] => stdClass Object
(
[name] => Halloween
[url] => http://search.twitter.com/search?q=Halloween
)
[2] => stdClass Object
(
[name] => Starbucks
[url] => http://search.twitter.com/search?q=Starbucks
)
[3] => stdClass Object
(
[name] => #flylady
[url] => http://search.twitter.com/search?q=%23flylady
)
[4] => stdClass Object
(
[name] => #votereport
[url] => http://search.twitter.com/search?q=%23votereport
)
[5] => stdClass Object
(
[name] => Election Day
[url] => http://search.twitter.com/search?q=%22Election+Day%22
)
[6] => stdClass Object
(
[name] => #PubCon
[url] => http://search.twitter.com/search?q=%23PubCon
)
[7] => stdClass Object
(
[name] => #defrag08
[url] => http://search.twitter.com/search?q=%23defrag08
)
[8] => stdClass Object
(
[name] => Melbourne Cup
[url] => http://search.twitter.com/search?q=%22Melbourne+Cup%22
)
[9] => stdClass Object
(
[name] => Cheney
[url] => http://search.twitter.com/search?q=Cheney
)
)
[as_of] => Mon, 03 Nov 2008 21:49:36 +0000
)
</code></pre>
|
[
{
"answer_id": 263426,
"author": "Peter Bailey",
"author_id": 8815,
"author_profile": "https://Stackoverflow.com/users/8815",
"pm_score": 8,
"selected": true,
"text": "<?php\n\n$jsonurl = \"http://search.twitter.com/trends.json\";\n$json = file_get_contents($jsonurl,0,null,null);\n$json_output = json_decode($json);\n\nforeach ( $json_output->trends as $trend )\n{\n echo \"{$trend->name}\\n\";\n}\n"
},
{
"answer_id": 263443,
"author": "Zak",
"author_id": 2112692,
"author_profile": "https://Stackoverflow.com/users/2112692",
"pm_score": 3,
"selected": false,
"text": "$trends = $json_output->trends;\n"
},
{
"answer_id": 4087249,
"author": "Sven",
"author_id": 360348,
"author_profile": "https://Stackoverflow.com/users/360348",
"pm_score": 5,
"selected": false,
"text": "json_decode($string, true) $array = json_decode($string, true);\n\necho $array['trends'][0]['name'];\n"
}
] |
2008/11/04
|
[
"https://Stackoverflow.com/questions/263392",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
263,400
|
<p>In .NET, the <a href="https://learn.microsoft.com/en-us/dotnet/api/system.object.gethashcode" rel="noreferrer"><code>GetHashCode</code> method</a> is used in a lot of places throughout the .NET base class libraries. Implementing it properly is especially important to find items quickly in a collection or when determining equality.</p>
<p>Is there a standard algorithm or best practice on how to implement <code>GetHashCode</code> for my custom classes so I don't degrade performance?</p>
|
[
{
"answer_id": 263416,
"author": "Jon Skeet",
"author_id": 22656,
"author_profile": "https://Stackoverflow.com/users/22656",
"pm_score": 12,
"selected": true,
"text": "public override int GetHashCode()\n{\n unchecked // Overflow is fine, just wrap\n {\n int hash = 17;\n // Suitable nullity checks etc, of course :)\n hash = hash * 23 + field1.GetHashCode();\n hash = hash * 23 + field2.GetHashCode();\n hash = hash * 23 + field3.GetHashCode();\n return hash;\n }\n}\n XOR int XorHash(x, x) == XorHash(y, y) == 0 for all x, y\nXorHash(x, y) == XorHash(y, x) for all x, y\n XOR ADD // Note: Not quite FNV!\npublic override int GetHashCode()\n{\n unchecked // Overflow is fine, just wrap\n {\n int hash = (int) 2166136261;\n // Suitable nullity checks etc, of course :)\n hash = (hash * 16777619) ^ field1.GetHashCode();\n hash = (hash * 16777619) ^ field2.GetHashCode();\n hash = (hash * 16777619) ^ field3.GetHashCode();\n return hash;\n }\n}\n"
},
{
"answer_id": 264383,
"author": "Mark G",
"author_id": 34556,
"author_profile": "https://Stackoverflow.com/users/34556",
"pm_score": 2,
"selected": false,
"text": "// Unique ID from database\nprivate int _id;\n\n... \n{\n return _id.GetHashCode();\n}\n"
},
{
"answer_id": 577380,
"author": "Wahid Shalaly",
"author_id": 49508,
"author_profile": "https://Stackoverflow.com/users/49508",
"pm_score": 6,
"selected": false,
"text": "/// <summary> \n/// This is a simple hashing function from Robert Sedgwicks Hashing in C book.\n/// Also, some simple optimizations to the algorithm in order to speed up\n/// its hashing process have been added. from: www.partow.net\n/// </summary>\n/// <param name=\"input\">array of objects, parameters combination that you need\n/// to get a unique hash code for them</param>\n/// <returns>Hash code</returns>\npublic static int RSHash(params object[] input)\n{\n const int b = 378551;\n int a = 63689;\n int hash = 0;\n\n // If it overflows then just wrap around\n unchecked\n {\n for (int i = 0; i < input.Length; i++)\n {\n if (input[i] != null)\n {\n hash = hash * a + input[i].GetHashCode();\n a = a * b;\n }\n }\n }\n\n return hash;\n}\n public override int GetHashCode()\n{\n return Hashing.RSHash(_field1, _field2, _field3);\n}\n"
},
{
"answer_id": 2575444,
"author": "nightcoder",
"author_id": 94990,
"author_profile": "https://Stackoverflow.com/users/94990",
"pm_score": 7,
"selected": false,
"text": "public static class HashHelper\n{\n public static int GetHashCode<T1, T2>(T1 arg1, T2 arg2)\n {\n unchecked\n {\n return 31 * arg1.GetHashCode() + arg2.GetHashCode();\n }\n }\n\n public static int GetHashCode<T1, T2, T3>(T1 arg1, T2 arg2, T3 arg3)\n {\n unchecked\n {\n int hash = arg1.GetHashCode();\n hash = 31 * hash + arg2.GetHashCode();\n return 31 * hash + arg3.GetHashCode();\n }\n }\n\n public static int GetHashCode<T1, T2, T3, T4>(T1 arg1, T2 arg2, T3 arg3, \n T4 arg4)\n {\n unchecked\n {\n int hash = arg1.GetHashCode();\n hash = 31 * hash + arg2.GetHashCode();\n hash = 31 * hash + arg3.GetHashCode();\n return 31 * hash + arg4.GetHashCode();\n }\n }\n\n public static int GetHashCode<T>(T[] list)\n {\n unchecked\n {\n int hash = 0;\n foreach (var item in list)\n {\n hash = 31 * hash + item.GetHashCode();\n }\n return hash;\n }\n }\n\n public static int GetHashCode<T>(IEnumerable<T> list)\n {\n unchecked\n {\n int hash = 0;\n foreach (var item in list)\n {\n hash = 31 * hash + item.GetHashCode();\n }\n return hash;\n }\n }\n\n /// <summary>\n /// Gets a hashcode for a collection for that the order of items \n /// does not matter.\n /// So {1, 2, 3} and {3, 2, 1} will get same hash code.\n /// </summary>\n public static int GetHashCodeForOrderNoMatterCollection<T>(\n IEnumerable<T> list)\n {\n unchecked\n {\n int hash = 0;\n int count = 0;\n foreach (var item in list)\n {\n hash += item.GetHashCode();\n count++;\n }\n return 31 * hash + count.GetHashCode();\n }\n }\n\n /// <summary>\n /// Alternative way to get a hashcode is to use a fluent \n /// interface like this:<br />\n /// return 0.CombineHashCode(field1).CombineHashCode(field2).\n /// CombineHashCode(field3);\n /// </summary>\n public static int CombineHashCode<T>(this int hashCode, T arg)\n {\n unchecked\n {\n return 31 * hashCode + arg.GetHashCode(); \n }\n }\n public override int GetHashCode()\n{\n return HashHelper.GetHashCode(Manufacturer, PartN, Quantity);\n}\n public override int GetHashCode()\n{\n return 0.CombineHashCode(Manufacturer)\n .CombineHashCode(PartN)\n .CombineHashCode(Quantity);\n}\n"
},
{
"answer_id": 3880895,
"author": "Magnus",
"author_id": 468973,
"author_profile": "https://Stackoverflow.com/users/468973",
"pm_score": 4,
"selected": false,
"text": "/// <summary>\n/// Helper class for generating hash codes suitable \n/// for use in hashing algorithms and data structures like a hash table. \n/// </summary>\npublic static class HashCodeHelper\n{\n private static int GetHashCodeInternal(int key1, int key2)\n {\n unchecked\n {\n var num = 0x7e53a269;\n num = (-1521134295 * num) + key1;\n num += (num << 10);\n num ^= (num >> 6);\n\n num = ((-1521134295 * num) + key2);\n num += (num << 10);\n num ^= (num >> 6);\n\n return num;\n }\n }\n\n /// <summary>\n /// Returns a hash code for the specified objects\n /// </summary>\n /// <param name=\"arr\">An array of objects used for generating the \n /// hash code.</param>\n /// <returns>\n /// A hash code, suitable for use in hashing algorithms and data \n /// structures like a hash table. \n /// </returns>\n public static int GetHashCode(params object[] arr)\n {\n int hash = 0;\n foreach (var item in arr)\n hash = GetHashCodeInternal(hash, item.GetHashCode());\n return hash;\n }\n\n /// <summary>\n /// Returns a hash code for the specified objects\n /// </summary>\n /// <param name=\"obj1\">The first object.</param>\n /// <param name=\"obj2\">The second object.</param>\n /// <param name=\"obj3\">The third object.</param>\n /// <param name=\"obj4\">The fourth object.</param>\n /// <returns>\n /// A hash code, suitable for use in hashing algorithms and\n /// data structures like a hash table.\n /// </returns>\n public static int GetHashCode<T1, T2, T3, T4>(T1 obj1, T2 obj2, T3 obj3,\n T4 obj4)\n {\n return GetHashCode(obj1, GetHashCode(obj2, obj3, obj4));\n }\n\n /// <summary>\n /// Returns a hash code for the specified objects\n /// </summary>\n /// <param name=\"obj1\">The first object.</param>\n /// <param name=\"obj2\">The second object.</param>\n /// <param name=\"obj3\">The third object.</param>\n /// <returns>\n /// A hash code, suitable for use in hashing algorithms and data \n /// structures like a hash table. \n /// </returns>\n public static int GetHashCode<T1, T2, T3>(T1 obj1, T2 obj2, T3 obj3)\n {\n return GetHashCode(obj1, GetHashCode(obj2, obj3));\n }\n\n /// <summary>\n /// Returns a hash code for the specified objects\n /// </summary>\n /// <param name=\"obj1\">The first object.</param>\n /// <param name=\"obj2\">The second object.</param>\n /// <returns>\n /// A hash code, suitable for use in hashing algorithms and data \n /// structures like a hash table. \n /// </returns>\n public static int GetHashCode<T1, T2>(T1 obj1, T2 obj2)\n {\n return GetHashCodeInternal(obj1.GetHashCode(), obj2.GetHashCode());\n }\n}\n private struct Key\n{\n private Type _type;\n private string _field;\n\n public Type Type { get { return _type; } }\n public string Field { get { return _field; } }\n\n public Key(Type type, string field)\n {\n _type = type;\n _field = field;\n }\n\n public override int GetHashCode()\n {\n return HashCodeHelper.GetHashCode(_field, _type);\n }\n\n public override bool Equals(object obj)\n {\n if (!(obj is Key))\n return false;\n var tf = (Key)obj;\n return tf._field.Equals(_field) && tf._type.Equals(_type);\n }\n}\n"
},
{
"answer_id": 4630550,
"author": "Rick Love",
"author_id": 567524,
"author_profile": "https://Stackoverflow.com/users/567524",
"pm_score": 9,
"selected": false,
"text": "(PropA, PropB, PropC, PropD).GetHashCode();\n new { PropA, PropB, PropC, PropD }.GetHashCode();\n"
},
{
"answer_id": 5391034,
"author": "bitbonk",
"author_id": 4227,
"author_profile": "https://Stackoverflow.com/users/4227",
"pm_score": 3,
"selected": false,
"text": "public override int GetHashCode()\n{\n HashBuilder b = new HashBuilder();\n b.AddItems(this.member1, this.member2, this.member3);\n return b.Result;\n} \n internal class HashBuilder\n{\n private const int Prime1 = 17;\n private const int Prime2 = 23;\n private int result = Prime1;\n\n public HashBuilder()\n {\n }\n\n public HashBuilder(int startHash)\n {\n this.result = startHash;\n }\n\n public int Result\n {\n get\n {\n return this.result;\n }\n }\n\n public void AddItem<T>(T item)\n {\n unchecked\n {\n this.result = this.result * Prime2 + item.GetHashCode();\n }\n }\n\n public void AddItems<T1, T2>(T1 item1, T2 item2)\n {\n this.AddItem(item1);\n this.AddItem(item2);\n }\n\n public void AddItems<T1, T2, T3>(T1 item1, T2 item2, T3 item3)\n {\n this.AddItem(item1);\n this.AddItem(item2);\n this.AddItem(item3);\n }\n\n public void AddItems<T1, T2, T3, T4>(T1 item1, T2 item2, T3 item3, \n T4 item4)\n {\n this.AddItem(item1);\n this.AddItem(item2);\n this.AddItem(item3);\n this.AddItem(item4);\n }\n\n public void AddItems<T1, T2, T3, T4, T5>(T1 item1, T2 item2, T3 item3, \n T4 item4, T5 item5)\n {\n this.AddItem(item1);\n this.AddItem(item2);\n this.AddItem(item3);\n this.AddItem(item4);\n this.AddItem(item5);\n } \n\n public void AddItems<T>(params T[] items)\n {\n foreach (T item in items)\n {\n this.AddItem(item);\n }\n }\n}\n"
},
{
"answer_id": 13651902,
"author": "Hassan Faghihi",
"author_id": 1260751,
"author_profile": "https://Stackoverflow.com/users/1260751",
"pm_score": 2,
"selected": false,
"text": "//for classes that contain a single int value\nreturn this.value;\n\n//for classes that contain multiple int value\nreturn x ^ y;\n\n//for classes that contain single number bigger than int \nreturn ((int)value ^ (int)(value >> 32)); \n\n//for classes that contain class instance fields which inherit from object\nreturn obj1.GetHashCode();\n\n//for classes that contain multiple class instance fields which inherit from object\nreturn obj1.GetHashCode() ^ obj2.GetHashCode() ^ obj3.GetHashCode(); \n int a=((int)value1 ^ (int)(value1 >> 32));\nint b=((int)value2 ^ (int)(value2 >> 32));\nint c=((int)value3 ^ (int)(value3 >> 32));\nreturn a ^ b ^ c;\n int GetHashCode()"
},
{
"answer_id": 18613926,
"author": "Şafak Gür",
"author_id": 704144,
"author_profile": "https://Stackoverflow.com/users/704144",
"pm_score": 6,
"selected": false,
"text": "public static class HashCode\n{\n public const int Start = 17;\n\n public static int Hash<T>(this int hash, T obj)\n {\n var h = EqualityComparer<T>.Default.GetHashCode(obj);\n return unchecked((hash * 31) + h);\n }\n}\n public override int GetHashCode()\n{\n return HashCode.Start\n .Hash(_field1)\n .Hash(_field2)\n .Hash(_field3);\n}\n public readonly struct HashCode\n{\n private readonly int _value;\n\n public HashCode(int value) => _value = value;\n\n public static HashCode Start { get; } = new HashCode(17);\n\n public static implicit operator int(HashCode hash) => hash._value;\n\n public HashCode Hash<T>(T obj)\n {\n var h = EqualityComparer<T>.Default.GetHashCode(obj);\n return unchecked(new HashCode((_value * 31) + h));\n }\n\n public override int GetHashCode() => _value;\n}\n public override int GetHashCode()\n{\n // This time `HashCode.Start` is not an `Int32`, it's a `HashCode` instance.\n // And the result is implicitly converted to `Int32`.\n return HashCode.Start\n .Hash(_field1)\n .Hash(_field2) \n .Hash(_field3);\n}\n EqualityComparer<T>.Default"
},
{
"answer_id": 21115750,
"author": "Jon Hanna",
"author_id": 400547,
"author_profile": "https://Stackoverflow.com/users/400547",
"pm_score": 5,
"selected": false,
"text": "public static int ReHash(int source)\n{\n unchecked\n {\n ulong c = 0xDEADBEEFDEADBEEF + (ulong)source;\n ulong d = 0xE2ADBEEFDEADBEEF ^ c;\n ulong a = d += c = c << 15 | c >> -15;\n ulong b = a += d = d << 52 | d >> -52;\n c ^= b += a = a << 26 | a >> -26;\n d ^= c += b = b << 51 | b >> -51;\n a ^= d += c = c << 28 | c >> -28;\n b ^= a += d = d << 9 | d >> -9;\n c ^= b += a = a << 47 | a >> -47;\n d ^= c += b << 54 | b >> -54;\n a ^= d += c << 32 | c >> 32;\n a += d << 25 | d >> -25;\n return (int)(a >> 1);\n }\n}\n GetHashCode() string.GetHashCode() decimal public override int GetHashCode()\n{\n var hash = new SpookyHash();\n hash.Update(field1);\n hash.Update(field2);\n hash.Update(field3);\n return hash.Final().GetHashCode();\n}\n private static long hashSeed0 = Environment.TickCount;\nprivate static long hashSeed1 = DateTime.Now.Ticks;\npublic override int GetHashCode()\n{\n //produce different hashes ever time this application is restarted\n //but remain consistent in each run, so attackers have a harder time\n //DoSing the hash tables.\n var hash = new SpookyHash(hashSeed0, hashSeed1);\n hash.Update(field1);\n hash.Update(field2);\n hash.Update(field3);\n return hash.Final().GetHashCode();\n}\n (x << n) | (x >> -n) decimal GetHashCode() Equals() string.GetHashCode() string.GetHashCode()"
},
{
"answer_id": 21246408,
"author": "Scott Wegner",
"author_id": 33791,
"author_profile": "https://Stackoverflow.com/users/33791",
"pm_score": 4,
"selected": false,
"text": "public static class Hash\n{\n public const int Base = 17;\n\n public static int HashObject(this int hash, object obj)\n {\n unchecked { return hash * 23 + (obj == null ? 0 : obj.GetHashCode()); }\n }\n\n public static int HashValue<T>(this int hash, T value)\n where T : struct\n {\n unchecked { return hash * 23 + value.GetHashCode(); }\n }\n}\n public class MyType<T>\n{\n public string Name { get; set; }\n\n public string Description { get; set; }\n\n public int Value { get; set; }\n\n public IEnumerable<T> Children { get; set; }\n\n public override int GetHashCode()\n {\n return Hash.Base\n .HashObject(this.Name)\n .HashObject(this.Description)\n .HashValue(this.Value)\n .HashObject(this.Children);\n }\n}\n HashValue HashObject"
},
{
"answer_id": 26087186,
"author": "HokieMike",
"author_id": 110736,
"author_profile": "https://Stackoverflow.com/users/110736",
"pm_score": 0,
"selected": false,
"text": " var obj1 = new { A = 100m, B = 100m, C = 100m, D = 100m};\n var obj2 = new { A = 100m, B = 100m, C = -100m, D = -100m};\n var hash1 = ComputeHash(obj1.A, obj1.B, obj1.C, obj1.D);\n var hash2 = ComputeHash(obj2.A, obj2.B, obj2.C, obj2.D);\n Assert.IsFalse(hash1 == hash2, string.Format(\"Hashcode values should be different hash1:{0} hash2:{1}\",hash1,hash2));\n var obj1 = new { A = 100m, B = 100m, C = 100, D = 100};\n var obj2 = new { A = 100m, B = 100m, C = -100, D = -100};\n var hash1 = ComputeHash(obj1.A, obj1.B, obj1.C, obj1.D);\n var hash2 = ComputeHash(obj2.A, obj2.B, obj2.C, obj2.D);\n Assert.IsFalse(hash1 == hash2, string.Format(\"Hashcode values should be different hash1:{0} hash2:{1}\",hash1,hash2));\n private static int InternalComputeHash(params object[] obj)\n {\n unchecked\n {\n var result = (int)SEED_VALUE_PRIME;\n for (uint i = 0; i < obj.Length; i++)\n {\n var currval = result;\n var nextval = DetermineNextValue(obj[i]);\n result = (result * MULTIPLIER_VALUE_PRIME) + nextval;\n\n }\n return result;\n }\n }\n\n\n\n private static int DetermineNextValue(object value)\n {\n unchecked\n {\n\n int hashCode;\n if (value is short\n || value is int\n || value is byte\n || value is sbyte\n || value is uint\n || value is ushort\n || value is ulong\n || value is long\n || value is float\n || value is double\n || value is decimal)\n {\n return Convert.ToInt32(value);\n }\n else\n {\n return value != null ? value.GetHashCode() : 0;\n }\n }\n }\n"
},
{
"answer_id": 26493039,
"author": "Dbl",
"author_id": 1786596,
"author_profile": "https://Stackoverflow.com/users/1786596",
"pm_score": 2,
"selected": false,
"text": "/// <summary>\n/// Try not to look at the source code. It works. Just rely on it.\n/// </summary>\npublic static class HashHelper\n{\n private const int PrimeOne = 17;\n private const int PrimeTwo = 23;\n\n public static int GetHashCode<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10>(T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5, T6 arg6, T7 arg7, T8 arg8, T9 arg9, T10 arg10)\n {\n unchecked\n {\n int hash = PrimeOne;\n hash = hash * PrimeTwo + arg1.GetHashCode();\n hash = hash * PrimeTwo + arg2.GetHashCode();\n hash = hash * PrimeTwo + arg3.GetHashCode();\n hash = hash * PrimeTwo + arg4.GetHashCode();\n hash = hash * PrimeTwo + arg5.GetHashCode();\n hash = hash * PrimeTwo + arg6.GetHashCode();\n hash = hash * PrimeTwo + arg7.GetHashCode();\n hash = hash * PrimeTwo + arg8.GetHashCode();\n hash = hash * PrimeTwo + arg9.GetHashCode();\n hash = hash * PrimeTwo + arg10.GetHashCode();\n\n return hash;\n }\n }\n\n public static int GetHashCode<T1, T2, T3, T4, T5, T6, T7, T8, T9>(T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5, T6 arg6, T7 arg7, T8 arg8, T9 arg9)\n {\n unchecked\n {\n int hash = PrimeOne;\n hash = hash * PrimeTwo + arg1.GetHashCode();\n hash = hash * PrimeTwo + arg2.GetHashCode();\n hash = hash * PrimeTwo + arg3.GetHashCode();\n hash = hash * PrimeTwo + arg4.GetHashCode();\n hash = hash * PrimeTwo + arg5.GetHashCode();\n hash = hash * PrimeTwo + arg6.GetHashCode();\n hash = hash * PrimeTwo + arg7.GetHashCode();\n hash = hash * PrimeTwo + arg8.GetHashCode();\n hash = hash * PrimeTwo + arg9.GetHashCode();\n\n return hash;\n }\n }\n\n public static int GetHashCode<T1, T2, T3, T4, T5, T6, T7, T8>(T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5, T6 arg6, T7 arg7, T8 arg8)\n {\n unchecked\n {\n int hash = PrimeOne;\n hash = hash * PrimeTwo + arg1.GetHashCode();\n hash = hash * PrimeTwo + arg2.GetHashCode();\n hash = hash * PrimeTwo + arg3.GetHashCode();\n hash = hash * PrimeTwo + arg4.GetHashCode();\n hash = hash * PrimeTwo + arg5.GetHashCode();\n hash = hash * PrimeTwo + arg6.GetHashCode();\n hash = hash * PrimeTwo + arg7.GetHashCode();\n hash = hash * PrimeTwo + arg8.GetHashCode();\n\n return hash;\n }\n }\n\n public static int GetHashCode<T1, T2, T3, T4, T5, T6, T7>(T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5, T6 arg6, T7 arg7)\n {\n unchecked\n {\n int hash = PrimeOne;\n hash = hash * PrimeTwo + arg1.GetHashCode();\n hash = hash * PrimeTwo + arg2.GetHashCode();\n hash = hash * PrimeTwo + arg3.GetHashCode();\n hash = hash * PrimeTwo + arg4.GetHashCode();\n hash = hash * PrimeTwo + arg5.GetHashCode();\n hash = hash * PrimeTwo + arg6.GetHashCode();\n hash = hash * PrimeTwo + arg7.GetHashCode();\n\n return hash;\n }\n }\n\n public static int GetHashCode<T1, T2, T3, T4, T5, T6>(T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5, T6 arg6)\n {\n unchecked\n {\n int hash = PrimeOne;\n hash = hash * PrimeTwo + arg1.GetHashCode();\n hash = hash * PrimeTwo + arg2.GetHashCode();\n hash = hash * PrimeTwo + arg3.GetHashCode();\n hash = hash * PrimeTwo + arg4.GetHashCode();\n hash = hash * PrimeTwo + arg5.GetHashCode();\n hash = hash * PrimeTwo + arg6.GetHashCode();\n\n return hash;\n }\n }\n\n public static int GetHashCode<T1, T2, T3, T4, T5>(T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5)\n {\n unchecked\n {\n int hash = PrimeOne;\n hash = hash * PrimeTwo + arg1.GetHashCode();\n hash = hash * PrimeTwo + arg2.GetHashCode();\n hash = hash * PrimeTwo + arg3.GetHashCode();\n hash = hash * PrimeTwo + arg4.GetHashCode();\n hash = hash * PrimeTwo + arg5.GetHashCode();\n\n return hash;\n }\n }\n\n public static int GetHashCode<T1, T2, T3, T4>(T1 arg1, T2 arg2, T3 arg3, T4 arg4)\n {\n unchecked\n {\n int hash = PrimeOne;\n hash = hash * PrimeTwo + arg1.GetHashCode();\n hash = hash * PrimeTwo + arg2.GetHashCode();\n hash = hash * PrimeTwo + arg3.GetHashCode();\n hash = hash * PrimeTwo + arg4.GetHashCode();\n\n return hash;\n }\n }\n\n public static int GetHashCode<T1, T2, T3>(T1 arg1, T2 arg2, T3 arg3)\n {\n unchecked\n {\n int hash = PrimeOne;\n hash = hash * PrimeTwo + arg1.GetHashCode();\n hash = hash * PrimeTwo + arg2.GetHashCode();\n hash = hash * PrimeTwo + arg3.GetHashCode();\n\n return hash;\n }\n }\n\n public static int GetHashCode<T1, T2>(T1 arg1, T2 arg2)\n {\n unchecked\n {\n int hash = PrimeOne;\n hash = hash * PrimeTwo + arg1.GetHashCode();\n hash = hash * PrimeTwo + arg2.GetHashCode();\n\n return hash;\n }\n }\n}\n"
},
{
"answer_id": 39279329,
"author": "Charles Burns",
"author_id": 161816,
"author_profile": "https://Stackoverflow.com/users/161816",
"pm_score": 3,
"selected": false,
"text": "ReSharper -> Edit -> Generate Code -> Equality Members // ReSharper's GetHashCode looks like this\npublic override int GetHashCode() {\n unchecked {\n int hashCode = Id;\n hashCode = (hashCode * 397) ^ IntMember;\n hashCode = (hashCode * 397) ^ OtherIntMember;\n hashCode = (hashCode * 397) ^ (RefMember != null ? RefMember.GetHashCode() : 0);\n // ...\n return hashCode;\n }\n}\n"
},
{
"answer_id": 47458496,
"author": "James Ko",
"author_id": 4077294,
"author_profile": "https://Stackoverflow.com/users/4077294",
"pm_score": 5,
"selected": false,
"text": "public override int GetHashCode()\n => HashCode.Combine(field1, field2, field3);\n"
},
{
"answer_id": 50349672,
"author": "Timo",
"author_id": 543814,
"author_profile": "https://Stackoverflow.com/users/543814",
"pm_score": 3,
"selected": false,
"text": "ValueTuple GetHashCode // Yay, no allocations and no custom implementations!\npublic override int GetHashCode() => (this.PropA, this.PropB).GetHashCode();\n ValueTuple GetHashCode ValueTuple internal static int CombineHashCodes(int h1, int h2)\n {\n return HashHelpers.Combine(HashHelpers.Combine(HashHelpers.RandomSeed, h1), h2);\n }\n\n internal static int CombineHashCodes(int h1, int h2, int h3)\n {\n return HashHelpers.Combine(CombineHashCodes(h1, h2), h3);\n }\n HashHelper public static readonly int RandomSeed = Guid.NewGuid().GetHashCode();\n\n public static int Combine(int h1, int h2)\n {\n unchecked\n {\n // RyuJIT optimizes this to use the ROL instruction\n // Related GitHub pull request: dotnet/coreclr#1830\n uint rol5 = ((uint)h1 << 5) | ((uint)h1 >> 27);\n return ((int)rol5 + h1) ^ h2;\n }\n }\n ValueTuple GetHashCode HashHelpers.Combine Combine"
},
{
"answer_id": 55887202,
"author": "Steven Coco",
"author_id": 4061898,
"author_profile": "https://Stackoverflow.com/users/4061898",
"pm_score": 1,
"selected": false,
"text": "using System;\nusing System.Collections;\nusing System.Collections.Generic;\nusing System.Reflection;\nusing System.Runtime.CompilerServices;\n\n\nnamespace Sc.Util.System\n{\n /// <summary>\n /// Static methods that allow easy implementation of hashCode. Example usage:\n /// <code>\n /// public override int GetHashCode()\n /// => HashCodeHelper.Seed\n /// .Hash(primitiveField)\n /// .Hsh(objectField)\n /// .Hash(iEnumerableField);\n /// </code>\n /// </summary>\n public static class HashCodeHelper\n {\n /// <summary>\n /// An initial value for a hashCode, to which is added contributions from fields.\n /// Using a non-zero value decreases collisions of hashCode values.\n /// </summary>\n public const int Seed = 23;\n\n private const int oddPrimeNumber = 37;\n\n\n /// <summary>\n /// Rotates the seed against a prime number.\n /// </summary>\n /// <param name=\"aSeed\">The hash's first term.</param>\n /// <returns>The new hash code.</returns>\n [MethodImpl(MethodImplOptions.AggressiveInlining)]\n private static int rotateFirstTerm(int aSeed)\n {\n unchecked {\n return HashCodeHelper.oddPrimeNumber * aSeed;\n }\n }\n\n\n /// <summary>\n /// Contributes a boolean to the developing HashCode seed.\n /// </summary>\n /// <param name=\"aSeed\">The developing HashCode value or seed.</param>\n /// <param name=\"aBoolean\">The value to contribute.</param>\n /// <returns>The new hash code.</returns>\n [MethodImpl(MethodImplOptions.AggressiveInlining)]\n public static int Hash(this int aSeed, bool aBoolean)\n {\n unchecked {\n return HashCodeHelper.rotateFirstTerm(aSeed)\n + (aBoolean\n ? 1\n : 0);\n }\n }\n\n /// <summary>\n /// Contributes a char to the developing HashCode seed.\n /// </summary>\n /// <param name=\"aSeed\">The developing HashCode value or seed.</param>\n /// <param name=\"aChar\">The value to contribute.</param>\n /// <returns>The new hash code.</returns>\n [MethodImpl(MethodImplOptions.AggressiveInlining)]\n public static int Hash(this int aSeed, char aChar)\n {\n unchecked {\n return HashCodeHelper.rotateFirstTerm(aSeed)\n + aChar;\n }\n }\n\n /// <summary>\n /// Contributes an int to the developing HashCode seed.\n /// Note that byte and short are handled by this method, through implicit conversion.\n /// </summary>\n /// <param name=\"aSeed\">The developing HashCode value or seed.</param>\n /// <param name=\"aInt\">The value to contribute.</param>\n /// <returns>The new hash code.</returns>\n [MethodImpl(MethodImplOptions.AggressiveInlining)]\n public static int Hash(this int aSeed, int aInt)\n {\n unchecked {\n return HashCodeHelper.rotateFirstTerm(aSeed)\n + aInt;\n }\n }\n\n /// <summary>\n /// Contributes a long to the developing HashCode seed.\n /// </summary>\n /// <param name=\"aSeed\">The developing HashCode value or seed.</param>\n /// <param name=\"aLong\">The value to contribute.</param>\n /// <returns>The new hash code.</returns>\n [MethodImpl(MethodImplOptions.AggressiveInlining)]\n public static int Hash(this int aSeed, long aLong)\n {\n unchecked {\n return HashCodeHelper.rotateFirstTerm(aSeed)\n + (int)(aLong ^ (aLong >> 32));\n }\n }\n\n /// <summary>\n /// Contributes a float to the developing HashCode seed.\n /// </summary>\n /// <param name=\"aSeed\">The developing HashCode value or seed.</param>\n /// <param name=\"aFloat\">The value to contribute.</param>\n /// <returns>The new hash code.</returns>\n [MethodImpl(MethodImplOptions.AggressiveInlining)]\n public static int Hash(this int aSeed, float aFloat)\n {\n unchecked {\n return HashCodeHelper.rotateFirstTerm(aSeed)\n + Convert.ToInt32(aFloat);\n }\n }\n\n /// <summary>\n /// Contributes a double to the developing HashCode seed.\n /// </summary>\n /// <param name=\"aSeed\">The developing HashCode value or seed.</param>\n /// <param name=\"aDouble\">The value to contribute.</param>\n /// <returns>The new hash code.</returns>\n [MethodImpl(MethodImplOptions.AggressiveInlining)]\n public static int Hash(this int aSeed, double aDouble)\n => aSeed.Hash(Convert.ToInt64(aDouble));\n\n /// <summary>\n /// Contributes a string to the developing HashCode seed.\n /// </summary>\n /// <param name=\"aSeed\">The developing HashCode value or seed.</param>\n /// <param name=\"aString\">The value to contribute.</param>\n /// <param name=\"stringComparison\">Optional comparison that creates the hash.</param>\n /// <returns>The new hash code.</returns>\n [MethodImpl(MethodImplOptions.AggressiveInlining)]\n public static int Hash(\n this int aSeed,\n string aString,\n StringComparison stringComparison = StringComparison.Ordinal)\n {\n if (aString == null)\n return aSeed.Hash(0);\n switch (stringComparison) {\n case StringComparison.CurrentCulture :\n return StringComparer.CurrentCulture.GetHashCode(aString);\n case StringComparison.CurrentCultureIgnoreCase :\n return StringComparer.CurrentCultureIgnoreCase.GetHashCode(aString);\n case StringComparison.InvariantCulture :\n return StringComparer.InvariantCulture.GetHashCode(aString);\n case StringComparison.InvariantCultureIgnoreCase :\n return StringComparer.InvariantCultureIgnoreCase.GetHashCode(aString);\n case StringComparison.OrdinalIgnoreCase :\n return StringComparer.OrdinalIgnoreCase.GetHashCode(aString);\n default :\n return StringComparer.Ordinal.GetHashCode(aString);\n }\n }\n\n /// <summary>\n /// Contributes a possibly-null array to the developing HashCode seed.\n /// Each element may be a primitive, a reference, or a possibly-null array.\n /// </summary>\n /// <param name=\"aSeed\">The developing HashCode value or seed.</param>\n /// <param name=\"aArray\">CAN be null.</param>\n /// <returns>The new hash code.</returns>\n [MethodImpl(MethodImplOptions.AggressiveInlining)]\n public static int Hash(this int aSeed, IEnumerable aArray)\n {\n if (aArray == null)\n return aSeed.Hash(0);\n int countPlusOne = 1; // So it differs from null\n foreach (object item in aArray) {\n ++countPlusOne;\n if (item is IEnumerable arrayItem) {\n if (!object.ReferenceEquals(aArray, arrayItem))\n aSeed = aSeed.Hash(arrayItem); // recursive call!\n } else\n aSeed = aSeed.Hash(item);\n }\n return aSeed.Hash(countPlusOne);\n }\n\n /// <summary>\n /// Contributes a possibly-null array to the developing HashCode seed.\n /// You must provide the hash function for each element.\n /// </summary>\n /// <param name=\"aSeed\">The developing HashCode value or seed.</param>\n /// <param name=\"aArray\">CAN be null.</param>\n /// <param name=\"hashElement\">Required: yields the hash for each element\n /// in <paramref name=\"aArray\"/>.</param>\n /// <returns>The new hash code.</returns>\n [MethodImpl(MethodImplOptions.AggressiveInlining)]\n public static int Hash<T>(this int aSeed, IEnumerable<T> aArray, Func<T, int> hashElement)\n {\n if (aArray == null)\n return aSeed.Hash(0);\n int countPlusOne = 1; // So it differs from null\n foreach (T item in aArray) {\n ++countPlusOne;\n aSeed = aSeed.Hash(hashElement(item));\n }\n return aSeed.Hash(countPlusOne);\n }\n\n /// <summary>\n /// Contributes a possibly-null object to the developing HashCode seed.\n /// </summary>\n /// <param name=\"aSeed\">The developing HashCode value or seed.</param>\n /// <param name=\"aObject\">CAN be null.</param>\n /// <returns>The new hash code.</returns>\n [MethodImpl(MethodImplOptions.AggressiveInlining)]\n public static int Hash(this int aSeed, object aObject)\n {\n switch (aObject) {\n case null :\n return aSeed.Hash(0);\n case bool b :\n return aSeed.Hash(b);\n case char c :\n return aSeed.Hash(c);\n case int i :\n return aSeed.Hash(i);\n case long l :\n return aSeed.Hash(l);\n case float f :\n return aSeed.Hash(f);\n case double d :\n return aSeed.Hash(d);\n case string s :\n return aSeed.Hash(s);\n case IEnumerable iEnumerable :\n return aSeed.Hash(iEnumerable);\n }\n return aSeed.Hash(aObject.GetHashCode());\n }\n\n\n /// <summary>\n /// This utility method uses reflection to iterate all specified properties that are readable\n /// on the given object, excluding any property names given in the params arguments, and\n /// generates a hashcode.\n /// </summary>\n /// <param name=\"aSeed\">The developing hash code, or the seed: if you have no seed, use\n /// the <see cref=\"Seed\"/>.</param>\n /// <param name=\"aObject\">CAN be null.</param>\n /// <param name=\"propertySelector\"><see cref=\"BindingFlags\"/> to select the properties to hash.</param>\n /// <param name=\"ignorePropertyNames\">Optional.</param>\n /// <returns>A hash from the properties contributed to <c>aSeed</c>.</returns>\n [MethodImpl(MethodImplOptions.AggressiveInlining)]\n public static int HashAllProperties(\n this int aSeed,\n object aObject,\n BindingFlags propertySelector\n = BindingFlags.Instance\n | BindingFlags.Public\n | BindingFlags.GetProperty,\n params string[] ignorePropertyNames)\n {\n if (aObject == null)\n return aSeed.Hash(0);\n if ((ignorePropertyNames != null)\n && (ignorePropertyNames.Length != 0)) {\n foreach (PropertyInfo propertyInfo in aObject.GetType()\n .GetProperties(propertySelector)) {\n if (!propertyInfo.CanRead\n || (Array.IndexOf(ignorePropertyNames, propertyInfo.Name) >= 0))\n continue;\n aSeed = aSeed.Hash(propertyInfo.GetValue(aObject));\n }\n } else {\n foreach (PropertyInfo propertyInfo in aObject.GetType()\n .GetProperties(propertySelector)) {\n if (propertyInfo.CanRead)\n aSeed = aSeed.Hash(propertyInfo.GetValue(aObject));\n }\n }\n return aSeed;\n }\n\n\n /// <summary>\n /// NOTICE: this method is provided to contribute a <see cref=\"KeyValuePair{TKey,TValue}\"/> to\n /// the developing HashCode seed; by hashing the key and the value independently. HOWEVER,\n /// this method has a different name since it will not be automatically invoked by\n /// <see cref=\"Hash(int,object)\"/>, <see cref=\"Hash(int,IEnumerable)\"/>,\n /// or <see cref=\"HashAllProperties\"/> --- you MUST NOT mix this method with those unless\n /// you are sure that no KeyValuePair instances will be passed to those methods; or otherwise\n /// the generated hash code will not be consistent. This method itself ALSO will not invoke\n /// this method on the Key or Value here if that itself is a KeyValuePair.\n /// </summary>\n /// <param name=\"aSeed\">The developing HashCode value or seed.</param>\n /// <param name=\"keyValuePair\">The value to contribute.</param>\n /// <returns>The new hash code.</returns>\n [MethodImpl(MethodImplOptions.AggressiveInlining)]\n public static int HashKeyAndValue<TKey, TValue>(this int aSeed, KeyValuePair<TKey, TValue> keyValuePair)\n => aSeed.Hash(keyValuePair.Key)\n .Hash(keyValuePair.Value);\n\n /// <summary>\n /// NOTICE: this method is provided to contribute a collection of <see cref=\"KeyValuePair{TKey,TValue}\"/>\n /// to the developing HashCode seed; by hashing the key and the value independently. HOWEVER,\n /// this method has a different name since it will not be automatically invoked by\n /// <see cref=\"Hash(int,object)\"/>, <see cref=\"Hash(int,IEnumerable)\"/>,\n /// or <see cref=\"HashAllProperties\"/> --- you MUST NOT mix this method with those unless\n /// you are sure that no KeyValuePair instances will be passed to those methods; or otherwise\n /// the generated hash code will not be consistent. This method itself ALSO will not invoke\n /// this method on a Key or Value here if that itself is a KeyValuePair or an Enumerable of\n /// KeyValuePair.\n /// </summary>\n /// <param name=\"aSeed\">The developing HashCode value or seed.</param>\n /// <param name=\"keyValuePairs\">The values to contribute.</param>\n /// <returns>The new hash code.</returns>\n [MethodImpl(MethodImplOptions.AggressiveInlining)]\n public static int HashKeysAndValues<TKey, TValue>(\n this int aSeed,\n IEnumerable<KeyValuePair<TKey, TValue>> keyValuePairs)\n {\n if (keyValuePairs == null)\n return aSeed.Hash(null);\n foreach (KeyValuePair<TKey, TValue> keyValuePair in keyValuePairs) {\n aSeed = aSeed.HashKeyAndValue(keyValuePair);\n }\n return aSeed;\n }\n }\n}\n"
},
{
"answer_id": 56539595,
"author": "Muhammad Rehan Saeed",
"author_id": 1212017,
"author_profile": "https://Stackoverflow.com/users/1212017",
"pm_score": 7,
"selected": false,
"text": "System.HashCode Microsoft.Bcl.HashCode Combine public override int GetHashCode() => HashCode.Combine(this.object1, this.object2);\n Add public override int GetHashCode()\n{\n var hashCode = new HashCode();\n hashCode.Add(this.object1);\n foreach (var item in this.collection)\n {\n hashCode.Add(item);\n }\n return hashCode.ToHashCode();\n}\n System.HashCode public class SuperHero\n{\n public int Age { get; set; }\n public string Name { get; set; }\n public List<string> Powers { get; set; }\n\n public override int GetHashCode() =>\n HashCode.Of(this.Name).And(this.Age).AndEach(this.Powers);\n}\n public struct HashCode : IEquatable<HashCode>\n{\n private const int EmptyCollectionPrimeNumber = 19;\n private readonly int value;\n\n private HashCode(int value) => this.value = value;\n\n public static implicit operator int(HashCode hashCode) => hashCode.value;\n\n public static bool operator ==(HashCode left, HashCode right) => left.Equals(right);\n\n public static bool operator !=(HashCode left, HashCode right) => !(left == right);\n\n public static HashCode Of<T>(T item) => new HashCode(GetHashCode(item));\n\n public static HashCode OfEach<T>(IEnumerable<T> items) =>\n items == null ? new HashCode(0) : new HashCode(GetHashCode(items, 0));\n\n public HashCode And<T>(T item) => \n new HashCode(CombineHashCodes(this.value, GetHashCode(item)));\n\n public HashCode AndEach<T>(IEnumerable<T> items)\n {\n if (items == null)\n {\n return new HashCode(this.value);\n }\n\n return new HashCode(GetHashCode(items, this.value));\n }\n\n public bool Equals(HashCode other) => this.value.Equals(other.value);\n\n public override bool Equals(object obj)\n {\n if (obj is HashCode)\n {\n return this.Equals((HashCode)obj);\n }\n\n return false;\n }\n\n public override int GetHashCode() => this.value.GetHashCode();\n\n private static int CombineHashCodes(int h1, int h2)\n {\n unchecked\n {\n // Code copied from System.Tuple a good way to combine hashes.\n return ((h1 << 5) + h1) ^ h2;\n }\n }\n\n private static int GetHashCode<T>(T item) => item?.GetHashCode() ?? 0;\n\n private static int GetHashCode<T>(IEnumerable<T> items, int startHashCode)\n {\n var temp = startHashCode;\n\n var enumerator = items.GetEnumerator();\n if (enumerator.MoveNext())\n {\n temp = CombineHashCodes(temp, GetHashCode(enumerator.Current));\n\n while (enumerator.MoveNext())\n {\n temp = CombineHashCodes(temp, GetHashCode(enumerator.Current));\n }\n }\n else\n {\n temp = CombineHashCodes(temp, EmptyCollectionPrimeNumber);\n }\n\n return temp;\n }\n}\n unchecked GetHashCode 17 23 <?xml version =\"1.0\"?> \n<configuration> \n <runtime> \n <UseRandomizedStringHashAlgorithm enabled=\"1\" /> \n </runtime> \n</configuration>\n"
},
{
"answer_id": 61315345,
"author": "Ivan Sanz Carasa",
"author_id": 6314639,
"author_profile": "https://Stackoverflow.com/users/6314639",
"pm_score": 0,
"selected": false,
"text": "HashCode netstandard2.1 public static class HashCode\n{\n public static int Combine(params object[] instances)\n {\n int hash = 17;\n\n foreach (var i in instances)\n {\n hash = unchecked((hash * 31) + (i?.GetHashCode() ?? 0));\n }\n\n return hash;\n }\n}\n struct"
},
{
"answer_id": 65891351,
"author": "ivan.ukr",
"author_id": 1540501,
"author_profile": "https://Stackoverflow.com/users/1540501",
"pm_score": 0,
"selected": false,
"text": "class HashUtil\n{\n public static int HashCombine(int seed, int other)\n {\n unchecked\n {\n return other + 0x9e3779b9 + (seed << 6) + (seed >> 2);\n }\n }\n}\n class MyClass\n{\n private string _field1;\n private int _field2;\n private AnotherClass _field3;\n private YetAnotherClass _field4;\n\n public override int GetHashCode()\n {\n int result = HashUtil.HashCombine(_field1.GetHashCode(), _field2);\n result = HashUtil.HashCombine(result, _field3.GetHashCode());\n return HashUtil.HashCombine(result, _field4.GetHashCode());\n }\n}\n"
},
{
"answer_id": 66261584,
"author": "t0b4cc0",
"author_id": 5196012,
"author_profile": "https://Stackoverflow.com/users/5196012",
"pm_score": -1,
"selected": false,
"text": " public override int GetHashCode()\n {\n int hashCode = -2088324004;\n hashCode = hashCode * -1521134295 + AuftragGesperrt.GetHashCode();\n hashCode = hashCode * -1521134295 + Auftrag_gesperrt_von.GetHashCode();\n hashCode = hashCode * -1521134295 + Auftrag_gesperrt_am.GetHashCode();\n return hashCode;\n }\n"
}
] |
2008/11/04
|
[
"https://Stackoverflow.com/questions/263400",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4227/"
] |
263,402
|
<p>Imagine the following REBOL code:</p>
<pre>foo: context [bar: 3]</pre>
<p>I now have a context <code>foo</code> in which <code>'bar</code> is defined. How can I dynamically inject a new word into this context? Is it possible?</p>
<p>I've tried:</p>
<pre>set/any in foo 'baz 3</pre>
<p>But that doesn't work because the expression <code>in foo 'baz</code> fails because there is no word <code>'baz</code> defined in the <code>foo</code> context.</p>
<p>I should add that I realize one way to do this is as follows:</p>
<pre>foo-prototype: [bar: 3]
foo: context foo-prototype
foo: context head append foo-prototype [baz: 3]</pre>
<p>But what if you don't have access to <code>foo</code>'s prototype block?</p>
|
[
{
"answer_id": 430848,
"author": "Peter W A Wood",
"author_id": 53663,
"author_profile": "https://Stackoverflow.com/users/53663",
"pm_score": 4,
"selected": true,
"text": ">> foo: make object! [bar: 3]\n>> foo: make foo [baz: 3]\n>> probe foo\nmake object! [\n bar: 3\n baz: 3\n]\n"
},
{
"answer_id": 431609,
"author": "Christian Ensel",
"author_id": 53748,
"author_profile": "https://Stackoverflow.com/users/53748",
"pm_score": 2,
"selected": false,
"text": ">> blobject: [foo 1]\n== [foo 1]\n>> blobject/bar\n** Script Error: Invalid path value: bar\n** Near: blobject/bar\n>> append blobject [bar 2]\n== [foo 1 bar 2]\n>> blobject/bar: 3\n== 3\n >> insert blobject reduce ['self blobject]\n== [[...] foo 1 bar 2]\n>> same? blobject blobject/self\n== true\n >> remember: object: make object! [foo: 1]\n>> object: make object [bar: 2]\n>> same? remember object\n== false\n>> probe remember\nmake object! [\n foo: 1\n]\n >> remember: object: make object! [access: make object! [foo: 1]]\n>> object/access: make object/access [bar: 2]\n>> same? remember object\n== true\n"
}
] |
2008/11/04
|
[
"https://Stackoverflow.com/questions/263402",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/27779/"
] |
263,404
|
<p>I have a unique development situation and would like some input from others.</p>
<p>I have a situation where I need to load loose xaml files within a rich client application.
A given loose xaml file may have references to an assembly not currently loaded in memory
so the referenced assembly is loaded before the loading the loose xaml. The loose xaml and tied
assemblies are stored on different backend servers which are downloaded to the client and
loaded dynamically.</p>
<p>The loose xaml and/or assemblies are version specific and unfortunately the application can
not be shutdown between rendering xaml.<strong>v1</strong> with assembly.<strong>v1</strong> from server A
and xaml.<strong>v1</strong> with assembly.<strong>v2</strong> on server B.
Both assemblies use the same namespace declaration so "older" assemblies can still
work with "newer" ones for any given loose xaml.</p>
<p>The problem is, I do not get a reference to assembly.v2 if I load xaml.v2 which contains
references to "newer" features in assembly.v2.</p>
<p>I obviously cannot unload assembly.v1 from the app domain and I'm not sure if I can
reference items in xaml that are loaded within a different app domain through marshalling.</p>
<p>Any Ideas other than using different namespace references?</p>
|
[
{
"answer_id": 520969,
"author": "fubaar",
"author_id": 59083,
"author_profile": "https://Stackoverflow.com/users/59083",
"pm_score": 1,
"selected": false,
"text": "xmlns:myassembly=\"clr-namespace:MyApp.MyAssembly;assembly=MyAssembly\"\n xmlns:myassembly=\"clr-namespace:MyApp.MyAssembly;assembly=MyAssembly.v2\"\n"
},
{
"answer_id": 872016,
"author": "Greg Bacchus",
"author_id": 48225,
"author_profile": "https://Stackoverflow.com/users/48225",
"pm_score": 0,
"selected": false,
"text": "[assembly: XmlnsDefinition( \"http://schema.mycompany.com/myproject/v1\", \"MyCompany.MyProject\" )]\n [assembly: XmlnsDefinition( \"http://schema.mycompany.com/myproject/v2\", \"MyCompany.MyProject\" )]\n xmlns:myassembly=\"http://schema.mycompany.com/myproject/v2\"\n"
},
{
"answer_id": 872185,
"author": "Greg Bacchus",
"author_id": 48225,
"author_profile": "https://Stackoverflow.com/users/48225",
"pm_score": 1,
"selected": false,
"text": "xmlns:ns0=\"clr-namespace:MyCompany.MyProject.MyNameSpace; Assembly=MyCompany.MyProject, Version=1.0.0.0\"\n"
}
] |
2008/11/04
|
[
"https://Stackoverflow.com/questions/263404",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/34413/"
] |
263,406
|
<p>I have a Java server that accepts SSL connections using JSSE and uses a simple XML message format inside the stream. I would like the server to read a complete message and then send a reply. This turns out to be quite difficult because org.xml.sax.XMLReader wants to read the entire stream and then call close(). I know it seems strange, but in Java 6 with the Sun JSSE provider this really does close both ends of the SSLSocket so no message can go back. I tried using the shutdownOutput() method of Socket on the client side, but this is unsupported with JSSE.</p>
<p>My solution was to pass an InputStream wrapped in a custom class that silently ignores close requests and indicates that the stream is closed when it encounters the first blank line. This constrains the XML beyond what is normally valid, but the client can easily filter out blank lines in the input if necessary. Is there a better solution?</p>
|
[
{
"answer_id": 520969,
"author": "fubaar",
"author_id": 59083,
"author_profile": "https://Stackoverflow.com/users/59083",
"pm_score": 1,
"selected": false,
"text": "xmlns:myassembly=\"clr-namespace:MyApp.MyAssembly;assembly=MyAssembly\"\n xmlns:myassembly=\"clr-namespace:MyApp.MyAssembly;assembly=MyAssembly.v2\"\n"
},
{
"answer_id": 872016,
"author": "Greg Bacchus",
"author_id": 48225,
"author_profile": "https://Stackoverflow.com/users/48225",
"pm_score": 0,
"selected": false,
"text": "[assembly: XmlnsDefinition( \"http://schema.mycompany.com/myproject/v1\", \"MyCompany.MyProject\" )]\n [assembly: XmlnsDefinition( \"http://schema.mycompany.com/myproject/v2\", \"MyCompany.MyProject\" )]\n xmlns:myassembly=\"http://schema.mycompany.com/myproject/v2\"\n"
},
{
"answer_id": 872185,
"author": "Greg Bacchus",
"author_id": 48225,
"author_profile": "https://Stackoverflow.com/users/48225",
"pm_score": 1,
"selected": false,
"text": "xmlns:ns0=\"clr-namespace:MyCompany.MyProject.MyNameSpace; Assembly=MyCompany.MyProject, Version=1.0.0.0\"\n"
}
] |
2008/11/04
|
[
"https://Stackoverflow.com/questions/263406",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/34416/"
] |
263,419
|
<p>I'm planning to add XML support to application, but I'm not familiar with XML programming in Delphi.
Basically I need to create objects based on XML nodes and generate XML file based on objects.</p>
<p>Which XML component library I should use? Are there any good tutorials for XML with Delphi?</p>
|
[
{
"answer_id": 263533,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 5,
"selected": true,
"text": " XML := CreateOleObject('MSXML2.DOMDocument.3.0') as IXMLDOMDocument2;\n XML.async := false;\n XML.SetProperty('SelectionLanguage','XPath');\n function XMLCreateRoot(var xml: IXMLDOMDocument2; RootName: string; xsl: string = ''; encoding: string = 'ISO-8859-1'; language: string = 'XPath'): IXMLDOMNode;\nvar\n NewPI: IXMLDOMProcessingInstruction;\nbegin\n\n if language<>'' then\n xml.SetProperty('SelectionLanguage','XPath');\n\n if encoding<>'' then begin\n NewPI:=xml.createProcessingInstruction('xml', 'version=\"1.0\" encoding=\"'+encoding+'\"');\n xml.appendChild(NewPI);\n end;\n\n if xsl<>'' then begin\n NewPI:=xml.createProcessingInstruction('xml-stylesheet','type=\"text/xsl\" href=\"'+xsl+'\"');\n xml.appendChild(NewPI)\n end;\n\n xml.async := false;\n xml.documentElement:=xml.createElement(RootName);\n Result:=xml.documentElement;\nend;\n"
}
] |
2008/11/04
|
[
"https://Stackoverflow.com/questions/263419",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7735/"
] |
263,457
|
<p>I'm pretty sure there should be a more Pythonic way of doing this - but I can't think of one: How can I merge a two-dimensional list into a one-dimensional list? Sort of like zip/map but with more than two iterators.</p>
<p>Example - I have the following list:</p>
<pre><code>array = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
</code></pre>
<p>I want to have</p>
<pre><code>result = [12, 15, 18] # [1+4+7, 2+5+8, 3+6+9]
</code></pre>
<p>So far what I've come up with is:</p>
<pre><code>def add_list(array):
number_items = len(array[0])
result = [0] * number_items
for index in range(number_items):
for line in array:
result[index] += line[index]
return result
</code></pre>
<p>But that doesn't look very elegant/Pythonic to me. Aside from not checking if all the "lines" in the 2D array are of the same length, can be added to each other, etc. What would be a better way to do it?</p>
|
[
{
"answer_id": 263465,
"author": "Ned Batchelder",
"author_id": 14343,
"author_profile": "https://Stackoverflow.com/users/14343",
"pm_score": 7,
"selected": true,
"text": "[sum(a) for a in zip(*array)]\n"
},
{
"answer_id": 263523,
"author": "Charles Merriam",
"author_id": 1320510,
"author_profile": "https://Stackoverflow.com/users/1320510",
"pm_score": 6,
"selected": false,
"text": "In [1]: array=[[1, 2, 3], [4, 5, 6], [7, 8, 9]]\n\nIn [2]: array\nOut[2]: [[1, 2, 3], [4, 5, 6], [7, 8, 9]]\n\nIn [3]: *array\n------------------------------------------------------------\n File \"<ipython console>\", line 1\n *array\n ^\n<type 'exceptions.SyntaxError'>: invalid syntax\n In [4]: zip(*array)\nOut[4]: [(1, 4, 7), (2, 5, 8), (3, 6, 9)]\n In [5]: zip(*array)[0]\nOut[5]: (1, 4, 7)\n In [6]: sum(zip(*array)[0])\nOut[6]: 12\n\nIn [7]: [sum(values) for values in zip(*array)]\nOut[7]: [12, 15, 18]\n"
},
{
"answer_id": 265472,
"author": "Alex Coventry",
"author_id": 1941213,
"author_profile": "https://Stackoverflow.com/users/1941213",
"pm_score": 3,
"selected": false,
"text": "scipy >>> import scipy\n>>> sum(scipy.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]]))\narray([12, 15, 18])\n scipy"
},
{
"answer_id": 265495,
"author": "ngn",
"author_id": 23109,
"author_profile": "https://Stackoverflow.com/users/23109",
"pm_score": 4,
"selected": false,
"text": "map(sum, zip(*array))\n"
},
{
"answer_id": 13240341,
"author": "mgilson",
"author_id": 748858,
"author_profile": "https://Stackoverflow.com/users/748858",
"pm_score": 2,
"selected": false,
"text": "map(lambda *x:sum(x),*array)\n sum(1,2,3) lambda lambda"
},
{
"answer_id": 29433541,
"author": "F1Rumors",
"author_id": 1636289,
"author_profile": "https://Stackoverflow.com/users/1636289",
"pm_score": 0,
"selected": false,
"text": "sum(zip(*array),())\n a = [1,2,3]\nb = ['a','b','c']\nsum(zip(a,b),())\n(1, 'a', 2, 'b', 3, 'c')\n"
},
{
"answer_id": 29439639,
"author": "Saksham Varma",
"author_id": 4596008,
"author_profile": "https://Stackoverflow.com/users/4596008",
"pm_score": 0,
"selected": false,
"text": "print [sum(x) for x in zip(*array)]\n chain itertools from itertools import chain\n\nfor x in array.chain.from_iterable(zip(*array)):\n print x \n# prints 1, 4, 7, 2, 5, 8, ...\n"
}
] |
2008/11/04
|
[
"https://Stackoverflow.com/questions/263457",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20670/"
] |
263,469
|
<p>I have a C# .NET web project that I'm currently working on. What I'm trying to do is read some files that I dropped into a dir which is at the same level as fileReader.cs which is attempting to read them. On a normal desktop app the following would work:</p>
<pre><code>DirectoryInfo di = new DirectoryInfo(./myDir);
</code></pre>
<p>However because it's a web project the execution context is different, and I don't know how to access these files?</p>
<p>Eventually fileReader will be called in an installation routine. I intend to override one of the Installer.cs' abstract methods so will this affect the execution context?</p>
|
[
{
"answer_id": 263474,
"author": "Omer van Kloeten",
"author_id": 4979,
"author_profile": "https://Stackoverflow.com/users/4979",
"pm_score": 2,
"selected": false,
"text": "Server.MapPath"
},
{
"answer_id": 263480,
"author": "splattne",
"author_id": 6461,
"author_profile": "https://Stackoverflow.com/users/6461",
"pm_score": 2,
"selected": false,
"text": "Server.MapPath(\"mydir/file.some\")\n Server.MapPath(\"/scripts/mydir/file.some\")\n"
}
] |
2008/11/04
|
[
"https://Stackoverflow.com/questions/263469",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16684/"
] |
263,477
|
<p>I have a gridview like below:</p>
<pre><code> <asp:GridView DataKeyNames="TransactionID"
AllowSorting="True" AllowPaging="True"ID="grvBrokerage"
runat="server" AutoGenerateColumns="False"
CssClass="datatable" Width="100%"
<Columns>
<asp:BoundField DataField="BrkgAccountNameOutput"
HeaderText="Account Name"/>
<asp:BoundField DataField="TransactionAmount"
HeaderText="Transaction Amount"
SortExpression="TransactionAmount" />
<asp:BoundField DataField="TransType"
HeaderText="Transaction Type"
SortExpression="TransType"/>
<asp:BoundField DataField="AccountBalance"
HeaderText="Account Balance"/>
<asp:BoundField DataField="CreateDt"
HeaderText="Transaction Date" />
</Columns>
</asp:GridView>
</code></pre>
<p>I have a page with a gridview and a objectdatasource control. AllowPaging and AllowSorting is enabled. Here is the method I use that gets the data and binds the objectdatasource to the grid:</p>
<pre><code> protected void BindBrokerageDetails()
{
HomePage master = (HomePage)Page.Master;
BrokerageAccount brokerageAccount = new BrokerageAccount();
brokerageAccount.UserID = new Guid(Membership.GetUser().ProviderUserKey.ToString());
ddlBrokerageDetails.DataSource = brokerageAccount.GetAll();
ddlBrokerageDetails.DataTextField = "Account Name";
ddlBrokerageDetails.DataValueField = "Account Name";
ddlBrokerageDetails.DataBind();
if (ddlBrokerageDetails.Items.Count > 0)
{
BrokerageTransactions brokerageaccountdetails = new
BrokerageTransactions();
DataSet ds = BrokerageAccount.GetBrkID2(
new Guid(Membership
.GetUser()
.ProviderUserKey
.ToString()),
ddlBrokerageDetails
.SelectedItem
.Text
.ToString());
foreach (DataRow dr in ds.Tables[0].Rows)
{
brokerageaccountdetails.BrokerageId = new Guid(dr["BrkrgId"].ToString());
}
ddlBrokerageDetails.SelectedItem.Value = brokerageaccountdetails.BrokerageId.ToString();
grvBrokerage.DataSource = ObjectDataSource1;
grvBrokerage.DataBind();
}
}
</code></pre>
<p>I have a sorting event, but when I check the grvBrokerage.DataSource, it is null. I am curious as to why? Here is the code for that?</p>
<pre><code> protected void grvBrokerage_Sorting(object sender, GridViewSortEventArgs e)
{
DataTable dt = grvBrokerage.DataSource as DataTable;
if (dt != null)
{
DataView dv = new DataView(dt);
dv.Sort = e.SortExpression + " " + e.SortDirection;
grvBrokerage.DataSource = dv;
grvBrokerage.DataBind();
}
}
</code></pre>
<p>Here is the ObjectDataSource declaration:</p>
<pre><code><asp:ObjectDataSource ID="ObjectDataSource1"
runat="server"
SelectMethod="GetAllWithId"
TypeName="BrokerageTransactions">
<SelectParameters>
<asp:ControlParameter
ControlID="ddlBrokerageDetails"
Name="brokid"
PropertyName="SelectedValue"
Type="Object" />
</SelectParameters>
</asp:ObjectDataSource>
</code></pre>
<p>Thanks,
X</p>
|
[
{
"answer_id": 635431,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "Protected Sub gvRevstatus_Sorting(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewSortEventArgs) Handles gvRevstatus.Sorting\n Dim instance As GridView = gvRevstatus Dim cmd As String\n\n cmd = \"SELECT Status,CONVERT(VARCHAR(10),StatusDate,101) AS StatusDate,RevNo,CommentBY FROM tabStatus WHERE ID =\" & CInt(lblId.Text.Trim) & _\n \" Order by StatusDate\"\n dim gvtab as datatable = BOClaim.GVBoundTab(cnstr, cmd, gvstatus) ' my own classto databind\n Dim dv As New DataView(gvtab)\n dv.Sort = e.SortExpression\n\n gvRevstatus.DataSource = dv\n gvRevstatus.DataBind()\nEnd Sub\n"
}
] |
2008/11/04
|
[
"https://Stackoverflow.com/questions/263477",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/33690/"
] |
263,478
|
<p>Given a result set, how can I determin the actual names of the fields specified in the query (NOT their aliases).</p>
<pre><code>$query = "SELECT first AS First_Name, last AS Last_Name FROM people";
$dbResult = mysql_query($query);
$fieldCount = mysql_num_fields($dbResult);
for ($i=0; $i<$fieldCount; $i++) {
// Set some values
$fieldName = mysql_field_name($dbResult, $i);
}
</code></pre>
<p>This example returns field names, but in this example it returns the alias "First_Name" instead of the actual field name "first".</p>
<p>Is it possible to get the actual field name from such a query. Particularly if I am writing a function and have no idea what query will be thrown at it.</p>
|
[
{
"answer_id": 263846,
"author": "TonyUser",
"author_id": 22873,
"author_profile": "https://Stackoverflow.com/users/22873",
"pm_score": 0,
"selected": false,
"text": "information_schema"
},
{
"answer_id": 263993,
"author": "SeanDowney",
"author_id": 5261,
"author_profile": "https://Stackoverflow.com/users/5261",
"pm_score": 0,
"selected": false,
"text": " field FieldAlias\n field as FieldAlias\n"
}
] |
2008/11/04
|
[
"https://Stackoverflow.com/questions/263478",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/34418/"
] |
263,485
|
<p>I wish to dynamically change the scroll position of a Silverlight ListBox from C#, and I need to know how to access the ScrollViewer element of a ListBox control from C#?</p>
<p>Thanks guys,
Jeff</p>
|
[
{
"answer_id": 266951,
"author": "Bryant",
"author_id": 10893,
"author_profile": "https://Stackoverflow.com/users/10893",
"pm_score": 2,
"selected": false,
"text": "public class TestBox : ListBox\n{\n private ScrollViewer _scrollHost;\n\n protected override void PrepareContainerForItemOverride(DependencyObject element, object item)\n {\n var itemsHost = VisualTreeHelper.GetParent(element) as Panel;\n\n for (DependencyObject obj = itemsHost; obj != item && obj != null; obj = VisualTreeHelper.GetParent(obj))\n {\n ScrollViewer viewer = obj as ScrollViewer;\n if (viewer != null)\n {\n _scrollHost = viewer;\n break;\n }\n }\n\n base.PrepareContainerForItemOverride(element, item);\n }\n}\n"
},
{
"answer_id": 791652,
"author": "Dan",
"author_id": 59532,
"author_profile": "https://Stackoverflow.com/users/59532",
"pm_score": 3,
"selected": false,
"text": "var myScrollviewer = myListBox.GetTemplateChild(\"ScrollViewer\") as ScrollViewer;"
},
{
"answer_id": 1820127,
"author": "Sergii",
"author_id": 404353,
"author_profile": "https://Stackoverflow.com/users/404353",
"pm_score": -1,
"selected": false,
"text": "ScrollViewer scrollViewer = yourListBox.getScrollHost();\n myListBox.ItemsSource = list;\n"
},
{
"answer_id": 2190899,
"author": "E.Létondor",
"author_id": 265132,
"author_profile": "https://Stackoverflow.com/users/265132",
"pm_score": 0,
"selected": false,
"text": "myListBox.ApplyTemplate();\n"
},
{
"answer_id": 12875328,
"author": "Yop",
"author_id": 1743696,
"author_profile": "https://Stackoverflow.com/users/1743696",
"pm_score": 1,
"selected": false,
"text": "private void ScrollViewer_Loaded(object sender, System.Windows.RoutedEventArgs e)\n {\n myScrollViewer = (sender as ScrollViewer);\n }\n"
}
] |
2008/11/04
|
[
"https://Stackoverflow.com/questions/263485",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12172/"
] |
263,486
|
<p>In a forms model, I used to get the current logged-in user by:</p>
<pre><code>Page.CurrentUser
</code></pre>
<p>How do I get the current user inside a controller class in ASP.NET MVC?</p>
|
[
{
"answer_id": 263502,
"author": "Sean",
"author_id": 29941,
"author_profile": "https://Stackoverflow.com/users/29941",
"pm_score": 4,
"selected": false,
"text": "Membership.GetUser().UserName\n"
},
{
"answer_id": 263508,
"author": "dove",
"author_id": 30913,
"author_profile": "https://Stackoverflow.com/users/30913",
"pm_score": 6,
"selected": false,
"text": "HttpContext.Current.User"
},
{
"answer_id": 263853,
"author": "Haacked",
"author_id": 598,
"author_profile": "https://Stackoverflow.com/users/598",
"pm_score": 9,
"selected": true,
"text": "User ViewData ViewPage"
},
{
"answer_id": 679924,
"author": "jrb",
"author_id": 82332,
"author_profile": "https://Stackoverflow.com/users/82332",
"pm_score": 4,
"selected": false,
"text": "Request.IsAuthenticated Page.User.Identity"
},
{
"answer_id": 916264,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 8,
"selected": false,
"text": "User User.Identity.Name User.IsInRole(\"Administrator\")"
},
{
"answer_id": 3667881,
"author": "tifoz",
"author_id": 442425,
"author_profile": "https://Stackoverflow.com/users/442425",
"pm_score": 4,
"selected": false,
"text": "System.Web.HttpContext.Current.User.Identity.Name"
},
{
"answer_id": 5790729,
"author": "Gediminas Bukauskas",
"author_id": 683517,
"author_profile": "https://Stackoverflow.com/users/683517",
"pm_score": 2,
"selected": false,
"text": "IPrincipal currentUser = HttpContext.Current.User;\nbool writeEnable = currentUser.IsInRole(\"Administrator\") ||\n ...\n currentUser.IsInRole(\"Operator\");\n"
},
{
"answer_id": 8080415,
"author": "live-love",
"author_id": 436341,
"author_profile": "https://Stackoverflow.com/users/436341",
"pm_score": 2,
"selected": false,
"text": "MembershipUser u = Membership.GetUser(LoginUser.UserName);\n"
},
{
"answer_id": 8110578,
"author": "heriawan",
"author_id": 1043990,
"author_profile": "https://Stackoverflow.com/users/1043990",
"pm_score": 3,
"selected": false,
"text": "User.Identity.Name"
},
{
"answer_id": 17254386,
"author": "MattC",
"author_id": 1118428,
"author_profile": "https://Stackoverflow.com/users/1118428",
"pm_score": 3,
"selected": false,
"text": "WebSecurity.CurrentUserId\n using System.Web.Security;\n"
},
{
"answer_id": 18947973,
"author": "radbyx",
"author_id": 306028,
"author_profile": "https://Stackoverflow.com/users/306028",
"pm_score": 5,
"selected": false,
"text": "System.Web.HttpContext.Current.User.Identity.Name\n"
},
{
"answer_id": 31020699,
"author": "Ognyan Dimitrov",
"author_id": 1042934,
"author_profile": "https://Stackoverflow.com/users/1042934",
"pm_score": 2,
"selected": false,
"text": "var ticket = FormsAuthentication.Decrypt(\n HttpContext.Current.Request.Cookies[FormsAuthentication.FormsCookieName].Value);\n\nif (ticket.Expired)\n{\n throw new InvalidOperationException(\"Ticket expired.\");\n}\n\nIPrincipal user = (System.Security.Principal.IPrincipal) new RolePrincipal(new FormsIdentity(ticket));\n"
},
{
"answer_id": 32056880,
"author": "Clay Smith",
"author_id": 947978,
"author_profile": "https://Stackoverflow.com/users/947978",
"pm_score": 3,
"selected": false,
"text": "System.Security.Principal.WindowsIdentity.GetCurrent().Name"
},
{
"answer_id": 34951257,
"author": "Beau D'Amore",
"author_id": 1744254,
"author_profile": "https://Stackoverflow.com/users/1744254",
"pm_score": 2,
"selected": false,
"text": "// Find currently logged in user\nUserPrincipal adUser = null;\nusing (HostingEnvironment.Impersonate())\n{\n var userContext = System.Web.HttpContext.Current.User.Identity;\n PrincipalContext ctx = new PrincipalContext(ContextType.Domain, ConfigurationManager.AppSettings[\"AllowedDomain\"], null,\n ContextOptions.Negotiate | ContextOptions.SecureSocketLayer);\n adUser = UserPrincipal.FindByIdentity(ctx, userContext.Name);\n}\n//Then work with 'adUser' from here...\n using (HostingEnvironment.Impersonate()){ ... }\n impersonate <system.web>\n <identity impersonate=\"true\" />\n <authentication mode=\"Windows\" />\n"
},
{
"answer_id": 41614794,
"author": "Gilberto B. Terra Jr.",
"author_id": 1890549,
"author_profile": "https://Stackoverflow.com/users/1890549",
"pm_score": 3,
"selected": false,
"text": "User.Identity.Name\n using Microsoft.AspNet.Identity;\n User.Identity.GetUserId();\n"
},
{
"answer_id": 45673764,
"author": "Rajeev Jayaswal",
"author_id": 2155858,
"author_profile": "https://Stackoverflow.com/users/2155858",
"pm_score": 2,
"selected": false,
"text": "Request.LogonUserIdentity.Name;\n"
},
{
"answer_id": 46490789,
"author": "Fereydoon Barikzehy",
"author_id": 3569825,
"author_profile": "https://Stackoverflow.com/users/3569825",
"pm_score": 2,
"selected": false,
"text": "var username = System.Web.HttpContext.Current.User.Identity.Name;\n"
},
{
"answer_id": 48412527,
"author": "Raj Baral",
"author_id": 6348730,
"author_profile": "https://Stackoverflow.com/users/6348730",
"pm_score": 3,
"selected": false,
"text": "var user= System.Web.HttpContext.Current.User.Identity.GetUserName();\n var userName = System.Security.Principal.WindowsIdentity.GetCurrent().Name; //will give 'Domain//UserName'\n\nEnvironment.UserName - Will Display format : 'Username'\n"
},
{
"answer_id": 55939966,
"author": "Daniel King",
"author_id": 3207739,
"author_profile": "https://Stackoverflow.com/users/3207739",
"pm_score": 1,
"selected": false,
"text": "string sUserName = null;\nstring url = Request.Url.ToString();\n\nif (url.Contains(\"localhost\"))\n sUserName = System.Security.Principal.WindowsIdentity.GetCurrent().Name;\nelse\n sUserName = User.Identity.Name;\n"
},
{
"answer_id": 64514714,
"author": "Samif",
"author_id": 13428645,
"author_profile": "https://Stackoverflow.com/users/13428645",
"pm_score": 1,
"selected": false,
"text": "<li>Hello @User.Identity.Name</li>\n"
}
] |
2008/11/04
|
[
"https://Stackoverflow.com/questions/263486",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/31505/"
] |
263,503
|
<p>I am using the following code to determine free space on a volume.
The folder was provided using NSOpenPanel. The item selected was a mounted volume and the path returned is \Volumes\Name</p>
<pre><code>NSDictionary* fileAttributes = [[NSFileManager defaultManager] fileSystemAttributesAtPath:folder];
unsigned long long size = [[fileAttributes objectForKey:NSFileSystemFreeSize] longLongValue];
</code></pre>
<p>Is there a better method to determine the free space on a mounted volume using Cocoa?</p>
<p>Update: This is in fact the best way to determine the free space on a volume. It appeared it wasn't working but that was due to the fact that folder was actually /Volumes rather than /Volume/VolumeName</p>
|
[
{
"answer_id": 264486,
"author": "diciu",
"author_id": 2811,
"author_profile": "https://Stackoverflow.com/users/2811",
"pm_score": 1,
"selected": false,
"text": "#include <sys/param.h>\n#include <sys/mount.h>\n\nint main()\n{\n struct statfs buf;\n\n int retval = statfs(\"/Volumes/KINGSTON\", &buf);\n\n printf(\"KINGSTON Retval: %d, fundamental file system block size %ld, total data blocks %d, total in 512 blocks: %ld\\n\",\n retval, buf.f_bsize, buf.f_blocks, (buf.f_bsize / 512) * buf.f_blocks); \n printf(\"Free 512 blocks: %ld\\n\", (buf.f_bsize / 512) * buf.f_bfree); \n exit(0);\n}\n"
},
{
"answer_id": 269161,
"author": "AlanKley",
"author_id": 8761,
"author_profile": "https://Stackoverflow.com/users/8761",
"pm_score": 2,
"selected": false,
"text": "NSDictionary* fileAttributes = [[NSFileManager defaultManager] fileSystemAttributesAtPath:folder];\n\nunsigned long long size = [[fileAttributes objectForKey:NSFileSystemFreeSize] longLongValue]; \n"
}
] |
2008/11/04
|
[
"https://Stackoverflow.com/questions/263503",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8761/"
] |
263,507
|
<p>I'm trying to get the zoom controls to show up in a <code>mapview</code>, the following code almost works, but the zoom controls appear in the top left of the <code>mapview</code>, not the bottom center like I'm specifying via <code>setGravity()</code>. Can someone enlighten me as to what I'm missing?</p>
<pre><code>zoomView = (LinearLayout) mapView.getZoomControls();
zoomView.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,ViewGroup.LayoutParams.WRAP_CONTENT));
zoomView.setGravity(Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL);
mapView.addView(zoomView);
</code></pre>
<p>These views/layouts are all constructed programmatically, there is no layout file to tweak.</p>
|
[
{
"answer_id": 280237,
"author": "Reto Meier",
"author_id": 822,
"author_profile": "https://Stackoverflow.com/users/822",
"pm_score": 4,
"selected": false,
"text": "RelativeLayout LinearLayout layout.xml <?xml version=\"1.0\" encoding=\"utf-8\"?>\n<RelativeLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" \n android:layout_width=\"fill_parent\" \n android:layout_height=\"fill_parent\"> \n <com.google.android.maps.MapView\n android:id=\"@+id/myMapView\"\n android:layout_width=\"fill_parent\" \n android:layout_height=\"fill_parent\"\n android:enabled=\"true\"\n android:clickable=\"true\"\n android:apiKey=\"MY_MAP_API_KEY\"\n />\n <LinearLayout android:id=\"@+id/layout_zoom\" \n android:layout_width=\"wrap_content\" \n android:layout_height=\"wrap_content\" \n android:layout_alignParentBottom=\"true\" \n android:layout_centerHorizontal=\"true\" \n /> \n</RelativeLayout> \n MapView onCreate LinearLayout zoomLayout =(LinearLayout)findViewById(R.id.layout_zoom); \nView zoomView = myMapView.getZoomControls(); \nzoomLayout.addView(zoomView, new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT)); \nmyMapView.displayZoomControls(true);\n"
},
{
"answer_id": 325159,
"author": "jasonhudgins",
"author_id": 24590,
"author_profile": "https://Stackoverflow.com/users/24590",
"pm_score": 2,
"selected": false,
"text": " // layout to insert zoomcontrols at the bottom center of a mapview\n MapView.LayoutParams params = MapView.LayoutParams(\n LayoutParams.WRAP_CONTENT,\n LayoutParams.WRAP_CONTENT,\n mapViewWidth / 2, mapViewHeight,\n MapView.LayoutParams.BOTTOM_CENTER);\n\n // add zoom controls\n mapView.addView(mapView.getZoomControls(), params);\n"
},
{
"answer_id": 471155,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "MapView.LayoutParams params = MapView.LayoutParams(\n MapView.LayoutParams params = **new** MapView.LayoutParams(\n"
},
{
"answer_id": 594435,
"author": "magegu",
"author_id": 71828,
"author_profile": "https://Stackoverflow.com/users/71828",
"pm_score": 2,
"selected": false,
"text": " public class MyMapActivity extends MapActivity { public void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n\n RelativeLayout relativeLayout = new RelativeLayout(this);\n setContentView(relativeLayout);\n\n final MapView mapView = new MapView(this, DEBUG_MAP_API_KEY);\n RelativeLayout.LayoutParams mapViewLayoutParams = new\nRelativeLayout.LayoutParams\n(RelativeLayout.LayoutParams.FILL_PARENT,RelativeLayout.LayoutParams.FILL_PARENT );\n relativeLayout.addView(mapView, mapViewLayoutParams);\n\n RelativeLayout.LayoutParams zoomControlsLayoutParams = new\nRelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT,\nRelativeLayout.LayoutParams.WRAP_CONTENT );\n zoomControlsLayoutParams.addRule\n(RelativeLayout.ALIGN_PARENT_BOTTOM);\n zoomControlsLayoutParams.addRule\n(RelativeLayout.CENTER_HORIZONTAL);\n\n relativeLayout.addView(mapView.getZoomControls(),\nzoomControlsLayoutParams);\n\n mapView.setClickable(true);\n mapView.setEnabled(true);\n\n } \n"
},
{
"answer_id": 2499889,
"author": "jcrowson",
"author_id": 296810,
"author_profile": "https://Stackoverflow.com/users/296810",
"pm_score": 5,
"selected": false,
"text": "OnCreate() MapView view.setBuiltInZoomControls(true);"
},
{
"answer_id": 5985426,
"author": "George",
"author_id": 321984,
"author_profile": "https://Stackoverflow.com/users/321984",
"pm_score": 3,
"selected": false,
"text": "mapView.setBuiltInZoomControls(true);\nZoomButtonsController zbc = mapView.getZoomButtonsController();\nViewGroup container = zbc.getContainer();\nfor (int i = 0; i < container.getChildCount(); i++) {\n View child = container.getChildAt(i);\n if (child instanceof ZoomControls) {\n FrameLayout.LayoutParams lp = (FrameLayout.LayoutParams) child.getLayoutParams();\n lp.gravity = Gravity.RIGHT | Gravity.BOTTOM;\n child.requestLayout();\n break;\n } \n}\n"
},
{
"answer_id": 52492336,
"author": "Manoj Reddy",
"author_id": 7135592,
"author_profile": "https://Stackoverflow.com/users/7135592",
"pm_score": 2,
"selected": false,
"text": "MapView map = (MapView)findViewById(R.id.mapview);\nmap.setBuiltInZoomControls(true);\n"
}
] |
2008/11/04
|
[
"https://Stackoverflow.com/questions/263507",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/24590/"
] |
263,518
|
<p>Currently I have an application that receives an uploaded file from my web application. I now need to transfer that file to a file server which happens to be located on the same network (however this might not always be the case).</p>
<p>I was attempting to use the webclient class in C# .NET.</p>
<pre><code> string filePath = "C:\\test\\564.flv";
try
{
WebClient client = new WebClient();
NetworkCredential nc = new NetworkCredential(uName, password);
Uri addy = new Uri("\\\\192.168.1.28\\Files\\test.flv");
client.Credentials = nc;
byte[] arrReturn = client.UploadFile(addy, filePath);
Console.WriteLine(arrReturn.ToString());
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
</code></pre>
<p>The machine located at 192.168.1.28 is a file server and has a share c:\Files.
As of right now I am receiving an error of Login failed bad user name or password, but I can open explorer and type in that path login successfully. I can also login using remote desktop, so I know the user account works.</p>
<p>Any ideas on this error?
Is it possible to transfer a file directly like that? With the webclient class or maybe some other class?</p>
|
[
{
"answer_id": 263525,
"author": "TheSoftwareJedi",
"author_id": 18941,
"author_profile": "https://Stackoverflow.com/users/18941",
"pm_score": 5,
"selected": true,
"text": "File.Copy(filepath, \"\\\\\\\\192.168.1.28\\\\Files\");\n"
},
{
"answer_id": 2938207,
"author": "Erandika Sandaruwan",
"author_id": 353936,
"author_profile": "https://Stackoverflow.com/users/353936",
"pm_score": 2,
"selected": false,
"text": "namespace FileUpload\n{\npublic partial class Form1 : Form\n{\n string fileName = \"\";\n public Form1()\n {\n InitializeComponent();\n }\n\n private void button1_Click(object sender, EventArgs e)\n {\n\n string path = \"\";\n OpenFileDialog fDialog = new OpenFileDialog();\n fDialog.Title = \"Attach customer proposal document\";\n fDialog.Filter = \"Doc Files|*.doc|Docx File|*.docx|PDF doc|*.pdf\";\n fDialog.InitialDirectory = @\"C:\\\";\n if (fDialog.ShowDialog() == DialogResult.OK)\n {\n fileName = System.IO.Path.GetFileName(fDialog.FileName);\n path = Path.GetDirectoryName(fDialog.FileName);\n textBox1.Text = path + \"\\\\\" + fileName;\n\n }\n }\n\n private void button2_Click(object sender, EventArgs e)\n {\n try\n {\n WebClient client = new WebClient();\n\n NetworkCredential nc = new NetworkCredential(\"erandika1986\", \"123\");\n\n Uri addy = new Uri(@\"\\\\192.168.2.4\\UploadDocs\\\"+fileName);\n\n client.Credentials = nc;\n byte[] arrReturn = client.UploadFile(addy, textBox1.Text);\n MessageBox.Show(arrReturn.ToString());\n\n }\n catch (Exception ex1)\n {\n MessageBox.Show(ex1.Message);\n }\n }\n}\n}\n"
}
] |
2008/11/04
|
[
"https://Stackoverflow.com/questions/263518",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21664/"
] |
263,548
|
<p>The C# project I'm working on uses nHibernate and the connection string is in the web.config as a property of a Hibernate element. I need to read the connection string in the installer to get a connection manually without using Hibernate. I know I can use configManager.connectionStrings, but as the connection string is already defined in the Hibernate portion of web.config I don't want to copy it again into the connectionStrings element. So how can I access this?</p>
|
[
{
"answer_id": 520833,
"author": "Chris S",
"author_id": 21574,
"author_profile": "https://Stackoverflow.com/users/21574",
"pm_score": 0,
"selected": false,
"text": "<hibernate>\n <add key=\"hibernate.connection.provider\" value=\"NHibernate.Connection.DriverConnectionProvider\"/>\n <add key=\"hibernate.dialect\" value=\"NHibernate.Dialect.MsSql2000Dialect\"/>\n <add key=\"hibernate.connection.driver_class\" value=\"NHibernate.Driver.SqlClientDriver\"/>\n <add key=\"hibernate.connection.connection_string\" value=\"${local}\"/>\n</hibernate>\n\n<connectionStrings>\n <add name=\"local\" connectionString=\"server=(local);database=db;Uid=username;Pwd=password;\"/>\n</connectionStrings>\n"
}
] |
2008/11/04
|
[
"https://Stackoverflow.com/questions/263548",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16684/"
] |
263,550
|
<p>I'm sorry I could not think of a better title.</p>
<p>The problem is the following:</p>
<p>For our customer we have created (as part of a larger application) a
graphical designer which they can use to build "scenario's".</p>
<p>These scenario's consist of "Composites" which in turn consist
of "Commands". These command objects all derive from CommandBase and
implement an interface called ICompilable.</p>
<p>The scenario class also implements ICompilable. When Compile() is called
on a command an array of bytes is returned which can then be send to the device
for which they are intended (can't disclose to much info about that hardware, sorry)</p>
<p>Just to give you an idea:</p>
<pre><code>var scenario = new Scenario();
scenario.Add(new DelayCommand(1));
scenario.Add(new CountWithValueCommand(1,ActionEnum.Add,1));
scenario.Add(new DirectPowerCommand(23,false,150));
scenario.Add(new WaitCommand(3));
scenario.Add(new DirectPowerCommand(23,false,150));
scenario.Add(new SkipIfCommand(1,OperatorEnum.SmallerThan,10));
scenario.Add(new JumpCommand(2));
byte[] compiledData = scenario.Compile();
</code></pre>
<p>The graphical designer abstracts all this from the user and allows
him (or her) to simply drag en drop composites onto the designer surface.
(Composites can group commands so we can provide building blocks for returning tasks)</p>
<p>Recently our customer came to us and said, "well the designer is really cool,
but we have some people who would rather have some kind of programming language,
just something simple."</p>
<p>(Simple to them of course)</p>
<p>I would very much like to provide them with a simple language,
that can call various commmands and also replace SkipIfCommand with
a nicer structure, etc...</p>
<p>I have no idea where to start or what my options are (without breaking what we have)</p>
<p>I have heard about people embedding languages such as Python,
people writing their own language an parsers, etc...</p>
<p>Any suggestions?</p>
<p>PS: Users only work with composites, never with commands.
Composites are loaded dynamically at runtime (along with their graphical designer)
and may be provided by third parties in seperate assemblies.</p>
|
[
{
"answer_id": 263675,
"author": "Charles Merriam",
"author_id": 1320510,
"author_profile": "https://Stackoverflow.com/users/1320510",
"pm_score": 3,
"selected": true,
"text": "SCENARIO MyScenario\nDELAY 1\nCOUNT 1 ADD 1\nDIRECT_POWER 23, False, 150\nWAIT 3\n...\nEND_SCENARIO\n scenario :: 'SCENARIO' label newline _cmds END_SCENARIO\ncmds:: _delay or _count or _direct_power or...\ndelay:: 'DELAY' number\n def scenario():\n match_word('SCENARIO')\n scenario_name = match_label()\n emit('var scenario = new Scenario();')\n cmds()\n match_word('END_SCENARIO')\n emit('byte[] ' + scenario_name + ' = scenario.Compile();')\n\ndef delay():\n match_word('DELAY')\n length = match_number()\n emit('scenario.Add(new DelayCommand('+ length +'))')\n\ndef cmds():\n word = peek_next_word()\n if word == 'DELAY':\n delay()\n elif ...\n"
},
{
"answer_id": 263727,
"author": "S.Lott",
"author_id": 10661,
"author_profile": "https://Stackoverflow.com/users/10661",
"pm_score": 1,
"selected": false,
"text": "import * from someInterfaceModule\nscenario= Scenario(\n Delay(1),\n Repeat( Range(10),\n DirectPower( 23, False, 150),\n Wait(3),\n DirectPower( 23, False, 150)\n )\n)\nscenario.compile()\n"
}
] |
2008/11/04
|
[
"https://Stackoverflow.com/questions/263550",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/28149/"
] |
263,551
|
<p>Does anyone know how to databind the .Source property of the WebBrowser in WPF ( 3.5SP1 )?
I have a listview that I want to have a small WebBrowser on the left, and content on the right, and to databind the source of each WebBrowser with the URI in each object bound to the list item.</p>
<p>This is what I have as a proof of concept so far, but the "<code><WebBrowser Source="{Binding Path=WebAddress}"</code>" does not compile.</p>
<pre><code><DataTemplate x:Key="dealerLocatorLayout" DataType="DealerLocatorAddress">
<StackPanel Orientation="Horizontal">
<!--Web Control Here-->
<WebBrowser Source="{Binding Path=WebAddress}"
ScrollViewer.HorizontalScrollBarVisibility="Disabled"
ScrollViewer.VerticalScrollBarVisibility="Disabled"
Width="300"
Height="200"
/>
<StackPanel Orientation="Vertical">
<StackPanel Orientation="Horizontal">
<Label Content="{Binding Path=CompanyName}" FontWeight="Bold" Foreground="Blue" />
<TextBox Text="{Binding Path=DisplayName}" FontWeight="Bold" />
</StackPanel>
<TextBox Text="{Binding Path=Street[0]}" />
<TextBox Text="{Binding Path=Street[1]}" />
<TextBox Text="{Binding Path=PhoneNumber}"/>
<TextBox Text="{Binding Path=FaxNumber}"/>
<TextBox Text="{Binding Path=Email}"/>
<TextBox Text="{Binding Path=WebAddress}"/>
</StackPanel>
</StackPanel>
</DataTemplate>
</code></pre>
|
[
{
"answer_id": 265648,
"author": "Todd White",
"author_id": 30833,
"author_profile": "https://Stackoverflow.com/users/30833",
"pm_score": 8,
"selected": true,
"text": "WebBrowser.Source DependencyProperty AttachedProperty public static class WebBrowserUtility\n{\n public static readonly DependencyProperty BindableSourceProperty =\n DependencyProperty.RegisterAttached(\"BindableSource\", typeof(string), typeof(WebBrowserUtility), new UIPropertyMetadata(null, BindableSourcePropertyChanged));\n\n public static string GetBindableSource(DependencyObject obj)\n {\n return (string) obj.GetValue(BindableSourceProperty);\n }\n\n public static void SetBindableSource(DependencyObject obj, string value)\n {\n obj.SetValue(BindableSourceProperty, value);\n }\n\n public static void BindableSourcePropertyChanged(DependencyObject o, DependencyPropertyChangedEventArgs e)\n {\n WebBrowser browser = o as WebBrowser;\n if (browser != null)\n {\n string uri = e.NewValue as string;\n browser.Source = !String.IsNullOrEmpty(uri) ? new Uri(uri) : null;\n }\n }\n\n}\n <WebBrowser ns:WebBrowserUtility.BindableSource=\"{Binding WebAddress}\"/>\n"
},
{
"answer_id": 976289,
"author": "RoelF",
"author_id": 120480,
"author_profile": "https://Stackoverflow.com/users/120480",
"pm_score": 5,
"selected": false,
"text": "<UserControl x:Class=\"HtmlBox\">\n <WebBrowser x:Name=\"browser\" />\n</UserControl>\n public static readonly DependencyProperty HtmlTextProperty = DependencyProperty.Register(\"HtmlText\", typeof(string), typeof(HtmlBox));\n\npublic string HtmlText {\n get { return (string)GetValue(HtmlTextProperty); }\n set { SetValue(HtmlTextProperty, value); }\n}\n\nprotected override void OnPropertyChanged(DependencyPropertyChangedEventArgs e) {\n base.OnPropertyChanged(e);\n if (e.Property == HtmlTextProperty) {\n DoBrowse();\n }\n}\n private void DoBrowse() {\n if (!string.IsNullOrEmpty(HtmlText)) {\n browser.NavigateToString(HtmlText);\n }\n}\n <Controls:HtmlBox HtmlText=\"{Binding MyHtml}\" />\n"
},
{
"answer_id": 2791680,
"author": "Olaf Japp",
"author_id": 2607769,
"author_profile": "https://Stackoverflow.com/users/2607769",
"pm_score": 2,
"selected": false,
"text": "public class RichTextBoxHelper\n{\n public static readonly DependencyProperty BindableSelectionTextProperty =\n DependencyProperty.RegisterAttached(\"BindableSelectionText\", typeof(string), \n typeof(RichTextBoxHelper), new PropertyMetadata(null, BindableSelectionTextPropertyChanged));\n\n public static string GetBindableSelectionText(DependencyObject obj)\n {\n return (string)obj.GetValue(BindableSelectionTextProperty);\n }\n\n public static void SetBindableSelectionText(DependencyObject obj, string value)\n {\n obj.SetValue(BindableSelectionTextProperty, value);\n }\n\n public static void BindableSelectionTextPropertyChanged(DependencyObject o, DependencyPropertyChangedEventArgs e)\n {\n RichTextBox rtb = o as RichTextBox;\n if (rtb != null)\n {\n string text = e.NewValue as string;\n if (text != null)\n rtb.Selection.Text = text;\n }\n }\n} \n <RichTextBox IsReadOnly='False' TextWrapping='Wrap' utilities:RichTextBoxHelper.BindableSelectionText=\"{Binding Content}\"/>\n"
},
{
"answer_id": 6613466,
"author": "Samuel Jack",
"author_id": 1727,
"author_profile": "https://Stackoverflow.com/users/1727",
"pm_score": 5,
"selected": false,
"text": "public static class WebBrowserBehaviors\n{\n public static readonly DependencyProperty BindableSourceProperty =\n DependencyProperty.RegisterAttached(\"BindableSource\", typeof(object), typeof(WebBrowserBehaviors), new UIPropertyMetadata(null, BindableSourcePropertyChanged));\n\n public static object GetBindableSource(DependencyObject obj)\n {\n return (string)obj.GetValue(BindableSourceProperty);\n }\n\n public static void SetBindableSource(DependencyObject obj, object value)\n {\n obj.SetValue(BindableSourceProperty, value);\n }\n\n public static void BindableSourcePropertyChanged(DependencyObject o, DependencyPropertyChangedEventArgs e)\n {\n WebBrowser browser = o as WebBrowser;\n if (browser == null) return;\n\n Uri uri = null;\n\n if (e.NewValue is string )\n {\n var uriString = e.NewValue as string;\n uri = string.IsNullOrWhiteSpace(uriString) ? null : new Uri(uriString);\n }\n else if (e.NewValue is Uri)\n {\n uri = e.NewValue as Uri;\n }\n\n browser.Source = uri;\n }\n"
},
{
"answer_id": 13408103,
"author": "William",
"author_id": 1828205,
"author_profile": "https://Stackoverflow.com/users/1828205",
"pm_score": -1,
"selected": false,
"text": "xaml xmlns:reportViewer=\"clr-namespace:CoMS.Modules.Report\" \n"
},
{
"answer_id": 37354907,
"author": "ΩmegaMan",
"author_id": 285795,
"author_profile": "https://Stackoverflow.com/users/285795",
"pm_score": 0,
"selected": false,
"text": "public static void BindableSourcePropertyChanged(DependencyObject o, DependencyPropertyChangedEventArgs e)\n{\n WebBrowser browser = o as WebBrowser;\n\n if ((browser != null) && (e.NewValue != null))\n browser.Source = e.NewValue as Uri ?? new Uri((string)e.NewValue);\n\n}\n"
}
] |
2008/11/04
|
[
"https://Stackoverflow.com/questions/263551",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/32772/"
] |
263,566
|
<p>I'm trying to use SubSonic for a new project with an existing database but when I try to build the project after generating the SubSonic files I'm getting these same two exceptions on different classes:</p>
<ul>
<li>Partial declarations of 'MyData.UserCollection' must not specify different base classes</li>
<li>Type 'MyData.UserCollection' already defines a member called 'UserCollection' with the same parameter types</li>
</ul>
<p>I'm able to successfully build a new project using the Northwind DB so I believe the error has something to do with the way the tables are setup but I'm not sure where to go from there. Any help is appreciated.</p>
|
[
{
"answer_id": 263717,
"author": "Jonathan S.",
"author_id": 2034,
"author_profile": "https://Stackoverflow.com/users/2034",
"pm_score": 1,
"selected": false,
"text": "public partial class UserCollectionCollection : ActiveList<UserCollection, UserCollectionCollection>\npublic partial class UserCollection : ActiveList<User, UserCollection>\n regexMatchExpression=\"Collection\" \nregexReplaceExpression=\"Group\"\n"
}
] |
2008/11/04
|
[
"https://Stackoverflow.com/questions/263566",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2034/"
] |
263,578
|
<p>I am using the ReportViewer control from Visual Studio 2008 in Local Mode with objects as the data source. My classes are mapped to data tables in my database. In the objects, it loads related objects as needed. So it leaves the reference null until you try to use the property, then it tries to load it from the database automatically. The classes use the System.Data.SqlClient namespace.</p>
<p>When I interact with the objects in my Windows Forms application, everything works as expected. But when I pass the object to be used as a Report Data Source and it tries to automatically load the related object, it fails. The code creates a SqlConnection object and when I call GetCommand() on it, the following exception is thrown:</p>
<pre><code>[System.Security.SecurityException] {
"Request for the permission of type 'System.Data.SqlClient.SqlClientPermission, System.Data, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' failed."
} System.Security.SecurityException
</code></pre>
<p>I've tried searching for the error, but all the results that show up are for CLR assemblies running on a SQL Server or ASP.Net. I've tried adding the following call in my code (as suggested in the search results) before creating the SqlConnection objects, but it didn't apparently do anything:</p>
<pre><code>System.Data.SqlClient.SqlClientPermission(System.Security.Permissions.PermissionState.Unrestricted).Assert();
</code></pre>
<p>Any ideas?</p>
|
[
{
"answer_id": 265207,
"author": "James Osborn",
"author_id": 6686,
"author_profile": "https://Stackoverflow.com/users/6686",
"pm_score": 0,
"selected": false,
"text": "System.Data.SqlClient.SqlClientPermission mPermission = new SqlClientPermission(System.Security.Permissions.PermissionState.Unrestricted);\ntry\n{\n mPermission.Assert();\n //rest of your code\n}\n//Handle Exceptions\n"
},
{
"answer_id": 321678,
"author": "CuppM",
"author_id": 34440,
"author_profile": "https://Stackoverflow.com/users/34440",
"pm_score": 3,
"selected": true,
"text": "reportViewer.LocalReport.ExecuteReportInCurrentAppDomain(System.Reflection.Assembly.GetExecutingAssembly().Evidence);\n"
},
{
"answer_id": 6106005,
"author": "Artem Koshelev",
"author_id": 55209,
"author_profile": "https://Stackoverflow.com/users/55209",
"pm_score": 3,
"selected": false,
"text": "ExecuteReportInCurrentAppDomain LocalReport.SetBasePermissionsForSandboxAppDomain PermissionSet permissions = new PermissionSet(PermissionState.None);\npermissions.AddPermission(new FileIOPermission(PermissionState.Unrestricted));\npermissions.AddPermission(new SecurityPermission(SecurityPermissionFlag.Execution));\nReportViewer1.LocalReport.SetBasePermissionsForSandboxAppDomain(permissions);\n"
},
{
"answer_id": 20885970,
"author": "pseudocoder",
"author_id": 724088,
"author_profile": "https://Stackoverflow.com/users/724088",
"pm_score": 1,
"selected": false,
"text": " Dim permissions As PermissionSet = New PermissionSet(PermissionState.Unrestricted)\n myReportViewer.LocalReport.SetBasePermissionsForSandboxAppDomain(permissions)\n"
}
] |
2008/11/04
|
[
"https://Stackoverflow.com/questions/263578",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/34440/"
] |
263,582
|
<p>In the following table structure:</p>
<pre><code>Fruits
(
fruit_id,
fruitName
)
Vegetables
(
vegetable_id,
vegetableName
)
favoriteFoods
(
food_id,
foodName,
type_id (References either a fruit or a vegetable)
)
</code></pre>
<p>I realize that I could forgo using a foreign key constraint on the favoriteFoods table and then simply add a type field to the favoriteFoods table to differentiate between fruits and vegetables. But how would you structure the tables so that you could actually create the necessary foreign key constraints? </p>
|
[
{
"answer_id": 263593,
"author": "wonderchook",
"author_id": 32113,
"author_profile": "https://Stackoverflow.com/users/32113",
"pm_score": 3,
"selected": true,
"text": "Food\n (\n food_id,\n foodName,\n foodType\n )\n\nfavoriteFoods\n (\n favoritefood_id,\n fkfood_id\n )\n"
},
{
"answer_id": 265653,
"author": "Walter Mitty",
"author_id": 19937,
"author_profile": "https://Stackoverflow.com/users/19937",
"pm_score": 0,
"selected": false,
"text": "Fruits ( \n fruit_id,\n food_id references favoritefoods.food_id,\n fruitName)\nVegetables(\n vegetable_id,\n food_id references favoritefoods.food_id,\n vegetableName)\nfavoriteFoods (\n food_id,\n foodName)\n"
}
] |
2008/11/04
|
[
"https://Stackoverflow.com/questions/263582",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20178/"
] |
263,585
|
<p>I have over the course of a few projects developed a pattern for creating immutable (readonly) objects and immutable object graphs. Immutable objects carry the benefit of being 100% thread safe and can therefore be reused across threads. In my work I very often use this pattern in Web applications for configuration settings and other objects that I load and cache in memory. Cached objects should always be immutable as you want to guarantee they are not unexpectedly changed.</p>
<p>Now, you can of course easily design immutable objects as in the following example:</p>
<pre><code>public class SampleElement
{
private Guid id;
private string name;
public SampleElement(Guid id, string name)
{
this.id = id;
this.name = name;
}
public Guid Id
{
get { return id; }
}
public string Name
{
get { return name; }
}
}
</code></pre>
<p>This is fine for simple classes - but for more complex classes I do not fancy the concept of passing all values through a constructor. Having setters on the properties is more desirable and your code constructing a new object gets easier to read. </p>
<p>So how do you create immutable objects with setters?</p>
<p>Well, in my pattern objects start out as being fully mutable until you freeze them with a single method call. Once an object is frozen it will stay immutable forever - it cannot be turned into a mutable object again. If you need a mutable version of the object, you simply clone it.</p>
<p>Ok, now on to some code. I have in the following code snippets tried to boil the pattern down to its simplest form. The IElement is the base interface that all immutable objects must ultimately implement. </p>
<pre><code>public interface IElement : ICloneable
{
bool IsReadOnly { get; }
void MakeReadOnly();
}
</code></pre>
<p>The Element class is the default implementation of the IElement interface:</p>
<pre><code>public abstract class Element : IElement
{
private bool immutable;
public bool IsReadOnly
{
get { return immutable; }
}
public virtual void MakeReadOnly()
{
immutable = true;
}
protected virtual void FailIfImmutable()
{
if (immutable) throw new ImmutableElementException(this);
}
...
}
</code></pre>
<p>Let's refactor the SampleElement class above to implement the immutable object pattern:</p>
<pre><code>public class SampleElement : Element
{
private Guid id;
private string name;
public SampleElement() {}
public Guid Id
{
get
{
return id;
}
set
{
FailIfImmutable();
id = value;
}
}
public string Name
{
get
{
return name;
}
set
{
FailIfImmutable();
name = value;
}
}
}
</code></pre>
<p>You can now change the Id property and the Name property as long as the object has not been marked as immutable by calling the MakeReadOnly() method. Once it is immutable, calling a setter will yield an ImmutableElementException.</p>
<p>Final note:
The full pattern is more complex than the code snippets shown here. It also contains support for collections of immutable objects and complete object graphs of immutable object graphs. The full pattern enables you to turn an entire object graph immutable by calling the MakeReadOnly() method on the outermost object. Once you start creating larger object models using this pattern the risk of leaky objects increases. A leaky object is an object that fails to call the FailIfImmutable() method before making a change to the object. To test for leaks I have also developed a generic leak detector class for use in unit tests. It uses reflection to test if all properties and methods throw the ImmutableElementException in the immutable state.
In other words TDD is used here.</p>
<p>I have grown to like this pattern a lot and find great benefits in it. So what I would like to know is if any of you are using similar patterns? If yes, do you know of any good resources that document it? I am essentially looking for potential improvements and for any standards that might already exist on this topic.</p>
|
[
{
"answer_id": 263626,
"author": "Konrad Rudolph",
"author_id": 1968,
"author_profile": "https://Stackoverflow.com/users/1968",
"pm_score": 3,
"selected": false,
"text": "System.Drawing.Point readonly"
},
{
"answer_id": 263719,
"author": "Marc Gravell",
"author_id": 23354,
"author_profile": "https://Stackoverflow.com/users/23354",
"pm_score": 6,
"selected": true,
"text": "virtual [public|protected] void Freeze()\n{\n if(!frozen)\n {\n frozen = true;\n OnFrozen();\n }\n}\nprotected virtual void OnFrozen() {} // subclass can add code here.\n"
},
{
"answer_id": 263912,
"author": "Robert Paulson",
"author_id": 14033,
"author_profile": "https://Stackoverflow.com/users/14033",
"pm_score": 3,
"selected": false,
"text": "List<int> list = new List<int> { 1, 2, 3};\nReadOnlyCollection<int> readOnlyList = list.AsReadOnly();\n Add( T item) bool IsReadOnly { get; }"
},
{
"answer_id": 265025,
"author": "spoulson",
"author_id": 3347,
"author_profile": "https://Stackoverflow.com/users/3347",
"pm_score": 2,
"selected": false,
"text": "private set public class SampleElement {\n public SampleElement(Guid id, string name) {\n Id = id;\n Name = name;\n }\n\n public Guid Id {\n get; private set;\n }\n\n public string Name {\n get; private set;\n }\n}\n"
},
{
"answer_id": 4091679,
"author": "Merlyn Morgan-Graham",
"author_id": 232593,
"author_profile": "https://Stackoverflow.com/users/232593",
"pm_score": 2,
"selected": false,
"text": "INotifyPropertyChanged"
},
{
"answer_id": 15929373,
"author": "bradgonesurfing",
"author_id": 158285,
"author_profile": "https://Stackoverflow.com/users/158285",
"pm_score": 2,
"selected": false,
"text": "class Foo{ \n ...\n public Foo \n Set\n ( double? majorBar=null\n , double? minorBar=null\n , int? cats=null\n , double? dogs=null)\n {\n return new Foo\n ( majorBar ?? MajorBar\n , minorBar ?? MinorBar\n , cats ?? Cats\n , dogs ?? Dogs);\n }\n\n public Foo\n ( double R\n , double r\n , int l\n , double e\n ) \n {\n ....\n }\n}\n var f = new Foo(10,20,30,40);\nvar g = f.Set(cat:99);\n"
},
{
"answer_id": 21604550,
"author": "Jos Bosmans",
"author_id": 3005076,
"author_profile": "https://Stackoverflow.com/users/3005076",
"pm_score": 2,
"selected": false,
"text": "public class Immutable<T> where T : IElement\n{\n private T value;\n\n public Immutable(T mutable) \n {\n this.value = (T) mutable.Clone();\n this.value.MakeReadOnly();\n }\n\n public T Value \n {\n get \n {\n return this.value;\n }\n }\n\n public static implicit operator Immutable<T>(T mutable) \n {\n return new Immutable<T>(mutable);\n }\n\n public static implicit operator T(Immutable<T> immutable)\n {\n return immutable.value;\n }\n}\n // All elements of this list are guaranteed to be immutable\nList<Immutable<SampleElement>> elements = \n new List<Immutable<SampleElement>>();\n\nfor (int i = 1; i < 10; i++) \n{\n SampleElement newElement = new SampleElement();\n newElement.Id = Guid.NewGuid();\n newElement.Name = \"Sample\" + i.ToString();\n\n // The compiler will automatically convert to Immutable<SampleElement> for you\n // because of the implicit conversion operator\n elements.Add(newElement);\n}\n\nforeach (SampleElement element in elements)\n Console.Out.WriteLine(element.Name);\n\nelements[3].Value.Id = Guid.NewGuid(); // This will throw an ImmutableElementException\n"
}
] |
2008/11/04
|
[
"https://Stackoverflow.com/questions/263585",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/27393/"
] |
263,586
|
<p>I'm writing an implementation of a virtual machine in C#, and I need to implement the VM's stack, which can contain two types of entry - return entries or backtrack entries. What is the best way of implementing this?</p>
<p>I'm currently using a base type, as follows:</p>
<pre><code>class StackEntry { }
class Return : StackEntry { uint pc; }
class Backtrack : StackEntry { uint pc; object backtrack; }
Stack<StackEntry> stack;
</code></pre>
<p>This works OK, but the resulting type testing and downcasting feels clumsy.</p>
<p>Is there a better way of handling this type of construction?</p>
|
[
{
"answer_id": 263635,
"author": "Mike Burton",
"author_id": 22225,
"author_profile": "https://Stackoverflow.com/users/22225",
"pm_score": 4,
"selected": true,
"text": "StackEntry { protected virtual void PostPop(); }\nReturn : StackEntry { protected override void PostPop(); }\nBacktrack : StackEntry { protected override void PostPop(); }\n"
},
{
"answer_id": 263643,
"author": "Konrad Rudolph",
"author_id": 1968,
"author_profile": "https://Stackoverflow.com/users/1968",
"pm_score": 0,
"selected": false,
"text": "union"
}
] |
2008/11/04
|
[
"https://Stackoverflow.com/questions/263586",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/34438/"
] |
263,599
|
<p>I'm wondering how slow it's going to be switching between 2 databases on every call of every page of a site. The site has many different databases for different clients, along with a "global" database that is used for some general settings. I'm wondering if there would be much time added for the execution of each script if it has to connect to the database, select a DB, do a query or 2, switch to another DB and then complete the page generation. I could also have the data repeated in each DB, I just need to mantain it (will only change when upgrading).</p>
<p>So, in the end, how fast is <code>mysql_select_db()</code>?</p>
<p><strong>Edit:</strong> Yes, I could connect to each DB separately, but as this is often the slowest part of any PHP script, I'd like to avoid this, especially since it's on every page. (It's slow because PHP has to do some kind of address resolution (be it an IP or host name) and then MySQL has to check the login parameters both times.)</p>
|
[
{
"answer_id": 263634,
"author": "Rob Prouse",
"author_id": 30827,
"author_profile": "https://Stackoverflow.com/users/30827",
"pm_score": 4,
"selected": true,
"text": "SELECT * FROM db1.table1;\n"
},
{
"answer_id": 264129,
"author": "staticsan",
"author_id": 28832,
"author_profile": "https://Stackoverflow.com/users/28832",
"pm_score": 1,
"selected": false,
"text": "mysql_connect() mysql_select_db() USE"
}
] |
2008/11/04
|
[
"https://Stackoverflow.com/questions/263599",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5441/"
] |
263,607
|
<p><strong>The Setup:</strong></p>
<p>I'm working on a website that uses <code>Formsauthentication</code> using cookies to store the login ticket. The site also has an <code>HTTPHandler</code> that manages images stored in the database. The handler caches the images to be public and expire in 20 minutes. We have noticed that since the images have the same lifecycle as a page the images also include the <code>Formsauthentication</code> cookie. The configuration is IIS 6, Win2k server, Content Expiration is not enabled.</p>
<p><strong>The Problem:</strong></p>
<p>What we are experiencing is Person A logs in and hits a couple of pages. Then Person B hits the default page not logging in and get's the cookie for Person A and is able to see all of Person's A data. We have reproduced the problem once by turning on Content Expiration in IIS but have not reproduced consistently so we are not sure if Content Expiration helped us reproduce it. We are assuming since the images are being cached as public and they also contain the cookie with the <code>FormsAuthentication</code>, it's somehow possible for Person B to unintentionally get Person A's cookie. We know this isn't a attack on the website.</p>
<p>Has anyone experienced anything similar to this behavior? If so, can you provide any advice on how to reproduce this issue consistently?</p>
|
[
{
"answer_id": 263729,
"author": "Lee Kowalkowski",
"author_id": 30945,
"author_profile": "https://Stackoverflow.com/users/30945",
"pm_score": 0,
"selected": false,
"text": "Cache-control: no-cache=\"set-cookie,set-cookie2\"\n"
}
] |
2008/11/04
|
[
"https://Stackoverflow.com/questions/263607",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
263,614
|
<p>A Java version of this question was just answered, and, well, I don't know how to do this in .net. </p>
<p>So how do you calculate the display width of a string in C# / .net?</p>
|
[
{
"answer_id": 263637,
"author": "Andrew Bullock",
"author_id": 28543,
"author_profile": "https://Stackoverflow.com/users/28543",
"pm_score": 3,
"selected": false,
"text": "Graphics.MeasureString"
}
] |
2008/11/04
|
[
"https://Stackoverflow.com/questions/263614",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2323/"
] |
263,623
|
<p>Is there any Ruby equivalent for Python's builtin <code>zip</code> function? If not, what is a concise way of doing the same thing?</p>
<p>A bit of context: this came up when I was trying to find a clean way of doing a check involving two arrays. If I had <code>zip</code>, I could have written something like:</p>
<pre><code>zip(a, b).all? {|pair| pair[0] === pair[1]}
</code></pre>
<p>I'd also accept a clean way of doing this without anything resembling <code>zip</code> (where "clean" means "without an explicit loop").</p>
|
[
{
"answer_id": 263652,
"author": "dgtized",
"author_id": 34450,
"author_profile": "https://Stackoverflow.com/users/34450",
"pm_score": 6,
"selected": true,
"text": "[1,2].zip([3,4]) => [[1,3],[2,4]]\n a.zip(b).all? {|pair| pair[0] === pair[1]}\n a.zip(b).all? {|a,b| a === b }\n"
},
{
"answer_id": 263670,
"author": "jonnii",
"author_id": 4590,
"author_profile": "https://Stackoverflow.com/users/4590",
"pm_score": 0,
"selected": false,
"text": "a.eql?(b)\n a = %w[a b c]\nb = %w[1 2 3]\nc = ['a', 'b', 'c']\n\na.eql?(b) # => false\na.eql?(c) # => true\na.eql?(c.reverse) # => false\n"
},
{
"answer_id": 266848,
"author": "jonnii",
"author_id": 4590,
"author_profile": "https://Stackoverflow.com/users/4590",
"pm_score": -1,
"selected": false,
"text": "it \"returns true if other has the same length and each pair of corresponding elements are eql\" do\n a = [1, 2, 3, 4]\n b = [1, 2, 3, 4]\n a.should eql(b)\n [].should eql([])\nend\n"
}
] |
2008/11/04
|
[
"https://Stackoverflow.com/questions/263623",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/34443/"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.