qid
int64 4
19.1M
| question
stringlengths 18
48.3k
| answers
list | date
stringlengths 10
10
| metadata
list |
---|---|---|---|---|
28,952 |
<p>Is it possible to get a breakdown of CPU utilization <strong>by database</strong>?</p>
<p>I'm ideally looking for a Task Manager type interface for SQL server, but instead of looking at the CPU utilization of each PID (like <code>taskmgr</code>) or each SPID (like <code>spwho2k5</code>), I want to view the total CPU utilization of each database. Assume a single SQL instance.</p>
<p>I realize that tools could be written to collect this data and report on it, but I'm wondering if there is any tool that lets me see a live view of which databases are contributing most to the <code>sqlservr.exe</code> CPU load.</p>
|
[
{
"answer_id": 488509,
"author": "Brent Ozar",
"author_id": 26837,
"author_profile": "https://Stackoverflow.com/users/26837",
"pm_score": 8,
"selected": true,
"text": "SELECT total_worker_time/execution_count AS AvgCPU \n, total_worker_time AS TotalCPU\n, total_elapsed_time/execution_count AS AvgDuration \n, total_elapsed_time AS TotalDuration \n, (total_logical_reads+total_physical_reads)/execution_count AS AvgReads \n, (total_logical_reads+total_physical_reads) AS TotalReads\n, execution_count \n, SUBSTRING(st.TEXT, (qs.statement_start_offset/2)+1 \n, ((CASE qs.statement_end_offset WHEN -1 THEN datalength(st.TEXT) \nELSE qs.statement_end_offset \nEND - qs.statement_start_offset)/2) + 1) AS txt \n, query_plan\nFROM sys.dm_exec_query_stats AS qs \ncross apply sys.dm_exec_sql_text(qs.sql_handle) AS st \ncross apply sys.dm_exec_query_plan (qs.plan_handle) AS qp \nORDER BY 1 DESC\n USE msdb\nDECLARE @StringToExecute VARCHAR(1000)\nSET @StringToExecute = 'SELECT * FROM AdventureWorks.dbo.ErrorLog'\nEXEC @StringToExecute\n"
},
{
"answer_id": 10094733,
"author": "friism",
"author_id": 2942,
"author_profile": "https://Stackoverflow.com/users/2942",
"pm_score": 3,
"selected": false,
"text": "select dbs.name, cacheobjtype, total_cpu_time, total_execution_count from\n (select top 10\n sum(qs.total_worker_time) as total_cpu_time, \n sum(qs.execution_count) as total_execution_count, \n count(*) as number_of_statements, \n qs.plan_handle\n from \n sys.dm_exec_query_stats qs \n group by qs.plan_handle\n order by sum(qs.total_worker_time) desc\n ) a\ninner join \n(SELECT plan_handle, pvt.dbid, cacheobjtype\nFROM (\n SELECT plan_handle, epa.attribute, epa.value, cacheobjtype\n FROM sys.dm_exec_cached_plans \n OUTER APPLY sys.dm_exec_plan_attributes(plan_handle) AS epa\n /* WHERE cacheobjtype = 'Compiled Plan' AND objtype = 'adhoc' */) AS ecpa \nPIVOT (MAX(ecpa.value) FOR ecpa.attribute IN (\"dbid\", \"sql_handle\")) AS pvt\n) b on a.plan_handle = b.plan_handle\ninner join sys.databases dbs on dbid = dbs.database_id\n"
},
{
"answer_id": 31783992,
"author": "Anvesh",
"author_id": 2281778,
"author_profile": "https://Stackoverflow.com/users/2281778",
"pm_score": 0,
"selected": false,
"text": "SELECT \n DB_NAME(st.dbid) AS DatabaseName\n ,OBJECT_SCHEMA_NAME(st.objectid,dbid) AS SchemaName\n ,cp.objtype AS ObjectType\n ,OBJECT_NAME(st.objectid,dbid) AS Objects\n ,MAX(cp.usecounts)AS Total_Execution_count\n ,SUM(qs.total_worker_time) AS Total_CPU_Time\n ,SUM(qs.total_worker_time) / (max(cp.usecounts) * 1.0) AS Avg_CPU_Time \nFROM sys.dm_exec_cached_plans cp \nINNER JOIN sys.dm_exec_query_stats qs \n ON cp.plan_handle = qs.plan_handle\nCROSS APPLY sys.dm_exec_sql_text(cp.plan_handle) st\nWHERE DB_NAME(st.dbid) IS NOT NULL\nGROUP BY DB_NAME(st.dbid),OBJECT_SCHEMA_NAME(objectid,st.dbid),cp.objtype,OBJECT_NAME(objectid,st.dbid) \nORDER BY sum(qs.total_worker_time) desc\n"
},
{
"answer_id": 39525462,
"author": "Eduard Okhvat",
"author_id": 6838246,
"author_profile": "https://Stackoverflow.com/users/6838246",
"pm_score": 1,
"selected": false,
"text": "select session_id, cpu_time, program_name, login_name, database_id \n from sys.dm_exec_sessions \n where session_id > 50;\n\nselect sum(cpu_time)/1000 as cpu_seconds, database_id \n from sys.dm_exec_sessions \ngroup by database_id\norder by cpu_seconds desc;\n"
}
] |
2008/08/26
|
[
"https://Stackoverflow.com/questions/28952",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1690/"
] |
28,965 |
<p>Watching SO come online has been quite an education for me. I'd like to make a checklist of various vunerabilities and exploits used against web sites, and what programming techniques can be used to defend against them.</p>
<ul>
<li>What categories of vunerabilities?
<ul>
<li>crashing site</li>
<li>breaking into server</li>
<li>breaking into other people's logins</li>
<li>spam</li>
<li><a href="http://en.wikipedia.org/wiki/Internet_sock_puppet" rel="nofollow noreferrer">sockpuppeting</a>, <a href="http://en.wikipedia.org/wiki/Internet_sock_puppet#Meatpuppet" rel="nofollow noreferrer">meatpuppeting</a></li>
<li>etc...</li>
</ul></li>
<li>What kind of defensive programming techniques?</li>
<li>etc...</li>
</ul>
|
[
{
"answer_id": 28978,
"author": "Ross",
"author_id": 2025,
"author_profile": "https://Stackoverflow.com/users/2025",
"pm_score": 2,
"selected": false,
"text": "mysql_real_escape_string"
}
] |
2008/08/26
|
[
"https://Stackoverflow.com/questions/28965",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/116/"
] |
28,975 |
<p>I've followed the <a href="http://incubator.apache.org/couchdb/index.html" rel="noreferrer">CouchDB</a> project with interest over the last couple of years, and see it is now an Apache Incubator project. Prior to that, the CouchDB web site was full of <em>do not use for production code</em> type disclaimers, so I'd done no more than keep an eye on it. I'd be interested to know your experiences if you've been using CouchDB either for a live project, or a technology pilot. </p>
|
[
{
"answer_id": 29060,
"author": "Till",
"author_id": 2859,
"author_profile": "https://Stackoverflow.com/users/2859",
"pm_score": 4,
"selected": false,
"text": "GET 0.10.x 0.9.1"
}
] |
2008/08/26
|
[
"https://Stackoverflow.com/questions/28975",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2745/"
] |
28,982 |
<p>Related to my <a href="https://stackoverflow.com/questions/28975/anyone-using-couchdb">CouchDB</a> question.</p>
<p>Can anyone explain MapReduce in terms a numbnuts could understand?</p>
|
[
{
"answer_id": 29029,
"author": "Damien B",
"author_id": 3069,
"author_profile": "https://Stackoverflow.com/users/3069",
"pm_score": 4,
"selected": false,
"text": "for each document\n for each word in the document\n get the counter associated to the word for the document\n increment that counter \n end for\nend for\n Map phase (input: document key, document)\nfor each word in the document\n emit an event with the word as the key and the value \"1\"\nend for\n\nReduce phase (input: key (a word), an iterator going through the emitted values)\nfor each value in the iterator\n sum up the value in a counter\nend for\n"
},
{
"answer_id": 29086,
"author": "Johnno Nolan",
"author_id": 1116,
"author_profile": "https://Stackoverflow.com/users/1116",
"pm_score": 6,
"selected": false,
"text": "SELECT SUM(salary)\nFROM employees\nWHERE salary > 1000\nGROUP by deptname\n"
},
{
"answer_id": 30655,
"author": "chakrit",
"author_id": 3055,
"author_profile": "https://Stackoverflow.com/users/3055",
"pm_score": 8,
"selected": false,
"text": "A = [1, 2, 3]\nforeach (item in A) A[item] = A[item] * 2\n A = [1, 2, 3].Map(x => x * 2)\n 1 : 1 => 1 * 2 : 2 \n2 : 2 => 2 * 2 : 4 \n3 : 3 => 3 * 2 : 6 \n A = [7, 8, 9]\nsum = 0\nforeach (item in A) sum = sum + A[item]\n A = [7, 8, 9]\nsum = A.reduce( 0, (x, y) => x + y )\n result = 0\n7 : result = result + 7 = 0 + 7 = 7\n8 : result = result + 8 = 7 + 8 = 15\n9 : result = result + 9 = 15 + 9 = 24\n result = A = [7, 8, 9]\nB = [1, 2, 3]\nsum = 0\nsum = A.reduce( sum, (x, y) => x + y )\nsum = B.reduce( sum, (x, y) => x + y )\n A = [7, 8, 9]\nB = [1, 2, 3]\n\nsum_func = (x, y) => x + y\nsum = A.reduce( B.reduce( 0, sum_func ), sum_func )\n"
},
{
"answer_id": 762443,
"author": "Rainer Joswig",
"author_id": 69545,
"author_profile": "https://Stackoverflow.com/users/69545",
"pm_score": 5,
"selected": false,
"text": "(defparameter *cities*\n '((a :people 100000 :size 200)\n (b :people 200000 :size 300)\n (c :people 150000 :size 210)))\n (map 'list\n (lambda (city)\n (list (first city)\n (/ (getf (rest city) :people)\n (getf (rest city) :size))))\n *cities*)\n\n=> ((A 500) (B 2000/3) (C 5000/7))\n (reduce (lambda (a b)\n (if (> (second a) (second b))\n a\n b))\n '((A 500) (B 2000/3) (C 5000/7)))\n\n => (C 5000/7)\n (reduce (lambda (a b)\n (if (> (second a) (second b))\n a\n b))\n (map 'list\n (lambda (city)\n (list (first city)\n (/ (getf (rest city) :people)\n (getf (rest city) :size))))\n *cities*))\n (defun density (city)\n (list (first city)\n (/ (getf (rest city) :people)\n (getf (rest city) :size))))\n\n(defun max-density (a b)\n (if (> (second a) (second b))\n a\n b))\n (reduce 'max-density\n (map 'list 'density *cities*))\n\n => (C 5000/7)\n MAP REDUCE"
},
{
"answer_id": 6584690,
"author": "Mike Dewar",
"author_id": 270572,
"author_profile": "https://Stackoverflow.com/users/270572",
"pm_score": 2,
"selected": false,
"text": "cat input | map | reduce > output\n"
},
{
"answer_id": 26993598,
"author": "Prometheus",
"author_id": 2587178,
"author_profile": "https://Stackoverflow.com/users/2587178",
"pm_score": 4,
"selected": false,
"text": "map(String key, String value):\n\n// key: document name\n// value: document contents\nfor each word w in value:\nEmitIntermediate(w, “1”);\n\nreduce(String key, Iterator values):\n\n// key: a word\n// values: a list of counts\nint result = 0;\nfor each v in values:\n result += ParseInt(v);\nEmit(AsString(result));\n"
},
{
"answer_id": 35546776,
"author": "Rafay",
"author_id": 569085,
"author_profile": "https://Stackoverflow.com/users/569085",
"pm_score": 3,
"selected": false,
"text": "In [2]: data = [1, 2, 3, 4, 5, 6]\nIn [3]: mapped_result = map(lambda x: x*2, data)\n\nIn [4]: mapped_result\nOut[4]: [2, 4, 6, 8, 10, 12]\n\nIn [10]: final_result = reduce(lambda x, y: x+y, mapped_result)\n\nIn [11]: final_result\nOut[11]: 42\n mapped_result 42 thread_1 [1, 2, 3] thread_2 [4, 5, 6] [2, 4, 6, 8, 10, 12]"
}
] |
2008/08/26
|
[
"https://Stackoverflow.com/questions/28982",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2745/"
] |
29,004 |
<p>Sometimes I need to quickly extract some arbitrary data from XML files to put into a CSV format. What's your best practices for doing this in the Unix terminal? I would love some code examples, so for instance how can I get the following problem solved?</p>
<p>Example XML input:</p>
<pre class="lang-html prettyprint-override"><code><root>
<myel name="Foo" />
<myel name="Bar" />
</root>
</code></pre>
<p>My desired CSV output:</p>
<pre><code>Foo,
Bar,
</code></pre>
|
[
{
"answer_id": 29023,
"author": "Peter Hilton",
"author_id": 2670,
"author_profile": "https://Stackoverflow.com/users/2670",
"pm_score": 3,
"selected": false,
"text": "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>\n<xsl:stylesheet version=\"1.0\" xmlns:xsl=\"http://www.w3.org/1999/XSL/Transform\">\n <xsl:output method=\"text\"/>\n\n <xsl:template match=\"root\">\n <xsl:apply-templates select=\"myel\"/>\n </xsl:template>\n\n <xsl:template match=\"myel\">\n <xsl:for-each select=\"@*\">\n <xsl:value-of select=\".\"/>\n <xsl:value-of select=\"','\"/>\n </xsl:for-each>\n <xsl:text> </xsl:text>\n </xsl:template> \n</xsl:stylesheet>\n"
},
{
"answer_id": 29602,
"author": "jelovirt",
"author_id": 2679,
"author_profile": "https://Stackoverflow.com/users/2679",
"pm_score": 4,
"selected": false,
"text": "<xsl:stylesheet xmlns:xsl=\"http://www.w3.org/1999/XSL/Transform\" version=\"1.0\">\n <xsl:output method=\"text\"/>\n <xsl:template match=\"root\">\n <xsl:for-each select=\"myel\">\n <xsl:value-of select=\"@name\"/>\n <xsl:text>,</xsl:text>\n <xsl:if test=\"not(position() = last())\">\n <xsl:text>
</xsl:text>\n </xsl:if>\n </xsl:for-each>\n </xsl:template>\n</xsl:stylesheet>\n xsltproc stylesheet.xsl source.xml\n"
},
{
"answer_id": 29670,
"author": "AndrewR",
"author_id": 2994,
"author_profile": "https://Stackoverflow.com/users/2994",
"pm_score": 2,
"selected": false,
"text": "#!/usr/bin/ruby -w\n\nrequire 'rexml/document'\n\nxml = REXML::Document.new(File.open(ARGV[0].to_s))\nxml.elements.each(\"//myel\") { |el| puts \"#{el.attributes['name']},\" if el.attributes['name'] }\n"
},
{
"answer_id": 58479,
"author": "DaveP",
"author_id": 3577,
"author_profile": "https://Stackoverflow.com/users/3577",
"pm_score": 3,
"selected": false,
"text": "cat file.xml | xml sel -t -m 'xpathExpression' -v 'elemName' 'literal' -v 'elname' -n\n"
},
{
"answer_id": 90983,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "sed -n 's/^\\s`*`<myel\\s`*`name=\"\\([^\"]`*`\\)\".`*`$/\\1,/p' test.xml\n"
},
{
"answer_id": 21250512,
"author": "Uday Thombre",
"author_id": 3217934,
"author_profile": "https://Stackoverflow.com/users/3217934",
"pm_score": 1,
"selected": false,
"text": "<root>\n<myel name=\"Foo\" />\n<myel name=\"Bar\" />\n</root>\n cat text.xml | tr -s \"\\\"\" \" \" | awk '{printf \"%s,\\n\", $3}'\n"
},
{
"answer_id": 64622701,
"author": "Reino",
"author_id": 2703456,
"author_profile": "https://Stackoverflow.com/users/2703456",
"pm_score": 1,
"selected": false,
"text": "xidel -s input.xml -e '//myel/concat(@name,\",\")'\n"
},
{
"answer_id": 74336359,
"author": "jpseng",
"author_id": 16332641,
"author_profile": "https://Stackoverflow.com/users/16332641",
"pm_score": 0,
"selected": false,
"text": "<root>\n <myel name=\"Foo\" />\n <myel name=\"Bar\">\n <mysubel>stairway to heaven</mysubel>\n </myel>\n</root>\n yq e '.root.myel.0.+name' $INPUT yq e '.root.myel.0.+@name' $INPUT Foo\n yq yq --input-format xml --output-format props $INPUT root.myel.0.+name = Foo\nroot.myel.1.+name = Bar\nroot.myel.1.mysubel = stairway to heaven\n yq yq --input-format xml --output-format json $INPUT {\n \"root\": {\n \"myel\": [\n {\n \"+name\": \"Foo\"\n },\n {\n \"+name\": \"Bar\",\n \"mysubel\": \"stairway to heaven\"\n }\n ]\n }\n}\n yq --input-format xml $FILE YAML root:\n myel:\n - +name: Foo\n - +name: Bar\n mysubel: stairway to heaven\n"
}
] |
2008/08/26
|
[
"https://Stackoverflow.com/questions/29004",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/261/"
] |
29,011 |
<p>I have</p>
<pre><code>class Foo < ActiveRecord::Base
named_scope :a, lambda { |a| :conditions => { :a => a } }
named_scope :b, lambda { |b| :conditions => { :b => b } }
end
</code></pre>
<p>I'd like</p>
<pre><code>class Foo < ActiveRecord::Base
named_scope :ab, lambda { |a,b| :conditions => { :a => a, :b => b } }
end
</code></pre>
<p>but I'd prefer to do it in a DRY fashion. I can get the same effect by using</p>
<pre><code> Foo.a(something).b(something_else)
</code></pre>
<p>but it's not particularly lovely.</p>
|
[
{
"answer_id": 30719,
"author": "PJ.",
"author_id": 3230,
"author_profile": "https://Stackoverflow.com/users/3230",
"pm_score": 3,
"selected": true,
"text": "\n def self.ab(a, b)\n a(a).b(b)\n end\n "
},
{
"answer_id": 30753,
"author": "James A. Rosen",
"author_id": 1190,
"author_profile": "https://Stackoverflow.com/users/1190",
"pm_score": 0,
"selected": false,
"text": "Foo.ab(x, y).c(z)\n ab(x, y) b(y)"
},
{
"answer_id": 847512,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "@category.products.ab(x, y)\n named_scope :a, :conditions => {}\nnamed_scope :b, :conditions => {}\nnamed_scope :ab, :through => [:a, :b]\n"
},
{
"answer_id": 3290095,
"author": "Oinak",
"author_id": 97635,
"author_profile": "https://Stackoverflow.com/users/97635",
"pm_score": 1,
"selected": false,
"text": "class Thing\n #...\n named_scope :billable_by, lambda{|user| {:conditions => {:billable_id => user.id } } }\n named_scope :billable_by_tom, lambda{ self.billable_by(User.find_by_name('Tom').id).proxy_options }\n #...\nend\n"
},
{
"answer_id": 3672581,
"author": "aceofspades",
"author_id": 237150,
"author_profile": "https://Stackoverflow.com/users/237150",
"pm_score": 0,
"selected": false,
"text": "class Foo < ActiveRecord::Base\n #named_scope :ab, lambda { |a,b| :conditions => { :a => a, :b => b } }\n # alias_scope, returns a Scope defined procedurally\n alias_scope :ab, lambda {\n Foo.a.b\n }\nend\n"
},
{
"answer_id": 30533540,
"author": "Meta Lambda",
"author_id": 2481743,
"author_profile": "https://Stackoverflow.com/users/2481743",
"pm_score": 4,
"selected": false,
"text": "scope :optional, ->() {where(option: true)}\nscope :accepted, ->() {where(accepted: true)}\nscope :optional_and_accepted, ->() { self.optional.merge(self.accepted) }\n"
}
] |
2008/08/26
|
[
"https://Stackoverflow.com/questions/29011",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1190/"
] |
29,040 |
<p>I have one table "orders" with a foreing key "ProductID".</p>
<p>I want to show the orders in a grid with the <strong>product name</strong>, without <strong>LazyLoad</strong> for better performance, but I if use <strong>DataLoadOptions</strong> it retrieves <strong>all</strong> Product fields, which seams like a <strong>overkill</strong>.</p>
<p>Is there a way to retrieve <strong>only</strong> the Product name in the first query?
Can I set some attribute in the DBML?</p>
<p>In this <a href="http://visualstudiomagazine.com/listings/list.aspx?id=566" rel="nofollow noreferrer">table</a> says that "Foreign-key values" are "Visible" in Linq To SQL, but don't know what this means.</p>
<p><strong>Edit</strong>: Changed the title, because I'm not really sure the there is no solution.<br>
Can't believe no one has the same problem, it is a very common scenario.</p>
|
[
{
"answer_id": 29069,
"author": "Scott Wisniewski",
"author_id": 1737192,
"author_profile": "https://Stackoverflow.com/users/1737192",
"pm_score": 0,
"selected": false,
"text": "var q = from p in dataContext.products select p.ProductName;\nvar results = q.ToList();\n"
},
{
"answer_id": 29119,
"author": "liammclennan",
"author_id": 2785,
"author_profile": "https://Stackoverflow.com/users/2785",
"pm_score": 3,
"selected": false,
"text": "from order in DB.GetTable<Orders>()\njoin product in DB.GetTable<Products>()\non order.ProductID = product.ID\nselect new { ID = order.ID, Name = order.Name, ProductName = product.Name };\n"
}
] |
2008/08/26
|
[
"https://Stackoverflow.com/questions/29040",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2385/"
] |
29,053 |
<p>Code:</p>
<pre><code><html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Unusual Array Lengths!</title>
<script type="text/javascript">
var arrayList = new Array();
arrayList = [1, 2, 3, 4, 5, ];
alert(arrayList.length);
</script>
</head>
<body>
</body>
</html>
</code></pre>
<p>Notice the extra comma in the array declaration.
The code above gives different outputs for various browsers:</p>
<p>Safari: 5</p>
<p>Firefox: 5</p>
<p>IE: 6</p>
<p>The extra comma in the array is being ignored by Safari and FF while IE treats it as another object in the array.</p>
<p>On some search, I have found mixed opinions about which answer is correct. Most people say that IE is correct but then Safari is also doing the same thing as Firefox. I haven't tested this on other browsers like Opera but I assume that there are discrepancies.</p>
<p>My questions:</p>
<p>i. <strong>Which one of these is correct?</strong></p>
<p><em>Edit: By general consensus (and ECMAScript guidelines) we assume that IE is again at fault.</em> </p>
<p>ii. <strong>Are there any other such Javascript browser quirks that I should be wary of?</strong></p>
<p><em>Edit: Yes, there are loads of Javascript quirks. <a href="http://www.quirksmode.org" rel="nofollow noreferrer">www.quirksmode.org</a> is a good resource for the same.</em></p>
<p>iii. <strong>How do I avoid errors such as these?</strong></p>
<p><em>Edit: Use <a href="http://www.jslint.com/" rel="nofollow noreferrer">JSLint</a> to validate your javascript. Or, use some external <a href="http://openjsan.org/" rel="nofollow noreferrer">libraries</a>. Or, <a href="https://stackoverflow.com/questions/29053/javascript-browser-quirks-arraylength#29062">sanitize</a> your code.</em></p>
<p><em>Thanks to <a href="https://stackoverflow.com/users/3069/damien-b">DamienB</a>, <a href="https://stackoverflow.com/users/1790/jasonbunting">JasonBunting</a>, <a href="https://stackoverflow.com/users/2168/john">John</a> and <a href="https://stackoverflow.com/users/1968/konrad-rudolph">Konrad Rudolph</a> for their inputs.</em></p>
|
[
{
"answer_id": 29062,
"author": "Damien B",
"author_id": 3069,
"author_profile": "https://Stackoverflow.com/users/3069",
"pm_score": 2,
"selected": false,
"text": "if(!arrayList[arrayList.length -1]) arrayList.pop();\n"
}
] |
2008/08/26
|
[
"https://Stackoverflow.com/questions/29053",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/384/"
] |
29,061 |
<p>When I try to use an <strong>ssh</strong> command in a shell script, the command just sits there. Do you have an example of how to use <strong>ssh</strong> in a shell script?</p>
|
[
{
"answer_id": 29078,
"author": "Iker Jimenez",
"author_id": 2697,
"author_profile": "https://Stackoverflow.com/users/2697",
"pm_score": 0,
"selected": false,
"text": "expect"
},
{
"answer_id": 29083,
"author": "Mats Fredriksson",
"author_id": 2973,
"author_profile": "https://Stackoverflow.com/users/2973",
"pm_score": 6,
"selected": true,
"text": "ssh user@host command\n ssh user@host ls\n"
},
{
"answer_id": 29089,
"author": "Steve M",
"author_id": 1693,
"author_profile": "https://Stackoverflow.com/users/1693",
"pm_score": 2,
"selected": false,
"text": "~/.ssh/authorized_keys ssh-agent"
},
{
"answer_id": 29114,
"author": "Jon Ericson",
"author_id": 1438,
"author_profile": "https://Stackoverflow.com/users/1438",
"pm_score": 5,
"selected": false,
"text": "ssh host command\n ssh host \"command1; command2\"\n"
}
] |
2008/08/26
|
[
"https://Stackoverflow.com/questions/29061",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1438/"
] |
29,067 |
<p>I have a repeater that is bound to some data.</p>
<p>I bind to the <strong>ItemDataBound</strong> event, and I am attempting to <strong>programmatically</strong> create a <strong>UserControl</strong>:</p>
<p>In a nutshell:</p>
<pre><code>void rptrTaskList_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
CCTask task = (CCTask)e.Item.DataItem;
if (task is ExecTask)
{
ExecTaskControl foo = new ExecTaskControl();
e.Item.Controls.Add(foo);
}
}
</code></pre>
<p>The problem is that while the binding works, the user control is not rendered to the main page.</p>
|
[
{
"answer_id": 29080,
"author": "FlySwat",
"author_id": 1965,
"author_profile": "https://Stackoverflow.com/users/1965",
"pm_score": 1,
"selected": false,
"text": "ExecTaskControl foo = (ExecTaskControl)LoadControl(\"tasks\\\\ExecTaskControl.ascx\");\n"
},
{
"answer_id": 29543,
"author": "abigblackman",
"author_id": 2279,
"author_profile": "https://Stackoverflow.com/users/2279",
"pm_score": 0,
"selected": false,
"text": "var myPage = new System.Web.UI.Page();\nvar myControl = (Controls.MemberRating)myPage.LoadControl(\"~/Controls/MemberRating.ascx\");\n"
}
] |
2008/08/26
|
[
"https://Stackoverflow.com/questions/29067",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1965/"
] |
29,088 |
<p>What is the difference between a <a href="http://msdn.microsoft.com/en-us/library/system.text.regularexpressions.group.aspx" rel="nofollow noreferrer">Group</a> and a <a href="http://msdn.microsoft.com/en-us/library/system.text.regularexpressions.match.aspx" rel="nofollow noreferrer">Match</a> in .NET's RegEx?</p>
|
[
{
"answer_id": 29108,
"author": "Blair Conrad",
"author_id": 1199,
"author_profile": "https://Stackoverflow.com/users/1199",
"pm_score": 4,
"selected": true,
"text": "string text = \"One car red car blue car\";\nstring pat = @\"(\\w+)\\s+(car)\";\nMatch m = r.Match(text);\n m (\\w+) (car)"
},
{
"answer_id": 29143,
"author": "Mats Fredriksson",
"author_id": 2973,
"author_profile": "https://Stackoverflow.com/users/2973",
"pm_score": 2,
"selected": false,
"text": "// Example I made up on the spot, probably doesn't work very well\n\"(?<protocol>\\w+)://(?<domain>[^/]+)(?<path>/[^?])\"\n Match match = pattern.Match(urls);\nif (!match.Success) \n continue;\nstring protocol = match.Groups[\"protocol\"].Value;\nstring domain = match.Groups[1].Value;\n"
}
] |
2008/08/26
|
[
"https://Stackoverflow.com/questions/29088",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1463/"
] |
29,099 |
<p>Since debate without meaningful terms is <a href="https://stackoverflow.com/questions/24270/whats-the-point-of-oop">meaningless</a>, I figured I would point at the elephant in the room and ask: What exactly makes a language "object-oriented"? I'm not looking for a textbook answer here, but one based on your experiences with OO languages that work well in your domain, whatever it may be.</p>
<p>A related question that might help to answer first is: What is the archetype of object-oriented languages and why?</p>
|
[
{
"answer_id": 29217,
"author": "Quibblesome",
"author_id": 1143,
"author_profile": "https://Stackoverflow.com/users/1143",
"pm_score": -1,
"selected": false,
"text": "foreach(House house in location.Houses)\n{\n foreach(Deliverable mail in new Mailbag(new Deliverable[]\n {\n GetLetters(), \n GetPackages(), \n GetAdvertisingJunk()\n })\n {\n if(mail.AddressedTo(house))\n {\n house.Deliver(mail);\n }\n }\n}\n foreach(Deliverable myMail in GetMail())\n{\n IReadable readable = myMail as IReadable;\n if ( readable != null )\n {\n Console.WriteLine(readable.Text);\n }\n}\n"
},
{
"answer_id": 216593,
"author": "interstar",
"author_id": 8482,
"author_profile": "https://Stackoverflow.com/users/8482",
"pm_score": 3,
"selected": false,
"text": " f(x)\n o.m(x) \n"
}
] |
2008/08/26
|
[
"https://Stackoverflow.com/questions/29099",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3121/"
] |
29,107 |
<p>Can anyone suggest a good implementation of a generic collection class that implements the <code>IBindingListView</code> & <code>IBindingList</code> interfaces and provides Filtering and Searching capabilities?</p>
<p>I see my current options as:<br /></p>
<ul>
<li>Using a class that someone else has written and tested</li>
<li>Inheriting from <code>BindingList<T></code>, and implementing the <code>IBindingListView</code> interfaces</li>
<li>Write a custom collection from scratch, implementing <code>IBindingListView</code> and <code>IBindingList</code>.</li>
</ul>
<p>Obviously, the first option is my preferred choice.</p>
|
[
{
"answer_id": 29146,
"author": "Joseph Daigle",
"author_id": 507,
"author_profile": "https://Stackoverflow.com/users/507",
"pm_score": 1,
"selected": false,
"text": "BindlingList<T> IBindingListView"
},
{
"answer_id": 165333,
"author": "Aaron Wagner",
"author_id": 3909,
"author_profile": "https://Stackoverflow.com/users/3909",
"pm_score": 6,
"selected": true,
"text": "Equin.ApplicationFramework.BindingListView var lst = new List<DemoClass>\n{\n new DemoClass { Prop1 = \"a\", Prop2 = \"b\", Prop3 = \"c\" },\n new DemoClass { Prop1 = \"a\", Prop2 = \"e\", Prop3 = \"f\" },\n new DemoClass { Prop1 = \"b\", Prop2 = \"h\", Prop3 = \"i\" },\n new DemoClass { Prop1 = \"b\", Prop2 = \"k\", Prop3 = \"l\" }\n};\ndataGridView1.DataSource = new BindingListView<DemoClass>(lst);\n// you can now sort by clicking the column headings \n//\n// to filter the view...\nvar view = (BindingListView<DemoClass>)dataGridView1.DataSource; \nview.ApplyFilter(dc => dc.Prop1 == \"a\");\n"
}
] |
2008/08/26
|
[
"https://Stackoverflow.com/questions/29107",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/708/"
] |
29,141 |
<p>The problem: Loading an excel spreadsheet template. Using the Save command with a different filename and then quitting the interop object. This ends up saving the original template file. Not the result that is liked.</p>
<pre><code>public void saveAndExit(string filename)
{
excelApplication.Save(filename);
excelApplication.Quit();
}
</code></pre>
<p>Original file opened is c:\testing\template.xls
The file name that is passed in is c:\testing\7777 (date).xls</p>
<p>Does anyone have an answer?</p>
<p>(The answer I chose was the most correct and thorough though the wbk.Close() requires parameters passed to it. Thanks.)</p>
|
[
{
"answer_id": 29232,
"author": "Kevin Crumley",
"author_id": 1818,
"author_profile": "https://Stackoverflow.com/users/1818",
"pm_score": 4,
"selected": true,
"text": "Microsoft.Office.Interop.Excel.Workbook wbk = excelApplication.Workbooks[0]; //or some other way of obtaining this workbook reference, as Jason Z mentioned\nwbk.SaveAs(filename, Type.Missing, Type.Missing, Type.Missing,\n Type.Missing, Type.Missing, XlSaveAsAccessMode.xlNoChange, \n Type.Missing, Type.Missing, Type.Missing, Type.Missing,\n Type.Missing);\nwbk.Close();\nexcelApplication.Quit();\n"
}
] |
2008/08/26
|
[
"https://Stackoverflow.com/questions/29141",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3135/"
] |
29,142 |
<p>This is a follow-on question to the <a href="https://stackoverflow.com/questions/29061/how-do-you-use-ssh-in-a-shell-script">How do you use ssh in a shell script?</a> question. If I want to execute a command on the remote machine that runs in the background on that machine, how do I get the ssh command to return? When I try to just include the ampersand (&) at the end of the command it just hangs. The exact form of the command looks like this:</p>
<pre><code>ssh user@target "cd /some/directory; program-to-execute &"
</code></pre>
<p>Any ideas? One thing to note is that logins to the target machine always produce a text banner and I have <strong>SSH</strong> keys set up so no password is required.</p>
|
[
{
"answer_id": 29172,
"author": "Jax",
"author_id": 23,
"author_profile": "https://Stackoverflow.com/users/23",
"pm_score": 10,
"selected": true,
"text": "nohup myprogram > foo.out 2> foo.err < /dev/null &\n"
},
{
"answer_id": 30638,
"author": "hometoast",
"author_id": 2009,
"author_profile": "https://Stackoverflow.com/users/2009",
"pm_score": 5,
"selected": false,
"text": "user@localhost $ screen -t remote-command\nuser@localhost $ ssh user@target # now inside of a screen session\nuser@remotehost $ cd /some/directory; program-to-execute &\n screen -ls\n screen -d -r remote-command\n user@localhost $ tmux\nuser@localhost $ ssh user@target # now inside of a tmux session\nuser@remotehost $ cd /some/directory; program-to-execute &\n tmux list-sessions\n tmux attach <session number>\n"
},
{
"answer_id": 56693,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 3,
"selected": false,
"text": "ssh user@target \"cd /some/directory; nohup myprogram > foo.out 2> foo.err < /dev/null\"\n ssh user@target \"cd /some/directory; nohup myprogram > /dev/null 2>&1\"\n"
},
{
"answer_id": 2831449,
"author": "Russ",
"author_id": 340853,
"author_profile": "https://Stackoverflow.com/users/340853",
"pm_score": 8,
"selected": false,
"text": "ssh -n -f user@host \"sh -c 'cd /whereever; nohup ./whatever > /dev/null 2>&1 &'\"\n"
},
{
"answer_id": 4566447,
"author": "Randy Wilson",
"author_id": 558746,
"author_profile": "https://Stackoverflow.com/users/558746",
"pm_score": 0,
"selected": false,
"text": "ssh -i keyFile user@host bash -c \"\\\"nohup ./script arg1 arg2 > output.txt 2>&1 &\\\"\"\n ProcessBuilder b = new ProcessBuilder(\"ssh\", \"-i\", \"keyFile\", \"bash\", \"-c\",\n \"\\\"nohup ./script arg1 arg2 > output.txt 2>&1 &\\\"\");\nProcess process = b.start();\n// then read from process.getInputStream() and close it.\n"
},
{
"answer_id": 6464547,
"author": "Kevin Duterne",
"author_id": 752109,
"author_profile": "https://Stackoverflow.com/users/752109",
"pm_score": -1,
"selected": false,
"text": "a@A:~> ssh-keygen -t rsa\nGenerating public/private rsa key pair.\nEnter file in which to save the key (/home/a/.ssh/id_rsa): \nCreated directory '/home/a/.ssh'.\nEnter passphrase (empty for no passphrase): \nEnter same passphrase again: \nYour identification has been saved in /home/a/.ssh/id_rsa.\nYour public key has been saved in /home/a/.ssh/id_rsa.pub.\nThe key fingerprint is:\n3e:4f:05:79:3a:9f:96:7c:3b:ad:e9:58:37:bc:37:e4 a@A\n a@A:~> ssh b@B mkdir -p .ssh\nb@B's password: \n a@A:~> cat .ssh/id_rsa.pub | ssh b@B 'cat >> .ssh/authorized_keys'\nb@B's password: \n a@A:~> ssh b@B\n"
},
{
"answer_id": 9748364,
"author": "AskApache Webmaster",
"author_id": 1472950,
"author_profile": "https://Stackoverflow.com/users/1472950",
"pm_score": 5,
"selected": false,
"text": "&>/dev/null >/dev/null 2>/dev/null >/dev/null 2>&1 sh -c '( ( command ) & )' ssh askapache 'sh -c \"( ( nohup chown -R ask:ask /www/askapache.com &>/dev/null ) & )\"'\n ssh askapache 'nohup sh -c \"( ( chown -R ask:ask /www/askapache.com &>/dev/null ) & )\"'\n ssh askapache 'nice -n 19 sh -c \"( ( nohup chown -R ask:ask /www/askapache.com &>/dev/null ) & )\"'\n"
},
{
"answer_id": 12288730,
"author": "cmcginty",
"author_id": 64313,
"author_profile": "https://Stackoverflow.com/users/64313",
"pm_score": 4,
"selected": false,
"text": "ssh REMOTE \"sh -c \\\"(nohup sleep 30; touch nohup-exit) > /dev/null &\\\"\"\n"
},
{
"answer_id": 17863122,
"author": "fs82",
"author_id": 2272538,
"author_profile": "https://Stackoverflow.com/users/2272538",
"pm_score": 3,
"selected": false,
"text": "ssh -x remoteServer \"cd yourRemoteDir; ./yourRemoteScript.sh </dev/null >/dev/null 2>&1 & \" \n"
},
{
"answer_id": 21348923,
"author": "MLSC",
"author_id": 2515498,
"author_profile": "https://Stackoverflow.com/users/2515498",
"pm_score": -1,
"selected": false,
"text": "sshpass while read pass port user ip; do\nsshpass -p$pass ssh -p $port $user@$ip <<ENDSSH1\n COMMAND 1\n .\n .\n .\n COMMAND n\nENDSSH1\ndone <<____HERE\n PASS PORT USER IP\n . . . .\n . . . .\n . . . .\n PASS PORT USER IP \n____HERE\n"
},
{
"answer_id": 24696479,
"author": "neil",
"author_id": 3829191,
"author_profile": "https://Stackoverflow.com/users/3829191",
"pm_score": 3,
"selected": false,
"text": "ssh user@target \"at now -f /home/foo.sh\"\n"
},
{
"answer_id": 44525428,
"author": "PaulT",
"author_id": 8155537,
"author_profile": "https://Stackoverflow.com/users/8155537",
"pm_score": 1,
"selected": false,
"text": "# simple_script.sh (located on remote server)\n\n#!/bin/bash\n\ncat /var/log/messages | grep <some value> | awk -F \" \" '{print $8}'\n ssh user@ip \"/path/to/simple_script.sh\"\n"
},
{
"answer_id": 55239462,
"author": "user889030",
"author_id": 889030,
"author_profile": "https://Stackoverflow.com/users/889030",
"pm_score": 2,
"selected": false,
"text": "sudo /home/script.sh -opt1 > /tmp/script.out &\n"
},
{
"answer_id": 56222587,
"author": "zebrilo",
"author_id": 1057470,
"author_profile": "https://Stackoverflow.com/users/1057470",
"pm_score": 2,
"selected": false,
"text": "tmux new -d <shell cmd> ssh someone@elsewhere 'tmux new -d sleep 600'\n elsewhere tmux attach ssh someone@elsewhere 'tmux new -d \"~/myscript.sh; bash\"'\n"
},
{
"answer_id": 60342175,
"author": "richprice316",
"author_id": 12075255,
"author_profile": "https://Stackoverflow.com/users/12075255",
"pm_score": 0,
"selected": false,
"text": "YOUR-COMMAND &> YOUR-LOG.log & \n"
},
{
"answer_id": 60437534,
"author": "ijt",
"author_id": 484529,
"author_profile": "https://Stackoverflow.com/users/484529",
"pm_score": 4,
"selected": false,
"text": "ssh user@host 'myprogram >out.log 2>err.log &'\n"
},
{
"answer_id": 69708739,
"author": "Sathesh",
"author_id": 689956,
"author_profile": "https://Stackoverflow.com/users/689956",
"pm_score": 0,
"selected": false,
"text": "program-to-execute &!"
}
] |
2008/08/26
|
[
"https://Stackoverflow.com/questions/29142",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/171/"
] |
29,145 |
<p>I know that there are a few (automatic) ways to create a data access layer to manipulate an existing database (LINQ to SQL, Hibernate, etc...). But I'm getting kind of tired (and I believe that there should be a better way of doing things) of stuff like:</p>
<ol>
<li>Creating/altering tables in Visio</li>
<li>Using Visio's "Update Database" to create/alter the database</li>
<li>Importing the tables into a "LINQ to SQL classes" object</li>
<li>Changing the code accordingly</li>
<li>Compiling</li>
</ol>
<p>What about a way to generate the database schema from the objects/entities definition? I can't seem to find good references for tools like this (and I would expect some kind of built-in support in at least some frameworks).</p>
<p>It would be perfect if I could just:</p>
<ol>
<li>Change the object definition</li>
<li>Change the code that manipulates the object</li>
<li>Compile (the database changes are done auto-magically)</li>
</ol>
|
[
{
"answer_id": 4281637,
"author": "Lucero",
"author_id": 88558,
"author_profile": "https://Stackoverflow.com/users/88558",
"pm_score": 0,
"selected": false,
"text": "CREATE"
}
] |
2008/08/26
|
[
"https://Stackoverflow.com/questions/29145",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2841/"
] |
29,155 |
<p>What are the differences between delegates and an events? Don't both hold references to functions that can be executed?</p>
|
[
{
"answer_id": 24712324,
"author": "faby",
"author_id": 3515042,
"author_profile": "https://Stackoverflow.com/users/3515042",
"pm_score": 7,
"selected": false,
"text": "public class Animal\n{\n public Action Run {get; set;}\n\n public void RaiseEvent()\n {\n if (Run != null)\n {\n Run();\n }\n }\n}\n Animal animal= new Animal();\nanimal.Run += () => Console.WriteLine(\"I'm running\");\nanimal.Run += () => Console.WriteLine(\"I'm still running\") ;\nanimal.RaiseEvent();\n animal.Run += () => Console.WriteLine(\"I'm running\");\nanimal.Run += () => Console.WriteLine(\"I'm still running\");\nanimal.Run = () => Console.WriteLine(\"I'm sleeping\") ;\n + = += Animal animal.Run() animal.Run.Invoke() events public class ArgsSpecial : EventArgs\n{\n public ArgsSpecial (string val)\n {\n Operation=val;\n }\n\n public string Operation {get; set;}\n} \n\npublic class Animal\n{\n // Empty delegate. In this way you are sure that value is always != null \n // because no one outside of the class can change it.\n public event EventHandler<ArgsSpecial> Run = delegate{} \n \n public void RaiseEvent()\n { \n Run(this, new ArgsSpecial(\"Run faster\"));\n }\n}\n Animal animal= new Animal();\n animal.Run += (sender, e) => Console.WriteLine(\"I'm running. My value is {0}\", e.Operation);\n animal.RaiseEvent();\n animal.Run() animal.Run.Invoke() public delegate void EventHandler (object sender, EventArgs e)\n EventHandler<ArgsSpecial> EventHandler"
},
{
"answer_id": 28581895,
"author": "Miguel Gamboa",
"author_id": 1140754,
"author_profile": "https://Stackoverflow.com/users/1140754",
"pm_score": 3,
"selected": false,
"text": "class interface List Dictionary"
},
{
"answer_id": 29595337,
"author": "Trevor",
"author_id": 258982,
"author_profile": "https://Stackoverflow.com/users/258982",
"pm_score": 3,
"selected": false,
"text": "EventHandler List<Person> class Mediator\n{\n public delegate void PersonChangedDelegate(Person p); //delegate type definition\n public static PersonChangedDelegate PersonChangedDel; //delegate instance. Detail view will \"subscribe\" to this.\n public static void OnPersonChanged(Person p) //Form1 will call this when the drop-down changes.\n {\n if (PersonChangedDel != null)\n {\n PersonChangedDel(p);\n }\n }\n}\n public partial class DetailView : UserControl\n{\n public DetailView()\n {\n InitializeComponent();\n Mediator.PersonChangedDel += DetailView_PersonChanged;\n }\n\n void DetailView_PersonChanged(Person p)\n {\n BindData(p);\n }\n\n public void BindData(Person p)\n {\n lblPersonHairColor.Text = p.HairColor;\n lblPersonId.Text = p.IdPerson.ToString();\n lblPersonName.Text = p.Name;\n lblPersonNickName.Text = p.NickName;\n\n }\n}\n private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)\n{\n Mediator.OnPersonChanged((Person)comboBox1.SelectedItem); //Call the mediator's OnPersonChanged method. This will in turn call all the methods assigned (i.e. subscribed to) to the delegate -- in this case `DetailView_PersonChanged`.\n}\n PersonChangedDel = null class Mediator\n{\n\n private static readonly Mediator _Instance = new Mediator();\n\n private Mediator() { }\n\n public static Mediator GetInstance()\n {\n return _Instance;\n }\n\n public event EventHandler<PersonChangedEventArgs> PersonChanged; //this is just a property we expose to add items to the delegate.\n\n public void OnPersonChanged(object sender, Person p)\n {\n var personChangedDelegate = PersonChanged as EventHandler<PersonChangedEventArgs>;\n if (personChangedDelegate != null)\n {\n personChangedDelegate(sender, new PersonChangedEventArgs() { Person = p });\n }\n }\n}\n public delegate void EventHandler<TEventArgs>(object sender, TEventArgs e);\n public partial class DetailView : UserControl\n{\n public DetailView()\n {\n InitializeComponent();\n Mediator.GetInstance().PersonChanged += DetailView_PersonChanged;\n }\n\n void DetailView_PersonChanged(object sender, PersonChangedEventArgs e)\n {\n BindData(e.Person);\n }\n\n public void BindData(Person p)\n {\n lblPersonHairColor.Text = p.HairColor;\n lblPersonId.Text = p.IdPerson.ToString();\n lblPersonName.Text = p.Name;\n lblPersonNickName.Text = p.NickName;\n\n }\n}\n private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)\n{\n Mediator.GetInstance().OnPersonChanged(this, (Person)comboBox1.SelectedItem);\n}\n class PersonChangedEventArgs\n{\n public Person Person { get; set; }\n}\n"
},
{
"answer_id": 39460456,
"author": "Venkatesh Muniyandi",
"author_id": 4418611,
"author_profile": "https://Stackoverflow.com/users/4418611",
"pm_score": 2,
"selected": false,
"text": " /*\nThis is working program in Visual Studio. It is not running in fiddler because of infinite loop in code.\nThis code demonstrates the difference between event and delegate\n Event is an delegate reference with two restrictions for increased protection\n\n 1. Cannot be invoked directly\n 2. Cannot assign value to delegate reference directly\n\nToggle between Event vs Delegate in the code by commenting/un commenting the relevant lines\n*/\n\npublic class RoomTemperatureController\n{\n private int _roomTemperature = 25;//Default/Starting room Temperature\n private bool _isAirConditionTurnedOn = false;//Default AC is Off\n private bool _isHeatTurnedOn = false;//Default Heat is Off\n private bool _tempSimulator = false;\n public delegate void OnRoomTemperatureChange(int roomTemperature); //OnRoomTemperatureChange is a type of Delegate (Check next line for proof)\n // public OnRoomTemperatureChange WhenRoomTemperatureChange;// { get; set; }//Exposing the delegate to outside world, cannot directly expose the delegate (line above), \n public event OnRoomTemperatureChange WhenRoomTemperatureChange;// { get; set; }//Exposing the delegate to outside world, cannot directly expose the delegate (line above), \n\n public RoomTemperatureController()\n {\n WhenRoomTemperatureChange += InternalRoomTemperatuerHandler;\n }\n private void InternalRoomTemperatuerHandler(int roomTemp)\n {\n System.Console.WriteLine(\"Internal Room Temperature Handler - Mandatory to handle/ Should not be removed by external consumer of ths class: Note, if it is delegate this can be removed, if event cannot be removed\");\n }\n\n //User cannot directly asign values to delegate (e.g. roomTempControllerObj.OnRoomTemperatureChange = delegateMethod (System will throw error)\n public bool TurnRoomTeperatureSimulator\n {\n set\n {\n _tempSimulator = value;\n if (value)\n {\n SimulateRoomTemperature(); //Turn on Simulator \n }\n }\n get { return _tempSimulator; }\n }\n public void TurnAirCondition(bool val)\n {\n _isAirConditionTurnedOn = val;\n _isHeatTurnedOn = !val;//Binary switch If Heat is ON - AC will turned off automatically (binary)\n System.Console.WriteLine(\"Aircondition :\" + _isAirConditionTurnedOn);\n System.Console.WriteLine(\"Heat :\" + _isHeatTurnedOn);\n\n }\n public void TurnHeat(bool val)\n {\n _isHeatTurnedOn = val;\n _isAirConditionTurnedOn = !val;//Binary switch If Heat is ON - AC will turned off automatically (binary)\n System.Console.WriteLine(\"Aircondition :\" + _isAirConditionTurnedOn);\n System.Console.WriteLine(\"Heat :\" + _isHeatTurnedOn);\n\n }\n\n public async void SimulateRoomTemperature()\n {\n while (_tempSimulator)\n {\n if (_isAirConditionTurnedOn)\n _roomTemperature--;//Decrease Room Temperature if AC is turned On\n if (_isHeatTurnedOn)\n _roomTemperature++;//Decrease Room Temperature if AC is turned On\n System.Console.WriteLine(\"Temperature :\" + _roomTemperature);\n if (WhenRoomTemperatureChange != null)\n WhenRoomTemperatureChange(_roomTemperature);\n System.Threading.Thread.Sleep(500);//Every second Temperature changes based on AC/Heat Status\n }\n }\n\n}\n\npublic class MySweetHome\n{\n RoomTemperatureController roomController = null;\n public MySweetHome()\n {\n roomController = new RoomTemperatureController();\n roomController.WhenRoomTemperatureChange += TurnHeatOrACBasedOnTemp;\n //roomController.WhenRoomTemperatureChange = null; //Setting NULL to delegate reference is possible where as for Event it is not possible.\n //roomController.WhenRoomTemperatureChange.DynamicInvoke();//Dynamic Invoke is possible for Delgate and not possible with Event\n roomController.SimulateRoomTemperature();\n System.Threading.Thread.Sleep(5000);\n roomController.TurnAirCondition (true);\n roomController.TurnRoomTeperatureSimulator = true;\n\n }\n public void TurnHeatOrACBasedOnTemp(int temp)\n {\n if (temp >= 30)\n roomController.TurnAirCondition(true);\n if (temp <= 15)\n roomController.TurnHeat(true);\n\n }\n public static void Main(string []args)\n {\n MySweetHome home = new MySweetHome();\n }\n\n\n}\n"
},
{
"answer_id": 64929776,
"author": "VimNing",
"author_id": 5290519,
"author_profile": "https://Stackoverflow.com/users/5290519",
"pm_score": 2,
"selected": false,
"text": "delegate event += -= new // eventTest.SomeoneSay = null; // Compile Error.\n// eventTest.SomeoneSay = new Say(SayHello); // Compile Error.\n delegate public class DelegateTest\n{\n public delegate void Say(); // Define a pointer type \"void <- ()\" named \"Say\".\n private Say say;\n\n public DelegateTest() {\n say = new Say(SayHello); // Setup the field, Say say, first.\n say += new Say(SayGoodBye);\n \n say.Invoke();\n }\n \n public void SayHello() { /* display \"Hello World!\" to your GUI. */ }\n public void SayGoodBye() { /* display \"Good bye!\" to your GUI. */ }\n}\n event public class EventTest\n{\n public delegate void Say();\n public event Say SomeoneSay; // Use the type \"Say\" to define event, an \n // auto-setup-everything-good field for you.\n public EventTest() {\n SomeoneSay += SayHello;\n SomeoneSay += SayGoodBye;\n\n SomeoneSay();\n }\n \n public void SayHello() { /* display \"Hello World!\" to your GUI. */ }\n public void SayGoodBye() { /* display \"Good bye!\" to your GUI. */ }\n}\n"
}
] |
2008/08/26
|
[
"https://Stackoverflow.com/questions/29155",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2993/"
] |
29,157 |
<p>I am using StretchImage because the box is resizable with splitters. It looks like the default is some kind of smooth bilinear filtering, causing my image to be blurry and have moire patterns. </p>
|
[
{
"answer_id": 5079308,
"author": "Alex D",
"author_id": 621520,
"author_profile": "https://Stackoverflow.com/users/621520",
"pm_score": 2,
"selected": false,
"text": " private void Form1_Load(object sender, EventArgs e)\n {\n // set image location\n imgOriginal = new Bitmap(Image.FromFile(@\"C:\\images\\TestImage.bmp\"));\n picBox.Image = imgOriginal;\n\n // set Picture Box Attributes\n picBox.SizeMode = PictureBoxSizeMode.StretchImage;\n\n // set Slider Attributes\n zoomSlider.Minimum = 1;\n zoomSlider.Maximum = 5;\n zoomSlider.SmallChange = 1;\n zoomSlider.LargeChange = 1;\n zoomSlider.UseWaitCursor = false;\n\n SetPictureBoxSize();\n\n // reduce flickering\n this.DoubleBuffered = true;\n }\n\n // picturebox size changed triggers paint event\n private void SetPictureBoxSize()\n {\n Size s = new Size(Convert.ToInt32(imgOriginal.Width * zoomSlider.Value), Convert.ToInt32(imgOriginal.Height * zoomSlider.Value));\n picBox.Size = s;\n }\n\n\n // looks for user trackbar changes\n private void trackBar1_Scroll(object sender, EventArgs e)\n {\n if (zoomSlider.Value > 0)\n {\n SetPictureBoxSize();\n }\n }\n\n // redraws image using nearest neighbour resampling\n private void picBox_Paint_1(object sender, PaintEventArgs e)\n {\n e.Graphics.InterpolationMode = InterpolationMode.NearestNeighbor;\n e.Graphics.DrawImage(\n imgOriginal,\n new Rectangle(0, 0, picBox.Width, picBox.Height),\n // destination rectangle \n 0,\n 0, // upper-left corner of source rectangle\n imgOriginal.Width, // width of source rectangle\n imgOriginal.Height, // height of source rectangle\n GraphicsUnit.Pixel);\n }\n"
},
{
"answer_id": 13484101,
"author": "JYelton",
"author_id": 161052,
"author_profile": "https://Stackoverflow.com/users/161052",
"pm_score": 6,
"selected": true,
"text": "OnPaint using System.Drawing.Drawing2D;\nusing System.Windows.Forms;\n\n/// <summary>\n/// Inherits from PictureBox; adds Interpolation Mode Setting\n/// </summary>\npublic class PictureBoxWithInterpolationMode : PictureBox\n{\n public InterpolationMode InterpolationMode { get; set; }\n\n protected override void OnPaint(PaintEventArgs paintEventArgs)\n {\n paintEventArgs.Graphics.InterpolationMode = InterpolationMode;\n base.OnPaint(paintEventArgs);\n }\n}\n"
}
] |
2008/08/26
|
[
"https://Stackoverflow.com/questions/29157",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2543/"
] |
29,168 |
<p>My master branch layout is like this:</p>
<p><strong>/</strong> <-- top level</p>
<p><strong>/client</strong> <-- desktop client source files</p>
<p><strong>/server</strong> <-- Rails app</p>
<p>What I'd like to do is only pull down the /server directory in my <code>deploy.rb</code>, but I can't seem to find any way to do that. The /client directory is huge, so setting up a hook to copy /server to / won't work very well, it needs to only pull down the Rails app.</p>
|
[
{
"answer_id": 861804,
"author": "Simon Woodside",
"author_id": 102675,
"author_profile": "https://Stackoverflow.com/users/102675",
"pm_score": 2,
"selected": false,
"text": "set :project, \"mysubdirectory\""
},
{
"answer_id": 2047574,
"author": "thodg",
"author_id": 248701,
"author_profile": "https://Stackoverflow.com/users/248701",
"pm_score": 7,
"selected": true,
"text": "set :deploy_subdir, \"project/subdir\"\n require 'capistrano/recipes/deploy/strategy/remote_cache'\n\nclass RemoteCacheSubdir < Capistrano::Deploy::Strategy::RemoteCache\n\n private\n\n def repository_cache_subdir\n if configuration[:deploy_subdir] then\n File.join(repository_cache, configuration[:deploy_subdir])\n else\n repository_cache\n end\n end\n\n def copy_repository_cache\n logger.trace \"copying the cached version to #{configuration[:release_path]}\"\n if copy_exclude.empty? \n run \"cp -RPp #{repository_cache_subdir} #{configuration[:release_path]} && #{mark}\"\n else\n exclusions = copy_exclude.map { |e| \"--exclude=\\\"#{e}\\\"\" }.join(' ')\n run \"rsync -lrpt #{exclusions} #{repository_cache_subdir}/* #{configuration[:release_path]} && #{mark}\"\n end\n end\n\nend\n\n\nset :strategy, RemoteCacheSubdir.new(self)\n"
},
{
"answer_id": 6969505,
"author": "Stephan Wehner",
"author_id": 447469,
"author_profile": "https://Stackoverflow.com/users/447469",
"pm_score": 0,
"selected": false,
"text": "# Capistrano assumes that the repository root is Rails.root\nnamespace :uploads do\n # We have the Rails application in a subdirectory rails_app\n # Capistrano doesn't provide an elegant way to deal with that\n # for the git case. (For subversion it is straightforward.)\n task :mv_rails_app_dir, :roles => :app do\n run \"mv #{release_path}/rails_app/* #{release_path}/ \"\n end\nend\n\nbefore 'deploy:finalize_update', 'uploads:mv_rails_app_dir'\n"
},
{
"answer_id": 8928491,
"author": "Thomas Fankhauser",
"author_id": 408557,
"author_profile": "https://Stackoverflow.com/users/408557",
"pm_score": 3,
"selected": false,
"text": "set :repository, \"[email protected]:name/project.git\"\nset :branch, \"master\"\nset :subdir, \"server\"\n\nafter \"deploy:update_code\", \"deploy:checkout_subdir\"\n\nnamespace :deploy do\n\n desc \"Checkout subdirectory and delete all the other stuff\"\n task :checkout_subdir do\n run \"mv #{current_release}/#{subdir}/ /tmp && rm -rf #{current_release}/* && mv /tmp/#{subdir}/* #{current_release}\"\n end\n\nend\n"
},
{
"answer_id": 21344915,
"author": "Mr Friendly",
"author_id": 3233988,
"author_profile": "https://Stackoverflow.com/users/3233988",
"pm_score": 5,
"selected": false,
"text": "Capfile # Define a new SCM strategy, so we can deploy only a subdirectory of our repo.\nmodule RemoteCacheWithProjectRootStrategy\n def test\n test! \" [ -f #{repo_path}/HEAD ] \"\n end\n\n def check\n test! :git, :'ls-remote', repo_url\n end\n\n def clone\n git :clone, '--mirror', repo_url, repo_path\n end\n\n def update\n git :remote, :update\n end\n\n def release\n git :archive, fetch(:branch), fetch(:project_root), '| tar -x -C', release_path, \"--strip=#{fetch(:project_root).count('/')+1}\"\n end\nend\n deploy.rb # Set up a strategy to deploy only a project directory (not the whole repo)\nset :git_strategy, RemoteCacheWithProjectRootStrategy\nset :project_root, 'relative/path/from/your/repo'\n release git archive --strip tar :repo_tree set :repo_url, 'https://example.com/your_repo.git'\nset :repo_tree, 'relative/path/from/your/repo' # relative path to project root in repo\n"
},
{
"answer_id": 23497408,
"author": "JAlberto",
"author_id": 2699576,
"author_profile": "https://Stackoverflow.com/users/2699576",
"pm_score": 1,
"selected": false,
"text": "# Usage: \n# 1. Drop this file into lib/capistrano/remote_cache_with_project_root_strategy.rb\n# 2. Add the following to your Capfile:\n# require 'capistrano/git'\n# require './lib/capistrano/remote_cache_with_project_root_strategy'\n# 3. Add the following to your config/deploy.rb\n# set :git_strategy, RemoteCacheWithProjectRootStrategy\n# set :project_root, 'subdir/path'\n\n# Define a new SCM strategy, so we can deploy only a subdirectory of our repo.\nmodule RemoteCacheWithProjectRootStrategy\n include Capistrano::Git::DefaultStrategy\n def test\n test! \" [ -f #{repo_path}/HEAD ] \"\n end\n\n def check\n test! :git, :'ls-remote -h', repo_url\n end\n\n def clone\n git :clone, '--mirror', repo_url, repo_path\n end\n\n def update\n git :remote, :update\n end\n\n def release\n git :archive, fetch(:branch), fetch(:project_root), '| tar -x -C', release_path, \"--strip=#{fetch(:project_root).count('/')+1}\"\n end\nend\n"
},
{
"answer_id": 25446122,
"author": "fsainz",
"author_id": 499154,
"author_profile": "https://Stackoverflow.com/users/499154",
"pm_score": 2,
"selected": false,
"text": "set :repository, \"[email protected]:name/project.git\"\nset :branch, \"master\"\nset :subdir, \"relative_path_to_my/subdir\"\n\n\nnamespace :deploy do\n\n desc \"Checkout subdirectory and delete all the other stuff\"\n task :checkout_subdir do\n\n subdir = fetch(:subdir)\n subdir_last_folder = File.basename(subdir)\n release_subdir_path = File.join(release_path, subdir)\n\n tmp_base_folder = File.join(\"/tmp\", \"capistrano_subdir_hack\")\n tmp_destination = File.join(tmp_base_folder, subdir_last_folder)\n\n cmd = []\n # Settings for my-zsh\n # cmd << \"unsetopt nomatch && setopt rmstarsilent\" \n # create temporary folder\n cmd << \"mkdir -p #{tmp_base_folder}\" \n # delete previous temporary files \n cmd << \"rm -rf #{tmp_base_folder}/*\" \n # move subdir contents to tmp \n cmd << \"mv #{release_subdir_path}/ #{tmp_destination}\" \n # delete contents inside release \n cmd << \"rm -rf #{release_path}/*\" \n # move subdir contents to release \n cmd << \"mv #{tmp_destination}/* #{release_path}\" \n cmd = cmd.join(\" && \")\n\n on roles(:app) do\n within release_path do\n execute cmd\n end\n end\n end\n\nend\n\nafter \"deploy:updating\", \"deploy:checkout_subdir\"\n"
}
] |
2008/08/26
|
[
"https://Stackoverflow.com/questions/29168",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/574/"
] |
29,174 |
<p>I'm using <a href="http://jquery.com/" rel="noreferrer">jQuery</a> and <a href="http://www.ericmmartin.com/projects/simplemodal/" rel="noreferrer">SimpleModal</a> in an ASP.Net project to make some nice dialogs for a web app. Unfortunately, any buttons in a modal dialog can no longer execute their postbacks, which is not really acceptable.</p>
<p>There is one source I've found with a <a href="http://blog.hurlman.com/post/jQuery2c-simpleModal2c-and-ASPNet-postbacks-do-not-play-well-together.aspx" rel="noreferrer">workaround</a>, but for the life of me I can't get it to work, mostly because I am not fully understanding all of the necessary steps.</p>
<p>I also have a workaround, which is to replace the postbacks, but it's ugly and probably not the most reliable. I would really like to make the postbacks work again. Any ideas?</p>
<p>UPDATE: I should clarify, the postbacks are not working because the Javascript used to execute the post backs has broken in some way, so nothing happens at all when the button is clicked.</p>
|
[
{
"answer_id": 30846,
"author": "Chris Zwiryk",
"author_id": 734,
"author_profile": "https://Stackoverflow.com/users/734",
"pm_score": 2,
"selected": false,
"text": "btn.OnClientClick = string.Format(\"{0}; dlg.close();\",\n ClientScript.GetPostBackEventReference(btn, null));\n"
},
{
"answer_id": 31338,
"author": "tghw",
"author_id": 2363,
"author_profile": "https://Stackoverflow.com/users/2363",
"pm_score": 6,
"selected": true,
"text": "<form> 'form' 'body' persist: true appendTo"
},
{
"answer_id": 236607,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "function modalShow(dialog) {\n\n // if the user clicks \"Save\" in dialog\n dialog.data.find('#ButtonSave').click(function(ev) {\n ev.preventDefault();\n\n //Perfom validation \n\n // close the dialog\n $.modal.close();\n\n //Fire the click event of the hidden button to cause a postback\n dialog.data.find('#ButtonSaveTask').click();\n });\n\n dialog.data.find(\"#ButtonCancel\").click(function(ev) {\n ev.preventDefault();\n $.modal.close();\n });\n} \n"
},
{
"answer_id": 407194,
"author": "Greg Hurlman",
"author_id": 35,
"author_profile": "https://Stackoverflow.com/users/35",
"pm_score": 0,
"selected": false,
"text": "$('#myJQselector').modal({onClose: mynewClose}); function myNewClose (dialog) { dialog.close(); __doPostBack = newDoPostBack; }"
},
{
"answer_id": 1786639,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "{appendTo:'form'} {appendTo:'#aspnetForm'}"
},
{
"answer_id": 2459299,
"author": "Steve",
"author_id": 295293,
"author_profile": "https://Stackoverflow.com/users/295293",
"pm_score": 2,
"selected": false,
"text": "private void CloseDialog()\n{\n string script = string.Format(@\"closeDialog()\");\n ScriptManager.RegisterClientScriptBlock(this, typeof(Page), UniqueID, script, true);\n}\n function closeDialog() {\n $.modal.close();\n }\n"
},
{
"answer_id": 22773523,
"author": "jcmordan",
"author_id": 2624360,
"author_profile": "https://Stackoverflow.com/users/2624360",
"pm_score": -1,
"selected": false,
"text": "$(\"#simplemodal-overlay\").appendTo('form');\n$(\"#simplemodal-container\").appendTo('form');\n"
}
] |
2008/08/26
|
[
"https://Stackoverflow.com/questions/29174",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2363/"
] |
29,242 |
<p>I work a lot with network and serial communications software, so it is often necessary for me to have code to display or log hex dumps of data packets.</p>
<p>Every time I do this, I write yet another hex-dump routine from scratch. I'm about to do so again, but figured I'd ask here: Is there any good free hex dump code for C++ out there somewhere?</p>
<p>Features I'd like:</p>
<ul>
<li>N bytes per line (where N is somehow configurable)</li>
<li>optional ASCII/UTF8 dump alongside the hex</li>
<li>configurable indentation, per-line prefixes, per-line suffixes, etc.</li>
<li>minimal dependencies (ideally, I'd like the code to all be in a header file, or be a snippet I can just paste in)</li>
</ul>
<p><strong>Edit:</strong> Clarification: I am looking for code that I can easily drop in to my own programs to write to stderr, stdout, log files, or other such output streams. I'm not looking for a command-line hex dump utility.</p>
|
[
{
"answer_id": 29395,
"author": "nohat",
"author_id": 3101,
"author_profile": "https://Stackoverflow.com/users/3101",
"pm_score": 4,
"selected": true,
"text": "xxd vim * Distribute freely and credit me,\n* make money and share with me,\n* lose money and don't ask me.\n hexdump"
},
{
"answer_id": 29865,
"author": "epatel",
"author_id": 842,
"author_profile": "https://Stackoverflow.com/users/842",
"pm_score": 6,
"selected": false,
"text": "#include <ctype.h>\n#include <stdio.h>\n\nvoid hexdump(void *ptr, int buflen) {\n unsigned char *buf = (unsigned char*)ptr;\n int i, j;\n for (i=0; i<buflen; i+=16) {\n printf(\"%06x: \", i);\n for (j=0; j<16; j++) \n if (i+j < buflen)\n printf(\"%02x \", buf[i+j]);\n else\n printf(\" \");\n printf(\" \");\n for (j=0; j<16; j++) \n if (i+j < buflen)\n printf(\"%c\", isprint(buf[i+j]) ? buf[i+j] : '.');\n printf(\"\\n\");\n }\n}\n"
}
] |
2008/08/27
|
[
"https://Stackoverflow.com/questions/29242",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1175/"
] |
29,243 |
<p>Here is my sample code:</p>
<pre><code>from xml.dom.minidom import *
def make_xml():
doc = Document()
node = doc.createElement('foo')
node.innerText = 'bar'
doc.appendChild(node)
return doc
if __name__ == '__main__':
make_xml().writexml(sys.stdout)
</code></pre>
<p>when I run the above code I get this:</p>
<pre><code><?xml version="1.0" ?>
<foo/>
</code></pre>
<p>I would like to get:</p>
<pre><code><?xml version="1.0" ?>
<foo>bar</foo>
</code></pre>
<p>I just guessed that there was an innerText property, it gives no compiler error, but does not seem to work... how do I go about creating a text node?</p>
|
[
{
"answer_id": 29255,
"author": "dF.",
"author_id": 3002,
"author_profile": "https://Stackoverflow.com/users/3002",
"pm_score": 4,
"selected": true,
"text": "node.noSuchAttr = 'bar' minidom ElementTree import sys\nfrom xml.etree.cElementTree import Element, ElementTree\n\ndef make_xml():\n node = Element('foo')\n node.text = 'bar'\n doc = ElementTree(node)\n return doc\n\nif __name__ == '__main__':\n make_xml().write(sys.stdout)\n"
},
{
"answer_id": 29262,
"author": "mmattax",
"author_id": 1638,
"author_profile": "https://Stackoverflow.com/users/1638",
"pm_score": 4,
"selected": false,
"text": "\nfrom xml.dom.minidom import *\ndef make_xml():\n doc = Document();\n node = doc.createElement('foo')\n node.appendChild(doc.createTextNode('bar'))\n doc.appendChild(node)\n return doc\nif __name__ == '__main__':\n make_xml().writexml(sys.stdout)\n"
}
] |
2008/08/27
|
[
"https://Stackoverflow.com/questions/29243",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1638/"
] |
29,244 |
<p>I have the following HTML (note the CSS making the background black and text white)</p>
<pre><code><html>
<select id="opts" style="background-color: black; color: white;">
<option>first</option>
<option>second</option>
</select>
</html>
</code></pre>
<p>Safari is smart enough to make the small triangle that appears to the right of the text the same color as the foreground text.</p>
<p>Other browsers basically ignore the CSS, so they're fine too.</p>
<p>Firefox 3 however applies the background color but leaves the triangle black, so you can't see it, like this</p>
<p><img src="https://i.stack.imgur.com/Mvc7a.jpg" alt="Example"></p>
<p>I can't find out how to fix this - can anyone help? Is there a <code>-moz-select-triangle-color</code> or something obscure like that?</p>
|
[
{
"answer_id": 29439,
"author": "RedWolves",
"author_id": 648,
"author_profile": "https://Stackoverflow.com/users/648",
"pm_score": 3,
"selected": true,
"text": "Vista XP SP 2"
},
{
"answer_id": 365359,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "select {\n background-image: url(../images/selectBox.gif);\n background-position: right;\n background-repeat: no-repeat;\n}\n"
},
{
"answer_id": 650183,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "select:-moz-system-metric(windows-default-theme) {\n background-image: url(../images/selectBox.gif);\n background-position: right;\n background-repeat: no-repeat;\n}\n"
}
] |
2008/08/27
|
[
"https://Stackoverflow.com/questions/29244",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/234/"
] |
29,284 |
<p>I was testing on a customer's box this afternoon which has Windows Vista (He had home, but I am testing on a Business Edition with same results).</p>
<p>We make use of a .DLL that gets the Hardware ID of the computer. It's usage is very simple and the sample program I have created works. The Dll is <a href="http://www.azsdk.com/hardwareid.html" rel="nofollow noreferrer">This from AzSdk</a>.
In fact, this works perfectly under Windows XP. However, for some strange reason, inside our project (way bigger), we get this exception: </p>
<pre><code>Exception Type: System.DllNotFoundException
Exception Message: Unable to load DLL 'HardwareID.dll': Invalid access to memory location. (Exception from HRESULT: 0x800703E6)
Exception Target Site: GetHardwareID
</code></pre>
<p>I don't know what can be causing the problem, since I have full control over the folder. The project is a c#.net Windows Forms application and everything works fine, except the call for the external library. </p>
<p>I am declaring it like this: (note: it's <em>not</em> a COM library and it doesn't need to be registered).</p>
<pre><code>[DllImport("HardwareID.dll")]
public static extern String GetHardwareID(bool HDD,
bool NIC, bool CPU, bool BIOS, string sRegistrationCode);
</code></pre>
<p>And then the calling code is quite simple:</p>
<pre><code>private void button1_Click(object sender, EventArgs e)
{
textBox1.Text = GetHardwareID(cb_HDD.Checked,
cb_NIC.Checked,
cb_CPU.Checked,
cb_BIOS.Checked,
"*Registration Code*");
}
</code></pre>
<p>When you create a sample application, it works, but inside my projectit doesn't. Under XP works fine. Any ideas about what should I do in Vista to make this work?
As I've said, the folder and its sub-folders have Full Control for "Everybody". </p>
<p><strong>UPDATE:</strong> I do not have Vista SP 1 installed. </p>
<p><strong>UPDATE 2:</strong> I have installed Vista SP1 and now, with UAC disabled, not even the simple sample works!!! :( Damn Vista.</p>
|
[
{
"answer_id": 30886,
"author": "imaginaryboy",
"author_id": 2508,
"author_profile": "https://Stackoverflow.com/users/2508",
"pm_score": 0,
"selected": false,
"text": "icacls C:\\Folder\n"
}
] |
2008/08/27
|
[
"https://Stackoverflow.com/questions/29284",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2684/"
] |
29,308 |
<p>In the <a href="http://herdingcode.com/" rel="nofollow noreferrer">herding code</a> podcast 14 someone mentions that stackoverflow displayed the queries that were executed during a request at the bottom of the page. </p>
<p>It sounds like an excellent idea to me. Every time a page loads I want to know what sql statements are executed and also a count of the total number of DB round trips.
Does anyone have a neat solution to this problem? </p>
<p>What do you think is an acceptable number of queries? I was thinking that during development I might have my application throw an exception if more than 30 queries are required to render a page.</p>
<p>EDIT: I think I must not have explained my question clearly. During a HTTP request a web application might execute a dozen or more sql statements. I want to have those statements appended to the bottom of the page, along with a count of the number of statements.</p>
<p>HERE IS MY SOLUTION:</p>
<p>I created a TextWriter class that the DataContext can write to:</p>
<pre><code>public class Logger : StreamWriter
{
public string Buffer { get; private set; }
public int QueryCounter { get; private set; }
public Logger() : base(new MemoryStream())
{}
public override void Write(string value)
{
Buffer += value + "<br/><br/>";
if (!value.StartsWith("--")) QueryCounter++;
}
public override void WriteLine(string value)
{
Buffer += value + "<br/><br/>";
if (!value.StartsWith("--")) QueryCounter++;
}
}
</code></pre>
<p>In the DataContext's constructor I setup the logger:</p>
<pre><code>public HeraldDBDataContext()
: base(ConfigurationManager.ConnectionStrings["Herald"].ConnectionString, mappingSource)
{
Log = new Logger();
}
</code></pre>
<p>Finally, I use the <code>Application_OnEndRequest</code> event to add the results to the bottom of the page:</p>
<pre><code>protected void Application_OnEndRequest(Object sender, EventArgs e)
{
Logger logger = DataContextFactory.Context.Log as Logger;
Response.Write("Query count : " + logger.QueryCounter);
Response.Write("<br/><br/>");
Response.Write(logger.Buffer);
}
</code></pre>
|
[
{
"answer_id": 29319,
"author": "Jedi Master Spooky",
"author_id": 1154,
"author_profile": "https://Stackoverflow.com/users/1154",
"pm_score": 2,
"selected": false,
"text": "var query = from p in db.Table\n select p;\n\nMessageBox.SHow(query.ToString());\n"
},
{
"answer_id": 29453,
"author": "FlySwat",
"author_id": 1965,
"author_profile": "https://Stackoverflow.com/users/1965",
"pm_score": 2,
"selected": false,
"text": "System.IO.StreamWriter httpResponseStreamWriter = \nnew StreamWriter(HttpContext.Current.Response.OutputStream);\n\ndataContext.Log = httpResponseStreamWriter;\n"
}
] |
2008/08/27
|
[
"https://Stackoverflow.com/questions/29308",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2785/"
] |
29,324 |
<p>What is the most straightforward way to create a hash table (or associative array...) in Java? My google-fu has turned up a couple examples, but is there a standard way to do this?</p>
<p>And is there a way to populate the table with a list of key->value pairs without individually calling an add method on the object for each pair?</p>
|
[
{
"answer_id": 29334,
"author": "John",
"author_id": 2168,
"author_profile": "https://Stackoverflow.com/users/2168",
"pm_score": 2,
"selected": false,
"text": "import java.util.HashMap;\n\nMap map = new HashMap();\n"
},
{
"answer_id": 29336,
"author": "Edmund Tay",
"author_id": 2633,
"author_profile": "https://Stackoverflow.com/users/2633",
"pm_score": 6,
"selected": true,
"text": "Map map = new HashMap();\nHashtable ht = new Hashtable();\n"
},
{
"answer_id": 29356,
"author": "Cem Catikkas",
"author_id": 3087,
"author_profile": "https://Stackoverflow.com/users/3087",
"pm_score": 3,
"selected": false,
"text": "Map<String, Integer> numbers = new HashMap<String, Integer>();\nnumbers.put(\"one\", 1);\nnumbers.put(\"two\", 2);\nnumbers.put(\"three\", 3);\n\nInteger one = numbers.get(\"one\");\nAssert.assertEquals(1, one);\n"
},
{
"answer_id": 30413,
"author": "Mocky",
"author_id": 3211,
"author_profile": "https://Stackoverflow.com/users/3211",
"pm_score": 0,
"selected": false,
"text": "key1=value1\nkey2=value2\n"
},
{
"answer_id": 31797,
"author": "izb",
"author_id": 974,
"author_profile": "https://Stackoverflow.com/users/974",
"pm_score": 5,
"selected": false,
"text": "private static final Hashtable<String,Integer> MYHASH = new Hashtable<String,Integer>() {{\n put(\"foo\", 1);\n put(\"bar\", 256);\n put(\"data\", 3);\n put(\"moredata\", 27);\n put(\"hello\", 32);\n put(\"world\", 65536);\n }};\n"
},
{
"answer_id": 13080134,
"author": "hedrick",
"author_id": 1146047,
"author_profile": "https://Stackoverflow.com/users/1146047",
"pm_score": 0,
"selected": false,
"text": "\"a\".hash() \"a\" 97 \"b\" 98 java.util"
},
{
"answer_id": 55966592,
"author": "Juraj Valkučák",
"author_id": 11446430,
"author_profile": "https://Stackoverflow.com/users/11446430",
"pm_score": -1,
"selected": false,
"text": "Hashtable<Object, Double> hashTable = new Hashtable<>();\n Optional<Double> optionalMax = hashTable.values().stream().max(Comparator.naturalOrder());\n\nif (optionalMax.isPresent())\n System.out.println(optionalMax.get());\n"
}
] |
2008/08/27
|
[
"https://Stackoverflow.com/questions/29324",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/145/"
] |
29,335 |
<p>My current employer uses a 3rd party hosted CRM provider and we have a fairly sophisticated integration tier between the two systems. Amongst the capabilities of the CRM provider is for developers to author business logic in a Java like language and on events such as the user clicking a button or submitting a new account into the system, have validation and/or business logic fire off. </p>
<p>One of the capabilities that we make use of is for that business code running on the hosted provider to invoke web services that we host. The canonical example is a sales rep entering in a new sales lead and hitting a button to ping our systems to see if we can identify that new lead based on email address, company/first/last name, etc, and if so, return back an internal GUID that represents that individual. This all works for us fine, but we've run into a wall again and again in trying to setup a sane dev environment to work against.</p>
<p>So while our use case is a bit nuanced, this can generally apply to any development house that builds APIs for 3rd party consumption: <b>what are some best practices when designing a development pipeline and environment when you're building APIs to be consumed by the outside world?</b></p>
<p>At our office, all our devs are behind a firewall, so code in progress can't be hit by the outside world, in our case the CRM provider. We could poke holes in the firewall but that's less than ideal from a security surface area standpoint. Especially if the # of devs who need to be in a DMZ like area is high. We currently are trying a single dev machine in the DMZ and then remoting into it as needed to do dev work, but that's created a resource scarcity issue if multiple devs need the box, let alone they're making potentially conflicting changes (e.g. different branches).</p>
<p>We've considered just mocking/faking incoming requests by building fake clients for these services, but that's a pretty major overhead in building out feature sets (though it does by nature reinforce a testability of our APIs). This also doesn't obviate the fact that sometimes we really do need to diagnose/debug issues coming from the real client itself, not some faked request payload.</p>
<p>What have others done in these types of scenarios? In this day and age of mashups, there have to be a lot of folks out there w/ experiences of developing APIs--what's worked (and not worked so) well for the folks out there?</p>
|
[
{
"answer_id": 29334,
"author": "John",
"author_id": 2168,
"author_profile": "https://Stackoverflow.com/users/2168",
"pm_score": 2,
"selected": false,
"text": "import java.util.HashMap;\n\nMap map = new HashMap();\n"
},
{
"answer_id": 29336,
"author": "Edmund Tay",
"author_id": 2633,
"author_profile": "https://Stackoverflow.com/users/2633",
"pm_score": 6,
"selected": true,
"text": "Map map = new HashMap();\nHashtable ht = new Hashtable();\n"
},
{
"answer_id": 29356,
"author": "Cem Catikkas",
"author_id": 3087,
"author_profile": "https://Stackoverflow.com/users/3087",
"pm_score": 3,
"selected": false,
"text": "Map<String, Integer> numbers = new HashMap<String, Integer>();\nnumbers.put(\"one\", 1);\nnumbers.put(\"two\", 2);\nnumbers.put(\"three\", 3);\n\nInteger one = numbers.get(\"one\");\nAssert.assertEquals(1, one);\n"
},
{
"answer_id": 30413,
"author": "Mocky",
"author_id": 3211,
"author_profile": "https://Stackoverflow.com/users/3211",
"pm_score": 0,
"selected": false,
"text": "key1=value1\nkey2=value2\n"
},
{
"answer_id": 31797,
"author": "izb",
"author_id": 974,
"author_profile": "https://Stackoverflow.com/users/974",
"pm_score": 5,
"selected": false,
"text": "private static final Hashtable<String,Integer> MYHASH = new Hashtable<String,Integer>() {{\n put(\"foo\", 1);\n put(\"bar\", 256);\n put(\"data\", 3);\n put(\"moredata\", 27);\n put(\"hello\", 32);\n put(\"world\", 65536);\n }};\n"
},
{
"answer_id": 13080134,
"author": "hedrick",
"author_id": 1146047,
"author_profile": "https://Stackoverflow.com/users/1146047",
"pm_score": 0,
"selected": false,
"text": "\"a\".hash() \"a\" 97 \"b\" 98 java.util"
},
{
"answer_id": 55966592,
"author": "Juraj Valkučák",
"author_id": 11446430,
"author_profile": "https://Stackoverflow.com/users/11446430",
"pm_score": -1,
"selected": false,
"text": "Hashtable<Object, Double> hashTable = new Hashtable<>();\n Optional<Double> optionalMax = hashTable.values().stream().max(Comparator.naturalOrder());\n\nif (optionalMax.isPresent())\n System.out.println(optionalMax.get());\n"
}
] |
2008/08/27
|
[
"https://Stackoverflow.com/questions/29335",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2228/"
] |
29,346 |
<p>I have a web application that needs to read (and possibly write) files from a network share. I was wondering what the best way to do this would be?</p>
<p>I can't give the network service or aspnet accounts access to the network share. I could possibly use impersonation.</p>
<p>The network share and the web application are both hosted on the same domain and I can create a new user on the domain specifically for this purpose however I'm not quite sure how to join the dots between creating the filestream and specifying the credentials to use in the web application.</p>
<hr>
<p>Unfortunately the drive isn't mapped as a network drive on the machine, it's only available to me as a network share so unfortunately I can't make a transparent call.</p>
<p>There is one problem I can think of with impersonation... I can only impersonate one user per application domain I <em>think</em> but I'm happy to be corrected. I may need to write this file to several different shares which means I may have to impersonate several users.</p>
<p>I like the idea of creating a token... if I can do that I'll be able to ask the use up front for their credentials and then dynamically apply the security and give them meaningful error messages if access is denied... I'm off to play but I'll be back with an update.</p>
|
[
{
"answer_id": 29349,
"author": "Dan Herbert",
"author_id": 392,
"author_profile": "https://Stackoverflow.com/users/392",
"pm_score": 0,
"selected": false,
"text": "aspnet"
},
{
"answer_id": 11900448,
"author": "Mike Perrenoud",
"author_id": 1195080,
"author_profile": "https://Stackoverflow.com/users/1195080",
"pm_score": 0,
"selected": false,
"text": "public interface IDocumentService\n{\n public string BuildTrustedRelationship(string privateKey);\n\n public byte[] ReadFile(string token, string fileName);\n\n public void WriteFile(string token, string fileName, byte[] file);\n}\n Application_start"
}
] |
2008/08/27
|
[
"https://Stackoverflow.com/questions/29346",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/493/"
] |
29,383 |
<p>Maybe this is a dumb question, but is there any way to convert a boolean value to a string such that 1 turns to "true" and 0 turns to "false"? I could just use an if statement, but it would be nice to know if there is a way to do that with the language or standard libraries. Plus, I'm a pedant. :)</p>
|
[
{
"answer_id": 29394,
"author": "Joseph Pecoraro",
"author_id": 792,
"author_profile": "https://Stackoverflow.com/users/792",
"pm_score": -1,
"selected": false,
"text": "#include <stdio.h>\n#include <stdarg.h>\n\n#define BOOL_STR(b) (b?\"true\":\"false\")\n\nint main (int argc, char const *argv[]) {\n bool alpha = true;\n printf( BOOL_STR(alpha) );\n return 0;\n}\n"
},
{
"answer_id": 29396,
"author": "dagorym",
"author_id": 171,
"author_profile": "https://Stackoverflow.com/users/171",
"pm_score": -1,
"selected": false,
"text": "#define PRINTBOOL(x) x?\"true\":\"false\"\n"
},
{
"answer_id": 29509,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "printf(\"%s\\n\", b?\"true\":\"false\");\n B2S(b) ((b)?\"true\":\"false\")\n 'b' 'b'"
},
{
"answer_id": 29536,
"author": "dwj",
"author_id": 346,
"author_profile": "https://Stackoverflow.com/users/346",
"pm_score": 2,
"selected": false,
"text": "#define BOOL_STR(b) ((b)?\"true\":\"false\")\n 1 == 2 ? \"true\" : \"false\"\n (1 == 2) ? \"true\" : \"false\"\n"
},
{
"answer_id": 29571,
"author": "graham.reeds",
"author_id": 342,
"author_profile": "https://Stackoverflow.com/users/342",
"pm_score": 8,
"selected": true,
"text": "bool t = true;\nbool f = false;\nstd::cout << std::noboolalpha << t << \" == \" << std::boolalpha << t << std::endl; \nstd::cout << std::noboolalpha << f << \" == \" << std::boolalpha << f << std::endl;\n std::boolalpha std::noboolalpha std::boolalpha std::cout std::cout"
},
{
"answer_id": 29798,
"author": "OJ.",
"author_id": 611,
"author_profile": "https://Stackoverflow.com/users/611",
"pm_score": 7,
"selected": false,
"text": "inline const char * const BoolToString(bool b)\n{\n return b ? \"true\" : \"false\";\n}\n // this is used in C, not C++. if you want to use printf, instead include <cstdio>\n//#include <stdio.h>\n// instead you should use the iostream libs\n#include <iostream>\n\n// not only is this a C include, it's totally unnecessary!\n//#include <stdarg.h>\n\n// Macros - not type-safe, has side-effects. Use inline functions instead\n//#define BOOL_STR(b) (b?\"true\":\"false\")\ninline const char * const BoolToString(bool b)\n{\n return b ? \"true\" : \"false\";\n}\n\nint main (int argc, char const *argv[]) {\n bool alpha = true;\n\n // printf? that's C, not C++\n //printf( BOOL_STR(alpha) );\n // use the iostream functionality\n std::cout << BoolToString(alpha);\n return 0;\n}\n"
},
{
"answer_id": 29831,
"author": "DrPizza",
"author_id": 2131,
"author_profile": "https://Stackoverflow.com/users/2131",
"pm_score": 4,
"selected": false,
"text": "std::string bool_as_text(bool b)\n{\n std::stringstream converter;\n converter << std::boolalpha << b; // flag boolalpha calls converter.setf(std::ios_base::boolalpha)\n return converter.str();\n}\n boost::lexical_cast<std::string>(my_bool)\n"
},
{
"answer_id": 29907,
"author": "Shadow2531",
"author_id": 1697,
"author_profile": "https://Stackoverflow.com/users/1697",
"pm_score": 4,
"selected": false,
"text": "\nconst char* bool_cast(const bool b) {\n return b ? \"true\" : \"false\";\n}\n \n#include <iostream>\n#include <string>\n#include <sstream>\nusing namespace std;\n\nstring bool_cast(const bool b) {\n ostringstream ss;\n ss << boolalpha << b;\n return ss.str();\n}\n\nint main() {\n cout << bool_cast(true) << \"\\n\";\n cout << bool_cast(false) << \"\\n\";\n}\n"
},
{
"answer_id": 30122,
"author": "Mat Noguchi",
"author_id": 1799,
"author_profile": "https://Stackoverflow.com/users/1799",
"pm_score": -1,
"selected": false,
"text": "std::string"
},
{
"answer_id": 49032470,
"author": "Erwan Guiomar",
"author_id": 7797382,
"author_profile": "https://Stackoverflow.com/users/7797382",
"pm_score": 0,
"selected": false,
"text": "std::to_string std::string"
},
{
"answer_id": 50468243,
"author": "UIResponder",
"author_id": 2776045,
"author_profile": "https://Stackoverflow.com/users/2776045",
"pm_score": 0,
"selected": false,
"text": "boolalpha std::cout << std::boolalpha << b << endl;\nstd::cout << std::noboolalpha << b << endl;\n"
},
{
"answer_id": 53763374,
"author": "Federico Spinelli",
"author_id": 6800578,
"author_profile": "https://Stackoverflow.com/users/6800578",
"pm_score": 2,
"selected": false,
"text": "bool to_convert{true};\nauto bool_to_string = [](bool b) -> std::string {\n return b ? \"true\" : \"false\";\n};\nstd::string str{\"string to print -> \"};\nstd::cout<<str+bool_to_string(to_convert);\n string to print -> true\n"
},
{
"answer_id": 57337518,
"author": "ewd",
"author_id": 1803860,
"author_profile": "https://Stackoverflow.com/users/1803860",
"pm_score": 2,
"selected": false,
"text": "constexpr char const* to_c_str(bool b) {\n return \n std::array<char const*, 2>{\"false\", \"true \"}[b]\n ;\n};\n"
},
{
"answer_id": 63468199,
"author": "carlsb3rg",
"author_id": 384024,
"author_profile": "https://Stackoverflow.com/users/384024",
"pm_score": 0,
"selected": false,
"text": "constexpr char const* toString(bool b)\n{\n return b ? \"true\" : \"false\";\n}\n"
},
{
"answer_id": 64771898,
"author": "Ciro Santilli OurBigBook.com",
"author_id": 895245,
"author_profile": "https://Stackoverflow.com/users/895245",
"pm_score": 3,
"selected": false,
"text": "std::format(\"{}\" #include <format>\nauto s6 = std::format(\"{:6}\", true); // value of s6 is \"true \"\n fmt sudo apt install libfmt-dev\n <format> <fmt/core.h> std::format fmt::format #include <string>\n#include <iostream>\n\n#include <fmt/core.h>\n\nint main() {\n std::string message = fmt::format(\"The {} answer is {}.\", true, false);\n std::cout << message << std::endl;\n}\n g++ -std=c++11 -o main.out main.cpp -lfmt\n./main.out\n The true answer is false.\n"
},
{
"answer_id": 67378885,
"author": "space.cadet",
"author_id": 3430981,
"author_profile": "https://Stackoverflow.com/users/3430981",
"pm_score": 1,
"selected": false,
"text": "bool myBool = true;\nstd::cout << \"The state of myBool is: \" << (myBool ? \"true\" : \"false\") << std::endl;\nenter code here\n (myBool ? \"true\" : \"false\")\n {\n if(myBool){\n return \"true\";\n } else {\n return \"false\";\n }\n}\n std::cout << std::boolalpha;\n std::cout << \"The state of myBool is: \" << std::boolalpha << myBool << std::noboolalpha;\n"
},
{
"answer_id": 73484243,
"author": "David - Walter",
"author_id": 19843777,
"author_profile": "https://Stackoverflow.com/users/19843777",
"pm_score": -1,
"selected": false,
"text": "#include <iostream>\n#include <string>\n\nusing namespace std;\n\nstring toBool(bool boolean)\n{\n string result;\n if(boolean == true)\n result = \"true\";\n else \n result = \"false\";\n return result;\n} \n\nint main()\n{\n bool myBoolean = true; //Boolean\n string booleanValue;\n booleanValue = toBool(myBoolean);\n cout << \"bool: \" << booleanValue << \"\\n\";\n }\n"
}
] |
2008/08/27
|
[
"https://Stackoverflow.com/questions/29383",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2147/"
] |
29,436 |
<p>I'm using the .NET CF 3.5. The type I want to create does not have a default constructor so I want to pass a string to an overloaded constructor. How do I do this?</p>
<p>Code:</p>
<pre><code>Assembly a = Assembly.LoadFrom("my.dll");
Type t = a.GetType("type info here");
// All ok so far, assembly loads and I can get my type
string s = "Pass me to the constructor of Type t";
MyObj o = Activator.CreateInstance(t); // throws MissMethodException
</code></pre>
|
[
{
"answer_id": 29444,
"author": "Matt Hamilton",
"author_id": 615,
"author_profile": "https://Stackoverflow.com/users/615",
"pm_score": 0,
"selected": false,
"text": "Type t = a.GetType(\"type info here\");\nvar ctors = t.GetConstructors();\nstring s = \"Pass me to the ctor of t\";\nMyObj o = ctors[0].Invoke(new[] { s }) as MyObj;\n"
},
{
"answer_id": 29472,
"author": "Chris Karcher",
"author_id": 2773,
"author_profile": "https://Stackoverflow.com/users/2773",
"pm_score": 4,
"selected": true,
"text": "MyObj o = null;\nAssembly a = Assembly.LoadFrom(\"my.dll\");\nType t = a.GetType(\"type info here\");\n\nConstructorInfo ctor = t.GetConstructor(new Type[] { typeof(string) });\nif(ctor != null)\n o = ctor.Invoke(new object[] { s });\n"
},
{
"answer_id": 29481,
"author": "Matt Hamilton",
"author_id": 615,
"author_profile": "https://Stackoverflow.com/users/615",
"pm_score": 1,
"selected": false,
"text": "static object GetInstanceFromParameters(Assembly a, string typeName, params object[] pars) \n{\n var t = a.GetType(typeName);\n\n var c = t.GetConstructor(pars.Select(p => p.GetType()).ToArray());\n if (c == null) return null;\n\n return c.Invoke(pars);\n}\n Foo f = GetInstanceFromParameters(a, \"SmartDeviceProject1.Foo\", \"hello\", 17) as Foo;\n"
}
] |
2008/08/27
|
[
"https://Stackoverflow.com/questions/29436",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/636/"
] |
29,437 |
<p>I want to shift the contents of an array of bytes by 12-bit to the left.</p>
<p>For example, starting with this array of type <code>uint8_t shift[10]</code>:</p>
<pre><code>{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0A, 0xBC}
</code></pre>
<p>I'd like to shift it to the left by 12-bits resulting in:</p>
<pre><code>{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xAB, 0xC0, 0x00}
</code></pre>
|
[
{
"answer_id": 29463,
"author": "Joseph Pecoraro",
"author_id": 792,
"author_profile": "https://Stackoverflow.com/users/792",
"pm_score": 2,
"selected": false,
"text": "N N - Total number of bits to shift\nF = (N / 8) - Full 8 bit integers shifted\nR = (N % 8) - Remaining bits that need to be shifted\n F R 0xBC R // 0xAB shifted 4 bits is:\n(0xAB & 0x0F) >> 4 // is the overflow (0x0A)\n0xAB << 4 // is the shifted value (0xB0)\n"
},
{
"answer_id": 29492,
"author": "Mike Haboustak",
"author_id": 2146,
"author_profile": "https://Stackoverflow.com/users/2146",
"pm_score": 4,
"selected": true,
"text": "unsigned char length = 10;\nunsigned char data[10] = {0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0A,0xBC};\nunsigned char *shift = data;\nwhile (shift < data+(length-2)) {\n *shift = (*(shift+1)&0x0F)<<4 | (*(shift+2)&0xF0)>>4;\n shift++;\n}\n*(data+length-2) = (*(data+length-1)&0x0F)<<4;\n*(data+length-1) = 0x00;\n unsigned char overflow[2];\n*overflow = (*data&0xF0)>>4;\n*(overflow+1) = (*data&0x0F)<<4 | (*(data+1)&0xF0)>>4;\nwhile (shift < data+(length-2)) {\n /* normal shifting */\n} \n/* now would be the time to copy it back if you want to carry it somewhere */\n*(data+length-2) = (*(data+length-1)&0x0F)<<4 | (*(overflow)&0x0F);\n*(data+length-1) = *(overflow+1); \n\n/* You could return a 16-bit carry int, \n * but endian-ness makes that look weird \n * if you care about the physical layout */\nunsigned short carry = *(overflow+1)<<8 | *overflow;\n"
},
{
"answer_id": 29504,
"author": "Mark Harrison",
"author_id": 116,
"author_profile": "https://Stackoverflow.com/users/116",
"pm_score": 3,
"selected": false,
"text": "iL a[i] iH a[i] iH = (i+1)L iL = (i+2)H a[i] = (iH << 4) OR iL\na[i] = ((a[i+1] & 0x0f) << 4) | ((a[i+2] & 0xf0) >> 4)\n 12 bits a[i+2] N-2 bytes iH = (i+1)L 0 a N for (i = 0; i < N - 2; ++i) {\n a[i] = ((a[i+1] & 0x0f) << 4) | ((a[i+2] & 0xf0) >> 4);\n}\na[N-2] = (a[N-1) & 0x0f) << 4;\na[N-1] = 0;\n 12 bits N bits M M = number of bits modulo 8 for (p = a, p2=a+N-2; p != p2; ++p) {\n *p = ((*(p+1) & 0x0f) << 4) | (((*(p+2) & 0xf0) >> 4);\n}\n"
},
{
"answer_id": 29508,
"author": "DMC",
"author_id": 3148,
"author_profile": "https://Stackoverflow.com/users/3148",
"pm_score": 1,
"selected": false,
"text": "#include <stdio.h>\n\nunsigned int array[] = {0x12345678,0x9abcdef0,0x12345678,0x9abcdef0,0x66666666};\n\nint main(void) {\n int count;\n unsigned int *from, *to;\n from = &array[0];\n to = &array[0];\n count = 5;\n\n while (count-- > 1) {\n *to++ = (*from<<12) | ((*++from>>20)&0xfff);\n };\n *to = (*from<<12);\n\n printf(\"%x\\n\", array[0]);\n printf(\"%x\\n\", array[1]);\n printf(\"%x\\n\", array[2]);\n printf(\"%x\\n\", array[3]);\n printf(\"%x\\n\", array[4]);\n\n return 0;\n}\n"
},
{
"answer_id": 29514,
"author": "Justin Tanner",
"author_id": 609,
"author_profile": "https://Stackoverflow.com/users/609",
"pm_score": 2,
"selected": false,
"text": "void shift_4bits_left(uint8_t* array, uint16_t size)\n{\n int i;\n uint8_t shifted = 0x00; \n uint8_t overflow = (0xF0 & array[0]) >> 4;\n\n for (i = (size - 1); i >= 0; i--)\n {\n shifted = (array[i] << 4) | overflow;\n overflow = (0xF0 & array[i]) >> 4;\n array[i] = shifted;\n }\n}\n"
},
{
"answer_id": 29532,
"author": "Dominic Cooney",
"author_id": 878,
"author_profile": "https://Stackoverflow.com/users/878",
"pm_score": 0,
"selected": false,
"text": "void shl12(uint8_t *v, size_t length) {\n if (length == 0) {\n return; // nothing to do\n }\n\n if (length > 1) {\n uint8_t last_byte, next_byte;\n next_byte = *(v + 1);\n\n for (size_t i = 0; i + 2 < length; i++, v++) {\n last_byte = next_byte;\n next_byte = *(v + 2);\n *v = ((last_byte & 0x0f) << 4) | (((next_byte) & 0xf0) >> 4);\n }\n\n // the next-to-last byte is half-empty\n *(v++) = (next_byte & 0x0f) << 4;\n }\n\n // the last byte is always empty\n *v = 0;\n}\n length length length length"
}
] |
2008/08/27
|
[
"https://Stackoverflow.com/questions/29437",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/609/"
] |
29,482 |
<p>How do I cast an <code>int</code> to an <code>enum</code> in C#?</p>
|
[
{
"answer_id": 29485,
"author": "FlySwat",
"author_id": 1965,
"author_profile": "https://Stackoverflow.com/users/1965",
"pm_score": 13,
"selected": true,
"text": "YourEnum foo = (YourEnum)yourInt;\n YourEnum foo = (YourEnum) Enum.Parse(typeof(YourEnum), yourString);\n\n// The foo.ToString().Contains(\",\") check is necessary for \n// enumerations marked with a [Flags] attribute.\nif (!Enum.IsDefined(typeof(YourEnum), foo) && !foo.ToString().Contains(\",\"))\n{\n throw new InvalidOperationException(\n $\"{yourString} is not an underlying value of the YourEnum enumeration.\"\n );\n}\n YourEnum foo = (YourEnum)Enum.ToObject(typeof(YourEnum), yourInt);\n"
},
{
"answer_id": 29488,
"author": "abigblackman",
"author_id": 2279,
"author_profile": "https://Stackoverflow.com/users/2279",
"pm_score": 7,
"selected": false,
"text": "int one = 1;\nMyEnum e = (MyEnum)one;\n"
},
{
"answer_id": 29489,
"author": "Matt Hamilton",
"author_id": 615,
"author_profile": "https://Stackoverflow.com/users/615",
"pm_score": 10,
"selected": false,
"text": "MyEnum e = (MyEnum)3;\n Enum.IsDefined if (Enum.IsDefined(typeof(MyEnum), 3)) { ... }\n"
},
{
"answer_id": 3166694,
"author": "L. D.",
"author_id": 382143,
"author_profile": "https://Stackoverflow.com/users/382143",
"pm_score": 6,
"selected": false,
"text": "MyEnum var MyEnumType = typeof(MyEnum);\n Enum.ToObject(typeof(MyEnum), 3)\n"
},
{
"answer_id": 3655831,
"author": "Tawani",
"author_id": 61525,
"author_profile": "https://Stackoverflow.com/users/61525",
"pm_score": 6,
"selected": false,
"text": "public static class EnumHelper\n{\n public static int[] ToIntArray<T>(T[] value)\n {\n int[] result = new int[value.Length];\n for (int i = 0; i < value.Length; i++)\n result[i] = Convert.ToInt32(value[i]);\n return result;\n }\n\n public static T[] FromIntArray<T>(int[] value) \n {\n T[] result = new T[value.Length];\n for (int i = 0; i < value.Length; i++)\n result[i] = (T)Enum.ToObject(typeof(T),value[i]);\n return result;\n }\n\n\n internal static T Parse<T>(string value, T defaultValue)\n {\n if (Enum.IsDefined(typeof(T), value))\n return (T) Enum.Parse(typeof (T), value);\n\n int num;\n if(int.TryParse(value,out num))\n {\n if (Enum.IsDefined(typeof(T), num))\n return (T)Enum.ToObject(typeof(T), num);\n }\n\n return defaultValue;\n }\n}\n"
},
{
"answer_id": 5655038,
"author": "Evan M",
"author_id": 603384,
"author_profile": "https://Stackoverflow.com/users/603384",
"pm_score": 5,
"selected": false,
"text": "for (var flagIterator = 0; flagIterator < 32; flagIterator++)\n{\n // Determine the bit value (1,2,4,...,Int32.MinValue)\n int bitValue = 1 << flagIterator;\n\n // Check to see if the current flag exists in the bit mask\n if ((intValue & bitValue) != 0)\n {\n // If the current flag exists in the enumeration, then we can add that value to the list\n // if the enumeration has that flag defined\n if (Enum.IsDefined(typeof(MyEnum), bitValue))\n Console.WriteLine((MyEnum)bitValue);\n }\n}\n enum Enum.GetUnderlyingType()"
},
{
"answer_id": 7847875,
"author": "MSkuta",
"author_id": 897609,
"author_profile": "https://Stackoverflow.com/users/897609",
"pm_score": 6,
"selected": false,
"text": "if (typeof(YourEnum).IsEnumDefined(valueToCast)) return (YourEnum)valueToCast;\nelse { //handle it here, if its not defined }\n"
},
{
"answer_id": 8094628,
"author": "Abdul Munim",
"author_id": 228656,
"author_profile": "https://Stackoverflow.com/users/228656",
"pm_score": 8,
"selected": false,
"text": "public static T ToEnum<T>(this string enumString)\n{\n return (T) Enum.Parse(typeof (T), enumString);\n}\n Color colorEnum = \"Red\".ToEnum<Color>();\n string color = \"Red\";\nvar colorEnum = color.ToEnum<Color>();\n"
},
{
"answer_id": 15005854,
"author": "Sébastien Duval",
"author_id": 1848457,
"author_profile": "https://Stackoverflow.com/users/1848457",
"pm_score": 6,
"selected": false,
"text": "public static class EnumEx\n{\n static public bool TryConvert<T>(int value, out T result)\n {\n result = default(T);\n bool success = Enum.IsDefined(typeof(T), value);\n if (success)\n {\n result = (T)Enum.ToObject(typeof(T), value);\n }\n return success;\n }\n}\n"
},
{
"answer_id": 20999570,
"author": "gmail user",
"author_id": 344394,
"author_profile": "https://Stackoverflow.com/users/344394",
"pm_score": 3,
"selected": false,
"text": "Enum enum orientation : byte\n{\n north = 1,\n south = 2,\n east = 3,\n west = 4\n}\n\nclass Program\n{\n static void Main(string[] args)\n {\n orientation myDirection = orientation.north;\n Console.WriteLine(“myDirection = {0}”, myDirection); //output myDirection =north\n Console.WriteLine((byte)myDirection); //output 1\n\n string strDir = Convert.ToString(myDirection);\n Console.WriteLine(strDir); //output north\n\n string myString = “north”; //to convert string to Enum\n myDirection = (orientation)Enum.Parse(typeof(orientation),myString);\n\n\n }\n}\n"
},
{
"answer_id": 21577017,
"author": "Shivprasad Koirala",
"author_id": 993672,
"author_profile": "https://Stackoverflow.com/users/993672",
"pm_score": 5,
"selected": false,
"text": "MyColors EnumColors = (MyColors)Enum.Parse(typeof(MyColors), \"Red\");\n"
},
{
"answer_id": 22830894,
"author": "atlaste",
"author_id": 1031591,
"author_profile": "https://Stackoverflow.com/users/1031591",
"pm_score": 8,
"selected": false,
"text": "int public enum Foo : short\n short .class public auto ansi serializable sealed BarFlag extends System.Enum\n{\n .custom instance void System.FlagsAttribute::.ctor()\n .custom instance void ComVisibleAttribute::.ctor(bool) = { bool(true) }\n\n .field public static literal valuetype BarFlag AllFlags = int32(0x3fff)\n .field public static literal valuetype BarFlag Foo1 = int32(1)\n .field public static literal valuetype BarFlag Foo2 = int32(0x2000)\n\n // and so on for all flags or enum values\n\n .field public specialname rtspecialname int32 value__\n}\n value__ Foo value__ System.Enum BarFlag Foo public enum MyEnum : int\n{\n Foo = 1,\n Bar = 2,\n Mek = 5\n}\n\nstatic void Main(string[] args)\n{\n var e1 = (MyEnum)5;\n var e2 = (MyEnum)6;\n\n Console.WriteLine(\"{0} {1}\", e1, e2);\n Console.ReadLine();\n}\n e2 value__ Console.WriteLine ToString() e1 e2 Enum.IsDefined(typeof(MyEnum), 6) public enum MyEnum : short\n{\n Mek = 5\n}\n\nstatic void Main(string[] args)\n{\n var e1 = (MyEnum)32769; // will not compile, out of bounds for a short\n\n object o = 5;\n var e2 = (MyEnum)o; // will throw at runtime, because o is of type int\n\n Console.WriteLine(\"{0} {1}\", e1, e2);\n Console.ReadLine();\n}\n"
},
{
"answer_id": 24534466,
"author": "LawMan",
"author_id": 2574087,
"author_profile": "https://Stackoverflow.com/users/2574087",
"pm_score": 3,
"selected": false,
"text": "[DataContract]\npublic class EnumMember\n{\n [DataMember]\n public string Description { get; set; }\n\n [DataMember]\n public int Value { get; set; }\n\n public static List<EnumMember> ConvertToList<T>()\n {\n Type type = typeof(T);\n\n if (!type.IsEnum)\n {\n throw new ArgumentException(\"T must be of type enumeration.\");\n }\n\n var members = new List<EnumMember>();\n\n foreach (string item in System.Enum.GetNames(type))\n {\n var enumType = System.Enum.Parse(type, item);\n\n members.Add(\n new EnumMember() { Description = enumType.GetDescriptionValue(), Value = ((IConvertible)enumType).ToInt32(null) });\n }\n\n return members;\n }\n}\n public static string GetDescriptionValue<T>(this T source)\n {\n FieldInfo fileInfo = source.GetType().GetField(source.ToString());\n DescriptionAttribute[] attributes = (DescriptionAttribute[])fileInfo.GetCustomAttributes(typeof(DescriptionAttribute), false); \n\n if (attributes != null && attributes.Length > 0)\n {\n return attributes[0].Description;\n }\n else\n {\n return source.ToString();\n }\n }\n return EnumMember.ConvertToList<YourType>();\n"
},
{
"answer_id": 24806564,
"author": "Ted",
"author_id": 429973,
"author_profile": "https://Stackoverflow.com/users/429973",
"pm_score": 5,
"selected": false,
"text": "public const int int int public static class Question\n{\n public static readonly int Role = 2;\n public static readonly int ProjectFunding = 3;\n public static readonly int TotalEmployee = 4;\n public static readonly int NumberOfServers = 5;\n public static readonly int TopBusinessConcern = 6;\n}\n"
},
{
"answer_id": 25045892,
"author": "CZahrobsky",
"author_id": 888792,
"author_profile": "https://Stackoverflow.com/users/888792",
"pm_score": 4,
"selected": false,
"text": "var result = EnumParser<MyEnum>.Parse(valueToParse, MyEnum.FirstValue);\n using System;\n\npublic class EnumParser<T> where T : struct\n{\n public static T Parse(int toParse, T defaultVal)\n {\n return Parse(toParse + \"\", defaultVal);\n }\n public static T Parse(string toParse, T defaultVal)\n {\n T enumVal = defaultVal;\n if (defaultVal is Enum && !String.IsNullOrEmpty(toParse))\n {\n int index;\n if (int.TryParse(toParse, out index))\n {\n Enum.TryParse(index + \"\", out enumVal);\n }\n else\n {\n if (!Enum.TryParse<T>(toParse + \"\", true, out enumVal))\n {\n MatchPartialName(toParse, ref enumVal);\n }\n }\n }\n return enumVal;\n }\n\n public static void MatchPartialName(string toParse, ref T enumVal)\n {\n foreach (string member in enumVal.GetType().GetEnumNames())\n {\n if (member.ToLower().Contains(toParse.ToLower()))\n {\n if (Enum.TryParse<T>(member + \"\", out enumVal))\n {\n break;\n }\n }\n }\n }\n}\n"
},
{
"answer_id": 27052239,
"author": "Will Yu",
"author_id": 1453988,
"author_profile": "https://Stackoverflow.com/users/1453988",
"pm_score": 4,
"selected": false,
"text": "enum Importance\n{}\n\nImportance importance;\n\nif (Enum.TryParse(value, out importance))\n{\n}\n"
},
{
"answer_id": 29343461,
"author": "Daniel Fisher lennybacon",
"author_id": 12679,
"author_profile": "https://Stackoverflow.com/users/12679",
"pm_score": 5,
"selected": false,
"text": "public static bool TryConvertToEnum<T>(this int instance, out T result)\n where T: Enum\n{\n var enumType = typeof (T);\n var success = Enum.IsDefined(enumType, instance);\n if (success)\n {\n result = (T)Enum.ToObject(enumType, instance);\n }\n else\n {\n result = default(T);\n }\n return success;\n}\n"
},
{
"answer_id": 34654243,
"author": "Franki1986",
"author_id": 1959238,
"author_profile": "https://Stackoverflow.com/users/1959238",
"pm_score": 3,
"selected": false,
"text": " public static class Enum<T> where T : struct\n {\n private static readonly IEnumerable<T> All = Enum.GetValues(typeof (T)).Cast<T>();\n private static readonly Dictionary<int, T> Values = All.ToDictionary(k => Convert.ToInt32(k));\n\n public static T? CastOrNull(int value)\n {\n T foundValue;\n if (Values.TryGetValue(value, out foundValue))\n {\n return foundValue;\n }\n\n // For enums with Flags-Attribut.\n try\n {\n bool isFlag = typeof(T).GetCustomAttributes(typeof(FlagsAttribute), false).Length > 0;\n if (isFlag)\n {\n int existingIntValue = 0;\n\n foreach (T t in Enum.GetValues(typeof(T)))\n {\n if ((value & Convert.ToInt32(t)) > 0)\n {\n existingIntValue |= Convert.ToInt32(t);\n }\n }\n if (existingIntValue == 0)\n {\n return null;\n }\n\n return (T)(Enum.Parse(typeof(T), existingIntValue.ToString(), true));\n }\n }\n catch (Exception)\n {\n return null;\n }\n return null;\n }\n }\n [Flags]\npublic enum PetType\n{\n None = 0, Dog = 1, Cat = 2, Fish = 4, Bird = 8, Reptile = 16, Other = 32\n};\n\ninteger values \n1=Dog;\n13= Dog | Fish | Bird;\n96= Other;\n128= Null;\n"
},
{
"answer_id": 40655361,
"author": "reza.cse08",
"author_id": 2597706,
"author_profile": "https://Stackoverflow.com/users/2597706",
"pm_score": 3,
"selected": false,
"text": "public enum FriendType \n{\n Default,\n Audio,\n Video,\n Image\n}\n\npublic static class EnumHelper<T>\n{\n public static T ConvertToEnum(dynamic value)\n {\n var result = default(T);\n var tempType = 0;\n\n //see Note below\n if (value != null &&\n int.TryParse(value.ToString(), out tempType) && \n Enum.IsDefined(typeof(T), tempType))\n {\n result = (T)Enum.ToObject(typeof(T), tempType); \n }\n return result;\n }\n}\n public enum MediaType : byte\n{\n Default,\n Audio,\n Video,\n Image\n} \n int.TryParse(value.ToString(), out tempType)\n byte.TryParse(value.ToString(), out tempType) EnumHelper<FriendType>.ConvertToEnum(null);\nEnumHelper<FriendType>.ConvertToEnum(\"\");\nEnumHelper<FriendType>.ConvertToEnum(\"-1\");\nEnumHelper<FriendType>.ConvertToEnum(\"6\");\nEnumHelper<FriendType>.ConvertToEnum(\"\");\nEnumHelper<FriendType>.ConvertToEnum(\"2\");\nEnumHelper<FriendType>.ConvertToEnum(-1);\nEnumHelper<FriendType>.ConvertToEnum(0);\nEnumHelper<FriendType>.ConvertToEnum(1);\nEnumHelper<FriendType>.ConvertToEnum(9);\n"
},
{
"answer_id": 41178912,
"author": "Kamran Shahid",
"author_id": 578178,
"author_profile": "https://Stackoverflow.com/users/578178",
"pm_score": 5,
"selected": false,
"text": "public static string ToEnumString<TEnum>(this int enumValue)\n{\n var enumString = enumValue.ToString();\n if (Enum.IsDefined(typeof(TEnum), enumValue))\n {\n enumString = ((TEnum) Enum.ToObject(typeof (TEnum), enumValue)).ToString();\n }\n return enumString;\n}\n"
},
{
"answer_id": 53679705,
"author": "Mohammad Aziz Nabizada",
"author_id": 10477046,
"author_profile": "https://Stackoverflow.com/users/10477046",
"pm_score": 4,
"selected": false,
"text": "public class Program\n{\n public enum Color : int\n {\n Blue = 0,\n Black = 1,\n Green = 2,\n Gray = 3,\n Yellow = 4\n }\n\n public static void Main(string[] args)\n {\n // From string\n Console.WriteLine((Color) Enum.Parse(typeof(Color), \"Green\"));\n\n // From int\n Console.WriteLine((Color)2);\n\n // From number you can also\n Console.WriteLine((Color)Enum.ToObject(typeof(Color), 2));\n }\n}\n"
},
{
"answer_id": 54477333,
"author": "Shivam Mishra",
"author_id": 6300340,
"author_profile": "https://Stackoverflow.com/users/6300340",
"pm_score": 3,
"selected": false,
"text": "class Program\n{\n static void Main(string[] args)\n {\n Console.WriteLine((int)Number.three); //Output=3\n\n Console.WriteLine((Number)3);// Outout three\n Console.Read();\n }\n\n public enum Number\n {\n Zero = 0,\n One = 1,\n Two = 2,\n three = 3\n }\n}\n"
},
{
"answer_id": 54818768,
"author": "Chad Hedgcock",
"author_id": 591097,
"author_profile": "https://Stackoverflow.com/users/591097",
"pm_score": 4,
"selected": false,
"text": "Int32 Enum public static TEnum ToEnum<TEnum>(this int val) where TEnum : struct, IComparable, IFormattable, IConvertible\n {\n if (!typeof(TEnum).IsEnum)\n {\n return default(TEnum);\n }\n\n if (Enum.IsDefined(typeof(TEnum), val))\n {//if a straightforward single value, return that\n return (TEnum)Enum.ToObject(typeof(TEnum), val);\n }\n\n var candidates = Enum\n .GetValues(typeof(TEnum))\n .Cast<int>()\n .ToList();\n\n var isBitwise = candidates\n .Select((n, i) => {\n if (i < 2) return n == 0 || n == 1;\n return n / 2 == candidates[i - 1];\n })\n .All(y => y);\n\n var maxPossible = candidates.Sum();\n\n if (\n Enum.TryParse(val.ToString(), out TEnum asEnum)\n && (val <= maxPossible || !isBitwise)\n ){//if it can be parsed as a bitwise enum with multiple flags,\n //or is not bitwise, return the result of TryParse\n return asEnum;\n }\n\n //If the value is higher than all possible combinations,\n //remove the high imaginary values not accounted for in the enum\n var excess = Enumerable\n .Range(0, 32)\n .Select(n => (int)Math.Pow(2, n))\n .Where(n => n <= val && n > 0 && !candidates.Contains(n))\n .Sum();\n\n return Enum.TryParse((val - excess).ToString(), out asEnum) ? asEnum : default(TEnum);\n }\n"
},
{
"answer_id": 56859286,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 4,
"selected": false,
"text": "public static T ToEnum<T>(dynamic value)\n{\n if (value == null)\n {\n // default value of an enum is the object that corresponds to\n // the default value of its underlying type\n // https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/default-values-table\n value = Activator.CreateInstance(Enum.GetUnderlyingType(typeof(T)));\n }\n else if (value is string name)\n {\n return (T)Enum.Parse(typeof(T), name);\n }\n\n return (T)Enum.ToObject(typeof(T),\n Convert.ChangeType(value, Enum.GetUnderlyingType(typeof(T))));\n}\n [Flags]\npublic enum A : uint\n{\n None = 0, \n X = 1 < 0,\n Y = 1 < 1\n}\n\nstatic void Main(string[] args)\n{\n var value = EnumHelper.ToEnum<A>(7m);\n var x = value.HasFlag(A.X); // true\n var y = value.HasFlag(A.Y); // true\n\n var value2 = EnumHelper.ToEnum<A>(\"X\");\n\n var value3 = EnumHelper.ToEnum<A>(null);\n\n Console.ReadKey();\n}\n"
},
{
"answer_id": 57230204,
"author": "Mselmi Ali",
"author_id": 9091039,
"author_profile": "https://Stackoverflow.com/users/9091039",
"pm_score": 3,
"selected": false,
"text": "int intToCast = 1;\nTargetEnum f = (TargetEnum) intToCast ;\n int intToCast = 1;\nif (Enum.IsDefined(typeof(TargetEnum), intToCast ))\n{\n TargetEnum target = (TargetEnum)intToCast ;\n}\nelse\n{\n // Throw your exception.\n}\n"
},
{
"answer_id": 58427564,
"author": "Aswal",
"author_id": 3560061,
"author_profile": "https://Stackoverflow.com/users/3560061",
"pm_score": 3,
"selected": false,
"text": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text.RegularExpressions;\n\nnamespace SamplePrograme\n{\n public class Program\n {\n public enum Suit : int\n {\n Spades = 0,\n Hearts = 1,\n Clubs = 2,\n Diamonds = 3\n }\n\n public static void Main(string[] args)\n {\n //from string\n Console.WriteLine((Suit) Enum.Parse(typeof(Suit), \"Clubs\"));\n\n //from int\n Console.WriteLine((Suit)1);\n\n //From number you can also\n Console.WriteLine((Suit)Enum.ToObject(typeof(Suit) ,1));\n }\n }\n}\n"
},
{
"answer_id": 61416134,
"author": "Reza Jenabi",
"author_id": 9549856,
"author_profile": "https://Stackoverflow.com/users/9549856",
"pm_score": 3,
"selected": false,
"text": "public static class Extensions\n{\n\n public static T ToEnum<T>(this string data) where T : struct\n {\n if (!Enum.TryParse(data, true, out T enumVariable))\n {\n if (Enum.IsDefined(typeof(T), enumVariable))\n {\n return enumVariable;\n }\n }\n\n return default;\n }\n\n public static T ToEnum<T>(this int data) where T : struct\n {\n return (T)Enum.ToObject(typeof(T), data);\n }\n}\n public enum DaysOfWeeks\n{\n Monday = 1,\n Tuesday = 2,\n Wednesday = 3,\n Thursday = 4,\n Friday = 5,\n Saturday = 6,\n Sunday = 7,\n}\n string Monday = \"Mon\";\n int Wednesday = 3;\n var Mon = Monday.ToEnum<DaysOfWeeks>();\n var Wed = Wednesday.ToEnum<DaysOfWeeks>();\n"
},
{
"answer_id": 62296386,
"author": "Inam Abbas",
"author_id": 7258037,
"author_profile": "https://Stackoverflow.com/users/7258037",
"pm_score": 3,
"selected": false,
"text": " public enum DaysOfWeeks\n {\n Monday = 1,\n Tuesday = 2,\n Wednesday = 3,\n Thursday = 4,\n Friday = 5,\n Saturday = 6,\n Sunday = 7,\n } \n\n var day= (DaysOfWeeks)5;\n Console.WriteLine(\"Day is : {0}\", day);\n Console.ReadLine();\n"
},
{
"answer_id": 62442964,
"author": "Cesar Alvarado Diaz",
"author_id": 1693210,
"author_profile": "https://Stackoverflow.com/users/1693210",
"pm_score": 2,
"selected": false,
"text": "YourEnum possibleEnum = (YourEnum)value; // There isn't any guarantee that it is part of the enum\nif (Enum.IsDefined(typeof(YourEnum), possibleEnum))\n{\n // Value exists in YourEnum\n}\n"
},
{
"answer_id": 64020962,
"author": "Shah Zain",
"author_id": 5196973,
"author_profile": "https://Stackoverflow.com/users/5196973",
"pm_score": 4,
"selected": false,
"text": "var result = Enum.TryParse(typeof(MyEnum), yourString, out yourEnum) \n MyEnum someValue = (MyEnum)myIntValue;\n"
},
{
"answer_id": 66050222,
"author": "Alexander",
"author_id": 208272,
"author_profile": "https://Stackoverflow.com/users/208272",
"pm_score": 3,
"selected": false,
"text": "var enumValue = (MyEnum?)enumInt;\n\nif (!enumValue.HasValue)\n{\n throw new ArgumentException(nameof(enumValue));\n}\n"
}
] |
2008/08/27
|
[
"https://Stackoverflow.com/questions/29482",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/493/"
] |
29,496 |
<p>I'd like to write a script/batch that will bunch up my daily IIS logs and zip them up by month.</p>
<p>ex080801.log which is in the format of ex<em>yymmdd</em>.log</p>
<p>ex080801.log - ex080831.log gets zipped up and the log files deleted.</p>
<p>The reason we do this is because on a heavy site a log file for one day could be 500mb to 1gb so we zip them up which compresses them by 98% and dump the real log file. We use webtrend to analyze the log files and it is capable of reading into a zip file.</p>
<p>Does anyone have any ideas on how to script this or would be willing to share some code?</p>
|
[
{
"answer_id": 29609,
"author": "David Crow",
"author_id": 2783,
"author_profile": "https://Stackoverflow.com/users/2783",
"pm_score": 5,
"selected": true,
"text": "7za.exe a -tzip ex%1-logs.zip %2\\ex%1*.log\ndel %2\\ex%1*.log\n ziplogs.bat 0808 c:\\logs"
},
{
"answer_id": 35030,
"author": "Steve Moon",
"author_id": 3660,
"author_profile": "https://Stackoverflow.com/users/3660",
"pm_score": 2,
"selected": false,
"text": "@echo off\nsetlocal\nFor /f \"skip=11 delims=/\" %%a in ('Dir D:\\logs\\W3SVC1\\*.log /B /O:-N /T:C')do move \"D:\\logs\\W3SVC1\\%%a\" \"D:\\logs\\W3SVC1\\old\\%%a\"\nd:\ncd \"\\logs\\W3SVC1\\old\"\ngzip -n *.log\nEndlocal\nexit\n"
},
{
"answer_id": 410448,
"author": "Cheeso",
"author_id": 48082,
"author_profile": "https://Stackoverflow.com/users/48082",
"pm_score": 1,
"selected": false,
"text": "function ZipUp-Files ( $directory )\n{\n\n $children = get-childitem -path $directory\n foreach ($o in $children) \n {\n if ($o.Name -ne \"TestResults\" -and \n $o.Name -ne \"obj\" -and \n $o.Name -ne \"bin\" -and \n $o.Name -ne \"tfs\" -and \n $o.Name -ne \"notused\" -and \n $o.Name -ne \"Release\")\n {\n if ($o.PSIsContainer)\n {\n ZipUp-Files ( $o.FullName )\n }\n else \n {\n if ($o.Name -ne \".tfs-ignore\" -and\n !$o.Name.EndsWith(\".cache\") -and\n !$o.Name.EndsWith(\".zip\") )\n {\n Write-output $o.FullName\n $e= $zipfile.AddFile($o.FullName)\n }\n }\n }\n }\n}\n\n\n[System.Reflection.Assembly]::LoadFrom(\"c:\\\\\\bin\\\\Ionic.Zip.dll\");\n\n$zipfile = new-object Ionic.Zip.ZipFile(\"zipsrc.zip\");\n\nZipUp-Files \"DotNetZip\"\n\n$zipfile.Save()\n"
},
{
"answer_id": 2366322,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "param([string]$Path = $(read-host \"Enter the path\"))\nfunction New-Zip\n{\n param([string]$zipfilename)\n set-content $zipfilename (\"PK\" + [char]5 + [char]6 + (\"$([char]0)\" * 18))\n (dir $zipfilename).IsReadOnly = $false\n}\nfunction Add-Zip\n{\n param([string]$zipfilename)\n\n if(-not (test-path($zipfilename)))\n {\n set-content $zipfilename (\"PK\" + [char]5 + [char]6 + (\"$([char]0)\" * 18))\n (dir $zipfilename).IsReadOnly = $false \n }\n\n $shellApplication = new-object -com shell.application\n $zipPackage = $shellApplication.NameSpace($zipfilename)\n\n foreach($file in $input) \n { \n $zipPackage.CopyHere($file.FullName)\n Start-sleep -milliseconds 500\n }\n}\n$FilesToZip = dir $Path -recurse -include *.log\nforeach ($file in $FilesToZip) {\nNew-Zip $file.BaseName\ndir $($file.directoryname+\"\\\"+$file.name) | Add-zip $($file.directoryname+\"\\$($file.basename).zip\")\ndel $($file.directoryname+\"\\\"+$file.name)\n}\n"
}
] |
2008/08/27
|
[
"https://Stackoverflow.com/questions/29496",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/648/"
] |
29,511 |
<p>In Ruby, trying to print out the individual elements of a String is giving me trouble. Instead of seeing each character, I'm seeing their ASCII values instead: </p>
<pre><code>>> a = "0123"
=> "0123"
>> a[0]
=> 48
</code></pre>
<p>I've looked online but can't find any way to get the original "0" back out of it. I'm a little new to Ruby to I know it has to be something simple but I just can't seem to find it.</p>
|
[
{
"answer_id": 29512,
"author": "SCdF",
"author_id": 1666,
"author_profile": "https://Stackoverflow.com/users/1666",
"pm_score": 3,
"selected": false,
"text": "a[0,1] a[0]"
},
{
"answer_id": 29521,
"author": "Joseph Pecoraro",
"author_id": 792,
"author_profile": "https://Stackoverflow.com/users/792",
"pm_score": 5,
"selected": true,
"text": "a[0].chr\n"
},
{
"answer_id": 38710,
"author": "Nathan Fritz",
"author_id": 4142,
"author_profile": "https://Stackoverflow.com/users/4142",
"pm_score": 3,
"selected": false,
"text": "\"ABC\"[2,1] \n\"ABC\"[2..2]\n\"ABC\".slice(2,1)\n"
},
{
"answer_id": 31042578,
"author": "John La Rooy",
"author_id": 174728,
"author_profile": "https://Stackoverflow.com/users/174728",
"pm_score": 0,
"selected": false,
"text": "each_char chars irb(main):001:0> a = \"0123\"\n=> \"0123\"\nirb(main):002:0> Array(a.each_char)\n=> [\"0\", \"1\", \"2\", \"3\"]\nirb(main):003:0> puts Array(a.each_char)\n0\n1\n2\n3\n=> nil\n"
}
] |
2008/08/27
|
[
"https://Stackoverflow.com/questions/29511",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/422/"
] |
29,525 |
<p>Can anyone tell me what is the <em>memory usage overhead associated with PHP opcode cache</em>? </p>
<p>I've seen a lot of reviews of <code>opcode cache</code> but all of them only concentrate on the performance increase. I have a small entry level <em>VPS and memory limits</em> are a concern for me. </p>
|
[
{
"answer_id": 29824,
"author": "AdamTheHutt",
"author_id": 1103,
"author_profile": "https://Stackoverflow.com/users/1103",
"pm_score": 0,
"selected": false,
"text": "limit APC apc_store() apc_fetch()"
}
] |
2008/08/27
|
[
"https://Stackoverflow.com/questions/29525",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2976/"
] |
29,531 |
<p>I want to use CodeDOM to both declare and initialize my static field in one statement. How can I do this?</p>
<pre><code>// for example
public static int MyField = 5;
</code></pre>
<p>I can seem to figure out how to declare a static field, and I can set its value later, but I can't seem to get the above effect.</p>
<p>@lomaxx,
Naw, I just want static. I don't want const. This value can change. I just wanted the simplicity of declaring and init'ing in one fell swoop. As if anything in the codedom world is simple. Every type name is 20+ characters long and you end up building these huge expression trees. Makes my eyes bug out. I'm only alive today thanks to resharper's reformatting.</p>
|
[
{
"answer_id": 29538,
"author": "Haacked",
"author_id": 598,
"author_profile": "https://Stackoverflow.com/users/598",
"pm_score": 1,
"selected": false,
"text": "private static Foo instance = new Foo();\n"
}
] |
2008/08/27
|
[
"https://Stackoverflow.com/questions/29531",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/404/"
] |
29,539 |
<p>Is there a one line function call that quits the program and displays a message? I know in Perl it's as simple as:</p>
<pre><code>die("Message goes here")
</code></pre>
<p>I'm tired of typing this:</p>
<pre><code>puts "Message goes here"
exit
</code></pre>
|
[
{
"answer_id": 29547,
"author": "Mike Stone",
"author_id": 122,
"author_profile": "https://Stackoverflow.com/users/122",
"pm_score": 1,
"selected": false,
"text": "def die(msg)\n puts msg\n exit\nend\n"
},
{
"answer_id": 29587,
"author": "Jörg W Mittag",
"author_id": 2988,
"author_profile": "https://Stackoverflow.com/users/2988",
"pm_score": 5,
"selected": false,
"text": "RuntimeError raise RuntimeError, 'Message goes here'\n"
},
{
"answer_id": 86325,
"author": "Chris Bunch",
"author_id": 422,
"author_profile": "https://Stackoverflow.com/users/422",
"pm_score": 10,
"selected": true,
"text": "abort abort(\"Message goes here\")\n abort STDERR puts STDOUT"
},
{
"answer_id": 43490860,
"author": "Giuse",
"author_id": 6392246,
"author_profile": "https://Stackoverflow.com/users/6392246",
"pm_score": 2,
"selected": false,
"text": "Kernel.at_exit { puts \"sayonara\" }\n# do whatever\n# [...]\n# call #exit or #abort or just let the program end\n# calling #exit! will skip the call\n"
}
] |
2008/08/27
|
[
"https://Stackoverflow.com/questions/29539",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/422/"
] |
29,558 |
<p>This might be on the "discussy" side, but I would really like to hear your view on this.</p>
<p>Previously I have often written data access classes that handled both reading and writing, which often led to poor naming, like FooIoHandler etc. The rule of thumb that classes that are hard to name probably are poorly designed suggests that this is not a good solution.</p>
<p>So, I have recently started splitting the data access into FooWriter and FooReader, which leads to nicer names and gives some additional flexibility, but at the same time I kind of like keeping it together, if the classes are not to big.</p>
<p>Is a reader/writer separation a better design, or should I combine them? If I should combine them, what the heck should I name the class?</p>
<p>Thanks /Erik</p>
|
[
{
"answer_id": 29577,
"author": "Yaakov Ellis",
"author_id": 51,
"author_profile": "https://Stackoverflow.com/users/51",
"pm_score": 2,
"selected": false,
"text": "Car car = new Car();\ncar.Manufacturer = \"Toyota\"\ncar.Model = \"Camry\"\ncar.Year = 2006;\ncar.CarID = CarDB.InsertCar(car)\ncar.OwnerID = 2;\nCarDB.UpdateCar(car);\n"
}
] |
2008/08/27
|
[
"https://Stackoverflow.com/questions/29558",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/276/"
] |
29,562 |
<p>I wrote a quick program in python to add a gtk GUI to a cli program. I was wondering how I can create an installer using distutils. Since it's just a GUI frontend for a command line app it only works in *nix anyway so I'm not worried about it being cross platform.</p>
<p>my main goal is to create a .deb package for debian/ubuntu users, but I don't understand make/configure files. I've primarily been a web developer up until now.</p>
<p><strong>edit</strong>: Does anyone know of a project that uses distutils so I could see it in action and, you know, actually try building it?</p>
<h2>Here are a few useful links</h2>
<ul>
<li><p><a href="https://wiki.ubuntu.com/PackagingGuide/Python" rel="nofollow noreferrer">Ubuntu Python Packaging Guide</a></p>
<p>This Guide is <strong><em>very</em></strong> helpful. I don't know how I missed it during my initial wave of gooling. It even walks you through packaging up an existing python application</p></li>
<li><p><a href="https://wiki.ubuntu.com/MOTU/GettingStarted" rel="nofollow noreferrer">The Ubuntu MOTU Project</a></p>
<p>This is the official package maintaining project at ubuntu. Anyone can join, and there are lots of tutorials and info about creating packages, of all types, which include the above 'python packaging guide'.</p></li>
<li><p><a href="http://episteme.arstechnica.com/eve/forums/a/tpc/f/96509133/m/808004952931" rel="nofollow noreferrer">"Python distutils to deb?" - Ars Technica Forum discussion</a></p>
<p>According to this conversation, you can't just use distutils. It doesn't follow the debian packaging format (or something like that). I guess that's why you need dh_make as seen in the Ubuntu Packaging guide</p></li>
<li><p><a href="http://osdir.com/ml/linux.debian.devel.python/2004-10/msg00013.html" rel="nofollow noreferrer">"A bdist_deb command for distutils</a></p>
<p>This one has some interesting discussion (it's also how I found the ubuntu guide) about concatenating a zip-file and a shell script to create some kind of universal executable (anything with python and bash that is). weird. Let me know if anyone finds more info on this practice because I've never heard of it.</p></li>
<li><p><A href="http://mail.python.org/pipermail/distutils-sig/2000-May/001000.html" rel="nofollow noreferrer">Description of the deb format and how distutils fit in - python mailing list</a></p></li>
</ul>
|
[
{
"answer_id": 29575,
"author": "Sander",
"author_id": 2928,
"author_profile": "https://Stackoverflow.com/users/2928",
"pm_score": 5,
"selected": true,
"text": "#!/usr/bin/python \n\nfrom distutils.core import setup \n\nsetup (name = 'Initech Package 3', \n description = \"Services and libraries ABC, DEF\", \n author = \"That Guy, Initech Ltd\", \n author_email = \"[email protected]\", \n version = '1.0.5', \n package_dir = {'Package3' : 'site-packages/Package3'}, \n packages = ['Package3', 'Package3.Queries'], \n data_files = [ \n ('/etc/Package3', ['etc/Package3/ExternalResources.conf']) \n ])\n"
},
{
"answer_id": 4716772,
"author": "Stuart Cardall",
"author_id": 555451,
"author_profile": "https://Stackoverflow.com/users/555451",
"pm_score": 3,
"selected": false,
"text": "apt-get install python-stdeb"
}
] |
2008/08/27
|
[
"https://Stackoverflow.com/questions/29562",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2908/"
] |
29,580 |
<p>It's one of those things that seems to have an odd curve where the more I think about it, the more it makes sense. To a certain extent, of course. And then it doesn't make sense to me at all.</p>
<p>Care to enlighten me?</p>
|
[
{
"answer_id": 289682,
"author": "Stein G. Strindhaug",
"author_id": 26115,
"author_profile": "https://Stackoverflow.com/users/26115",
"pm_score": 0,
"selected": false,
"text": "select * from hugetable where somecondition; limit offset"
},
{
"answer_id": 374980,
"author": "JoeBloggs",
"author_id": 34097,
"author_profile": "https://Stackoverflow.com/users/34097",
"pm_score": 2,
"selected": false,
"text": "SQL_CALC_FOUND_ROWS"
}
] |
2008/08/27
|
[
"https://Stackoverflow.com/questions/29580",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2293/"
] |
29,621 |
<p>On Windows I can do:</p>
<pre><code>HANDLE hCurrentProcess = GetCurrentProcess();
SetPriorityClass(hCurrentProcess, ABOVE_NORMAL_PRIORITY_CLASS);
</code></pre>
<p>How can I do the same thing on *nix?</p>
|
[
{
"answer_id": 29623,
"author": "Silas Snider",
"author_id": 2933,
"author_profile": "https://Stackoverflow.com/users/2933",
"pm_score": 6,
"selected": true,
"text": "#include <sys/time.h>\n#include <sys/resource.h>\n\nint main(){\n setpriority(PRIO_PROCESS, 0, -20);\n}\n"
}
] |
2008/08/27
|
[
"https://Stackoverflow.com/questions/29621",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/163/"
] |
29,624 |
<p>I have a form element that contains multiple lines of inputs. Think of each line as attributes of a new object that I want to create in my web application. And, I want to be able to create multiple new objects in one HTTP POST. I'm using Javascript's built-in cloneNode(true) method to clone each line. The problem is that each input-line also has a removal link attached to its onclick-event:</p>
<pre><code>// prototype based
<div class="input-line">
<input .../>
<a href="#" onclick="$(this).up().remove();"> Remove </a>
</div>
</code></pre>
<p>When the cloned input-line's removal link is clicked, it also removes any input-lines that were cloned from the same dom object. Is it possible to rebind the "this" object to the proper anchor tag after using cloneNode(true) on the above DOM element?</p>
|
[
{
"answer_id": 32281,
"author": "doekman",
"author_id": 56,
"author_profile": "https://Stackoverflow.com/users/56",
"pm_score": 0,
"selected": false,
"text": "var newItem = $(item).cloneNode(false);\nnewItem.innerHTML = $(item).innerHTML;\n"
},
{
"answer_id": 170515,
"author": "Greg",
"author_id": 24181,
"author_profile": "https://Stackoverflow.com/users/24181",
"pm_score": 0,
"selected": false,
"text": "<div id=\"x\">\n <div class=\"input-line\" id=\"y\">\n <input type=\"text\">\n <a href=\"#\" onclick=\"$(this).up().remove();\"> Remove </a>\n </div>\n</div>\n\n<script>\n\n$('x').appendChild($('y').cloneNode(true));\n$('x').appendChild($('y').cloneNode(true));\n$('x').appendChild($('y').cloneNode(true));\n\n</script>\n"
},
{
"answer_id": 175324,
"author": "J5.",
"author_id": 25380,
"author_profile": "https://Stackoverflow.com/users/25380",
"pm_score": 0,
"selected": false,
"text": "$(this).up().remove() function _debugRemoveInputLine(this) {\n debugger;\n $(this).up().remove();\n}"
},
{
"answer_id": 194969,
"author": "Kornel",
"author_id": 27009,
"author_profile": "https://Stackoverflow.com/users/27009",
"pm_score": 4,
"selected": true,
"text": "formObject.onclick = function(e)\n{\n e=e||event; // IE sucks\n var target = e.target||e.srcElement; // and sucks again\n\n // target is the element that has been clicked\n if (target && target.className=='remove') \n {\n target.parentNode.parentNode.removeChild(target.parentNode);\n return false; // stop event from bubbling elsewhere\n }\n}\n <div>\n <input…>\n <button type=button class=remove>Remove without JS handler!</button>\n</div>\n"
}
] |
2008/08/27
|
[
"https://Stackoverflow.com/questions/29624",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1376/"
] |
29,626 |
<p>In a VB.NET WinForms project, I get an exception</p>
<blockquote>
<p>Cannot access a disposed of object</p>
</blockquote>
<p>when closing a form. It occurs very rarely and I cannot recreate it on demand. The stack trace looks like this:</p>
<pre><code>Cannot access a disposed object. Object name: 'dbiSchedule'.
at System.Windows.Forms.Control.CreateHandle()
at System.Windows.Forms.Control.get_Handle()
at System.Windows.Forms.Control.PointToScreen(Point p)
at Dbi.WinControl.Schedule.dbiSchedule.a(Boolean A_0)
at Dbi.WinControl.Schedule.dbiSchedule.a(Object A_0, EventArgs A_1)
at System.Windows.Forms.Timer.OnTick(EventArgs e)
at System.Windows.Forms.Timer.TimerNativeWindow.WndProc(Message& m)
at System.Windows.Forms.NativeWindow.Callback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
</code></pre>
<p>The dbiSchedule is a schedule control from Dbi-tech. There is a timer on the form that updates the schedule on the screen every few minutes.</p>
<p>Any ideas what is causing the exception and how I might go about fixing it? or even just being able to recreate it on demand?</p>
<hr>
<p>Hej! Thanks for all the answers. We do stop the Timer on the FormClosing event and we do check the IsDisposed property on the schedule component before using it in the Timer Tick event but it doesn't help.</p>
<p>It's a really annoying problem because if someone did come up with a solution that worked - I wouldn't be able to confirm the solution because I cannot recreate the problem manually.</p>
|
[
{
"answer_id": 29637,
"author": "Gishu",
"author_id": 1695,
"author_profile": "https://Stackoverflow.com/users/1695",
"pm_score": 4,
"selected": false,
"text": "if ControlObject.IsDisposed then return; // or do whatever - but don't call control methods\n"
},
{
"answer_id": 9232678,
"author": "goku_da_master",
"author_id": 151325,
"author_profile": "https://Stackoverflow.com/users/151325",
"pm_score": 2,
"selected": false,
"text": "_timer.Start()\n Private Sub myForm_FormClosing(ByVal sender As System.Object, ByVal e As System.Windows.Forms.FormClosingEventArgs) Handles MyBase.FormClosing\n ' set the form closing flag so the timer doesn't fire even after the form is closed.\n _formIsClosing = True\n _timer.Stop()\n _timer.Dispose()\nEnd Sub\n Private Sub Timer_Elapsed(ByVal sender As System.Object, ByVal e As System.Timers.ElapsedEventArgs) Handles _timer.Elapsed\n ' Don't want the timer stepping on itself (ie. the time interval elapses before the first call is done processing)\n _timer.Stop()\n\n ' do work here\n\n ' Only start the timer if the form is open. Without this check, the timer will run even if the form is closed.\n If Not _formIsClosing Then\n _timer.Interval = _refreshInterval\n _timer.Start() ' ObjectDisposedException() is thrown here unless you check the _formIsClosing flag.\n End If\nEnd Sub\n"
}
] |
2008/08/27
|
[
"https://Stackoverflow.com/questions/29626",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/961/"
] |
29,630 |
<p>I've writen an Excel-based, database reporting tool. Currentely, all the VBA code is associated with a single XLS file. The user generates the report by clicking a button on the toolbar. Unfortunately, unless the user has saved the file under another file name, all the reported data gets wiped-out.</p>
<p>When I have created similar tools in Word, I can put all the code in a template (.dot) file and call it from there. If I put the template file in the Office startup folder, it will launch everytime I start Word. Is there a similar way, to package and distribute my code in Excel? I've tried using Add-ins, but I didn't find a way to call the code from the application window.</p>
|
[
{
"answer_id": 29778,
"author": "saschabeaumont",
"author_id": 592,
"author_profile": "https://Stackoverflow.com/users/592",
"pm_score": 3,
"selected": false,
"text": "Public Sub Workbook_Open()\n ' startup code / add toolbar / load saved settings, etc.\nEnd Sub\n"
}
] |
2008/08/27
|
[
"https://Stackoverflow.com/questions/29630",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2665/"
] |
29,645 |
<p>I have a few lines of PowerShell code that I would like to use as an automated script. The way I would like it to be able to work is to be able to call it using one of the following options:</p>
<ol>
<li>One command line that opens PowerShell, executes script and closes PowerShell (this would be used for a global build-routine)</li>
<li>A file that I can double-click to run the above (I would use this method when manually testing components of my build process)</li>
</ol>
<p>I have been going through PowerShell documentation online, and although I can find lots of scripts, I have been unable to find instructions on how to do what I need. Thanks for the help.</p>
|
[
{
"answer_id": 29649,
"author": "Matt Hamilton",
"author_id": 615,
"author_profile": "https://Stackoverflow.com/users/615",
"pm_score": 4,
"selected": true,
"text": "powershell.exe .\\foo.ps1\n"
},
{
"answer_id": 29675,
"author": "Yaakov Ellis",
"author_id": 51,
"author_profile": "https://Stackoverflow.com/users/51",
"pm_score": 2,
"selected": false,
"text": "C:\\WINDOWS\\system32\\windowspowershell\\v1.0\\powershell.exe LocationOfPS1File\n"
},
{
"answer_id": 20060430,
"author": "deadlydog",
"author_id": 602585,
"author_profile": "https://Stackoverflow.com/users/602585",
"pm_score": 3,
"selected": false,
"text": "PowerShell C:\\Path\\To\\YourPowerShellScript.ps1\n PowerShell .\\YourPowerShellScript.ps1\n @ECHO OFF\nSET ThisScriptsDirectory=%~dp0\nSET PowerShellScriptPath=%ThisScriptsDirectory%MyPowerShellScript.ps1\nPowerShell -NoProfile -ExecutionPolicy Bypass -Command \"& '%PowerShellScriptPath%'\"\n Start-Process PowerShell -ArgumentList 'Set-ExecutionPolicy RemoteSigned -Force' -Verb RunAs\n"
}
] |
2008/08/27
|
[
"https://Stackoverflow.com/questions/29645",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/51/"
] |
29,647 |
<p>Let's say I'm creating a program in C that needs to use a tempfile. Creating an ad hoc tempfile in /tmp is probably not a good idea. Is there a function or OS call to supply me with a tempfile name so that I can begin to write and read from it?</p>
|
[
{
"answer_id": 29656,
"author": "gavrie",
"author_id": 2794,
"author_profile": "https://Stackoverflow.com/users/2794",
"pm_score": 5,
"selected": true,
"text": "mkstemp(3) tmpfile(3) tmpfile mkstemp tmpfile"
},
{
"answer_id": 29693,
"author": "gavrie",
"author_id": 2794,
"author_profile": "https://Stackoverflow.com/users/2794",
"pm_score": 2,
"selected": false,
"text": "tmpnam tmpnam mkstemp tmpfile"
},
{
"answer_id": 37542952,
"author": "Cristiano Pereira",
"author_id": 6145218,
"author_profile": "https://Stackoverflow.com/users/6145218",
"pm_score": 0,
"selected": false,
"text": "int fd;\nfd = mkstemp(\"hdrXXXXXX);\n/* Read out the link to our file descriptor. */\nsprintf(path, \"/proc/self/fd/%d\", fd);\nmemset(result, 0, sizeof(result));\nreadlink(path, result, sizeof(result)-1);\n\n/* Print the result. */\nprintf(\"%s\\n\", result);\n"
},
{
"answer_id": 64954616,
"author": "hanshenrik",
"author_id": 1067003,
"author_profile": "https://Stackoverflow.com/users/1067003",
"pm_score": 0,
"selected": false,
"text": "FILE *tmp=tmpfile();\nchar path[PATH_MAX+1]={0};\nsprintf(path, \"/dev/fd/%d\", fileno(tmp));\nprintf(\"%s\\n\", path);\n"
}
] |
2008/08/27
|
[
"https://Stackoverflow.com/questions/29647",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/432/"
] |
29,654 |
<p>I'm developing a WinForms application (.Net 3.5, no WPF) where I want to be able to display foreign key lookups in a databound DataGridView. </p>
<p>An example of the sort of relationship is that I have a table of OrderLines. Orderlines have a foreign key relationship to Products and Products in turn have a foreign key relationship to ProductTypes. </p>
<p>I'd like to have a databound DataGridView where each row represents an orderline, displaying the line's product and producttype.</p>
<p>Users can add or edit orderlines direct to the grid and choose the product for the order line from a comboBoxColumn - this should then update the producttype column, showing the producttype for the selected product, in the same row.</p>
<p>The closest to a good fit that I've found so far is to introduce a domain object representing an orderline then bind the DataGridView to a collection of these orderlines. I then add properties to the orderline object that expose the product and the producttype, and raise relevant notifypropertychanged events to keep everything up to date. In my orderline repository I can then wire up the mappings between this orderline object and the three tables in my database.</p>
<p>This works for the databinding side of things, but having to hand code all that OR-mapping in the repository seems bad. I thought nHibernate would be able to help with this wiring up but am struggling with the mappings through all the foreign keys - they seem to work ok (the foreignkey lookup for an orderline's product creates the correct product object based on the foreign key) until I try to do the databinding, I can't get the databound id columns to update my product or producttype objects.</p>
<p>Is my general approach even in the right ballpark? If it is, what is a good solution to the mapping problem?</p>
<p>Or, is there a better solution to databinding rows including foreign key lookups that I haven't even considered?</p>
|
[
{
"answer_id": 225076,
"author": "Bevan",
"author_id": 30280,
"author_profile": "https://Stackoverflow.com/users/30280",
"pm_score": 0,
"selected": false,
"text": "myTextBox.DataBindings.Add(\"Text\", anOrderLine, \"OrderedPart.PartNumber\");\n"
}
] |
2008/08/27
|
[
"https://Stackoverflow.com/questions/29654",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2660/"
] |
29,664 |
<p>I need to specifically catch SQL server timeout exceptions so that they can be handled differently. I know I could catch the SqlException and then check if the message string Contains "Timeout" but was wondering if there is a better way to do it?</p>
<pre><code>try
{
//some code
}
catch (SqlException ex)
{
if (ex.Message.Contains("Timeout"))
{
//handle timeout
}
else
{
throw;
}
}
</code></pre>
|
[
{
"answer_id": 62688,
"author": "Jonathan",
"author_id": 6910,
"author_profile": "https://Stackoverflow.com/users/6910",
"pm_score": 8,
"selected": true,
"text": "if (ex.Number == -2)\n{\n //handle timeout\n}\n try\n{\n SqlConnection sql = new SqlConnection(@\"Network Library=DBMSSOCN;Data Source=YourServer,1433;Initial Catalog=YourDB;Integrated Security=SSPI;\");\n sql.Open();\n\n SqlCommand cmd = sql.CreateCommand();\n cmd.CommandText = \"DECLARE @i int WHILE EXISTS (SELECT 1 from sysobjects) BEGIN SELECT @i = 1 END\";\n cmd.ExecuteNonQuery(); // This line will timeout.\n\n cmd.Dispose();\n sql.Close();\n}\ncatch (SqlException ex)\n{\n if (ex.Number == -2) {\n Console.WriteLine (\"Timeout occurred\");\n }\n}\n"
},
{
"answer_id": 54634750,
"author": "John Evans",
"author_id": 2255709,
"author_profile": "https://Stackoverflow.com/users/2255709",
"pm_score": 4,
"selected": false,
"text": " try\n {\n // some code\n }\n catch (SqlException ex) when (ex.Number == -2) // -2 is a sql timeout\n {\n // handle timeout\n }\n"
}
] |
2008/08/27
|
[
"https://Stackoverflow.com/questions/29664",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2231/"
] |
29,668 |
<p>I have two machines in two different domains. On both I have VS 2005 installed. I want remote debug between them. Without authentication it is possible but I want to debug managed code. I don't want to debug directly since it is really crappy machine.</p>
<p>When I try to attach with debugger I get message "The trust relationship between this workstation and primary domain failed." Any idea how to overcome this ? I tried tricks with adding same local username on both machines but with no luck.</p>
<p>EDIT: I have same local users on both machines. I started both VS2005 and Debugging monitor with RunAs using local users. I turned Windows Auditing on debug machine and I see that local user from VS2005 machine is trying to logon. But he fails with error 0xC000018D (ERROR_TRUSTED_RELATIONSHIP_FAILURE)</p>
|
[
{
"answer_id": 17620190,
"author": "Walter Wilfinger",
"author_id": 2184185,
"author_profile": "https://Stackoverflow.com/users/2184185",
"pm_score": 1,
"selected": false,
"text": "PHYSICAL DOMAIN DOMAIN\\employee VIRTUAL PHYSICAL\\employee PHYSICAL VIRTUAL\\employee VIRTUAL DOMAIN\\employee VIRTUAL VIRTUAL\\employee PHYSICAL DOMAIN\\employee VIRTUAL"
}
] |
2008/08/27
|
[
"https://Stackoverflow.com/questions/29668",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/501/"
] |
29,686 |
<p>I'll have an ASP.net page that creates some Excel Sheets and sends them to the user. The problem is, sometimes I get Http timeouts, presumably because the Request runs longer than executionTimeout (110 seconds per default).</p>
<p>I just wonder what my options are to prevent this, without wanting to generally increase the executionTimeout in <code>web.config</code>?</p>
<p>In PHP, <a href="http://fr.php.net/manual/en/function.set-time-limit.php" rel="nofollow noreferrer"><code>set_time_limit</code></a> exists which can be used in a function to extend its life, but I did not see anything like that in C#/ASP.net?</p>
<p>How do you handle long-running functions in ASP.net?</p>
|
[
{
"answer_id": 29754,
"author": "John Hunter",
"author_id": 2253,
"author_profile": "https://Stackoverflow.com/users/2253",
"pm_score": 5,
"selected": true,
"text": "HttpContext.Current.Server.ScriptTimeout"
}
] |
2008/08/27
|
[
"https://Stackoverflow.com/questions/29686",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/91/"
] |
29,689 |
<p>I have a large codebase without Javadoc, and I want to run a program to write a skeleton with the basic Javadoc information (e.g., for each method's parameter write @param...), so I just have to fill the gaps left.</p>
<p>Anyone know a good solution for this?</p>
<p><strong>Edit:</strong></p>
<p>JAutodoc is what I was looking for. It has Ant tasks, an Eclipse plugin, and uses Velocity for the template definition.</p>
|
[
{
"answer_id": 16472314,
"author": "Booger",
"author_id": 636988,
"author_profile": "https://Stackoverflow.com/users/636988",
"pm_score": 4,
"selected": false,
"text": "/**\n"
},
{
"answer_id": 25558376,
"author": "Jorgesys",
"author_id": 250260,
"author_profile": "https://Stackoverflow.com/users/250260",
"pm_score": 3,
"selected": false,
"text": "/**\n * @param currDate\n * @param index\n * @return\n */\n public static String getAtoBinary(String currDate, int index){ \n String HourA = \"0\";\n try{\n String[] mydate = currDate.split(\"/\");\n HourA = mydate[index].substring(1, 2);\n }catch(Exception e){\n Log.e(TAG, e.getMessage());\n }\n return HourA;\n }\n"
}
] |
2008/08/27
|
[
"https://Stackoverflow.com/questions/29689",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2937/"
] |
29,696 |
<p>How do you stop the designer from auto generating code that sets the value for public properties on a user control?</p>
|
[
{
"answer_id": 29717,
"author": "Will Dean",
"author_id": 987,
"author_profile": "https://Stackoverflow.com/users/987",
"pm_score": 3,
"selected": false,
"text": "[Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]\n"
},
{
"answer_id": 29720,
"author": "Erik Hellström",
"author_id": 2795,
"author_profile": "https://Stackoverflow.com/users/2795",
"pm_score": 7,
"selected": true,
"text": "[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]\npublic string Name\n{\n get;\n set;\n}\n"
},
{
"answer_id": 20068998,
"author": "27k1",
"author_id": 835921,
"author_profile": "https://Stackoverflow.com/users/835921",
"pm_score": -1,
"selected": false,
"text": "[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]\npublic new string Name { \n get; \n set; \n}\n"
}
] |
2008/08/27
|
[
"https://Stackoverflow.com/questions/29696",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2253/"
] |
29,699 |
<p>I have a database with names in it such as John Doe etc. Unfortunately some of these names contain quotes like Keiran O'Keefe. Now when I try and search for such names as follows:</p>
<pre><code>SELECT * FROM PEOPLE WHERE SURNAME='O'Keefe'
</code></pre>
<p>I (understandably) get an error.</p>
<p>How do I prevent this error from occurring. I am using Oracle and PLSQL.</p>
|
[
{
"answer_id": 29727,
"author": "Matt Sheppard",
"author_id": 797,
"author_profile": "https://Stackoverflow.com/users/797",
"pm_score": 6,
"selected": true,
"text": "SELECT * FROM PEOPLE WHERE SURNAME='O'Keefe' SELECT * FROM PEOPLE WHERE SURNAME='O''Keefe' SELECT * FROM PEOPLE WHERE SURNAME=?"
},
{
"answer_id": 30303,
"author": "Rad",
"author_id": 1349,
"author_profile": "https://Stackoverflow.com/users/1349",
"pm_score": 1,
"selected": false,
"text": "Command = SELECT * FROM PEOPLE WHERE SURNAME=?\n"
},
{
"answer_id": 84265,
"author": "Laurent Schneider",
"author_id": 16166,
"author_profile": "https://Stackoverflow.com/users/16166",
"pm_score": 2,
"selected": false,
"text": "SELECT * FROM PEOPLE WHERE SURNAME=q'{O'Keefe}'\n"
},
{
"answer_id": 9307168,
"author": "rjmcb",
"author_id": 1166176,
"author_profile": "https://Stackoverflow.com/users/1166176",
"pm_score": 0,
"selected": false,
"text": "$db = Zend_Db_Table_Abstract::getDefaultAdapter(); $db->quoteInto('your_query_here = ?','your_value_here'); //SELECT * FROM PEOPLE WHERE SURNAME='O'Keefe' will become\nSELECT * FROM PEOPLE WHERE SURNAME='\\'O\\'Keefe\\''\n"
}
] |
2008/08/27
|
[
"https://Stackoverflow.com/questions/29699",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/445/"
] |
29,709 |
<p>I am using jQuery and trying to find a cross browser way to get the pixel coordinates of the caret in <code><textarea></code>s and <code>input</code> boxes such that I can place an absolutely positioned div around this location.</p>
<p>Is there some jQuery plugin? Or JavaScript snippet to do just that?</p>
|
[
{
"answer_id": 29934,
"author": "Cheekysoft",
"author_id": 1820,
"author_profile": "https://Stackoverflow.com/users/1820",
"pm_score": 0,
"selected": false,
"text": "function insertAtCursor(myField, myValue) {\n\n/* selecion model - ie */\nif (document.selection) {\n myField.focus();\n sel = document.selection.createRange();\n sel.text = myValue;\n}\n\n/* field.selectionstart/end firefox */ \nelse if (myField.selectionStart || myField.selectionStart == '0' ) {\n\n var startPos = myField.selectionStart;\n var endPos = myField.selectionEnd;\n myField.value = myField.value.substring(0, startPos)\n + myValue\n + myField.value.substring(endPos, myField.value.length);\n\n myField.selectionStart = startPos + myValue.length;\n myField.selectionEnd = startPos + myValue.length;\n myField.focus();\n} \n\n// cursor not active/present\nelse {\n myField.value += myValue;\n}\n"
},
{
"answer_id": 22446703,
"author": "Dan Dascalescu",
"author_id": 1269037,
"author_profile": "https://Stackoverflow.com/users/1269037",
"pm_score": 6,
"selected": true,
"text": "<div> <textarea> <span>"
}
] |
2008/08/27
|
[
"https://Stackoverflow.com/questions/29709",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/238/"
] |
29,731 |
<p>I have done a bit of research into this and it seems that the only way to sort a data bound combo box is to sort the data source itself (a DataTable in a DataSet in this case). </p>
<p>If that is the case then the question becomes what is the best way to sort a DataTable?</p>
<p>The combo box bindings are set in the designer initialize using</p>
<p><pre><code>myCombo.DataSource = this.typedDataSet;
myCombo.DataMember = "Table1";
myCombo.DisplayMember = "ColumnB";
myCombo.ValueMember = "ColumnA";</pre></code></p>
<p>I have tried setting
<pre><code>this.typedDataSet.Table1.DefaultView.Sort = "ColumnB DESC";</pre></code>
But that makes no difference, I have tried setting this in the control constructor, before and after a typedDataSet.Merge call.</p>
|
[
{
"answer_id": 29735,
"author": "Andy Rose",
"author_id": 1762,
"author_profile": "https://Stackoverflow.com/users/1762",
"pm_score": 0,
"selected": false,
"text": "DataView dv = myDataTable.Select(\"filter expression\", \"sort\");\n"
},
{
"answer_id": 29738,
"author": "Matt Hamilton",
"author_id": 615,
"author_profile": "https://Stackoverflow.com/users/615",
"pm_score": 2,
"selected": false,
"text": "myDataTable.DefaultView.Sort = \"Field1, Field2 DESC\";\n"
},
{
"answer_id": 29752,
"author": "urini",
"author_id": 373,
"author_profile": "https://Stackoverflow.com/users/373",
"pm_score": 0,
"selected": false,
"text": "view.Sort = \"State, ZipCode DESC\";\n"
},
{
"answer_id": 29939,
"author": "Andy Rose",
"author_id": 1762,
"author_profile": "https://Stackoverflow.com/users/1762",
"pm_score": 1,
"selected": false,
"text": "myCombo.DataSource = this.typedDataSet.Tables[\"Table1\"].DefaultView;\nmyCombo.DisplayMember = \"ColumnB\";\nmyCombo.ValueMember = \"ColumnA\";\n"
}
] |
2008/08/27
|
[
"https://Stackoverflow.com/questions/29731",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2253/"
] |
29,746 |
<p>I'm looking for something that will show me the size of each folder within my main folder recursively.</p>
<p>This is a <a href="http://en.wikipedia.org/wiki/LAMP_%28software_bundle%29" rel="nofollow noreferrer">LAMP</a> server with a CGI-Bin so most any PHP script should work or anything that will work in the CGI-Bin.</p>
<p>My hosting company does not provide an interface for me to see which folders are consuming the most amount of space. I don't know of anything on the Internet and did a few searches however I came up with no results. </p>
<p>Something implementing graphs (<a href="http://en.wikipedia.org/wiki/GD_Graphics_Library" rel="nofollow noreferrer">GD</a>/<a href="http://en.wikipedia.org/wiki/ImageMagick" rel="nofollow noreferrer">ImageMagick</a>) would be best but not required.</p>
<p>My host supports only Perl in the CGI-BIN.</p>
|
[
{
"answer_id": 29755,
"author": "lubos hasko",
"author_id": 275,
"author_profile": "https://Stackoverflow.com/users/275",
"pm_score": 4,
"selected": true,
"text": "function getDirectorySize($path)\n{\n $totalsize = 0;\n $totalcount = 0;\n $dircount = 0;\n if ($handle = opendir ($path))\n {\n while (false !== ($file = readdir($handle)))\n {\n $nextpath = $path . '/' . $file;\n if ($file != '.' && $file != '..' && !is_link ($nextpath))\n {\n if (is_dir ($nextpath))\n {\n $dircount++;\n $result = getDirectorySize($nextpath);\n $totalsize += $result['size'];\n $totalcount += $result['count'];\n $dircount += $result['dircount'];\n }\n elseif (is_file ($nextpath))\n {\n $totalsize += filesize ($nextpath);\n $totalcount++;\n }\n }\n }\n }\n closedir ($handle);\n $total['size'] = $totalsize;\n $total['count'] = $totalcount;\n $total['dircount'] = $dircount;\n return $total;\n}\n\nfunction sizeFormat($size)\n{\n if($size<1024)\n {\n return $size.\" bytes\";\n }\n else if($size<(1024*1024))\n {\n $size=round($size/1024,1);\n return $size.\" KB\";\n }\n else if($size<(1024*1024*1024))\n {\n $size=round($size/(1024*1024),1);\n return $size.\" MB\";\n }\n else\n {\n $size=round($size/(1024*1024*1024),1);\n return $size.\" GB\";\n }\n\n}\n $path=\"/httpd/html/pradeep/\";\n$ar=getDirectorySize($path);\n\necho \"<h4>Details for the path : $path</h4>\";\necho \"Total size : \".sizeFormat($ar['size']).\"<br>\";\necho \"No. of files : \".$ar['count'].\"<br>\";\necho \"No. of directories : \".$ar['dircount'].\"<br>\"; \n Details for the path : /httpd/html/pradeep/\nTotal size : 2.9 MB\nNo. of files : 196\nNo. of directories : 20\n"
},
{
"answer_id": 31911,
"author": "John Douthat",
"author_id": 2774,
"author_profile": "https://Stackoverflow.com/users/2774",
"pm_score": 1,
"selected": false,
"text": "$ du -h\n <?php $d = escapeshellcmd(dirname(__FILE__)); echo nl2br(`du -h $d`) ?>\n"
},
{
"answer_id": 39269519,
"author": "nilopa",
"author_id": 6782895,
"author_profile": "https://Stackoverflow.com/users/6782895",
"pm_score": 0,
"selected": false,
"text": "<?php\nif (isset($_POST[\"nivel\"])) {\n $mostrar_hasta_nivel = $_POST[\"nivel\"];\n $comenzar_nivel_inferior = $_POST[\"comenzar_nivel_inferior\"];\n // $mostrar_hasta_nivel = 3;\n\n global $nivel_directorio_raiz;\n global $nivel_directorio;\n\n $path = dirname(__FILE__);\n if ($comenzar_nivel_inferior == \"si\") {\n $path = substr($path, 0, strrpos($path, \"/\"));\n }\n $nivel_directorio_raiz = count(explode(\"/\", $path)) - 1;\n $numero_fila = 1;\n\n\n // Comienzo de Tabla\n echo \"<table border='1' cellpadding='3' cellspacing='0'>\";\n // Fila encabezado\n echo \"<tr style='font-size: 100%; font-weight: bold;' bgcolor='#e2e2e2'><td></td><td>Ruta</td><td align='center'>Nivel</td><td align='right' style='color:#0000ff;'>Ficheros</td><td align='right'>Acumulado fich.</td><td align='right'>Directorio</td><td align='right' style='color:#0000ff;'>Tamaño</td><td align='right'>Acumulado tamaño</td></tr>\";\n // Inicio Filas de datos\n echo \"<tr>\";\n\n //Función que se invoca a si misma de forma recursiva según recorre el directorio raiz ($path)\n FileCount($path, $mostrar_hasta_nivel, $nivel_directorio_raiz); \n\n // Din Filas de datos\n echo \"</tr>\";\n // Fin de tabla\n echo \"</table>\";\n echo \"<div style='font-size: 120%;'>\";\n echo \"<br>Total ficheros en la ruta <b><em>\" . $path . \":</em> \" . number_format($count,0,\",\",\".\") . \"</b><br>\";\n echo \"Tamaño total ficheros: <b>\". number_format($acumulado_tamanho, 0,\",\",\".\") . \" Kb.</b><br>\";\n echo \"</div>\";\n\n echo \"<div style='min-height: 60px;'></div>\";\n\n} else {\n ?>\n <form name=\"formulario\" id=\"formulario\" method=\"post\" action=\"<?php echo $_SERVER['PHP_SELF']; ?>\">\n <br /><h2>Informe del Alojamiento por directorios (Número de Archivos y Tamaño)</h2>\n <br />Nivel de directorios a mostrar: <input type=\"text\" name=\"nivel\" id=\"nivel\" value=\"3\"><br /><br />\n <input type=\"checkbox\" name=\"comenzar_nivel_inferior\" value=\"si\" checked=\"checked\"/> Comenzar en nivel de directorio inmediatamente inferior a la ubicación de este módulo PHP<br />(<?php echo dirname(__FILE__) ?>)<br /><br />\n <input type=\"submit\" name=\"comenzar\" id=\"comenzar\" value=\"Comenzar proceso\"><br /><br />\n </form>\n <?php\n}\n\n\n\n\nfunction FileCount($dir, $mostrar_hasta_nivel, $nivel_directorio_raiz){\n global $count;\n global $count_anterior;\n global $suma_tamanho;\n global $acumulado_tamanho;\n\n $arr=explode('&',$dir);\n foreach($arr as $val){\n global $ruta_actual;\n\n if(is_dir($val) && file_exists($val)){\n global $total_directorio;\n global $numero_fila;\n $total_directorio = 0;\n\n $ob=scandir($val);\n foreach($ob as $file){\n if($file==\".\"||$file==\"..\"){\n continue;\n }\n $file=$val.\"/\".$file;\n\n if(is_file($file)){\n $count++;\n $suma_tamanho = $suma_tamanho + filesize($file)/1024;\n $acumulado_tamanho = $acumulado_tamanho + filesize($file)/1024;\n $total_directorio++;\n } elseif(is_dir($file)){\n FileCount($file, $mostrar_hasta_nivel, $nivel_directorio_raiz);\n }\n }\n\n $nivel_directorio = count(explode(\"/\", $val)) - 1;\n\n if ($nivel_directorio > $mostrar_hasta_nivel) {\n } else {\n $atributo_fila = (($numero_fila%2)==1 ? \"background-color:#ffffff;\" : \"background-color:#f2f2f2;\");\n echo \"<tr style='\".$atributo_fila.\"'><td>\".$numero_fila.\"</td><td>\".$val.\" </td><td align='center'>\".$nivel_directorio.\"</td><td align='right' style='color:#0000ff;'>\".number_format(($count - $count_anterior),0,\",\",\".\").\"</td><td align='right'>\".number_format($count,0,\",\",\".\").\"</td><td align='right'>\".number_format($total_directorio,0,\",\",\".\").\"</td><td align='right' style='color:#0000ff;'>\".number_format($suma_tamanho,0,\",\",\".\").\" Kb.</td><td align='right'>\".number_format($acumulado_tamanho,0,\",\",\".\").\" Kb.</td></tr>\";\n\n $count_anterior = $count;\n $suma_tamanho = 0;\n $numero_fila++;\n }\n\n }\n }\n}\n?>\n"
}
] |
2008/08/27
|
[
"https://Stackoverflow.com/questions/29746",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/115/"
] |
29,751 |
<p>I am having problems submitting forms which contain UTF-8 strings with Ajax. I am developing a <a href="http://en.wikipedia.org/wiki/Apache_Struts" rel="noreferrer">Struts</a> web application which runs in a <a href="http://en.wikipedia.org/wiki/Apache_Tomcat" rel="noreferrer">Tomcat</a> server. This is the environment I set up to work with UTF-8:</p>
<ul>
<li><p>I have added the attributes <code>URIEncoding="UTF-8" useBodyEncodingForURI="true"</code> into the <code>Connector</code> tag to Tomcat's <code>conf/server.xml</code> file.</p></li>
<li><p>I have a <code>utf-8_general_ci</code> database</p></li>
<li><p>I am using the next filter to ensure my request and responses are encoded in UTF-8</p>
<pre><code>package filters;
import java.io.IOException;
import javax.servlet.*;
public class UTF8Filter implements Filter {
public void destroy() {}
public void doFilter(ServletRequest request,ServletResponse response, FilterChain chain)
throws IOException, ServletException {
request.setCharacterEncoding("UTF-8");
response.setContentType("text/html;charset=UTF-8");
chain.doFilter(request, response);
}
public void init(FilterConfig filterConfig) throws ServletException {
}
}
</code></pre></li>
<li><p>I use this filter in WEB-INF/web.xml</p></li>
<li><p>I am using the next code for my JSON responses:</p>
<pre><code>public static void populateWithJSON(HttpServletResponse response,JSONObject json)
{
String CONTENT_TYPE="text/x-json;charset=UTF-8";
response.setContentType(CONTENT_TYPE);
response.setHeader("Cache-Control", "no-cache");
try {
response.getWriter().write(json.toString());
} catch (IOException e) {
throw new ApplicationException("Application Exception raised in RetrievedStories", e);
}
}
</code></pre></li>
</ul>
<p>Everything seems to work fine (content coming from the database is displayed properly, and I am able to submit forms which are stored in UTF-8 in the database). The problem is that I am <strong>not able to submit forms with Ajax</strong>. I use jQuery, and I thought the problem was the lack of contentType field in the Ajax request. But I was wrong. I have a really simple form to submit comments which contains of an id and a body. The body field can be in different languages such as Spanish, German, or whatever.</p>
<p>If I submit my form with body textarea containing <code>contraseña</code>, <a href="http://en.wikipedia.org/wiki/Firebug_%28software%29" rel="noreferrer">Firebug</a> shows me:</p>
<blockquote>
<h3>Request Headers</h3>
<ul>
<li><strong><em>Host</em></strong> localhost:8080</li>
<li><strong><em>Accept-Charset</em></strong> ISO-8859-1, utf-8;q=0.7;*q=0.7</li>
<li><strong><em>Content-Type</em></strong> application/x-www-form-urlencoded; charset UTF-8</li>
</ul>
</blockquote>
<p>If I execute <em>Copy Location with parameters</em> in Firebug, the encoding seems already wrong:</p>
<pre><code>http://localhost:8080/Cerepedia/corporate/postStoryComment.do?&body=contrase%C3%B1a&id=88
</code></pre>
<p>This is my jQuery code:</p>
<pre><code>function addComment() {
var comment_body = $("#postCommentForm textarea").val();
var item_id = $("#postCommentForm input:hidden").val();
var url = rooturl+"corporate/postStoryComment.do?";
$.post(url, { id: item_id, body: comment_body } ,
function(data){
/* Do stuff with the answer */
}, "json"); }
</code></pre>
<p>A submission of a form with jQuery is causing the next error server side (note I am using <a href="http://en.wikipedia.org/wiki/Hibernate_%28Java%29" rel="noreferrer">Hibernate</a>).</p>
<pre><code>javax.servlet.ServletException: org.hibernate.exception.GenericJDBCException: Could not execute JDBC batch update
at org.apache.struts.action.RequestProcessor.processException(RequestProcessor.java:520)
at org.apache.struts.action.RequestProcessor.processActionPerform(RequestProcessor.java:427)
at org.apache.struts.action.RequestProcessor.process(RequestProcessor.java:228)
at org.apache.struts.action.ActionServlet.process(ActionServlet.java:1913)
at org.apache.struts.action.ActionServlet.doPost(ActionServlet.java:462)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:710)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:803)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at com.cerebra.cerepedia.security.AuthorizationFilter.doFilter(AuthorizationFilter.java:78)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at com.cerebra.cerepedia.hibernate.HibernateSessionRequestFilter.doFilter(HibernateSessionRequestFilter.java:30)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at filters.UTF8Filter.doFilter(UTF8Filter.java:14)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:230)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:175)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:128)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:104)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:261)
at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:844)
at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:581)
at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:447)
at java.lang.Thread.run(Unknown Source)
Caused by: org.hibernate.exception.GenericJDBCException: Could not execute JDBC batch update
at org.hibernate.exception.SQLStateConverter.handledNonSpecificException(SQLStateConverter.java:103)
at org.hibernate.exception.SQLStateConverter.convert(SQLStateConverter.java:91)
at org.hibernate.exception.JDBCExceptionHelper.convert(JDBCExceptionHelper.java:43)
at org.hibernate.jdbc.AbstractBatcher.executeBatch(AbstractBatcher.java:249)
at org.hibernate.engine.ActionQueue.executeActions(ActionQueue.java:235)
at org.hibernate.engine.ActionQueue.executeActions(ActionQueue.java:139)
at org.hibernate.event.def.AbstractFlushingEventListener.performExecutions(AbstractFlushingEventListener.java:298)
at org.hibernate.event.def.DefaultFlushEventListener.onFlush(DefaultFlushEventListener.java:27)
at org.hibernate.impl.SessionImpl.flush(SessionImpl.java:1000)
at org.hibernate.impl.SessionImpl.managedFlush(SessionImpl.java:338)
at org.hibernate.transaction.JDBCTransaction.commit(JDBCTransaction.java:106)
at com.cerebra.cerepedia.item.dao.ItemDAOHibernate.addComment(ItemDAOHibernate.java:505)
at com.cerebra.cerepedia.item.ItemManagerPOJOImpl.addComment(ItemManagerPOJOImpl.java:164)
at com.cerebra.cerepedia.struts.item.ItemAction.addComment(ItemAction.java:126)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.apache.struts.actions.DispatchAction.dispatchMethod(DispatchAction.java:269)
at org.apache.struts.actions.DispatchAction.execute(DispatchAction.java:170)
at org.apache.struts.actions.MappingDispatchAction.execute(MappingDispatchAction.java:166)
at org.apache.struts.action.RequestProcessor.processActionPerform(RequestProcessor.java:425)
... 26 more
Caused by: java.sql.BatchUpdateException: Incorrect string value: '\xF1a' for column 'body' at row 1
at com.mysql.jdbc.ServerPreparedStatement.executeBatch(ServerPreparedStatement.java:657)
at com.mchange.v2.c3p0.impl.NewProxyPreparedStatement.executeBatch(NewProxyPreparedStatement.java:1723)
at org.hibernate.jdbc.BatchingBatcher.doExecuteBatch(BatchingBatcher.java:48)
at org.hibernate.jdbc.AbstractBatcher.executeBatch(AbstractBatcher.java:242)
... 44 more
26-ago-2008 19:54:48 org.apache.catalina.core.StandardWrapperValve invoke
GRAVE: Servlet.service() para servlet action lanzó excepción
java.sql.BatchUpdateException: Incorrect string value: '\xF1a' for column 'body' at row 1
at com.mysql.jdbc.ServerPreparedStatement.executeBatch(ServerPreparedStatement.java:657)
at com.mchange.v2.c3p0.impl.NewProxyPreparedStatement.executeBatch(NewProxyPreparedStatement.java:1723)
at org.hibernate.jdbc.BatchingBatcher.doExecuteBatch(BatchingBatcher.java:48)
at org.hibernate.jdbc.AbstractBatcher.executeBatch(AbstractBatcher.java:242)
at org.hibernate.engine.ActionQueue.executeActions(ActionQueue.java:235)
at org.hibernate.engine.ActionQueue.executeActions(ActionQueue.java:139)
at org.hibernate.event.def.AbstractFlushingEventListener.performExecutions(AbstractFlushingEventListener.java:298)
at org.hibernate.event.def.DefaultFlushEventListener.onFlush(DefaultFlushEventListener.java:27)
at org.hibernate.impl.SessionImpl.flush(SessionImpl.java:1000)
at org.hibernate.impl.SessionImpl.managedFlush(SessionImpl.java:338)
at org.hibernate.transaction.JDBCTransaction.commit(JDBCTransaction.java:106)
at com.cerebra.cerepedia.item.dao.ItemDAOHibernate.addComment(ItemDAOHibernate.java:505)
at com.cerebra.cerepedia.item.ItemManagerPOJOImpl.addComment(ItemManagerPOJOImpl.java:164)
at com.cerebra.cerepedia.struts.item.ItemAction.addComment(ItemAction.java:126)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.apache.struts.actions.DispatchAction.dispatchMethod(DispatchAction.java:269)
at org.apache.struts.actions.DispatchAction.execute(DispatchAction.java:170)
at org.apache.struts.actions.MappingDispatchAction.execute(MappingDispatchAction.java:166)
at org.apache.struts.action.RequestProcessor.processActionPerform(RequestProcessor.java:425)
at org.apache.struts.action.RequestProcessor.process(RequestProcessor.java:228)
at org.apache.struts.action.ActionServlet.process(ActionServlet.java:1913)
at org.apache.struts.action.ActionServlet.doPost(ActionServlet.java:462)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:710)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:803)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at com.cerebra.cerepedia.security.AuthorizationFilter.doFilter(AuthorizationFilter.java:78)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at com.cerebra.cerepedia.hibernate.HibernateSessionRequestFilter.doFilter(HibernateSessionRequestFilter.java:30)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at filters.UTF8Filter.doFilter(UTF8Filter.java:14)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:230)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:175)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:128)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:104)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:261)
at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:844)
at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:581)
at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:447)
at java.lang.Thread.run(Unknown Source)
javax.servlet.ServletException: java.lang.NumberFormatException: null
at org.apache.struts.action.RequestProcessor.processException(RequestProcessor.java:520)
at org.apache.struts.action.RequestProcessor.processActionPerform(RequestProcessor.java:427)
at org.apache.struts.action.RequestProcessor.process(RequestProcessor.java:228)
at org.apache.struts.action.ActionServlet.process(ActionServlet.java:1913)
at org.apache.struts.action.ActionServlet.doGet(ActionServlet.java:449)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:690)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:803)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at com.cerebra.cerepedia.security.AuthorizationFilter.doFilter(AuthorizationFilter.java:78)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at com.cerebra.cerepedia.hibernate.HibernateSessionRequestFilter.doFilter(HibernateSessionRequestFilter.java:30)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at filters.UTF8Filter.doFilter(UTF8Filter.java:14)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:230)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:175)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:128)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:104)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:261)
at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:844)
at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:581)
at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:447)
at java.lang.Thread.run(Unknown Source)
Caused by: java.lang.NumberFormatException: null
at java.lang.Long.parseLong(Unknown Source)
at java.lang.Long.valueOf(Unknown Source)
at com.cerebra.cerepedia.struts.item.ItemAction.addComment(ItemAction.java:120)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.apache.struts.actions.DispatchAction.dispatchMethod(DispatchAction.java:269)
at org.apache.struts.actions.DispatchAction.execute(DispatchAction.java:170)
at org.apache.struts.actions.MappingDispatchAction.execute(MappingDispatchAction.java:166)
at org.apache.struts.action.RequestProcessor.processActionPerform(RequestProcessor.java:425)
... 26 more
26-ago-2008 20:13:25 org.apache.catalina.core.StandardWrapperValve invoke
GRAVE: Servlet.service() para servlet action lanzó excepción
java.lang.NumberFormatException: null
at java.lang.Long.parseLong(Unknown Source)
at java.lang.Long.valueOf(Unknown Source)
at com.cerebra.cerepedia.struts.item.ItemAction.addComment(ItemAction.java:120)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.apache.struts.actions.DispatchAction.dispatchMethod(DispatchAction.java:269)
at org.apache.struts.actions.DispatchAction.execute(DispatchAction.java:170)
at org.apache.struts.actions.MappingDispatchAction.execute(MappingDispatchAction.java:166)
at org.apache.struts.action.RequestProcessor.processActionPerform(RequestProcessor.java:425)
at org.apache.struts.action.RequestProcessor.process(RequestProcessor.java:228)
at org.apache.struts.action.ActionServlet.process(ActionServlet.java:1913)
at org.apache.struts.action.ActionServlet.doGet(ActionServlet.java:449)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:690)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:803)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at com.cerebra.cerepedia.security.AuthorizationFilter.doFilter(AuthorizationFilter.java:78)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at com.cerebra.cerepedia.hibernate.HibernateSessionRequestFilter.doFilter(HibernateSessionRequestFilter.java:30)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at filters.UTF8Filter.doFilter(UTF8Filter.java:14)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:230)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:175)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:128)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:104)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:261)
at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:844)
at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:581)
at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:447)
at java.lang.Thread.run(Unknown Source)
</code></pre>
|
[
{
"answer_id": 29756,
"author": "Pat",
"author_id": 238,
"author_profile": "https://Stackoverflow.com/users/238",
"pm_score": 4,
"selected": false,
"text": "$.ajaxSetup({ \n scriptCharset: \"utf-8\" , \n contentType: \"application/json; charset=utf-8\"\n});\n"
},
{
"answer_id": 732713,
"author": "Adnan",
"author_id": 88907,
"author_profile": "https://Stackoverflow.com/users/88907",
"pm_score": 1,
"selected": false,
"text": "htmlentities() html_entity_decode()"
},
{
"answer_id": 2048911,
"author": "Jesús Alonso",
"author_id": 248878,
"author_profile": "https://Stackoverflow.com/users/248878",
"pm_score": 2,
"selected": false,
"text": "content-type = application/x-www-form-urlencoded\n content-type = application/x-www-form-urlencoded; charset=UTF-8\n $.ajaxSetup({ scriptCharset: \"utf-8\" ,contentType: \"application/x-www-form-urlencoded; charset=UTF-8\" });\n"
},
{
"answer_id": 3129545,
"author": "Michael",
"author_id": 377662,
"author_profile": "https://Stackoverflow.com/users/377662",
"pm_score": 0,
"selected": false,
"text": "<?php header('Content-type: text/html; charset=utf-8'); ?>\n"
}
] |
2008/08/27
|
[
"https://Stackoverflow.com/questions/29751",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2138/"
] |
29,760 |
<p>I've got a problem here with an MSI deployment that I'm working on (using <a href="http://en.wikipedia.org/wiki/InstallShield" rel="nofollow noreferrer">InstallShield</a>). We have a program running in the background that needs to run per-user, and it needs to start automatically without user intervention.</p>
<p>The problem is with <a href="http://en.wikipedia.org/wiki/Group_Policy#Operation" rel="nofollow noreferrer">Group Policy Object</a>/<a href="http://en.wikipedia.org/wiki/Active_Directory" rel="nofollow noreferrer">Active Directory</a> (GPO/AD) deployment the application is started in the SYSTEM context before anyone is logged in rather than as the user who is about to log in. The application can only run once per user, and it seems that the SYSTEM process prevents the USER process from starting. This means the PCs need to be rebooted twice before the software can be deployed to the users. How do we to stop this?</p>
<p>Basically the current workflow is: </p>
<ol>
<li>Installation/upgrade runs... kill background application</li>
<li>Install new files</li>
<li>Startup background application</li>
</ol>
<p>This works for published applications and interactive <a href="http://en.wikipedia.org/wiki/Windows_Installer" rel="nofollow noreferrer">MSI</a> installations - it's only 'assigned' applications that seem to have the problem. As step 3 happens in the SYSTEM context rather than the user context :(</p>
<p>Ideally, I'd have the development team patch the EXE file to prevent launching in the SYSTEM context, but that's a release cycle away, and I'm looking for an installer-based solution for the interim.</p>
<p>(I don't know Installscript... So I'm guessing <a href="http://en.wikipedia.org/wiki/VBScript" rel="nofollow noreferrer">VBScript</a> is probably the way to go if there's no native InstallShield stuff I can use.)</p>
|
[
{
"answer_id": 29803,
"author": "saschabeaumont",
"author_id": 592,
"author_profile": "https://Stackoverflow.com/users/592",
"pm_score": 1,
"selected": false,
"text": "On Error Resume Next \nstrComputer = \".\"\nSet objWMIService = GetObject(\"winmgmts:\" _\n & \"{impersonationLevel=impersonate}!\\\\\" & strComputer & \"\\root\\cimv2\")\nSet colProcessList = objWMIService.ExecQuery _\n (\"Select * from Win32_Process Where Name = 'BackgroundProcess.exe'\")\nFor Each objProcess in colProcessList\n colProperties = objProcess.GetOwner(strNameOfUser,strUserDomain)\n If strNameOfUser = \"SYSTEM\" Then \n objProcess.Terminate()\n End If\nNext\n"
}
] |
2008/08/27
|
[
"https://Stackoverflow.com/questions/29760",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/592/"
] |
29,761 |
<p>Can anyone recommend a good repository viewer for Git, similar to gitk, that works on Mac OS X Leopard? (I'm not saying gitk doesn't work)</p>
<p>Of course I would like a native Mac application, but as I haven't found any, what are the best options to gitk?</p>
<p>I know about gitview, but I'm looking forward to evaluate as many alternatives as possible.</p>
<p><a href="http://sourceforge.net/projects/gitview" rel="noreferrer">http://sourceforge.net/projects/gitview</a></p>
|
[
{
"answer_id": 36858,
"author": "dbr",
"author_id": 745,
"author_profile": "https://Stackoverflow.com/users/745",
"pm_score": 2,
"selected": false,
"text": "git gui gitk"
}
] |
2008/08/27
|
[
"https://Stackoverflow.com/questions/29761",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2954/"
] |
29,810 |
<p>I am in charge of about 100+ documents (word document, not source code) that needs revision by different people in my department. Currently all the documents are in a shared folder where they will retrieve, revise and save back into the folder. </p>
<p>What I am doing now is looking up the "date modified" in the shared folder, opened up recent modified documents and use the "Track Change" function in MS Word to apply the changes. I find this a bit tedious.</p>
<p>So will it be better and easier if I commit this in a version control database?</p>
<p>Basically I want to keep different version of a file.</p>
<p><hr>
What have I learn from answers:</p>
<ul>
<li><p>Use Time Machine to save different
version (or Shadow copy in Vista)</p></li>
<li><p>There is a difference between text
and binary documents when you use
version control app. (I didn't know
that)</p></li>
<li><p>Diff won't work on binary files</p></li>
<li><p>A notification system (ie email) for revision is great</p></li>
<li><p>Google Docs revision feature.</p></li>
</ul>
<p><strong>Update</strong> : </p>
<p>I played around with Google Docs revision feature and feel that it is almost right for me. Just a bit annoyed with the too frequent versioning (autosaving). </p>
<p>But what feels right for me doesn't mean it feels right for my dept. Will they be okay with saving all these documents with Google? </p>
|
[
{
"answer_id": 8527923,
"author": "Gautam",
"author_id": 492561,
"author_profile": "https://Stackoverflow.com/users/492561",
"pm_score": 3,
"selected": false,
"text": "git .doc .odf .gitattributes diff"
}
] |
2008/08/27
|
[
"https://Stackoverflow.com/questions/29810",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1261/"
] |
29,820 |
<p>In Java, say you have a class that wraps an <code>ArrayList</code> (or any collection) of objects. </p>
<p>How would you return one of those objects such that the caller will not see any future changes to the object made in the ArrayList? </p>
<p>i.e. you want to return a deep copy of the object, but you don't know if it is cloneable.</p>
|
[
{
"answer_id": 29826,
"author": "Gishu",
"author_id": 1695,
"author_profile": "https://Stackoverflow.com/users/1695",
"pm_score": 3,
"selected": true,
"text": "ArrayList<ICloneable>()"
}
] |
2008/08/27
|
[
"https://Stackoverflow.com/questions/29820",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/142/"
] |
29,822 |
<p>One of our weblogic 8.1s has suddenly started logging giant amounts of logs and filling the disk.</p>
<p>The logs giving us hassle resides in </p>
<pre><code>mydrive:\bea\weblogic81\common\nodemanager\NodeManagerLogs\generatedManagedServer1\managedserveroutput.log
</code></pre>
<p>and the entries in the logfile is just the some kind of entries repeated again and again. Stuff like</p>
<pre><code>19:21:24,470 DEBUG [StdRowLockSemaphore] Lock 'TRIGGER_ACCESS' returned by: LLL-SCHEDULER_QuartzSchedulerThread
19:21:31,923 DEBUG [StdRowLockSemaphore] Lock 'STATE_ACCESS' is deLLLred by: QuartzScheduler_LLL-SCHEDULER-NACDLLLF011219763113220_ClusterManager
19:21:31,923 DEBUG [StdRowLockSemaphore] Lock 'STATE_ACCESS' is being obtained: QuartzScheduler_LLL-SCHEDULER-NACDLLLF011219763113220_ClusterManager
19:21:31,923 DEBUG [StdRowLockSemaphore] Lock 'STATE_ACCESS' given to: QuartzScheduler_LLL-SCHEDULER-NACDLLLF011219763113220_ClusterManager
19:21:31,923 DEBUG [StdRowLockSemaphore] Lock 'TRIGGER_ACCESS' is deLLLred by: QuartzScheduler_LLL-SCHEDULER-NACDLLLF011219763113220_ClusterManager
</code></pre>
<p>...</p>
<pre><code>19:17:46,798 DEBUG [CascadingAction] cascading to saveOrUpdate: mypackage.config.common.Share
19:17:46,798 DEBUG [DefaultSaveOrUpdateEventListener] reassociated uninitialized proxy
19:17:46,798 DEBUG [Cascade] done processing cascade ACTION_SAVE_UPDATE for: mypackage.config.common.FileLocation
19:17:46,798 DEBUG [Cascade] processing cascade ACTION_SAVE_UPDATE for: mypackage.config.common.FileLocation
19:17:46,798 DEBUG [CascadingAction] cascading to saveOrUpdate: mypackage.config.common.Share
19:17:46,798 DEBUG [DefaultSaveOrUpdateEventListener] reassociated uninitialized proxy
</code></pre>
<p>I can't find any debug settings set anywhere.
I've looked in the Remote Start classpath and Arguments for the managed server.</p>
<p>Can anyone point me in the direction to gain control over this logfile?</p>
|
[
{
"answer_id": 29826,
"author": "Gishu",
"author_id": 1695,
"author_profile": "https://Stackoverflow.com/users/1695",
"pm_score": 3,
"selected": true,
"text": "ArrayList<ICloneable>()"
}
] |
2008/08/27
|
[
"https://Stackoverflow.com/questions/29822",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/86/"
] |
29,841 |
<p>We have a Windows Service written in C#. The service spawns a thread that does this: </p>
<pre><code>private void ThreadWorkerFunction()
{
while(false == _stop) // stop flag set by other thread
{
try
{
openConnection();
doStuff();
closeConnection();
}
catch (Exception ex)
{
log.Error("Something went wrong.", ex);
Thread.Sleep(TimeSpan.FromMinutes(10));
}
}
}
</code></pre>
<p>We put the Thread.Sleep in after a couple of times when the database had gone away and we came back to 3Gb logs files full of database connection errors. </p>
<p>This has been running fine for months, but recently we've seen a few instances where the log.Error() statement logs a "System.InvalidOperationException: This SqlTransaction has completed; it is no longer usable" exception and then never ever comes back. The service can be left running for days but nothing more will be logged.</p>
<p>Having done some reading I know that Thread.Sleep is not ideal, but why would it simply never come back?</p>
|
[
{
"answer_id": 116008,
"author": "d4nt",
"author_id": 1039,
"author_profile": "https://Stackoverflow.com/users/1039",
"pm_score": 0,
"selected": false,
"text": "private void ThreadWorkerFunction()\n{\n DateTime? timeout = null;\n\n while (!_stop)\n {\n try\n {\n if (timeout == null || timeout < DateTime.Now)\n {\n openDatabaseConnections();\n\n doStuff();\n\n closeDatabaseConnections();\n }\n else\n {\n Thread.Sleep(1000);\n }\n }\n catch (ThreadInterruptedException tiex)\n {\n log.Error(\"The worker thread was interrupted... ignoring.\", tiex);\n }\n catch (Exception ex)\n {\n log.Error(\"Something went wrong.\", ex);\n\n timeout = DateTime.Now + TimeSpan.FromMinutes(10);\n }\n }\n}\n"
},
{
"answer_id": 3178592,
"author": "Michel",
"author_id": 383550,
"author_profile": "https://Stackoverflow.com/users/383550",
"pm_score": 2,
"selected": false,
"text": "bool hadError = false;\ntry {\n ...\n} catch (...) {\n hadError = true;\n}\nif (hadError)\n Thread.Sleep(...);\n"
}
] |
2008/08/27
|
[
"https://Stackoverflow.com/questions/29841",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1039/"
] |
29,845 |
<p>I have an application on which I am implementing localization.</p>
<p>I now need to dynamically reference a name in the resouce file.</p>
<p>assume I have a resource file called Login.resx, an a number of strings: foo="hello", bar="cruel" and baz="world"</p>
<p>normally, I will refer as:
String result =Login.foo;
and result=="hello";</p>
<p>my problem is, that at code time, I do not know if I want to refer to foo, bar or baz - I have a string that contains either "foo", "bar" or "baz". </p>
<p>I need something like:</p>
<p>Login["foo"];</p>
<p>Does anyone know if there is any way to dynamically reference a string in a resource file?</p>
|
[
{
"answer_id": 29866,
"author": "Konrad Rudolph",
"author_id": 1968,
"author_profile": "https://Stackoverflow.com/users/1968",
"pm_score": 5,
"selected": true,
"text": "ResourceManager Login.resx var resman = new System.Resources.ResourceManager(\n \"RootNamespace.Login\",\n System.Reflection.Assembly.GetExecutingAssembly()\n)\nvar text = resman.GetString(\"resname\");\n"
}
] |
2008/08/27
|
[
"https://Stackoverflow.com/questions/29845",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1090/"
] |
29,847 |
<p>I have a History Table in SQL Server that basically tracks an item through a process. The item has some fixed fields that don't change throughout the process, but has a few other fields including status and Id which increment as the steps of the process increase.</p>
<p>Basically I want to retrieve the last step for each item given a Batch Reference. So if I do a </p>
<pre><code>Select * from HistoryTable where BatchRef = @BatchRef
</code></pre>
<p>It will return all the steps for all the items in the batch - eg</p>
<pre>
<b>Id Status BatchRef ItemCount</b>
1 1 Batch001 100
1 2 Batch001 110
2 1 Batch001 60
2 2 Batch001 100
</pre>
<p>But what I really want is:</p>
<pre>
<b>Id Status BatchRef ItemCount</b>
1 2 Batch001 110
2 2 Batch001 100
</pre>
<p>Edit: Appologies - can't seem to get the TABLE tags to work with Markdown - followed the help to the letter, and looks fine in the preview</p>
|
[
{
"answer_id": 29848,
"author": "ZombieSheep",
"author_id": 377,
"author_profile": "https://Stackoverflow.com/users/377",
"pm_score": 3,
"selected": false,
"text": "select \n top 1 <fields> \nfrom \n HistoryTable \nwhere \n BatchRef = @BatchRef \norder by \n <IdentityColumn> DESC\n"
},
{
"answer_id": 29853,
"author": "Matt Hamilton",
"author_id": 615,
"author_profile": "https://Stackoverflow.com/users/615",
"pm_score": 0,
"selected": false,
"text": "with LastBatches as (\n select Batch, max(Id)\n from HistoryTable\n group by Batch\n)\nselect *\nfrom HistoryTable h\n join LastBatches b on b.Batch = h.Batch and b.Id = h.Id\n select *\nfrom HistoryTable h\n join (\n select Batch, max(Id)\n from HistoryTable\n group by Batch\n ) b on b.Batch = h.Batch and b.Id = h.Id\n"
},
{
"answer_id": 29861,
"author": "Henrik Gustafsson",
"author_id": 2010,
"author_profile": "https://Stackoverflow.com/users/2010",
"pm_score": 0,
"selected": false,
"text": "SELECT TOP 1 ...\n SELECT * FROM (\n SELECT\n ROW_NUMBER() OVER (ORDER BY key ASC) AS rownumber,\n columns\n FROM tablename\n) AS foo\nWHERE rownumber = n\n SELECT ... LIMIT 1 OFFSET 0\n"
},
{
"answer_id": 29862,
"author": "Mark Brackett",
"author_id": 2199,
"author_profile": "https://Stackoverflow.com/users/2199",
"pm_score": 4,
"selected": true,
"text": "SELECT * \nFROM HistoryTable\nJOIN (\n SELECT \n MAX(Id) as Id.\n BatchRef,\n ItemCount\n FROM HsitoryTable\n WHERE\n BacthRef = @batchRef\n GROUP BY\n BatchRef,\n ItemCount\n ) as Latest ON\n HistoryTable.Id = Latest.Id\n"
},
{
"answer_id": 36696,
"author": "JMcCon",
"author_id": 3677,
"author_profile": "https://Stackoverflow.com/users/3677",
"pm_score": 1,
"selected": false,
"text": "--Declare a temp table to hold the last step for each item id\nDECLARE @LastStepForEach TABLE (\nId int,\nStatus int,\nBatchRef char(10),\nItemCount int)\n\n--Loop counter\nDECLARE @count INT;\nSET @count = 0;\n\n--Loop through all of the items\nWHILE (@count < (SELECT MAX(Id) FROM HistoryTable WHERE BatchRef = @BatchRef))\nBEGIN\n SET @count = @count + 1;\n\n INSERT INTO @LastStepForEach (Id, Status, BatchRef, ItemCount)\n SELECT Id, Status, BatchRef, ItemCount\n FROM HistoryTable \n WHERE BatchRef = @BatchRef\n AND Id = @count\n AND Status = \n (\n SELECT MAX(Status) \n FROM HistoryTable \n WHERE BatchRef = @BatchRef \n AND Id = @count\n )\n\nEND\n\nSELECT * \nFROM @LastStepForEach\n"
},
{
"answer_id": 7949403,
"author": "Ram_God",
"author_id": 1020241,
"author_profile": "https://Stackoverflow.com/users/1020241",
"pm_score": 1,
"selected": false,
"text": "SELECT id, status, BatchRef, MAX(itemcount) AS maxItemcount \nFROM HistoryTable GROUP BY id, status, BatchRef \nHAVING status > 1 \n"
}
] |
2008/08/27
|
[
"https://Stackoverflow.com/questions/29847",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1075/"
] |
29,856 |
<p>The default Python install on OS X 10.5 is 2.5.1 with a FAT 32 bit (Intel and PPC) client. I want to setup apache and mysql to run django. In the past, I have run Apache and MySQL to match this install in 32 bit mode (even stripping out the 64 bit stuff from Apache to make it work).</p>
<p>I want to upgrade Python to 64 bit. I am completely comfortable with compiling it from source with one caveat. How do I match the way that the default install is laid out? Especially, with regards to site-packages being in <code>/Library/Python/2.5/</code> and not the one in buried at the top of the framework once I compile it. </p>
|
[
{
"answer_id": 31765,
"author": "John Douthat",
"author_id": 2774,
"author_profile": "https://Stackoverflow.com/users/2774",
"pm_score": 1,
"selected": false,
"text": "./configure --prefix=/usr/local/python64\nmake\nsudo make install\n"
}
] |
2008/08/27
|
[
"https://Stackoverflow.com/questions/29856",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3431280/"
] |
29,869 |
<p>I need to match and remove all tags using a regular expression in Perl. I have the following:</p>
<pre><code><\\??(?!p).+?>
</code></pre>
<p>But this still matches with the closing <code></p></code> tag. Any hint on how to match with the closing tag as well?</p>
<p>Note, this is being performed on xhtml.</p>
|
[
{
"answer_id": 29871,
"author": "Brian Warshaw",
"author_id": 1344,
"author_profile": "https://Stackoverflow.com/users/1344",
"pm_score": 1,
"selected": false,
"text": "/<\\/?[^p][^>]*>/ <pre> <param> /<\\/?(?!p>|p )[^>]+>/\n <p>"
},
{
"answer_id": 29875,
"author": "Konrad Rudolph",
"author_id": 1968,
"author_profile": "https://Stackoverflow.com/users/1968",
"pm_score": 0,
"selected": false,
"text": "/<\\/?([^p](\\s.+?)?|..+?)>/\n p"
},
{
"answer_id": 29911,
"author": "Vegard Larsen",
"author_id": 1606,
"author_profile": "https://Stackoverflow.com/users/1606",
"pm_score": -1,
"selected": false,
"text": "<p onclick=\"document.location.href='http://www.evil.com'\">Clickable text</p>\n"
},
{
"answer_id": 29917,
"author": "Xetius",
"author_id": 274,
"author_profile": "https://Stackoverflow.com/users/274",
"pm_score": 5,
"selected": true,
"text": "<(?!\\/?p(?=>|\\s.*>))\\/?.*?>\n\nx/\n< # Match open angle bracket\n(?! # Negative lookahead (Not matching and not consuming)\n \\/? # 0 or 1 /\n p # p\n (?= # Positive lookahead (Matching and not consuming)\n > # > - No attributes\n | # or\n \\s # whitespace\n .* # anything up to \n > # close angle brackets - with attributes\n ) # close positive lookahead\n) # close negative lookahead\n # if we have got this far then we don't match\n # a p tag or closing p tag\n # with or without attributes\n\\/? # optional close tag symbol (/)\n.*? # and anything up to\n> # first closing tag\n/\n"
},
{
"answer_id": 29965,
"author": "dbr",
"author_id": 745,
"author_profile": "https://Stackoverflow.com/users/745",
"pm_score": 2,
"selected": false,
"text": "<p></p> (<[^pP].*?>|</[^pP]>) (\n < # < opening tag\n [^pP].*? # p non-p character, then non-greedy anything\n > # > closing tag\n| # ....or....\n </ # </\n [^pP] # a non-p tag\n > # >\n)\n"
},
{
"answer_id": 29985,
"author": "John Siracusa",
"author_id": 164,
"author_profile": "https://Stackoverflow.com/users/164",
"pm_score": 5,
"selected": false,
"text": "# Remove all HTML except \"p\" tags\n$html =~ s{<(?>/?)(?:[^pP]|[pP][^\\s>/])[^>]*>}{}g;\n s{\n < # opening angled bracket\n (?>/?) # ratchet past optional / \n (?:\n [^pP] # non-p tag\n | # ...or...\n [pP][^\\s>/] # longer tag that begins with p (e.g., <pre>)\n )\n [^>]* # everything until closing angled bracket\n > # closing angled bracket\n }{}gx; # replace with nothing, globally\n use strict;\n\nuse HTML::TokeParser;\n\nmy $parser = HTML::TokeParser->new('/some/file.html')\n or die \"Could not open /some/file.html - $!\";\n\nwhile(my $t = $parser->get_token)\n{\n # Skip start or end tags that are not \"p\" tags\n next if(($t->[0] eq 'S' || $t->[0] eq 'E') && lc $t->[1] ne 'p');\n\n # Print everything else normally (see HTML::TokeParser docs for explanation)\n if($t->[0] eq 'T')\n {\n print $t->[1];\n }\n else\n {\n print $t->[-1];\n }\n}\n print"
},
{
"answer_id": 30193,
"author": "Jörg W Mittag",
"author_id": 2988,
"author_profile": "https://Stackoverflow.com/users/2988",
"pm_score": 4,
"selected": false,
"text": "<HTML /\n <HEAD /\n <TITLE / > /\n <P / >\n <html>\n <head>\n <title>\n >\n </title>\n </head>\n <body>\n <p>\n >\n </p>\n </body>\n</html>\n"
},
{
"answer_id": 100722,
"author": "moritz",
"author_id": 14132,
"author_profile": "https://Stackoverflow.com/users/14132",
"pm_score": 1,
"selected": false,
"text": " <(?>/?)(?!p).+?>\n"
},
{
"answer_id": 2928149,
"author": "y_nk",
"author_id": 335243,
"author_profile": "https://Stackoverflow.com/users/335243",
"pm_score": 2,
"selected": false,
"text": "<(?!\\/?p(?=>|\\s?.*>))\\/?.*?>\n <(?!\\/?(p|a|b|i|u|br)(?=>|\\s?.*>))\\/?.*?>\n"
},
{
"answer_id": 23641607,
"author": "zx81",
"author_id": 1078583,
"author_profile": "https://Stackoverflow.com/users/1078583",
"pm_score": 2,
"selected": false,
"text": "#!/usr/bin/perl\n$regex = '(<\\/?p[^>]*>)|<[^>]*>';\n$subject = 'Bad html <a> </I> <p>My paragraph</p> <i>Italics</i> <p class=\"blue\">second</p>';\n($replaced = $subject) =~ s/$regex/$1/eg;\nprint $replaced . \"\\n\";\n"
},
{
"answer_id": 66021740,
"author": "Adebowale",
"author_id": 2088109,
"author_profile": "https://Stackoverflow.com/users/2088109",
"pm_score": 0,
"selected": false,
"text": "~(<\\/?[^>]*(?<!<\\/p|p)>)~ig\n"
}
] |
2008/08/27
|
[
"https://Stackoverflow.com/questions/29869",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/274/"
] |
29,886 |
<p>I'm writing a simple photo album app using ASP.NET Ajax.<br>
The app uses async Ajax calls to pre-load the next photo in the album, without changing the URL in the browser.</p>
<p>The problem is that when the user clicks the <strong>back</strong> button in the browser, the app doesn't go back to the previous photo, instead, it navigates to the home page of the application.</p>
<p>Is there a way to trick the browser into adding each Ajax call to the browsing history?</p>
|
[
{
"answer_id": 3591659,
"author": "balupton",
"author_id": 130638,
"author_profile": "https://Stackoverflow.com/users/130638",
"pm_score": 4,
"selected": false,
"text": "hashchange hashchange"
},
{
"answer_id": 10233899,
"author": "Nikita Koksharov",
"author_id": 764206,
"author_profile": "https://Stackoverflow.com/users/764206",
"pm_score": 2,
"selected": false,
"text": "Path.map(\"#/page1\").to(function(){\n ...\n});\n\nPath.map(\"#/page2\").to(function(){\n ...\n});\n\nPath.root(\"#/mainpage\");\nPath.listen();\n"
}
] |
2008/08/27
|
[
"https://Stackoverflow.com/questions/29886",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/373/"
] |
29,890 |
<ol>
<li>You have multiple network adapters.</li>
<li>Bind a UDP socket to an local port, without specifying an address.</li>
<li>Receive packets on one of the adapters.</li>
</ol>
<p>How do you get the local ip address of the adapter which received the packet?</p>
<p>The question is, "What is the ip address from the receiver adapter?" not the address from the sender which we get in the </p>
<pre><code>receive_from( ..., &senderAddr, ... );
</code></pre>
<p>call.</p>
|
[
{
"answer_id": 29912,
"author": "diciu",
"author_id": 2811,
"author_profile": "https://Stackoverflow.com/users/2811",
"pm_score": -1,
"selected": false,
"text": "\nint nbytes = recvfrom(sock, buf, MAXBUFSIZE, MSG_WAITALL, (struct sockaddr *)&bindaddr, &addrlen); \n\n fprintf(stdout, \"Read %d bytes on local address %s\\n\", nbytes, inet_ntoa(bindaddr.sin_addr.s_addr));\n"
},
{
"answer_id": 29916,
"author": "Timbo",
"author_id": 1810,
"author_profile": "https://Stackoverflow.com/users/1810",
"pm_score": 3,
"selected": true,
"text": "IPAddress FindLocalIPAddressOfIncomingPacket( senderAddr )\n{\n foreach( adapter in EnumAllNetworkAdapters() )\n {\n adapterSubnet = adapter.subnetmask & adapter.ipaddress;\n senderSubnet = adapter.subnetmask & senderAddr;\n if( adapterSubnet == senderSubnet )\n {\n return adapter.ipaddress;\n }\n }\n}\n"
},
{
"answer_id": 3946022,
"author": "Chris Evans",
"author_id": 477458,
"author_profile": "https://Stackoverflow.com/users/477458",
"pm_score": -1,
"selected": false,
"text": "gethostbyname(\"localhost\");\n"
},
{
"answer_id": 63698826,
"author": "xyanping",
"author_id": 14206102,
"author_profile": "https://Stackoverflow.com/users/14206102",
"pm_score": 0,
"selected": false,
"text": " //create socket and bind to local address:INADDR_ANY:\n int s = socket(PF_INET,SOCK_DGRAM,0);\n bind(s,(struct sockaddr *)&myAddr,sizeof(myAddr)) ;\n // set option\n int onFlag=1;\n int ret = setsockopt(s,IPPROTO_IP,IP_PKTINFO,&onFlag,sizeof(onFlag));\n // prepare buffers\n // receive data buffer\n char dataBuf[1024] ;\n struct iovec iov = {\n .iov_base=dataBuf,\n .iov_len=sizeof(dataBuf)\n } ;\n // control buffer\n char cBuf[1024] ;\n // message\n struct msghdr msg = {\n .msg_name=NULL, // to receive peer addr with struct sockaddr_in\n .msg_namelen=0, // sizeof(struct sockaddr_in)\n .msg_iov=&iov,\n .msg_iovlen=1,\n .msg_control=cBuf,\n .msg_controllen=sizeof(cBuf)\n } ;\n while(1) {\n // reset buffers\n msg.msg_iov[0].iov_base = dataBuf ;\n msg.msg_iov[0].iov_len = sizeof(dataBuf) ;\n msg.msg_control = cBuf ;\n msg.msg_controllen = sizeof(cBuf) ;\n // receive\n recvmsg(s,&msg,0);\n for( struct cmsghdr* pcmsg=CMSG_FIRSTHDR(&msg);\n pcmsg!=NULL; pcmsg=CMSG_NXTHDR(&msg,pcmsg) ) {\n if(pcmsg->cmsg_level==IPPROTO_IP && pcmsg->cmsg_type==IP_PKTINFO) {\n struct in_pktinfo * pktinfo=(struct in_pktinfo *)CMSG_DATA(pcmsg);\n printf(\"ifindex=%d ip=%s\\n\", pktinfo->ipi_ifindex, inet_ntoa(pktinfo->ipi_addr)) ;\n }\n }\n }\n BOOL bOptVal = 1;\nsetsockopt(so, SOL_SOCKET, SO_REUSEADDR, (char *)&boOptVal, sizeof(bOptVal));\n receive_from( ..., &remoteAddr, ... ); SOCKET skNew = socket( )\n// Same local address and port as that of your first socket \n// INADDR_ANY\nbind(skNew, , )\n// set SO_REUSEADDR to true again\nsetsockopt(skNew, SOL_SOCKET, SO_REUSEADDR, (char *)&boOptVal, sizeof(bOptVal));\n\n// connect back \nconnect(skNew, remoteAddr)\n\n// get local address of the socket\ngetsocketname(skNew, )\n"
}
] |
2008/08/27
|
[
"https://Stackoverflow.com/questions/29890",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3186/"
] |
29,943 |
<p>Can someone please tell me how to submit an HTML form when the return key is pressed and if there are no buttons in the form?
<strong>The submit button is not there</strong>. I am using a custom div instead of that.</p>
|
[
{
"answer_id": 29951,
"author": "Sean Chambers",
"author_id": 2993,
"author_profile": "https://Stackoverflow.com/users/2993",
"pm_score": 3,
"selected": false,
"text": "j(\".textBoxClass\").keypress(function(e)\n{\n // if the key pressed is the enter key\n if (e.which == 13)\n {\n // do work\n }\n});\n"
},
{
"answer_id": 29961,
"author": "Bill the Lizard",
"author_id": 1288,
"author_profile": "https://Stackoverflow.com/users/1288",
"pm_score": 3,
"selected": false,
"text": "<SCRIPT TYPE=\"text/javascript\">\n<!--\n function submitenter(myfield,e)\n {\n var keycode;\n if (window.event) keycode = window.event.keyCode;\n else if (e) keycode = e.which;\n else return true;\n\n if (keycode == 13)\n {\n myfield.form.submit();\n return false;\n }\n else\n return true;\n }\n//-->\n</SCRIPT>\n <FORM ACTION=\"../cgi-bin/formaction.pl\">\n name: <INPUT NAME=realname SIZE=15><BR>\n password: <INPUT NAME=password TYPE=PASSWORD SIZE=10\n onKeyPress=\"return submitenter(this,event)\"><BR>\n<INPUT TYPE=SUBMIT VALUE=\"Submit\">\n</FORM>\n"
},
{
"answer_id": 29966,
"author": "John Hunter",
"author_id": 2253,
"author_profile": "https://Stackoverflow.com/users/2253",
"pm_score": 7,
"selected": false,
"text": "function checkSubmit(e) {\n if(e && e.keyCode == 13) {\n document.forms[0].submit();\n }\n}\n <div onKeyPress=\"return checkSubmit(event)\"/>"
},
{
"answer_id": 29987,
"author": "Chris Marasti-Georg",
"author_id": 96,
"author_profile": "https://Stackoverflow.com/users/96",
"pm_score": 7,
"selected": true,
"text": "<form action=\"\" method=\"get\">\n Name: <input type=\"text\" name=\"name\"/><br/>\n Pwd: <input type=\"password\" name=\"password\"/><br/>\n <div class=\"yourCustomDiv\"/>\n <input type=\"submit\" style=\"display:none\"/>\n</form>"
},
{
"answer_id": 31888,
"author": "palotasb",
"author_id": 3063,
"author_profile": "https://Stackoverflow.com/users/3063",
"pm_score": 0,
"selected": false,
"text": "<input type=\"image\"..."
},
{
"answer_id": 6602788,
"author": "StriplingWarrior",
"author_id": 120955,
"author_profile": "https://Stackoverflow.com/users/120955",
"pm_score": 6,
"selected": false,
"text": "<div class=\"hidden-submit\"><input type=\"submit\" tabindex=\"-1\"/></div>\n .hidden-submit {\n border: 0 none;\n height: 0;\n width: 0;\n padding: 0;\n margin: 0;\n overflow: hidden;\n}\n display: none tabindex"
},
{
"answer_id": 8164027,
"author": "Joel Purra",
"author_id": 907779,
"author_profile": "https://Stackoverflow.com/users/907779",
"pm_score": 4,
"selected": false,
"text": "<button> <button> <div> <img /> <input /> <button type=\"submit\">\n <img src=\"my-icon.png\" />\n Clicking will submit the form\n</button>\n <button> <input> <button type=\"submit\">Will submit the form</button>\n<button type=\"reset\">Will reset the form</button>\n<button type=\"button\">Will do nothing; add javascript onclick hooks</button>\n <button> <button> <button> <button> <a class=\"button\"> <button>"
},
{
"answer_id": 8491238,
"author": "Hawk",
"author_id": 1038583,
"author_profile": "https://Stackoverflow.com/users/1038583",
"pm_score": 3,
"selected": false,
"text": "//<![CDATA[\n\n//Send form if they hit enter.\ndocument.onkeypress = enter;\nfunction enter(e) {\n if (e.which == 13) { sendform(); }\n}\n\n//Form to send\nfunction sendform() {\n document.forms[0].submit();\n}\n//]]>\n"
},
{
"answer_id": 8797741,
"author": "denn",
"author_id": 1131402,
"author_profile": "https://Stackoverflow.com/users/1131402",
"pm_score": -1,
"selected": false,
"text": "<html>\n<head><title>title</title></head>\n<body>\n <form action=\"\" method=\"get\">\n Name: <input type=\"text\" name=\"name\"/><br/>\n Pwd: <input type=\"password\" name=\"password\" onkeypress=\"if(event.keyCode==13) {javascript:form.submit();}\" /><br/>\n <input type=\"submit\" onClick=\"javascript:form.submit();\"/>\n</form>\n</body>\n</html>\n"
},
{
"answer_id": 9872110,
"author": "Niente",
"author_id": 1293003,
"author_profile": "https://Stackoverflow.com/users/1293003",
"pm_score": 2,
"selected": false,
"text": "<form name='test' method=post action='sendme.php'>\n <input type=text name='test1'>\n <input type=button value='send' onClick='document.test.submit()'>\n <input type=image src='spacer.gif'> <!-- <<<< this is the secret! -->\n</form>\n"
},
{
"answer_id": 39457153,
"author": "AndrewH",
"author_id": 2469769,
"author_profile": "https://Stackoverflow.com/users/2469769",
"pm_score": -1,
"selected": false,
"text": "display: none <button /> <form action=\"\" method=\"get\">\n <input type=\"text\" name=\"name\" />\n <input type=\"password\" name=\"password\" />\n <div class=\"yourCustomDiv\"/>\n <button style=\"position:absolute;left:-10000px;right:9990px\"/>\n</form>\n <button/>"
},
{
"answer_id": 50689741,
"author": "realtimeguy",
"author_id": 9877849,
"author_profile": "https://Stackoverflow.com/users/9877849",
"pm_score": -1,
"selected": false,
"text": "<form action=\"hello.php\" method=\"get\">\n Name: <input type=\"text\" name=\"name\"/><br/>\n Pwd: <input type=\"password\" name=\"password\"/><br/>\n <div class=\"yourCustomDiv\"/>\n <input autofocus type=\"submit\" style=\"position:relative; left:-200px; height:0px;\" />\n</form>\n"
},
{
"answer_id": 56560933,
"author": "f_i",
"author_id": 5358188,
"author_profile": "https://Stackoverflow.com/users/5358188",
"pm_score": 0,
"selected": false,
"text": "<form method=\"post\" action=\"/url\" id=\"editMeta\">\n <textarea class=\"form-control\" onkeypress=\"submitOnEnter(event)\"></textarea>\n</form>\n function submitOnEnter(e) {\n if (e.which == 13) {\n document.getElementById(\"editMeta\").submit()\n }\n}\n"
}
] |
2008/08/27
|
[
"https://Stackoverflow.com/questions/29943",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/184/"
] |
29,971 |
<p>Setting up an integration server, I’m in doubt about the best approach regarding using multiple tasks to complete the build. Is the best way to set all in just one big-job or make small dependent ones?</p>
|
[
{
"answer_id": 29991,
"author": "Rob Wells",
"author_id": 2974,
"author_profile": "https://Stackoverflow.com/users/2974",
"pm_score": 0,
"selected": false,
"text": "</thebloodyobvious> (-:\n"
}
] |
2008/08/27
|
[
"https://Stackoverflow.com/questions/29971",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2267/"
] |
29,976 |
<p>We have a couple of ASP.Net dataview column templates that are dynamically added to the dataview depending on columns selected by users.</p>
<p>These templated cells need to handle custom databindings:</p>
<pre><code>public class CustomColumnTemplate:
ITemplate
{
public void InstantiateIn( Control container )
{
//create a new label
Label contentLabel = new Label();
//add a custom data binding
contentLabel.DataBinding +=
( sender, e ) =>
{
//do custom stuff at databind time
contentLabel.Text = //bound content
};
//add the label to the cell
container.Controls.Add( contentLabel );
}
}
...
myGridView.Columns.Add( new TemplateField
{
ItemTemplate = new CustomColumnTemplate(),
HeaderText = "Custom column"
} );
</code></pre>
<p>Firstly this seems rather messy, but there is also a resource issue. The <code>Label</code> is generated, and can't be disposed in the <code>InstantiateIn</code> because then it wouldn't be there to databind.</p>
<p>Is there a better pattern for these controls? </p>
<p>Is there a way to make sure that the label is disposed after the databind and render?</p>
|
[
{
"answer_id": 30536,
"author": "David Basarab",
"author_id": 2469,
"author_profile": "https://Stackoverflow.com/users/2469",
"pm_score": 3,
"selected": true,
"text": " //add a custom data binding\n contentLabel.DataBinding +=\n (object sender, EventArgs e ) =>\n {\n //do custom stuff at databind time\n ((Label)sender).Text = //bound content\n };\n"
},
{
"answer_id": 14066402,
"author": "jackvsworld",
"author_id": 1097054,
"author_profile": "https://Stackoverflow.com/users/1097054",
"pm_score": 1,
"selected": false,
"text": "IDisposable Dispose public class CustomColumnTemplate :\n ITemplate, IDisposable\n{\n private readonly ICollection<Control> labels = new List<Control>();\n\n public void Dispose()\n {\n foreach (Control label in this.labels)\n label.Dispose();\n }\n\n public void InstantiateIn(Control container)\n {\n //create a new label\n Label contentLabel = new Label();\n\n this.labels.Add(contentLabel);\n //add the label to the cell\n container.Controls.Add( contentLabel );\n }\n}\n Dispose IDisposable"
}
] |
2008/08/27
|
[
"https://Stackoverflow.com/questions/29976",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/905/"
] |
29,980 |
<p>So I'm working on some legacy code that's heavy on the manual database operations. I'm trying to maintain some semblance of quality here, so I'm going TDD as much as possible.</p>
<p>The code I'm working on needs to populate, let's say a <code>List<Foo></code> from a DataReader that returns all the fields required for a functioning Foo. However, if I want to verify that the code in fact returns one list item per one database row, I'm writing test code that looks something like this:</p>
<pre><code>Expect.Call(reader.Read()).Return(true);
Expect.Call(reader["foo_id"]).Return((long) 1);
// ....
Expect.Call(reader.Read()).Return(true);
Expect.Call(reader["foo_id"]).Return((long) 2);
// ....
Expect.Call(reader.Read()).Return(false);
</code></pre>
<p>Which is rather tedious and rather easily broken, too. </p>
<p>How should I be approaching this issue so that the result won't be a huge mess of brittle tests?</p>
<p>Btw I'm currently using Rhino.Mocks for this, but I can change it if the result is convincing enough. Just as long as the alternative isn't TypeMock, because their EULA was a bit too scary for my tastes last I checked.</p>
<p>Edit: I'm also currently limited to C# 2.</p>
|
[
{
"answer_id": 30055,
"author": "kokos",
"author_id": 1065,
"author_profile": "https://Stackoverflow.com/users/1065",
"pm_score": 0,
"selected": false,
"text": "var arrFoos = new Foos[]{...}; // what you expect\nvar expectedFoos = new List<Foo>(arrFoos); // make a list from the hardcoded array of expected Foos\nvar readerResult = ReadEntireList(reader); // read everything from reader and put in List<Foo>\nExpect.ContainSameFoos(expectedFoos, readerResult); // compare the two lists\n"
}
] |
2008/08/27
|
[
"https://Stackoverflow.com/questions/29980",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/266/"
] |
29,988 |
<p>I'd like my program to be able to email me error reports. How can I do this without hard-coding a username/password/SMTP server/etc. into the code? (Doing so would allow users to decompile the program and take over this email account.)</p>
<p>I've been told you could do some stuff with telneting to port 25, but I'm very fuzzy on the details. Most of the code snippets on Google assume you have a preexisting account, which doesn't work in this situation.</p>
<p>I am using .NET v3.5 (C# in particular), but I would imagine the ideas are similar enough in most languages. As long as you realize I'm doing this for an offline app, and don't supply me with PHP code or something, we should be fine.</p>
|
[
{
"answer_id": 30007,
"author": "aku",
"author_id": 1196,
"author_profile": "https://Stackoverflow.com/users/1196",
"pm_score": -1,
"selected": false,
"text": "MailMessage msg = new MailMessage(\"[email protected]\", \"[email protected]\");\nmsg.Subject = \"Check it out!\";\nmsg.Body = \"Visit stackoverflow.com!\";\nSmtpClient client = new SmtpClient(\"some.smtp.server\", 25);\nclient.Send(msg);\n"
}
] |
2008/08/27
|
[
"https://Stackoverflow.com/questions/29988",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3191/"
] |
29,995 |
<p>I want to practice my skills away from a keyboard (i.e. pen and paper) and I'm after simple practice questions like Fizz Buzz, Print the first N primes.</p>
<p>What are your favourite simple programming questions?</p>
|
[
{
"answer_id": 30047,
"author": "OysterD",
"author_id": 2638,
"author_profile": "https://Stackoverflow.com/users/2638",
"pm_score": 1,
"selected": false,
"text": "a1 * a2 * ... * aN / ai"
}
] |
2008/08/27
|
[
"https://Stackoverflow.com/questions/29995",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1736/"
] |
30,003 |
<p>I have the following html code: </p>
<pre><code><h3 id="headerid"><span onclick="expandCollapse('headerid')">&uArr;</span>Header title</h3>
</code></pre>
<p>I would like to toggle between up arrow and down arrow each time the user clicks the span tag. </p>
<pre><code>function expandCollapse(id) {
var arrow = $("#"+id+" span").html(); // I have tried with .text() too
if(arrow == "&dArr;") {
$("#"+id+" span").html("&uArr;");
} else {
$("#"+id+" span").html("&dArr;");
}
}
</code></pre>
<p>My function is going always the else path. If I make a javacript:alert of <code>arrow</code> variable I am getting the html entity represented as an arrow. How can I tell jQuery to interpret the <code>arrow</code> variable as a string and not as html. </p>
|
[
{
"answer_id": 30013,
"author": "jason saldo",
"author_id": 1293,
"author_profile": "https://Stackoverflow.com/users/1293",
"pm_score": 1,
"selected": false,
"text": "<div id=\"inplace\">\n<div id=\"myStatic\">Hello World!</div>\n<div id=\"myEdit\" style=\"display: none\">\n<input id=\"myNewTxt\" type=\"text\" />\n<input id=\"myOk\" type=\"button\" value=\"OK\" />\n<input id=\"myX\" type=\"button\" value=\"X\" />\n</div></div>\n $(\"#myStatic\").bind(\"click\", function(){\n $(\"#myNewTxt\").val($(\"#myStatic\").text());\n $(\"#myStatic,#myEdit\").toggle();\n });\n $(\"#myOk\").click(function(){\n $(\"#myStatic\").text($(\"#myNewTxt\").val());\n $(\"#myStatic,#myEdit\").toggle();\n });\n $(\"#myX\").click(function(){\n $(\"#myStatic,#myEdit\").toggle();\n });\n"
},
{
"answer_id": 30020,
"author": "jelovirt",
"author_id": 2679,
"author_profile": "https://Stackoverflow.com/users/2679",
"pm_score": 5,
"selected": true,
"text": "UPWARDS DOUBLE ARROW \"⇑\" \"\\u21d1\" function expandCollapse(id) {\n var arrow = $(\"#\"+id+\" span\").html();\n if(arrow == \"\\u21d1\") { \n $(\"#\"+id+\" span\").html(\"\\u21d3\"); \n } else { \n $(\"#\"+id+\" span\").html(\"\\u21d1\"); \n }\n}\n"
},
{
"answer_id": 30033,
"author": "travis",
"author_id": 1414,
"author_profile": "https://Stackoverflow.com/users/1414",
"pm_score": 2,
"selected": false,
"text": "arrow '⇓' '⇑' \"\\u21D1\" \"\\u21D3\" ⇑ ⇓ window.expandCollapse = function (id) { \n var $arrowSpan = $(\"#\" + id + \" span\"),\n arrowCharCode = $arrowSpan.text().charCodeAt(0);\n\n // 8659 is the unicode value of the html entity\n if (arrowCharCode === 8659) {\n $arrowSpan.html(\"⇑\"); \n } else { \n $arrowSpan.html(\"⇓\"); \n }\n\n // one liner:\n //$(\"#\" + id + \" span\").html( ($(\"#\" + id + \" span\").text().charCodeAt(0) === 8659) ? \"⇑\" : \"⇓\" );\n};\n"
},
{
"answer_id": 30039,
"author": "Juan",
"author_id": 550,
"author_profile": "https://Stackoverflow.com/users/550",
"pm_score": 1,
"selected": false,
"text": "<h3 id=\"headerId\"><span class=\"upArrow\">⇑</span>Header title</h3>\n $( '.upArrow, .downArrow' ).click( function( span ) {\n if ( span.hasClass( 'upArrow' ) )\n span.text( \"⇓\" );\n else\n span.text( \"⇑\" );\n span.toggleClass( 'upArrow' );\n span.toggleClass( 'downArrow' );\n} );\n"
}
] |
2008/08/27
|
[
"https://Stackoverflow.com/questions/30003",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2138/"
] |
30,005 |
<p>I have to load a PDF within a page.</p>
<p>Ideally I would like to have a loading animated gif which is replaced once the PDF has loaded.</p>
|
[
{
"answer_id": 30012,
"author": "travis",
"author_id": 1414,
"author_profile": "https://Stackoverflow.com/users/1414",
"pm_score": 8,
"selected": false,
"text": "$(\"#iFrameId\").on(\"load\", function () {\n // do something once the iframe is loaded\n});\n"
},
{
"answer_id": 31692,
"author": "travis",
"author_id": 1414,
"author_profile": "https://Stackoverflow.com/users/1414",
"pm_score": 2,
"selected": false,
"text": "iframe <html>\n <head>\n <meta http-equiv=\"refresh\" content=\"0;url=/pdfs/somepdf.pdf\" />\n </head>\n <body>\n </body>\n</html>\n"
},
{
"answer_id": 301951,
"author": "user22367",
"author_id": 22367,
"author_profile": "https://Stackoverflow.com/users/22367",
"pm_score": 0,
"selected": false,
"text": "<script type=\"text/javascript\">\n $(document).ready(function(){\n doMethod();\n });\n function actionIframe(iframe)\n {\n ... do what ever ...\n }\n function doMethod()\n { \n var iFrames = document.getElementsByTagName('iframe');\n\n // what ever action you want.\n function iAction()\n {\n // Iterate through all iframes in the page.\n for (var i = 0, j = iFrames.length; i < j; i++)\n {\n actionIframe(iFrames[i]);\n }\n }\n\n // Check if browser is Safari or Opera.\n if ($.browser.safari || $.browser.opera)\n {\n // Start timer when loaded.\n $('iframe').load(function()\n {\n setTimeout(iAction, 0);\n }\n );\n\n // Safari and Opera need something to force a load.\n for (var i = 0, j = iFrames.length; i < j; i++)\n {\n var iSource = iFrames[i].src;\n iFrames[i].src = '';\n iFrames[i].src = iSource;\n }\n }\n else\n {\n // For other good browsers.\n $('iframe').load(function()\n {\n actionIframe(this);\n }\n );\n }\n }\n</script>\n"
},
{
"answer_id": 933899,
"author": "keithics",
"author_id": 115330,
"author_profile": "https://Stackoverflow.com/users/115330",
"pm_score": 3,
"selected": false,
"text": "$(\"#iFrameId\").ready(function (){\n // do something once the iframe is loaded\n});\n"
},
{
"answer_id": 1344874,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 3,
"selected": false,
"text": "onload <iframe id=\"frameid\" src=\"page.aspx\"></iframe>\n<script language=\"javascript\">\n iframe = document.getElementById(\"frameid\");\n\n WaitForIFrame();\n\n function WaitForIFrame() {\n if (iframe.readyState != \"complete\") {\n setTimeout(\"WaitForIFrame();\", 200);\n } else {\n done();\n }\n }\n\n function done() {\n //some code after iframe has been loaded\n }\n</script> \n"
},
{
"answer_id": 6142082,
"author": "Chris Marisic",
"author_id": 37055,
"author_profile": "https://Stackoverflow.com/users/37055",
"pm_score": 2,
"selected": false,
"text": "$('#iframe').ready(function () {\n $(\"#loader\").fadeOut(2500, function (sender) {\n $(sender).remove();\n });\n});\n"
},
{
"answer_id": 8499902,
"author": "Michael Lu",
"author_id": 778964,
"author_profile": "https://Stackoverflow.com/users/778964",
"pm_score": 3,
"selected": false,
"text": ".wrapperdiv{\n background-image:url(img/loading.gif);\n background-repeat:no-repeat;\n background-position:center center; /*Can place your loader where ever you like */\n}\n ALLOWTRANSPARENCY=\"false\""
},
{
"answer_id": 15538712,
"author": "rinchik",
"author_id": 2387506,
"author_profile": "https://Stackoverflow.com/users/2387506",
"pm_score": 1,
"selected": false,
"text": " loader({href:'loader.gif', onComplete: function(){\n $('#pd').html('<iframe onLoad=\"loader.close();\" src=\"pdf\" width=\"720px\" height=\"600px\" >Please wait... your report is loading..</iframe>');\n }\n });\n"
},
{
"answer_id": 30410165,
"author": "Ethan",
"author_id": 2932891,
"author_profile": "https://Stackoverflow.com/users/2932891",
"pm_score": 0,
"selected": false,
"text": "$( document ).blur( function () {\n // Your code here...\n});\n"
},
{
"answer_id": 36468935,
"author": "令狐葱",
"author_id": 911838,
"author_profile": "https://Stackoverflow.com/users/911838",
"pm_score": 0,
"selected": false,
"text": "<embed/> window.onload = function () {\n\n\n //creating an iframe element\n var ifr = document.createElement('iframe');\n document.body.appendChild(ifr);\n\n // making the iframe fill the viewport\n ifr.width = '100%';\n ifr.height = window.innerHeight;\n\n // continuously checking to see if the pdf file has been loaded\n self.interval = setInterval(function () {\n if (ifr && ifr.contentDocument && ifr.contentDocument.readyState === 'complete' && ifr.contentDocument.embeds && ifr.contentDocument.embeds.length > 0) {\n clearInterval(self.interval);\n\n console.log(\"loaded\");\n //You can do print here: ifr.contentWindow.print();\n }\n }, 100); \n\n ifr.src = src;\n}\n"
},
{
"answer_id": 37965768,
"author": "AldorEla",
"author_id": 3454908,
"author_profile": "https://Stackoverflow.com/users/3454908",
"pm_score": 0,
"selected": false,
"text": ".loading-image { position: absolute; z-index: 0; }\n.iframe-element { position: relative; z-index: 1; }\n"
},
{
"answer_id": 68452436,
"author": "Mahdi Bashirpour",
"author_id": 6569224,
"author_profile": "https://Stackoverflow.com/users/6569224",
"pm_score": 1,
"selected": false,
"text": "function frameLoaded(element) {\n alert('LOADED');\n}; <iframe src=\"https://google.com\" title=\"W3Schools Free Online Web Tutorials\" onload=\"frameLoaded(this)\"></iframe> "
}
] |
2008/08/27
|
[
"https://Stackoverflow.com/questions/30005",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3168/"
] |
30,018 |
<p>How can I use XPath to select an XML-node based on its content? </p>
<p>If I e.g. have the following xml and I want to select the <author>-node that contains Ritchie to get the author's full name:</p>
<pre><code><books>
<book isbn='0131103628'>
<title>The C Programming Language</title>
<authors>
<author>Ritchie, Dennis M.</author>
<author>Kernighan, Brian W.</author>
</authors>
</book>
<book isbn='1590593898'>
<title>Joel on Software</title>
<authors>
<author>Spolsky, Joel</author>
</authors>
</book>
</books>
</code></pre>
|
[
{
"answer_id": 30019,
"author": "Cros",
"author_id": 1523,
"author_profile": "https://Stackoverflow.com/users/1523",
"pm_score": 2,
"selected": false,
"text": "/books/book/authors/author[contains(., 'Ritchie')]\n xmlDoc.SelectSingleNode(\"/books/book/authors/author[contains(., 'Ritchie')]\").InnerText;\n"
},
{
"answer_id": 30021,
"author": "Chris Marasti-Georg",
"author_id": 96,
"author_profile": "https://Stackoverflow.com/users/96",
"pm_score": 2,
"selected": false,
"text": "//author[contains(text(), 'Ritchie')]\n"
},
{
"answer_id": 30023,
"author": "aku",
"author_id": 1196,
"author_profile": "https://Stackoverflow.com/users/1196",
"pm_score": 6,
"selected": true,
"text": "/books/book/authors/author[contains(., 'Ritchie')]\n //author[contains(., 'Ritchie')]\n"
}
] |
2008/08/27
|
[
"https://Stackoverflow.com/questions/30018",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1523/"
] |
30,026 |
<p>I've seen a lot of commonality in regex capabilities of different regex-enabled tools/languages (e.g. perl, sed, java, vim, etc), but I've also many differences.</p>
<p>Is there a <em>standard</em> subset of regex capabilities that all regex-enabled tools/languages will support? How do regex capabilities vary between tools/languages?</p>
|
[
{
"answer_id": 30054,
"author": "Rob Wells",
"author_id": 2974,
"author_profile": "https://Stackoverflow.com/users/2974",
"pm_score": 1,
"selected": false,
"text": "\"xyxyxyzz\" \"(xy)*(xyz)?\" \"xyxyxyz\" \"xyxyxy\""
}
] |
2008/08/27
|
[
"https://Stackoverflow.com/questions/30026",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2045/"
] |
30,036 |
<p>Is there some way to do multi-threading in JavaScript?</p>
|
[
{
"answer_id": 30200,
"author": "17 of 26",
"author_id": 2284,
"author_profile": "https://Stackoverflow.com/users/2284",
"pm_score": 4,
"selected": false,
"text": "setTimeout()"
},
{
"answer_id": 13710318,
"author": "Jono",
"author_id": 1876818,
"author_profile": "https://Stackoverflow.com/users/1876818",
"pm_score": 2,
"selected": false,
"text": "egFunction() parent.egFunction();\n"
},
{
"answer_id": 21649532,
"author": "Ahmet Can Güven",
"author_id": 836048,
"author_profile": "https://Stackoverflow.com/users/836048",
"pm_score": 3,
"selected": false,
"text": " <div class=\"div1\">\n <input type=\"button\" value=\"start/stop\" onclick=\"_thread1.control ? _thread1.stop() : _thread1.start();\" /><span>Counting summation of numbers till 10000000000</span> = <span id=\"1\">0</span>\n</div>\n<div class=\"div2\">\n <input type=\"button\" value=\"start/stop\" onclick=\"_thread2.control ? _thread2.stop() : _thread2.start();\" /><span>Counting numbers can be divided with 13 till 10000000000</span> = <span id=\"2\">0</span>\n</div>\n<div class=\"div3\">\n <input type=\"button\" value=\"start/stop\" onclick=\"_thread3.control ? _thread3.stop() : _thread3.start();\" /><span>Counting numbers can be divided with 3 till 10000000000</span> = <span id=\"3\">0</span>\n</div>\n var _thread1 = {//This is my thread as object\n control: false,//this is my control that will be used for start stop\n value: 0, //stores my result\n current: 0, //stores current number\n func: function () { //this is my func that will run\n if (this.control) { // checking for control to run\n if (this.current < 10000000000) {\n this.value += this.current; \n document.getElementById(\"1\").innerHTML = this.value;\n this.current++;\n }\n }\n setTimeout(function () { // And here is the trick! setTimeout is a king that will help us simulate threading in javascript\n _thread1.func(); //You cannot use this.func() just try to call with your object name\n }, 0);\n },\n start: function () {\n this.control = true; //start function\n },\n stop: function () {\n this.control = false; //stop function\n },\n init: function () {\n setTimeout(function () {\n _thread1.func(); // the first call of our thread\n }, 0)\n }\n};\nvar _thread2 = {\n control: false,\n value: 0,\n current: 0,\n func: function () {\n if (this.control) {\n if (this.current % 13 == 0) {\n this.value++;\n }\n this.current++;\n document.getElementById(\"2\").innerHTML = this.value;\n }\n setTimeout(function () {\n _thread2.func();\n }, 0);\n },\n start: function () {\n this.control = true;\n },\n stop: function () {\n this.control = false;\n },\n init: function () {\n setTimeout(function () {\n _thread2.func();\n }, 0)\n }\n};\nvar _thread3 = {\n control: false,\n value: 0,\n current: 0,\n func: function () {\n if (this.control) {\n if (this.current % 3 == 0) {\n this.value++;\n }\n this.current++;\n document.getElementById(\"3\").innerHTML = this.value;\n }\n setTimeout(function () {\n _thread3.func();\n }, 0);\n },\n start: function () {\n this.control = true;\n },\n stop: function () {\n this.control = false;\n },\n init: function () {\n setTimeout(function () {\n _thread3.func();\n }, 0)\n }\n};\n\n_thread1.init();\n_thread2.init();\n_thread3.init();\n"
},
{
"answer_id": 30891727,
"author": "Ludovic Feltz",
"author_id": 2576706,
"author_profile": "https://Stackoverflow.com/users/2576706",
"pm_score": 6,
"selected": false,
"text": "setTimeout() setInterval() XMLHttpRequest setTimeout() //As a worker normally take another JavaScript file to execute we convert the function in an URL: http://stackoverflow.com/a/16799132/2576706\nfunction getScriptPath(foo){ return window.URL.createObjectURL(new Blob([foo.toString().match(/^\\s*function\\s*\\(\\s*\\)\\s*\\{(([\\s\\S](?!\\}$))*[\\s\\S])/)[1]],{type:'text/javascript'})); }\n\nvar MAX_VALUE = 10000;\n\n/*\n * Here are the workers\n */\n//Worker 1\nvar worker1 = new Worker(getScriptPath(function(){\n self.addEventListener('message', function(e) {\n var value = 0;\n while(value <= e.data){\n self.postMessage(value);\n value++;\n }\n }, false);\n}));\n//We add a listener to the worker to get the response and show it in the page\nworker1.addEventListener('message', function(e) {\n document.getElementById(\"result1\").innerHTML = e.data;\n}, false);\n\n\n//Worker 2\nvar worker2 = new Worker(getScriptPath(function(){\n self.addEventListener('message', function(e) {\n var value = 0;\n while(value <= e.data){\n self.postMessage(value);\n value++;\n }\n }, false);\n}));\nworker2.addEventListener('message', function(e) {\n document.getElementById(\"result2\").innerHTML = e.data;\n}, false);\n\n\n//Worker 3\nvar worker3 = new Worker(getScriptPath(function(){\n self.addEventListener('message', function(e) {\n var value = 0;\n while(value <= e.data){\n self.postMessage(value);\n value++;\n }\n }, false);\n}));\nworker3.addEventListener('message', function(e) {\n document.getElementById(\"result3\").innerHTML = e.data;\n}, false);\n\n\n// Start and send data to our worker.\nworker1.postMessage(MAX_VALUE); \nworker2.postMessage(MAX_VALUE); \nworker3.postMessage(MAX_VALUE); <div id=\"result1\"></div>\n<div id=\"result2\"></div>\n<div id=\"result3\"></div> //The 3 iframes containing the code (take the thread id in param)\n<iframe id=\"threadFrame1\" src=\"thread.html?id=1\"></iframe>\n<iframe id=\"threadFrame2\" src=\"thread.html?id=2\"></iframe>\n<iframe id=\"threadFrame3\" src=\"thread.html?id=3\"></iframe>\n\n//Divs that shows the result\n<div id=\"result1\"></div>\n<div id=\"result2\"></div>\n<div id=\"result3\"></div>\n\n\n<script>\n //This function is called by each iframe\n function threadResult(threadId, result) {\n document.getElementById(\"result\" + threadId).innerHTML = result;\n }\n</script>\n //Get the parameters in the URL: http://stackoverflow.com/a/1099670/2576706\nfunction getQueryParams(paramName) {\n var qs = document.location.search.split('+').join(' ');\n var params = {}, tokens, re = /[?&]?([^=]+)=([^&]*)/g;\n while (tokens = re.exec(qs)) {\n params[decodeURIComponent(tokens[1])] = decodeURIComponent(tokens[2]);\n }\n return params[paramName];\n}\n\n//The thread code (get the id from the URL, we can pass other parameters as needed)\nvar MAX_VALUE = 100000;\n(function thread() {\n var threadId = getQueryParams('id');\n for(var i=0; i<MAX_VALUE; i++){\n parent.threadResult(threadId, i);\n }\n})();\n setTimeout() setTimeout(function(){ /* Some tasks */ }, 0);\nsetTimeout(function(){ /* Some tasks */ }, 0);\n[...]\n var MAX_VALUE = 10000;\n\nfunction thread1(value, maxValue){\n var me = this;\n document.getElementById(\"result1\").innerHTML = value;\n value++;\n \n //Continue execution\n if(value<=maxValue)\n setTimeout(function () { me.thread1(value, maxValue); }, 0);\n}\n\nfunction thread2(value, maxValue){\n var me = this;\n document.getElementById(\"result2\").innerHTML = value;\n value++;\n \n if(value<=maxValue)\n setTimeout(function () { me.thread2(value, maxValue); }, 0);\n}\n\nfunction thread3(value, maxValue){\n var me = this;\n document.getElementById(\"result3\").innerHTML = value;\n value++;\n \n if(value<=maxValue)\n setTimeout(function () { me.thread3(value, maxValue); }, 0);\n}\n\nthread1(0, MAX_VALUE);\nthread2(0, MAX_VALUE);\nthread3(0, MAX_VALUE); <div id=\"result1\"></div>\n<div id=\"result2\"></div>\n<div id=\"result3\"></div> var MAX_VALUE = 10000;\n\nScheduler = {\n _tasks: [],\n add: function(func){\n this._tasks.push(func);\n }, \n start: function(){\n var tasks = this._tasks;\n var length = tasks.length;\n while(length>0){\n for(var i=0; i<length; i++){\n var res = tasks[i].next();\n if(res.done){\n tasks.splice(i, 1);\n length--;\n i--;\n }\n }\n }\n } \n}\n\n\nfunction* updateUI(threadID, maxValue) {\n var value = 0;\n while(value<=maxValue){\n yield document.getElementById(\"result\" + threadID).innerHTML = value;\n value++;\n }\n}\n\nScheduler.add(updateUI(1, MAX_VALUE));\nScheduler.add(updateUI(2, MAX_VALUE));\nScheduler.add(updateUI(3, MAX_VALUE));\n\nScheduler.start() <div id=\"result1\"></div>\n<div id=\"result2\"></div>\n<div id=\"result3\"></div>"
},
{
"answer_id": 40326763,
"author": "Chad Scira",
"author_id": 103696,
"author_profile": "https://Stackoverflow.com/users/103696",
"pm_score": 1,
"selected": false,
"text": "function blocking (exampleArgument) {\n // block thread\n}\n\n// turn blocking pure function into a worker task\nconst blockingAsync = task.wrap(blocking);\n\n// run task on a autoscaling worker pool\nblockingAsync('exampleArgumentValue').then(result => {\n // do something with result\n});\n"
}
] |
2008/08/27
|
[
"https://Stackoverflow.com/questions/30036",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/184/"
] |
30,049 |
<p>I got embroiled in a discussion about DOM implementation quirks yesterday, with gave rise to an interesting question regarding Text.splitText and Element.normalise behaviours, and how they should behave.</p>
<p>In <a href="http://www.w3.org/TR/1998/REC-DOM-Level-1-19981001/level-one-core.html" rel="nofollow noreferrer">DOM Level 1 Core</a>, Text.splitText is defined as...</p>
<blockquote>
<p>Breaks this Text node into two Text nodes at the specified offset, keeping both in the tree as siblings. This node then only contains all the content up to the offset point. And a new Text node, which is inserted as the next sibling of this node, contains all the content at and after the offset point.</p>
</blockquote>
<p>Normalise is...</p>
<blockquote>
<p>Puts all Text nodes in the full depth of the sub-tree underneath this Element into a "normal" form where only markup (e.g., tags, comments, processing instructions, CDATA sections, and entity references) separates Text nodes, i.e., there are no adjacent Text nodes. This can be used to ensure that the DOM view of a document is the same as if it were saved and re-loaded, and is useful when operations (such as XPointer lookups) that depend on a particular document tree structure are to be used.</p>
</blockquote>
<p>So, if I take a text node containing "Hello World", referenced in textNode, and do</p>
<pre><code>textNode.splitText(3)
</code></pre>
<p>textNode now has the content "Hello", and a new sibling containing " World"</p>
<p>If I then</p>
<pre><code>textNode.parent.normalize()
</code></pre>
<p><em>what is textNode</em>? The specification doesn't make it clear that textNode has to still be a child of it's previous parent, just updated to contain all adjacent text nodes (which are then removed). It seems to be to be a conforment behaviour to remove all the adjacent text nodes, and then recreate a new node with the concatenation of the values, leaving textNode pointing to something that is no longer part of the tree. Or, we can update textNode in the same fashion as in splitText, so it retains it's tree position, and gets a new value.</p>
<p>The choice of behaviour is really quite different, and I can't find a clarification on which is correct, or if this is simply an oversight in the specification (it doesn't seem to be clarified in levels 2 or 3). Can any DOM/XML gurus out there shed some light?</p>
|
[
{
"answer_id": 34202,
"author": "Sam Brightman",
"author_id": 2492,
"author_profile": "https://Stackoverflow.com/users/2492",
"pm_score": 2,
"selected": false,
"text": "textNode splitText"
}
] |
2008/08/27
|
[
"https://Stackoverflow.com/questions/30049",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1200/"
] |
30,058 |
<p>The <a href="http://developer.apple.com/documentation/AppleApplications/Reference/SafariWebContent/UsingiPhoneApplications/chapter_6_section_4.html" rel="nofollow noreferrer">Apple Developer Documentation</a> (link is dead now) explains that if you place a link in a web page and then click it whilst using Mobile Safari on the iPhone, the Google Maps application that is provided as standard with the iPhone will launch.</p>
<p>How can I launch the same Google Maps application with a specific address from within my own native iPhone application (i.e. not a web page through Mobile Safari) in the same way that tapping an address in Contacts launches the map?</p>
<p><strong>NOTE: THIS ONLY WORKS ON THE DEVICE ITSELF. NOT IN THE SIMULATOR.</strong></p>
|
[
{
"answer_id": 30079,
"author": "Adam Wright",
"author_id": 1200,
"author_profile": "https://Stackoverflow.com/users/1200",
"pm_score": 7,
"selected": true,
"text": "openURL UIApplication [someUIApplication openURL:[NSURL URLWithString:@\"http://maps.google.com/maps?q=London\"]]\n MKMapItem openInMapsWithLaunchOptions [[MKMapItem mapItemForCurrentLocation] openInMapsWithLaunchOptions:nil];\n"
},
{
"answer_id": 30163,
"author": "davidmytton",
"author_id": 2183,
"author_profile": "https://Stackoverflow.com/users/2183",
"pm_score": 5,
"selected": false,
"text": "UIApplication *app = [UIApplication sharedApplication];\n[app openURL:[NSURL URLWithString: @\"http://maps.google.com/maps?q=London\"]];\n"
},
{
"answer_id": 530813,
"author": "Jane Sales",
"author_id": 63994,
"author_profile": "https://Stackoverflow.com/users/63994",
"pm_score": 5,
"selected": false,
"text": "NSString *latlong = @\"-56.568545,1.256281\";\nNSString *url = [NSString stringWithFormat: @\"http://maps.google.com/maps?ll=%@\",\n[latlong stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];\n[[UIApplication sharedApplication] openURL:[NSURL URLWithString:url]];\n"
},
{
"answer_id": 1821520,
"author": "Pavel Kurta",
"author_id": 151793,
"author_profile": "https://Stackoverflow.com/users/151793",
"pm_score": 1,
"selected": false,
"text": "[[UIApplication sharedApplication] openURL:[NSURL URLWithString: @\"http://maps.google.com/maps?q=London\"]]\n"
},
{
"answer_id": 13861525,
"author": "Michael Baltaks",
"author_id": 23312,
"author_profile": "https://Stackoverflow.com/users/23312",
"pm_score": 4,
"selected": false,
"text": "[[UIApplication sharedApplication] canOpenURL:\n [NSURL URLWithString:@\"comgooglemaps://\"]]; http://maps.google.com/maps?q= comgooglemaps://?q="
},
{
"answer_id": 38436933,
"author": "Mannam Brahmam",
"author_id": 4720315,
"author_profile": "https://Stackoverflow.com/users/4720315",
"pm_score": 0,
"selected": false,
"text": "**Getting Directions between 2 locations**\n\n NSString *googleMapUrlString = [NSString stringWithFormat:@\"http://maps.google.com/?saddr=%@,%@&daddr=%@,%@\", @\"30.7046\", @\"76.7179\", @\"30.4414\", @\"76.1617\"];\n [[UIApplication sharedApplication] openURL:[NSURL URLWithString:googleMapUrlString]];\n"
},
{
"answer_id": 41384444,
"author": "Ruchin Somal",
"author_id": 6892444,
"author_profile": "https://Stackoverflow.com/users/6892444",
"pm_score": 3,
"selected": false,
"text": "<key>LSApplicationQueriesSchemes</key>\n<array>\n <string>comgooglemaps</string>\n</array>\n if ([[UIApplication sharedApplication] canOpenURL: [NSURL URLWithString:@\"comgooglemaps:\"]]) {\n NSString *urlString = [NSString stringWithFormat:@\"comgooglemaps://?ll=%@,%@\",destinationLatitude,destinationLongitude];\n [[UIApplication sharedApplication] openURL:[NSURL URLWithString:urlString]];\n } else { \n NSString *string = [NSString stringWithFormat:@\"http://maps.google.com/maps?ll=%@,%@\",destinationLatitude,destinationLongitude];\n [[UIApplication sharedApplication] openURL:[NSURL URLWithString:string]];\n }\n if UIApplication.sharedApplication().canOpenURL(NSURL(string: \"comgooglemaps:\")!) {\n var urlString = \"comgooglemaps://?ll=\\(destinationLatitude),\\(destinationLongitude)\"\n UIApplication.sharedApplication().openURL(NSURL(string: urlString)!)\n}\nelse {\n var string = \"http://maps.google.com/maps?ll=\\(destinationLatitude),\\(destinationLongitude)\"\n UIApplication.sharedApplication().openURL(NSURL(string: string)!)\n}\n if UIApplication.shared.canOpenURL(URL(string: \"comgooglemaps:\")!) {\n var urlString = \"comgooglemaps://?ll=\\(destinationLatitude),\\(destinationLongitude)\"\n UIApplication.shared.openURL(URL(string: urlString)!)\n}\nelse {\n var string = \"http://maps.google.com/maps?ll=\\(destinationLatitude),\\(destinationLongitude)\"\n UIApplication.shared.openURL(URL(string: string)!)\n}\n"
},
{
"answer_id": 42642769,
"author": "DURGESH",
"author_id": 5954633,
"author_profile": "https://Stackoverflow.com/users/5954633",
"pm_score": 1,
"selected": false,
"text": "NSString* addr = nil;\n addr = [NSString stringWithFormat:@\"http://maps.google.com/maps?daddr=%1.6f,%1.6f&saddr=Posizione attuale\", destinationLat,destinationLong];\n\nNSURL* url = [[NSURL alloc] initWithString:[addr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];\n[[UIApplication sharedApplication] openURL:url];\n"
},
{
"answer_id": 47990527,
"author": "Meet Doshi",
"author_id": 3908884,
"author_profile": "https://Stackoverflow.com/users/3908884",
"pm_score": 2,
"selected": false,
"text": "func openMapApp(latitude:String, longitude:String, address:String) {\n\n var myAddress:String = address\n\n //For Apple Maps\n let testURL2 = URL.init(string: \"http://maps.apple.com/\")\n\n //For Google Maps\n let testURL = URL.init(string: \"comgooglemaps-x-callback://\")\n\n //For Google Maps\n if UIApplication.shared.canOpenURL(testURL!) {\n var direction:String = \"\"\n myAddress = myAddress.replacingOccurrences(of: \" \", with: \"+\")\n\n direction = String(format: \"comgooglemaps-x-callback://?daddr=%@,%@&x-success=sourceapp://?resume=true&x-source=AirApp\", latitude, longitude)\n\n let directionsURL = URL.init(string: direction)\n if #available(iOS 10, *) {\n UIApplication.shared.open(directionsURL!)\n } else {\n UIApplication.shared.openURL(directionsURL!)\n }\n }\n //For Apple Maps\n else if UIApplication.shared.canOpenURL(testURL2!) {\n var direction:String = \"\"\n myAddress = myAddress.replacingOccurrences(of: \" \", with: \"+\")\n\n var CurrentLocationLatitude:String = \"\"\n var CurrentLocationLongitude:String = \"\"\n\n if let latitude = USERDEFAULT.value(forKey: \"CurrentLocationLatitude\") as? Double {\n CurrentLocationLatitude = \"\\(latitude)\"\n //print(myLatitude)\n }\n\n if let longitude = USERDEFAULT.value(forKey: \"CurrentLocationLongitude\") as? Double {\n CurrentLocationLongitude = \"\\(longitude)\"\n //print(myLongitude)\n }\n\n direction = String(format: \"http://maps.apple.com/?saddr=%@,%@&daddr=%@,%@\", CurrentLocationLatitude, CurrentLocationLongitude, latitude, longitude)\n\n let directionsURL = URL.init(string: direction)\n if #available(iOS 10, *) {\n UIApplication.shared.open(directionsURL!)\n } else {\n UIApplication.shared.openURL(directionsURL!)\n }\n\n }\n //For SAFARI Browser\n else {\n var direction:String = \"\"\n direction = String(format: \"http://maps.google.com/maps?q=%@,%@\", latitude, longitude)\n direction = direction.replacingOccurrences(of: \" \", with: \"+\")\n\n let directionsURL = URL.init(string: direction)\n if #available(iOS 10, *) {\n UIApplication.shared.open(directionsURL!)\n } else {\n UIApplication.shared.openURL(directionsURL!)\n }\n }\n}\n"
},
{
"answer_id": 54767602,
"author": "Abhirajsinh Thakore",
"author_id": 8306054,
"author_profile": "https://Stackoverflow.com/users/8306054",
"pm_score": 0,
"selected": false,
"text": "<key>LSApplicationQueriesSchemes</key>\n<array>\n<string>googlechromes</string>\n<string>comgooglemaps</string>\n</array>\n let destinationLatitude = \"40.7128\"\n let destinationLongitude = \"74.0060\"\n\n if UIApplication.shared.canOpenURL(URL(string: \"comgooglemaps:\")!) {\n if let url = URL(string: \"comgooglemaps://?ll=\\(destinationLatitude),\\(destinationLongitude)\"), !url.absoluteString.isEmpty {\n UIApplication.shared.open(url, options: [:], completionHandler: nil)\n }\n }else{\n if let url = URL(string: \"http://maps.google.com/maps?ll=\\(destinationLatitude),\\(destinationLongitude)\"), !url.absoluteString.isEmpty {\n UIApplication.shared.open(url, options: [:], completionHandler: nil)\n }\n }\n"
}
] |
2008/08/27
|
[
"https://Stackoverflow.com/questions/30058",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2183/"
] |
30,062 |
<p>Yesterday I wanted to add a boolean field to an Oracle table. However, there isn't actually a boolean data type in Oracle. Does anyone here know the best way to simulate a boolean? Googling the subject discovered several approaches</p>
<ol>
<li><p>Use an integer and just don't bother assigning anything other than 0 or 1 to it.</p></li>
<li><p>Use a char field with 'Y' or 'N' as the only two values.</p></li>
<li><p>Use an enum with the CHECK constraint.</p></li>
</ol>
<p>Do experienced Oracle developers know which approach is preferred/canonical?</p>
|
[
{
"answer_id": 30072,
"author": "ColinYounger",
"author_id": 1223,
"author_profile": "https://Stackoverflow.com/users/1223",
"pm_score": 7,
"selected": true,
"text": "getBoolean() create table tbool (bool char check (bool in (0,1));\ninsert into tbool values(0);\ninsert into tbool values(1);`\n"
},
{
"answer_id": 16398732,
"author": "Andrew Spencer",
"author_id": 587365,
"author_profile": "https://Stackoverflow.com/users/587365",
"pm_score": 4,
"selected": false,
"text": "select sum(is_ripe) from bananas select count(*) from bananas where is_ripe = 'Y' select sum(case is_ripe when 'Y' then 1 else 0) from bananas some_column is null some_column = 0"
},
{
"answer_id": 39841035,
"author": "Ben.12",
"author_id": 2209991,
"author_profile": "https://Stackoverflow.com/users/2209991",
"pm_score": 2,
"selected": false,
"text": "number ALTER TABLE my_table_name ADD (\nmy_new_boolean_column number(1) DEFAULT 0 NOT NULL\nCONSTRAINT my_new_boolean_column CHECK (my_new_boolean_column in (1,0))\n);\n my_table_name my_new_boolean_column NULL 0 1"
}
] |
2008/08/27
|
[
"https://Stackoverflow.com/questions/30062",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1694/"
] |
30,066 |
<p>I'm looking for a way to redirect all the stderr streams in interactive bash (ideally to its calling parent process).</p>
<p>I don't want to redirect stderr stream from each individual command, which I could do by appending <code>2> a_file</code> to each command.</p>
<p>By default, these stderr streams are redirected to the stdout of an interactive bash. I would like to get them on the stderr of this interactive bash process in order to prevent my stdout to be polluted by error messages and be able to treat them separatly.</p>
<p>Any ideas?</p>
<p>I still haven't found an answer ... But maybe it's actually a tty parameter. Does anybody knows something about tty/interactive shell responsibility for handling stderr ?</p>
|
[
{
"answer_id": 30085,
"author": "caerwyn",
"author_id": 2406,
"author_profile": "https://Stackoverflow.com/users/2406",
"pm_score": 2,
"selected": false,
"text": " $ bash -i 2> stderr.log\n $ \n"
},
{
"answer_id": 30088,
"author": "gavrie",
"author_id": 2794,
"author_profile": "https://Stackoverflow.com/users/2794",
"pm_score": 3,
"selected": false,
"text": "exec exec 2> /tmp/myfile"
},
{
"answer_id": 75132,
"author": "jtimberman",
"author_id": 7672,
"author_profile": "https://Stackoverflow.com/users/7672",
"pm_score": 2,
"selected": false,
"text": "ssh remotehost \"command\" 2>~/stderr\n $ ssh remotehost \"tail x;head x\" 2>~/stderr\n$ cat stderr \ntail: cannot open `x' for reading: No such file or directory\nhead: cannot open `x' for reading: No such file or directory\n"
},
{
"answer_id": 84426,
"author": "Gunstick",
"author_id": 15653,
"author_profile": "https://Stackoverflow.com/users/15653",
"pm_score": 2,
"selected": false,
"text": "$ ssh remotehost 'ls nosuchfile; ls /etc/passwd' >/tmp/stdout 2>/tmp/stderr \n$ cat /tmp/stdout \n/etc/passwd \n$ cat /tmp/stderr \nnosuchfile not found\n"
},
{
"answer_id": 731499,
"author": "crb",
"author_id": 51691,
"author_profile": "https://Stackoverflow.com/users/51691",
"pm_score": 0,
"selected": false,
"text": "ssh -t"
},
{
"answer_id": 4157470,
"author": "Kit Gerrits",
"author_id": 504851,
"author_profile": "https://Stackoverflow.com/users/504851",
"pm_score": 2,
"selected": false,
"text": "2>&1 stderr ssh -t remotehost tar -cf - /mnt/backup 2\\>backup.err > localbackup.tar\nEXITSTATUS=$?\nif [ $EXITSTATUS != \"0\" ] then \n echo Error occurred!\n ssh remotehost cat backup.err >localbackup.errors\n cat localbackup.errors\n ssh remotehost rm backup.err \nelse \n echo Backup completed successfully!\n ssh remotehost rm backup.err \nfi\n"
},
{
"answer_id": 18093445,
"author": "stefano",
"author_id": 1505651,
"author_profile": "https://Stackoverflow.com/users/1505651",
"pm_score": 2,
"selected": false,
"text": "{\n cmd1\n cmd2\n ...\n cmdN\n} 2> error.log\n { cmd1; cmd2; ... cmdN; } 2> error.log\n"
}
] |
2008/08/27
|
[
"https://Stackoverflow.com/questions/30066",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1044/"
] |
30,074 |
<p>We have several .NET applications that monitor a directory for new files, using FileSystemWatcher. The files are copied from another location, uploaded via FTP, etc. When they come in, the files are processed in one way or another. However, one problem that I have never seen a satisfactory answer for is: for large files, how does one know when the files being monitored are still being written to? Obviously, we need to wait until the files are complete and closed before we begin processing them. The event args in the FileSystemWatcher events do not seem to address this.</p>
|
[
{
"answer_id": 1431709,
"author": "Dirk Vollmar",
"author_id": 40347,
"author_profile": "https://Stackoverflow.com/users/40347",
"pm_score": 2,
"selected": false,
"text": "/// <summary>\n/// Waits until a file can be opened with write permission\n/// </summary>\npublic static void WaitReady(string fileName)\n{\n while (true)\n {\n try\n {\n using (System.IO.Stream stream = System.IO.File.Open(fileName, FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite))\n {\n if (stream != null)\n {\n System.Diagnostics.Trace.WriteLine(string.Format(\"Output file {0} ready.\", fileName));\n break;\n }\n }\n }\n catch (FileNotFoundException ex)\n {\n System.Diagnostics.Trace.WriteLine(string.Format(\"Output file {0} not yet ready ({1})\", fileName, ex.Message));\n }\n catch (IOException ex)\n {\n System.Diagnostics.Trace.WriteLine(string.Format(\"Output file {0} not yet ready ({1})\", fileName, ex.Message));\n }\n catch (UnauthorizedAccessException ex)\n {\n System.Diagnostics.Trace.WriteLine(string.Format(\"Output file {0} not yet ready ({1})\", fileName, ex.Message));\n }\n Thread.Sleep(500);\n }\n}\n"
}
] |
2008/08/27
|
[
"https://Stackoverflow.com/questions/30074",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2144/"
] |
30,080 |
<p>I have two points (a line segment) and a rectangle. I would like to know how to calculate if the line segment intersects the rectangle. </p>
|
[
{
"answer_id": 30109,
"author": "Chris Marasti-Georg",
"author_id": 96,
"author_profile": "https://Stackoverflow.com/users/96",
"pm_score": 5,
"selected": true,
"text": "public struct Line\n{\n public static Line Empty;\n\n private PointF p1;\n private PointF p2;\n\n public Line(PointF p1, PointF p2)\n {\n this.p1 = p1;\n this.p2 = p2;\n }\n\n public PointF P1\n {\n get { return p1; }\n set { p1 = value; }\n }\n\n public PointF P2\n {\n get { return p2; }\n set { p2 = value; }\n }\n\n public float X1\n {\n get { return p1.X; }\n set { p1.X = value; }\n }\n\n public float X2\n {\n get { return p2.X; }\n set { p2.X = value; }\n }\n\n public float Y1\n {\n get { return p1.Y; }\n set { p1.Y = value; }\n }\n\n public float Y2\n {\n get { return p2.Y; }\n set { p2.Y = value; }\n }\n}\n\npublic struct Polygon: IEnumerable<PointF>\n{\n private PointF[] points;\n\n public Polygon(PointF[] points)\n {\n this.points = points;\n }\n\n public PointF[] Points\n {\n get { return points; }\n set { points = value; }\n }\n\n public int Length\n {\n get { return points.Length; }\n }\n\n public PointF this[int index]\n {\n get { return points[index]; }\n set { points[index] = value; }\n }\n\n public static implicit operator PointF[](Polygon polygon)\n {\n return polygon.points;\n }\n\n public static implicit operator Polygon(PointF[] points)\n {\n return new Polygon(points);\n }\n\n IEnumerator<PointF> IEnumerable<PointF>.GetEnumerator()\n {\n return (IEnumerator<PointF>)points.GetEnumerator();\n }\n\n public IEnumerator GetEnumerator()\n {\n return points.GetEnumerator();\n }\n}\n\npublic enum Intersection\n{\n None,\n Tangent,\n Intersection,\n Containment\n}\n\npublic static class Geometry\n{\n\n public static Intersection IntersectionOf(Line line, Polygon polygon)\n {\n if (polygon.Length == 0)\n {\n return Intersection.None;\n }\n if (polygon.Length == 1)\n {\n return IntersectionOf(polygon[0], line);\n }\n bool tangent = false;\n for (int index = 0; index < polygon.Length; index++)\n {\n int index2 = (index + 1)%polygon.Length;\n Intersection intersection = IntersectionOf(line, new Line(polygon[index], polygon[index2]));\n if (intersection == Intersection.Intersection)\n {\n return intersection;\n }\n if (intersection == Intersection.Tangent)\n {\n tangent = true;\n }\n }\n return tangent ? Intersection.Tangent : IntersectionOf(line.P1, polygon);\n }\n\n public static Intersection IntersectionOf(PointF point, Polygon polygon)\n {\n switch (polygon.Length)\n {\n case 0:\n return Intersection.None;\n case 1:\n if (polygon[0].X == point.X && polygon[0].Y == point.Y)\n {\n return Intersection.Tangent;\n }\n else\n {\n return Intersection.None;\n }\n case 2:\n return IntersectionOf(point, new Line(polygon[0], polygon[1]));\n }\n\n int counter = 0;\n int i;\n PointF p1;\n int n = polygon.Length;\n p1 = polygon[0];\n if (point == p1)\n {\n return Intersection.Tangent;\n }\n\n for (i = 1; i <= n; i++)\n {\n PointF p2 = polygon[i % n];\n if (point == p2)\n {\n return Intersection.Tangent;\n }\n if (point.Y > Math.Min(p1.Y, p2.Y))\n {\n if (point.Y <= Math.Max(p1.Y, p2.Y))\n {\n if (point.X <= Math.Max(p1.X, p2.X))\n {\n if (p1.Y != p2.Y)\n {\n double xinters = (point.Y - p1.Y) * (p2.X - p1.X) / (p2.Y - p1.Y) + p1.X;\n if (p1.X == p2.X || point.X <= xinters)\n counter++;\n }\n }\n }\n }\n p1 = p2;\n }\n\n return (counter % 2 == 1) ? Intersection.Containment : Intersection.None;\n }\n\n public static Intersection IntersectionOf(PointF point, Line line)\n {\n float bottomY = Math.Min(line.Y1, line.Y2);\n float topY = Math.Max(line.Y1, line.Y2);\n bool heightIsRight = point.Y >= bottomY &&\n point.Y <= topY;\n //Vertical line, slope is divideByZero error!\n if (line.X1 == line.X2)\n {\n if (point.X == line.X1 && heightIsRight)\n {\n return Intersection.Tangent;\n }\n else\n {\n return Intersection.None;\n }\n }\n float slope = (line.X2 - line.X1)/(line.Y2 - line.Y1);\n bool onLine = (line.Y1 - point.Y) == (slope*(line.X1 - point.X));\n if (onLine && heightIsRight)\n {\n return Intersection.Tangent;\n }\n else\n {\n return Intersection.None;\n }\n }\n\n}\n"
},
{
"answer_id": 1593336,
"author": "Jaguar",
"author_id": 109338,
"author_profile": "https://Stackoverflow.com/users/109338",
"pm_score": 2,
"selected": false,
"text": "public static Intersection IntersectionOf(Line line1, Line line2)\n {\n // Fail if either line segment is zero-length.\n if (line1.X1 == line1.X2 && line1.Y1 == line1.Y2 || line2.X1 == line2.X2 && line2.Y1 == line2.Y2)\n return Intersection.None;\n\n if (line1.X1 == line2.X1 && line1.Y1 == line2.Y1 || line1.X2 == line2.X1 && line1.Y2 == line2.Y1)\n return Intersection.Intersection;\n if (line1.X1 == line2.X2 && line1.Y1 == line2.Y2 || line1.X2 == line2.X2 && line1.Y2 == line2.Y2)\n return Intersection.Intersection;\n\n // (1) Translate the system so that point A is on the origin.\n line1.X2 -= line1.X1; line1.Y2 -= line1.Y1;\n line2.X1 -= line1.X1; line2.Y1 -= line1.Y1;\n line2.X2 -= line1.X1; line2.Y2 -= line1.Y1;\n\n // Discover the length of segment A-B.\n double distAB = Math.Sqrt(line1.X2 * line1.X2 + line1.Y2 * line1.Y2);\n\n // (2) Rotate the system so that point B is on the positive X axis.\n double theCos = line1.X2 / distAB;\n double theSin = line1.Y2 / distAB;\n double newX = line2.X1 * theCos + line2.Y1 * theSin;\n line2.Y1 = line2.Y1 * theCos - line2.X1 * theSin; line2.X1 = newX;\n newX = line2.X2 * theCos + line2.Y2 * theSin;\n line2.Y2 = line2.Y2 * theCos - line2.X2 * theSin; line2.X2 = newX;\n\n // Fail if segment C-D doesn't cross line A-B.\n if (line2.Y1 < 0 && line2.Y2 < 0 || line2.Y1 >= 0 && line2.Y2 >= 0)\n return Intersection.None;\n\n // (3) Discover the position of the intersection point along line A-B.\n double posAB = line2.X2 + (line2.X1 - line2.X2) * line2.Y2 / (line2.Y2 - line2.Y1);\n\n // Fail if segment C-D crosses line A-B outside of segment A-B.\n if (posAB < 0 || posAB > distAB)\n return Intersection.None;\n\n // (4) Apply the discovered position to line A-B in the original coordinate system.\n return Intersection.Intersection;\n }\n"
},
{
"answer_id": 9686237,
"author": "lestival",
"author_id": 239483,
"author_profile": "https://Stackoverflow.com/users/239483",
"pm_score": 1,
"selected": false,
"text": "System.Drawing.Rectangle\n IntersectsWith();\n"
}
] |
2008/08/27
|
[
"https://Stackoverflow.com/questions/30080",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/623/"
] |
30,099 |
<p>In my browsings amongst the Internet, I came across <a href="http://www.reddit.com/r/programming/comments/6y6lr/ask_proggit_which_is_more_useful_to_know_c_or_java/" rel="nofollow noreferrer">this post</a>, which includes this</p>
<blockquote>
<p>"(Well written) C++ goes to great
lengths to make stack automatic
objects work "just like" primitives,
as reflected in Stroustrup's advice to
"do as the ints do". This requires a
much greater adherence to the
principles of Object Oriented
development: your class isn't right
until it "works like" an int,
following the "Rule of Three" that
guarantees it can (just like an int)
be created, copied, and correctly
destroyed as a stack automatic."</p>
</blockquote>
<p>I've done a little C, and C++ code, but just in passing, never anything serious, but I'm just curious, what it means exactly?</p>
<p>Can someone give an example?</p>
|
[
{
"answer_id": 30125,
"author": "Brad Barker",
"author_id": 12081,
"author_profile": "https://Stackoverflow.com/users/12081",
"pm_score": 1,
"selected": false,
"text": "MyObject x = MyObject(params); // onto the stack\n\nMyObject * y = new MyObject(params); // onto the heap\n"
},
{
"answer_id": 30186,
"author": "Christopher",
"author_id": 3186,
"author_profile": "https://Stackoverflow.com/users/3186",
"pm_score": 5,
"selected": true,
"text": "{\n obj a;\n} // a is destroyed here\n {\n obj* b = new obj;\n}\n {\n FILE* pF = fopen( ... );\n // ... do sth with pF\n fclose( pF );\n}\n {\n std::fstream f( ... );\n // do sth with f\n} // here f gets auto magically destroyed and the destructor frees the file\n {\n string v( \"bob\" );\n string k;\n\n v = k\n // v now contains \"bob\"\n} // v + k are destroyed here, and any memory used by v + k is freed\n"
},
{
"answer_id": 30238,
"author": "Konrad Rudolph",
"author_id": 1968,
"author_profile": "https://Stackoverflow.com/users/1968",
"pm_score": 2,
"selected": false,
"text": "auto auto static int main() {\n int a;\n auto int b;\n}\n var auto a = std::max(1.0, 4.0); // `a` now has type double.\n"
}
] |
2008/08/27
|
[
"https://Stackoverflow.com/questions/30099",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/841/"
] |
30,170 |
<p>Are there any useful techniques for reducing the repetition of constants in a CSS file?</p>
<p>(For example, a bunch of different selectors which should all apply the same colour, or the same font size)?</p>
|
[
{
"answer_id": 30177,
"author": "samjudson",
"author_id": 1908,
"author_profile": "https://Stackoverflow.com/users/1908",
"pm_score": 0,
"selected": false,
"text": "<div class=\"one two\">"
},
{
"answer_id": 30178,
"author": "KevinUK",
"author_id": 1469,
"author_profile": "https://Stackoverflow.com/users/1469",
"pm_score": 3,
"selected": false,
"text": "h1,h2 {\n color: #fff;\n}\n"
},
{
"answer_id": 30179,
"author": "Zack Peterson",
"author_id": 83,
"author_profile": "https://Stackoverflow.com/users/83",
"pm_score": 1,
"selected": false,
"text": "h1,h2 {\n color: %%YOURFAVORITECOLOR%%;\n}\n\ndiv.something {\n border-color: %%YOURFAVORITECOLOR%%;\n}\n h1,h2 {\n color: #E0EAF1;\n}\n\ndiv.something {\n border-color: #E0EAF1;\n}\n Dim CssText As String = System.IO.File.ReadAllText(\"C:\\source.css\")\nCssText = CssText.Replace(\"%%YOURFAVORITECOLOR%%\", \"#E0EAF1\")\nSystem.IO.File.WriteAllText(\"C:\\target.css\", CssText)\n"
},
{
"answer_id": 30189,
"author": "Joel Coehoorn",
"author_id": 3043,
"author_profile": "https://Stackoverflow.com/users/3043",
"pm_score": 3,
"selected": false,
"text": ".DefaultBackColor\n{\n background-color: #123456;\n}\n.SomeOtherStyle\n{\n //other stuff here\n}\n.DefaultForeColor\n{\n color:#654321;\n}\n <div class=\"DefaultBackColor SomeOtherStyle DefaultForeColor\">Your content</div>\n"
},
{
"answer_id": 31439095,
"author": "abhimanyuaryan",
"author_id": 4417582,
"author_profile": "https://Stackoverflow.com/users/4417582",
"pm_score": 2,
"selected": false,
"text": "p{\n background-color: #ccc; \n}\n\nh1{\n background-color: #ccc;\n}\n :root{\n --main--color: #ccc; \n}\n\np{\n background-color: var(--main-color);\n}\n\nh1{\n background-color: var(--main-color);\n}\n $base : #ccc;\n\np{\n background-color: $base;\n}\n\nh1{\n background-color: $base;\n}\n"
},
{
"answer_id": 32329417,
"author": "Ajay Gupta",
"author_id": 2663073,
"author_profile": "https://Stackoverflow.com/users/2663073",
"pm_score": 1,
"selected": false,
"text": "h1 {\n color: red;\n}\np {\n font-weight: bold;\n}\n .deflt-color {\n color: green;\n}\n.dflt-nrml-font {\n font-size: 12px;\n}\n.dflt-header-font {\n font-size: 18px;\n}\n"
},
{
"answer_id": 35889456,
"author": "John Slegers",
"author_id": 1946501,
"author_profile": "https://Stackoverflow.com/users/1946501",
"pm_score": 4,
"selected": true,
"text": "body, html {\n margin: 0;\n height: 100%;\n}\n\n.theme-default {\n --page-background-color: #cec;\n --page-color: #333;\n --button-border-width: 1px;\n --button-border-color: #333;\n --button-background-color: #f55;\n --button-color: #fff;\n --gutter-width: 1em;\n float: left;\n height: 100%;\n width: 100%;\n background-color: var(--page-background-color);\n color: var(--page-color);\n}\n\nbutton {\n background-color: var(--button-background-color);\n color: var(--button-color);\n border-color: var(--button-border-color);\n border-width: var(--button-border-width);\n}\n\n.pad-box {\n padding: var(--gutter-width);\n} <div class=\"theme-default\">\n <div class=\"pad-box\">\n <p>\n This is a test\n </p>\n <button>\n Themed button\n </button>\n </div>\n</div> @function exponent($base, $exponent) {\n $value: $base;\n @if $exponent > 1 {\n @for $i from 2 through $exponent {\n $value: $value * $base;\n }\n }\n @if $exponent < 1 {\n @for $i from 0 through -$exponent {\n $value: $value / $base;\n }\n }\n @return $value; \n}\n"
},
{
"answer_id": 38204623,
"author": "zloctb",
"author_id": 1673376,
"author_profile": "https://Stackoverflow.com/users/1673376",
"pm_score": 0,
"selected": false,
"text": " :root {\n --primary-color: red;\n }\n\n p {\n color: var(--primary-color);\n } \n\n<p> some red text </p>\n var styles = getComputedStyle(document.documentElement);\nvar value = String(styles.getPropertyValue('--primary-color')).trim(); \n\n\ndocument.documentElement.style.setProperty('--primary-color', 'blue');\n"
}
] |
2008/08/27
|
[
"https://Stackoverflow.com/questions/30170",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/797/"
] |
30,171 |
<p>Help! I have an Axis web service that is being consumed by a C# application. Everything works great, except that arrays of long values always come across as [0,0,0,0] - the right length, but the values aren't deserialized. I have tried with other primitives (ints, doubles) and the same thing happens. What do I do? I don't want to change the semantics of my service.</p>
|
[
{
"answer_id": 30172,
"author": "Chris Marasti-Georg",
"author_id": 96,
"author_profile": "https://Stackoverflow.com/users/96",
"pm_score": 4,
"selected": true,
"text": " <xsd:complexType name=\"ArrayOf_xsd_long\">\n <xsd:complexContent mixed=\"false\">\n <xsd:restriction base=\"soapenc:Array\">\n <xsd:attribute wsdl:arrayType=\"soapenc:long[]\" ref=\"soapenc:arrayType\" />\n </xsd:restriction>\n </xsd:complexContent>\n </xsd:complexType>\n [AttributeUsage(AttributeTargets.Method)]\npublic class LongArrayHelperAttribute : SoapExtensionAttribute\n{\n private int priority = 0;\n\n public override Type ExtensionType\n {\n get { return typeof (LongArrayHelper); }\n }\n\n public override int Priority\n {\n get { return priority; }\n set { priority = value; }\n }\n}\n\npublic class LongArrayHelper : SoapExtension\n{\n private static ILog log = LogManager.GetLogger(typeof (LongArrayHelper));\n\n public override object GetInitializer(LogicalMethodInfo methodInfo, SoapExtensionAttribute attribute)\n {\n return null;\n }\n\n public override object GetInitializer(Type serviceType)\n {\n return null;\n }\n\n public override void Initialize(object initializer)\n {\n }\n\n private Stream originalStream;\n\n private Stream newStream;\n\n public override void ProcessMessage(SoapMessage m)\n {\n switch (m.Stage)\n {\n case SoapMessageStage.AfterSerialize:\n newStream.Position = 0; //need to reset stream \n CopyStream(newStream, originalStream);\n break;\n\n case SoapMessageStage.BeforeDeserialize:\n XmlWriterSettings settings = new XmlWriterSettings();\n settings.Indent = false;\n settings.NewLineOnAttributes = false;\n settings.NewLineHandling = NewLineHandling.None;\n settings.NewLineChars = \"\";\n XmlWriter writer = XmlWriter.Create(newStream, settings);\n\n XmlDocument xmlDocument = new XmlDocument();\n xmlDocument.Load(originalStream);\n\n List<XmlElement> longArrayItems = new List<XmlElement>();\n Dictionary<string, XmlElement> multiRefs = new Dictionary<string, XmlElement>();\n FindImportantNodes(xmlDocument.DocumentElement, longArrayItems, multiRefs);\n FixLongArrays(longArrayItems, multiRefs);\n\n xmlDocument.Save(writer);\n newStream.Position = 0;\n break;\n }\n }\n\n private static void FindImportantNodes(XmlElement element, List<XmlElement> longArrayItems,\n Dictionary<string, XmlElement> multiRefs)\n {\n string val = element.GetAttribute(\"soapenc:arrayType\");\n if (val != null && val.Contains(\":long[\"))\n {\n longArrayItems.Add(element);\n }\n if (element.Name == \"multiRef\")\n {\n multiRefs[element.GetAttribute(\"id\")] = element;\n }\n foreach (XmlNode node in element.ChildNodes)\n {\n XmlElement child = node as XmlElement;\n if (child != null)\n {\n FindImportantNodes(child, longArrayItems, multiRefs);\n }\n }\n }\n\n private static void FixLongArrays(List<XmlElement> longArrayItems, Dictionary<string, XmlElement> multiRefs)\n {\n foreach (XmlElement element in longArrayItems)\n {\n foreach (XmlNode node in element.ChildNodes)\n {\n XmlElement child = node as XmlElement;\n if (child != null)\n {\n string href = child.GetAttribute(\"href\");\n if (href == null || href.Length == 0)\n {\n continue;\n }\n if (href.StartsWith(\"#\"))\n {\n href = href.Remove(0, 1);\n }\n XmlElement multiRef = multiRefs[href];\n if (multiRef == null)\n {\n continue;\n }\n child.RemoveAttribute(\"href\");\n child.InnerXml = multiRef.InnerXml;\n if (log.IsDebugEnabled)\n {\n log.Debug(\"Replaced multiRef id '\" + href + \"' with value: \" + multiRef.InnerXml);\n }\n }\n }\n }\n }\n\n public override Stream ChainStream(Stream s)\n {\n originalStream = s;\n newStream = new MemoryStream();\n return newStream;\n }\n\n private static void CopyStream(Stream from, Stream to)\n {\n TextReader reader = new StreamReader(from);\n TextWriter writer = new StreamWriter(to);\n writer.WriteLine(reader.ReadToEnd());\n writer.Flush();\n }\n}\n [SoapRpcMethod(\"\", RequestNamespace=\"http://some.service.provider\",\n ResponseNamespace=\"http://some.service.provider\")]\n [return : SoapElement(\"getFooReturn\")]\n [LongArrayHelper]\n public Foo getFoo()\n {\n object[] results = Invoke(\"getFoo\", new object[0]);\n return ((Foo) (results[0]));\n }\n"
},
{
"answer_id": 650260,
"author": "Tomer Gabel",
"author_id": 11558,
"author_profile": "https://Stackoverflow.com/users/11558",
"pm_score": 2,
"selected": false,
"text": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<soapenv:Envelope xmlns:soapenv=http://schemas.xmlsoap.org/soap/envelope/>\n <soapenv:Body>\n <doSomethingResponse>\n <doSomethingReturn>\n <doSomethingReturn href=\"#id0\"/>\n <doSomethingReturn href=\"#id1\"/>\n <doSomethingReturn href=\"#id2\"/>\n <doSomethingReturn href=\"#id3\"/>\n <doSomethingReturn href=\"#id4\"/>\n </doSomethingReturn>\n </doSomethingResponse>\n <multiRef id=\"id4\">5</multiRef>\n <multiRef id=\"id3\">4</multiRef>\n <multiRef id=\"id2\">3</multiRef>\n <multiRef id=\"id1\">2</multiRef>\n <multiRef id=\"id0\">1</multiRef>\n </soapenv:Body>\n</soapenv:Envelope>\n <parameter name=\"sendMultiRefs\" value=\"true\"/>\n java -cp %AXISCLASSPATH% org.apache.axis.client.AdminClient server-config.wsdl \n"
}
] |
2008/08/27
|
[
"https://Stackoverflow.com/questions/30171",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/96/"
] |
30,184 |
<p>I am creating a small modal form that is used in Winforms application. It is basically a progress bar of sorts. But I would like the user to be able to click anywhere in the form and drag it to move it around on the desktop while it is still being displayed.</p>
<p>How can I implement this behavior?</p>
|
[
{
"answer_id": 30241,
"author": "Timothy Fries",
"author_id": 3163,
"author_profile": "https://Stackoverflow.com/users/3163",
"pm_score": 6,
"selected": true,
"text": "private const int WM_NCHITTEST = 0x84;\nprivate const int HTCLIENT = 0x1;\nprivate const int HTCAPTION = 0x2;\n\nprotected override void WndProc(ref Message m)\n{\n switch(m.Msg)\n {\n case WM_NCHITTEST:\n base.WndProc(ref m);\n\n if ((int)m.Result == HTCLIENT)\n m.Result = (IntPtr)HTCAPTION;\n return;\n }\n\n base.WndProc(ref m);\n}\n"
},
{
"answer_id": 30245,
"author": "aku",
"author_id": 1196,
"author_profile": "https://Stackoverflow.com/users/1196",
"pm_score": 3,
"selected": false,
"text": "public partial class ProgressBarForm : Form\n{\n private bool mouseDown;\n private Point lastPos;\n\n public ProgressBarForm()\n {\n InitializeComponent();\n }\n\n private void progressBar1_MouseMove(object sender, MouseEventArgs e)\n {\n if (mouseDown)\n {\n int xoffset = MousePosition.X - lastPos.X;\n int yoffset = MousePosition.Y - lastPos.Y;\n Left += xoffset;\n Top += yoffset;\n lastPos = MousePosition;\n }\n }\n\n private void progressBar1_MouseDown(object sender, MouseEventArgs e)\n {\n mouseDown = true;\n lastPos = MousePosition;\n }\n\n private void progressBar1_MouseUp(object sender, MouseEventArgs e)\n {\n mouseDown = false;\n }\n}\n"
},
{
"answer_id": 30278,
"author": "FlySwat",
"author_id": 1965,
"author_profile": "https://Stackoverflow.com/users/1965",
"pm_score": 4,
"selected": false,
"text": "public const int WM_NCLBUTTONDOWN = 0xA1;\npublic const int HTCAPTION = 0x2;\n[DllImport(\"User32.dll\")]\npublic static extern bool ReleaseCapture();\n[DllImport(\"User32.dll\")]\npublic static extern int SendMessage(IntPtr hWnd, int Msg, int wParam, int lParam);\n\nvoid Form_Load(object sender, EventArgs e)\n{\n this.MouseDown += new MouseEventHandler(Form_MouseDown); \n}\n\nvoid Form_MouseDown(object sender, MouseEventArgs e)\n{ \n if (e.Button == MouseButtons.Left)\n {\n ReleaseCapture();\n SendMessage(Handle, WM_NCLBUTTONDOWN, HTCAPTION, 0);\n }\n}\n"
},
{
"answer_id": 21486168,
"author": "Simon Mourier",
"author_id": 403671,
"author_profile": "https://Stackoverflow.com/users/403671",
"pm_score": 2,
"selected": false,
"text": " private class MyTableLayoutPanel : Panel // or TableLayoutPanel, etc.\n {\n private Point _mouseDown;\n private Point _formLocation;\n private bool _capture;\n\n // NOTE: we cannot use the WM_NCHITTEST / HTCAPTION trick because the table is in control, not the owning form...\n protected override void OnMouseDown(MouseEventArgs e)\n {\n _capture = true;\n _mouseDown = e.Location;\n _formLocation = ((Form)TopLevelControl).Location;\n }\n\n protected override void OnMouseUp(MouseEventArgs e)\n {\n _capture = false;\n }\n\n protected override void OnMouseMove(MouseEventArgs e)\n {\n if (_capture)\n {\n int dx = e.Location.X - _mouseDown.X;\n int dy = e.Location.Y - _mouseDown.Y;\n Point newLocation = new Point(_formLocation.X + dx, _formLocation.Y + dy);\n ((Form)TopLevelControl).Location = newLocation;\n _formLocation = newLocation;\n }\n }\n }\n"
},
{
"answer_id": 34101694,
"author": "Wyllow Wulf",
"author_id": 5310022,
"author_profile": "https://Stackoverflow.com/users/5310022",
"pm_score": 0,
"selected": false,
"text": "#include <Windows.h>\n\nnamespace DragWithoutTitleBar {\n\n using namespace System;\n using namespace System::Windows::Forms;\n using namespace System::ComponentModel;\n using namespace System::Collections;\n using namespace System::Data;\n using namespace System::Drawing;\n\n public ref class Form1 : public System::Windows::Forms::Form\n {\n public:\n Form1(void) { InitializeComponent(); }\n\n protected:\n ~Form1() { if (components) { delete components; } }\n\n private:\n System::ComponentModel::Container ^components;\n HWND hWnd;\n\n#pragma region Windows Form Designer generated code\n void InitializeComponent(void)\n {\n this->SuspendLayout();\n this->AutoScaleDimensions = System::Drawing::SizeF(6, 13);\n this->AutoScaleMode = System::Windows::Forms::AutoScaleMode::Font;\n this->ClientSize = System::Drawing::Size(640, 480);\n this->FormBorderStyle = System::Windows::Forms::FormBorderStyle::None;\n this->Name = L\"Form1\";\n this->Text = L\"Form1\";\n this->Load += gcnew EventHandler(this, &Form1::Form1_Load);\n this->MouseDown += gcnew System::Windows::Forms::MouseEventHandler(this, &Form1::Form1_MouseDown);\n this->ResumeLayout(false);\n\n }\n#pragma endregion\n private: System::Void Form1_Load(Object^ sender, EventArgs^ e) {\n hWnd = static_cast<HWND>(Handle.ToPointer());\n }\n\n private: System::Void Form1_MouseDown(Object^ sender, System::Windows::Forms::MouseEventArgs^ e) {\n if (e->Button == System::Windows::Forms::MouseButtons::Left) {\n ::ReleaseCapture();\n ::SendMessage(hWnd, /*WM_NCLBUTTONDOWN*/ 0xA1, /*HT_CAPTION*/ 0x2, 0);\n }\n }\n\n };\n}\n"
}
] |
2008/08/27
|
[
"https://Stackoverflow.com/questions/30184",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/507/"
] |
30,188 |
<p>I am trying to set a <code>javascript</code> <code>date</code> so that it can be submitted via <code>JSON</code> to a <code>.NET</code> type, but when attempting to do this, <code>jQuery</code> sets the <code>date</code> to a full <code>string</code>, what format does it have to be in to be converted to a <code>.NET</code> type?</p>
<pre><code>var regDate = student.RegistrationDate.getMonth() + "/" + student.RegistrationDate.getDate() + "/" + student.RegistrationDate.getFullYear();
j("#student_registrationdate").val(regDate); // value to serialize
</code></pre>
<p>I am using <code>MonoRail</code> on the server to perform the binding to a <code>.NET</code> type, that aside I need to know what to set the form hidden field value to, to get properly sent to <code>.NET</code> code.</p>
|
[
{
"answer_id": 30241,
"author": "Timothy Fries",
"author_id": 3163,
"author_profile": "https://Stackoverflow.com/users/3163",
"pm_score": 6,
"selected": true,
"text": "private const int WM_NCHITTEST = 0x84;\nprivate const int HTCLIENT = 0x1;\nprivate const int HTCAPTION = 0x2;\n\nprotected override void WndProc(ref Message m)\n{\n switch(m.Msg)\n {\n case WM_NCHITTEST:\n base.WndProc(ref m);\n\n if ((int)m.Result == HTCLIENT)\n m.Result = (IntPtr)HTCAPTION;\n return;\n }\n\n base.WndProc(ref m);\n}\n"
},
{
"answer_id": 30245,
"author": "aku",
"author_id": 1196,
"author_profile": "https://Stackoverflow.com/users/1196",
"pm_score": 3,
"selected": false,
"text": "public partial class ProgressBarForm : Form\n{\n private bool mouseDown;\n private Point lastPos;\n\n public ProgressBarForm()\n {\n InitializeComponent();\n }\n\n private void progressBar1_MouseMove(object sender, MouseEventArgs e)\n {\n if (mouseDown)\n {\n int xoffset = MousePosition.X - lastPos.X;\n int yoffset = MousePosition.Y - lastPos.Y;\n Left += xoffset;\n Top += yoffset;\n lastPos = MousePosition;\n }\n }\n\n private void progressBar1_MouseDown(object sender, MouseEventArgs e)\n {\n mouseDown = true;\n lastPos = MousePosition;\n }\n\n private void progressBar1_MouseUp(object sender, MouseEventArgs e)\n {\n mouseDown = false;\n }\n}\n"
},
{
"answer_id": 30278,
"author": "FlySwat",
"author_id": 1965,
"author_profile": "https://Stackoverflow.com/users/1965",
"pm_score": 4,
"selected": false,
"text": "public const int WM_NCLBUTTONDOWN = 0xA1;\npublic const int HTCAPTION = 0x2;\n[DllImport(\"User32.dll\")]\npublic static extern bool ReleaseCapture();\n[DllImport(\"User32.dll\")]\npublic static extern int SendMessage(IntPtr hWnd, int Msg, int wParam, int lParam);\n\nvoid Form_Load(object sender, EventArgs e)\n{\n this.MouseDown += new MouseEventHandler(Form_MouseDown); \n}\n\nvoid Form_MouseDown(object sender, MouseEventArgs e)\n{ \n if (e.Button == MouseButtons.Left)\n {\n ReleaseCapture();\n SendMessage(Handle, WM_NCLBUTTONDOWN, HTCAPTION, 0);\n }\n}\n"
},
{
"answer_id": 21486168,
"author": "Simon Mourier",
"author_id": 403671,
"author_profile": "https://Stackoverflow.com/users/403671",
"pm_score": 2,
"selected": false,
"text": " private class MyTableLayoutPanel : Panel // or TableLayoutPanel, etc.\n {\n private Point _mouseDown;\n private Point _formLocation;\n private bool _capture;\n\n // NOTE: we cannot use the WM_NCHITTEST / HTCAPTION trick because the table is in control, not the owning form...\n protected override void OnMouseDown(MouseEventArgs e)\n {\n _capture = true;\n _mouseDown = e.Location;\n _formLocation = ((Form)TopLevelControl).Location;\n }\n\n protected override void OnMouseUp(MouseEventArgs e)\n {\n _capture = false;\n }\n\n protected override void OnMouseMove(MouseEventArgs e)\n {\n if (_capture)\n {\n int dx = e.Location.X - _mouseDown.X;\n int dy = e.Location.Y - _mouseDown.Y;\n Point newLocation = new Point(_formLocation.X + dx, _formLocation.Y + dy);\n ((Form)TopLevelControl).Location = newLocation;\n _formLocation = newLocation;\n }\n }\n }\n"
},
{
"answer_id": 34101694,
"author": "Wyllow Wulf",
"author_id": 5310022,
"author_profile": "https://Stackoverflow.com/users/5310022",
"pm_score": 0,
"selected": false,
"text": "#include <Windows.h>\n\nnamespace DragWithoutTitleBar {\n\n using namespace System;\n using namespace System::Windows::Forms;\n using namespace System::ComponentModel;\n using namespace System::Collections;\n using namespace System::Data;\n using namespace System::Drawing;\n\n public ref class Form1 : public System::Windows::Forms::Form\n {\n public:\n Form1(void) { InitializeComponent(); }\n\n protected:\n ~Form1() { if (components) { delete components; } }\n\n private:\n System::ComponentModel::Container ^components;\n HWND hWnd;\n\n#pragma region Windows Form Designer generated code\n void InitializeComponent(void)\n {\n this->SuspendLayout();\n this->AutoScaleDimensions = System::Drawing::SizeF(6, 13);\n this->AutoScaleMode = System::Windows::Forms::AutoScaleMode::Font;\n this->ClientSize = System::Drawing::Size(640, 480);\n this->FormBorderStyle = System::Windows::Forms::FormBorderStyle::None;\n this->Name = L\"Form1\";\n this->Text = L\"Form1\";\n this->Load += gcnew EventHandler(this, &Form1::Form1_Load);\n this->MouseDown += gcnew System::Windows::Forms::MouseEventHandler(this, &Form1::Form1_MouseDown);\n this->ResumeLayout(false);\n\n }\n#pragma endregion\n private: System::Void Form1_Load(Object^ sender, EventArgs^ e) {\n hWnd = static_cast<HWND>(Handle.ToPointer());\n }\n\n private: System::Void Form1_MouseDown(Object^ sender, System::Windows::Forms::MouseEventArgs^ e) {\n if (e->Button == System::Windows::Forms::MouseButtons::Left) {\n ::ReleaseCapture();\n ::SendMessage(hWnd, /*WM_NCLBUTTONDOWN*/ 0xA1, /*HT_CAPTION*/ 0x2, 0);\n }\n }\n\n };\n}\n"
}
] |
2008/08/27
|
[
"https://Stackoverflow.com/questions/30188",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2993/"
] |
30,211 |
<p>Is the ZIP compression that is built into Windows XP/Vista/2003/2008 able to be scripted at all? What executable would I have to call from a BAT/CMD file? or is it possible to do it with VBScript?</p>
<p>I realize that this is possible using <a href="http://en.wikipedia.org/wiki/WinZip" rel="noreferrer">WinZip</a>, <a href="http://en.wikipedia.org/wiki/7-Zip" rel="noreferrer">7-Zip</a> and other external applications, but I'm looking for something that requires no external applications to be installed.</p>
|
[
{
"answer_id": 30473,
"author": "Adam Davis",
"author_id": 2915,
"author_profile": "https://Stackoverflow.com/users/2915",
"pm_score": 6,
"selected": true,
"text": ".zip Sub NewZip(sPath)\n'Create empty Zip File\n'Changed by keepITcool Dec-12-2005\n If Len(Dir(sPath)) > 0 Then Kill sPath\n Open sPath For Output As #1\n Print #1, Chr$(80) & Chr$(75) & Chr$(5) & Chr$(6) & String(18, 0)\n Close #1\nEnd Sub\n\n\nFunction bIsBookOpen(ByRef szBookName As String) As Boolean\n' Rob Bovey\n On Error Resume Next\n bIsBookOpen = Not (Application.Workbooks(szBookName) Is Nothing)\nEnd Function\n\n\nFunction Split97(sStr As Variant, sdelim As String) As Variant\n'Tom Ogilvy\n Split97 = Evaluate(\"{\"\"\" & _\n Application.Substitute(sStr, sdelim, \"\"\",\"\"\") & \"\"\"}\")\nEnd Function\n\nSub Zip_File_Or_Files()\n Dim strDate As String, DefPath As String, sFName As String\n Dim oApp As Object, iCtr As Long, I As Integer\n Dim FName, vArr, FileNameZip\n\n DefPath = Application.DefaultFilePath\n If Right(DefPath, 1) <> \"\\\" Then\n DefPath = DefPath & \"\\\"\n End If\n\n strDate = Format(Now, \" dd-mmm-yy h-mm-ss\")\n FileNameZip = DefPath & \"MyFilesZip \" & strDate & \".zip\"\n\n 'Browse to the file(s), use the Ctrl key to select more files\n FName = Application.GetOpenFilename(filefilter:=\"Excel Files (*.xl*), *.xl*\", _\n MultiSelect:=True, Title:=\"Select the files you want to zip\")\n If IsArray(FName) = False Then\n 'do nothing\n Else\n 'Create empty Zip File\n NewZip (FileNameZip)\n Set oApp = CreateObject(\"Shell.Application\")\n I = 0\n For iCtr = LBound(FName) To UBound(FName)\n vArr = Split97(FName(iCtr), \"\\\")\n sFName = vArr(UBound(vArr))\n If bIsBookOpen(sFName) Then\n MsgBox \"You can't zip a file that is open!\" & vbLf & _\n \"Please close it and try again: \" & FName(iCtr)\n Else\n 'Copy the file to the compressed folder\n I = I + 1\n oApp.Namespace(FileNameZip).CopyHere FName(iCtr)\n\n 'Keep script waiting until Compressing is done\n On Error Resume Next\n Do Until oApp.Namespace(FileNameZip).items.Count = I\n Application.Wait (Now + TimeValue(\"0:00:01\"))\n Loop\n On Error GoTo 0\n End If\n Next iCtr\n\n MsgBox \"You find the zipfile here: \" & FileNameZip\n End If\nEnd Sub\n Sub Unzip1()\n Dim FSO As Object\n Dim oApp As Object\n Dim Fname As Variant\n Dim FileNameFolder As Variant\n Dim DefPath As String\n Dim strDate As String\n\n Fname = Application.GetOpenFilename(filefilter:=\"Zip Files (*.zip), *.zip\", _\n MultiSelect:=False)\n If Fname = False Then\n 'Do nothing\n Else\n 'Root folder for the new folder.\n 'You can also use DefPath = \"C:\\Users\\Ron\\test\\\"\n DefPath = Application.DefaultFilePath\n If Right(DefPath, 1) <> \"\\\" Then\n DefPath = DefPath & \"\\\"\n End If\n\n 'Create the folder name\n strDate = Format(Now, \" dd-mm-yy h-mm-ss\")\n FileNameFolder = DefPath & \"MyUnzipFolder \" & strDate & \"\\\"\n\n 'Make the normal folder in DefPath\n MkDir FileNameFolder\n\n 'Extract the files into the newly created folder\n Set oApp = CreateObject(\"Shell.Application\")\n\n oApp.Namespace(FileNameFolder).CopyHere oApp.Namespace(Fname).items\n\n 'If you want to extract only one file you can use this:\n 'oApp.Namespace(FileNameFolder).CopyHere _\n 'oApp.Namespace(Fname).items.Item(\"test.txt\")\n\n MsgBox \"You find the files here: \" & FileNameFolder\n\n On Error Resume Next\n Set FSO = CreateObject(\"scripting.filesystemobject\")\n FSO.deletefolder Environ(\"Temp\") & \"\\Temporary Directory*\", True\n End If\nEnd Sub\n"
},
{
"answer_id": 124775,
"author": "Jay",
"author_id": 20840,
"author_profile": "https://Stackoverflow.com/users/20840",
"pm_score": 5,
"selected": false,
"text": "Dim fso, winShell, MyTarget, MySource, file\nSet fso = CreateObject(\"Scripting.FileSystemObject\")\nSet winShell = createObject(\"shell.application\")\n\n\nMyTarget = Wscript.Arguments.Item(0)\nMySource = Wscript.Arguments.Item(1)\n\nWscript.Echo \"Adding \" & MySource & \" to \" & MyTarget\n\n'create a new clean zip archive\nSet file = fso.CreateTextFile(MyTarget, True)\nfile.write(\"PK\" & chr(5) & chr(6) & string(18,chr(0)))\nfile.close\n\nwinShell.NameSpace(MyTarget).CopyHere winShell.NameSpace(MySource).Items\n\ndo until winShell.namespace(MyTarget).items.count = winShell.namespace(MySource).items.count\n wscript.sleep 1000 \nloop\n\nSet winShell = Nothing\nSet fso = Nothing\n set fso=createobject(\"scripting.filesystemobject\")\nSet h=fso.getFile(DestZip)\ndo\n wscript.sleep 500\n max = h.size\nloop while h.size > max \n"
},
{
"answer_id": 410470,
"author": "Cheeso",
"author_id": 48082,
"author_profile": "https://Stackoverflow.com/users/48082",
"pm_score": 3,
"selected": false,
"text": "dim filename \nfilename = \"C:\\temp\\ZipFile-created-from-VBScript.zip\"\n\nWScript.echo(\"Instantiating a ZipFile object...\")\ndim zip \nset zip = CreateObject(\"Ionic.Zip.ZipFile\")\n\nWScript.echo(\"using AES256 encryption...\")\nzip.Encryption = 3\n\nWScript.echo(\"setting the password...\")\nzip.Password = \"Very.Secret.Password!\"\n\nWScript.echo(\"adding a selection of files...\")\nzip.AddSelectedFiles(\"*.js\")\nzip.AddSelectedFiles(\"*.vbs\")\n\nWScript.echo(\"setting the save name...\")\nzip.Name = filename\n\nWScript.echo(\"Saving...\")\nzip.Save()\n\nWScript.echo(\"Disposing...\")\nzip.Dispose()\n\nWScript.echo(\"Done.\")\n [System.Reflection.Assembly]::LoadFrom(\"c:\\\\dinoch\\\\bin\\\\Ionic.Zip.dll\");\n\n$directoryToZip = \"c:\\\\temp\";\n$zipfile = new-object Ionic.Zip.ZipFile;\n$e= $zipfile.AddEntry(\"Readme.txt\", \"This is a zipfile created from within powershell.\")\n$e= $zipfile.AddDirectory($directoryToZip, \"home\")\n$zipfile.Save(\"ZipFiles.ps1.out.zip\");\n zipit NewZip.zip -s \"This is string content for an entry\" Readme.txt src \n"
}
] |
2008/08/27
|
[
"https://Stackoverflow.com/questions/30211",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1414/"
] |
30,222 |
<p>I am writing a query in which I have to get the data for only the last year. What is the best way to do this?</p>
<pre><code>SELECT ... FROM ... WHERE date > '8/27/2007 12:00:00 AM'
</code></pre>
|
[
{
"answer_id": 30229,
"author": "samjudson",
"author_id": 1908,
"author_profile": "https://Stackoverflow.com/users/1908",
"pm_score": 9,
"selected": true,
"text": "SELECT ... From ... WHERE date > DATEADD(year,-1,GETDATE())\n"
},
{
"answer_id": 30232,
"author": "SQLMenace",
"author_id": 740,
"author_profile": "https://Stackoverflow.com/users/740",
"pm_score": 3,
"selected": false,
"text": "dateadd(yy,-1,getdate())\n"
},
{
"answer_id": 30252,
"author": "Grzegorz Gierlik",
"author_id": 1483,
"author_profile": "https://Stackoverflow.com/users/1483",
"pm_score": 2,
"selected": false,
"text": "GETDATE() DECLARE @start datetime\nSET @start = dbo.getdatewithouttime(DATEADD(year, -1, GETDATE())) -- cut time (hours, minutes, ect.) -- getdatewithouttime() function doesn't exist in MS SQL -- you have to write one\nSELECT column1, column2, ..., columnN FROM table WHERE date >= @start\n"
},
{
"answer_id": 30268,
"author": "Ivan Bosnic",
"author_id": 3221,
"author_profile": "https://Stackoverflow.com/users/3221",
"pm_score": 3,
"selected": false,
"text": "SELECT ... FROM ... WHERE YEAR(DATE) = YEAR(GETDATE()) - 1\n SELECT ... FROM ... WHERE YEAR(DATE) = YEAR(GETDATE()) - 1 AND DATE > '05/05/2007'\n"
},
{
"answer_id": 30273,
"author": "Mark Brackett",
"author_id": 2199,
"author_profile": "https://Stackoverflow.com/users/2199",
"pm_score": 3,
"selected": false,
"text": "SELECT * FROM TABLE WHERE Date >\n DATEADD(yy, -1, CONVERT(datetime, CONVERT(varchar, GETDATE(), 101)))\n"
},
{
"answer_id": 7501550,
"author": "imtheref",
"author_id": 949377,
"author_profile": "https://Stackoverflow.com/users/949377",
"pm_score": 0,
"selected": false,
"text": "DATEADD (*datepart* , *number* , *date* )\n"
},
{
"answer_id": 10657540,
"author": "Tony",
"author_id": 1404012,
"author_profile": "https://Stackoverflow.com/users/1404012",
"pm_score": 0,
"selected": false,
"text": "declare @iMonth int\ndeclare @sYear varchar(4)\ndeclare @sMonth varchar(2)\nset @iMonth = 0\nwhile @iMonth > -12\nbegin\n set @sYear = year(DATEADD(month,@iMonth,GETDATE()))\n set @sMonth = right('0'+cast(month(DATEADD(month,@iMonth,GETDATE())) as varchar(2)),2)\n select @sYear + @sMonth\n set @iMonth = @iMonth - 1\nend\n"
},
{
"answer_id": 16090603,
"author": "D.E. White",
"author_id": 2296481,
"author_profile": "https://Stackoverflow.com/users/2296481",
"pm_score": 4,
"selected": false,
"text": "SELECT .... FROM .... WHERE year(*your date column*) = year(DATEADD(year,-1,getdate()))\n"
},
{
"answer_id": 42305356,
"author": "kevinaskevin",
"author_id": 1877580,
"author_profile": "https://Stackoverflow.com/users/1877580",
"pm_score": 1,
"selected": false,
"text": "SELECT .... FROM .... WHERE year(date) > year(DATEADD(year, -2, GETDATE()))"
},
{
"answer_id": 47314098,
"author": "Rick Savoy",
"author_id": 2093345,
"author_profile": "https://Stackoverflow.com/users/2093345",
"pm_score": 0,
"selected": false,
"text": "SELECT ... FROM ....WHERE \nCONVERT(datetime,REPLACE(LEFT(LTRIM([MoYr]),2),'-\n','')+'/01/'+RIGHT(RTRIM([MoYr]),4)) >= DATEADD(year,-1,GETDATE())\n"
},
{
"answer_id": 59638416,
"author": "Connor",
"author_id": 9984657,
"author_profile": "https://Stackoverflow.com/users/9984657",
"pm_score": 1,
"selected": false,
"text": " SELECT ... From ... WHERE date BETWEEN CURDATE() - INTERVAL 1 YEAR AND CURDATE()\n"
},
{
"answer_id": 72329692,
"author": "lloydyu24",
"author_id": 7342548,
"author_profile": "https://Stackoverflow.com/users/7342548",
"pm_score": 0,
"selected": false,
"text": "YEAR(NOW())- 1\n YEAR(c.contractDate) = YEAR(NOW())- 1\n"
}
] |
2008/08/27
|
[
"https://Stackoverflow.com/questions/30222",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2486/"
] |
30,230 |
<p>I have some C# / asp.net code I inherited which has a textbox which I want to make multiline. I did so by adding textmode="multiline" but when I try to insert a newline, the enter key instead submits the form :P</p>
<p>I googled around and it seems like the default behavior should be for enter (or control-enter) to insert a newline. Like I said I inherited the code so I'm not sure if there's javascript monkeying around or if there's just a simple asp.net thing I have to do.</p>
|
[
{
"answer_id": 30261,
"author": "samjudson",
"author_id": 1908,
"author_profile": "https://Stackoverflow.com/users/1908",
"pm_score": 1,
"selected": false,
"text": "<asp:TextBox runat=\"server\" ID=\"textbox1\" TextMode=\"MultiLine\" />\n<br />\n<br />\n<asp:Button runat=\"server\" ID=\"button1\" Text=\"Button 1\" onclick=\"button1_Click\" />\n"
},
{
"answer_id": 30372,
"author": "Dave Ward",
"author_id": 60,
"author_profile": "https://Stackoverflow.com/users/60",
"pm_score": 1,
"selected": false,
"text": "function WebForm_FireDefaultButton(event, target) {\n if (event.keyCode == 13) {\n var src = event.srcElement || event.target;\n if (!src || (src.tagName.toLowerCase() != \"textarea\")) {\n var defaultButton;\n if (__nonMSDOMBrowser) {\n defaultButton = document.getElementById(target);\n }\n else {\n defaultButton = document.all[target];\n }\n if (defaultButton && typeof (defaultButton.click) != \"undefined\") {\n defaultButton.click();\n event.cancelBubble = true;\n if (event.stopPropagation) event.stopPropagation();\n return false;\n }\n }\n }\n return true;\n}\n"
},
{
"answer_id": 30826,
"author": "adambox",
"author_id": 2462,
"author_profile": "https://Stackoverflow.com/users/2462",
"pm_score": 0,
"selected": false,
"text": "<form name=\"Form1\" method=\"post\" action=\"default.aspx\" onsubmit=\"javascript:return WebForm_OnSubmit();\" id=\"Form1\">\n\n<script type=\"text/javascript\">\n//<![CDATA[\nvar theForm = document.forms['Form1'];\nif (!theForm) {\n theForm = document.Form1;\n}\nfunction __doPostBack(eventTarget, eventArgument) {\n if (!theForm.onsubmit || (theForm.onsubmit() != false)) {\n theForm.__EVENTTARGET.value = eventTarget;\n theForm.__EVENTARGUMENT.value = eventArgument;\n theForm.submit();\n }\n}\n//]]>\n</script>\n"
},
{
"answer_id": 32358,
"author": "adambox",
"author_id": 2462,
"author_profile": "https://Stackoverflow.com/users/2462",
"pm_score": 3,
"selected": true,
"text": "function WebForm_FireDefaultButton(event, target) {\n var element = event.target || event.srcElement;\n if (event.keyCode == 13 &&\n !(element &&\n element.tagName.toLowerCase() == \"textarea\"))\n {\n var defaultButton;\n if (__nonMSDOMBrowser)\n {\n defaultButton = document.getElementById(target);\n }\n else\n {\n defaultButton = document.all[target];\n }\n if (defaultButton && typeof defaultButton.click != \"undefined\")\n {\n defaultButton.click();\n event.cancelBubble = true;\n if (event.stopPropagation)\n {\n event.stopPropagation();\n }\n return false;\n }\n }\n return true;\n}\n"
}
] |
2008/08/27
|
[
"https://Stackoverflow.com/questions/30230",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2462/"
] |
30,239 |
<p>I have an images folder with a png in it. I would like to set a MenuItem's icon to that png. How do I write this in procedural code?</p>
|
[
{
"answer_id": 30285,
"author": "Timothy Fries",
"author_id": 3163,
"author_profile": "https://Stackoverflow.com/users/3163",
"pm_score": 7,
"selected": true,
"text": "menutItem.Icon = new System.Windows.Controls.Image \n { \n Source = new BitmapImage(new Uri(\"images/sample.png\", UriKind.Relative)) \n };\n"
},
{
"answer_id": 30287,
"author": "Arcturus",
"author_id": 900,
"author_profile": "https://Stackoverflow.com/users/900",
"pm_score": 5,
"selected": false,
"text": "<MenuItem>\n <MenuItem.Icon>\n <Image>\n <Image.Source>\n <BitmapImage UriSource=\"/your_assembly;component/your_path_here/Image.png\" />\n </Image.Source>\n </Image>\n </MenuItem.Icon>\n</MenuItem>\n"
},
{
"answer_id": 882961,
"author": "awe",
"author_id": 109392,
"author_profile": "https://Stackoverflow.com/users/109392",
"pm_score": 1,
"selected": false,
"text": "MenuItem item = new MenuItem();\nstring imagePath = \"D:\\\\Images\\\\Icon.png\");\nImage icon = new Image();\nicon.Source= new BitmapImage(new Uri(imagePath, UriKind.Absolute));\nitem.Icon = icon;\n"
},
{
"answer_id": 1504419,
"author": "IanR",
"author_id": 76116,
"author_profile": "https://Stackoverflow.com/users/76116",
"pm_score": 4,
"selected": false,
"text": "menutItem.Icon = new Image\n {\n Source = new BitmapImage(new Uri(\"pack://application:,,,/your_assembly;component/yourpath/Image.png\"))\n }\n"
},
{
"answer_id": 14787183,
"author": "Python Kid",
"author_id": 1451994,
"author_profile": "https://Stackoverflow.com/users/1451994",
"pm_score": 0,
"selected": false,
"text": "menuItem.Icon = New Image() With {.Source = New BitmapImage(New Uri(\"pack://application:,,,/your_assembly;component/yourpath/Image.png\"))}"
},
{
"answer_id": 17301152,
"author": "Basti Endres",
"author_id": 2502838,
"author_profile": "https://Stackoverflow.com/users/2502838",
"pm_score": 2,
"selected": false,
"text": "<MenuItem Header=\"Example\">\n <MenuItem.Icon>\n <Image Source=\"pack://siteoforigin:,,,/Resources/Example.png\"/>\n </MenuItem.Icon>\n</MenuItem>\n"
},
{
"answer_id": 19121780,
"author": "Gary95054",
"author_id": 1807138,
"author_profile": "https://Stackoverflow.com/users/1807138",
"pm_score": 1,
"selected": false,
"text": "<MenuItem Header=\"delete ctrl-d\" Click=\"cmiDelete_Click\">\n <MenuItem.Icon>\n <Image>\n <Image.Source>\n <ImageSource>Resources/Images/delete.png</ImageSource>\n </Image.Source>\n </Image>\n </MenuItem.Icon>\n</MenuItem>\n"
}
] |
2008/08/27
|
[
"https://Stackoverflow.com/questions/30239",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3047/"
] |
30,251 |
<blockquote>
<p><strong>Possible Duplicate:</strong><br>
<a href="https://stackoverflow.com/questions/83073/why-not-use-tables-for-layout-in-html">Why not use tables for layout in HTML?</a> </p>
</blockquote>
<p>Under what conditions should you choose tables instead of DIVs in HTML coding?</p>
|
[
{
"answer_id": 30264,
"author": "Peter Stuifzand",
"author_id": 1633,
"author_profile": "https://Stackoverflow.com/users/1633",
"pm_score": 1,
"selected": false,
"text": "div"
},
{
"answer_id": 30595,
"author": "Sören Kuklau",
"author_id": 1600,
"author_profile": "https://Stackoverflow.com/users/1600",
"pm_score": 2,
"selected": false,
"text": "<table> <table> <table> <div> <span>"
},
{
"answer_id": 46289,
"author": "Ben Scheirman",
"author_id": 3381,
"author_profile": "https://Stackoverflow.com/users/3381",
"pm_score": 3,
"selected": false,
"text": "<fieldset>\n <legend>New Blog Post</legend>\n\n <label for=\"title\">Title:</label>\n <input type=\"text\" name=\"title\" />\n\n <label for=\"body\">Body:</label>\n <textarea name=\"body\" rows=\"6\" cols=\"40\">\n </textarea>\n</fieldset>\n"
},
{
"answer_id": 46307,
"author": "Slartibartfast",
"author_id": 4433,
"author_profile": "https://Stackoverflow.com/users/4433",
"pm_score": 1,
"selected": false,
"text": "<dl>"
},
{
"answer_id": 67249,
"author": "JacquesB",
"author_id": 7488,
"author_profile": "https://Stackoverflow.com/users/7488",
"pm_score": 4,
"selected": false,
"text": "<table>"
},
{
"answer_id": 2801955,
"author": "Guy W",
"author_id": 337157,
"author_profile": "https://Stackoverflow.com/users/337157",
"pm_score": 0,
"selected": false,
"text": "divisions"
}
] |
2008/08/27
|
[
"https://Stackoverflow.com/questions/30251",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2141/"
] |
30,288 |
<p>Using CFML (ColdFusion Markup Langauge, aka ColdFusion), how can you compare if two single dimension arrays are the same?</p>
|
[
{
"answer_id": 30292,
"author": "Jason",
"author_id": 3242,
"author_profile": "https://Stackoverflow.com/users/3242",
"pm_score": 4,
"selected": false,
"text": "<cfset array1 = listToArray(\"tom,dick,harry,phred\")/>\n<cfset array2 = listToArray(\"dick,harry,phred\") />\n<cfset array3 = listToArray(\"tom,dick,harry,phred\")/>\n\n<cfoutput>\nArray2 equals Array1 #array2.equals(array1)# (returns a NO) <br/>\nArray3 equals Array1 #array3.equals(array1)# (returns a YES) <br/>\n</cfoutput>\n"
},
{
"answer_id": 50313,
"author": "Adam Tuttle",
"author_id": 751,
"author_profile": "https://Stackoverflow.com/users/751",
"pm_score": 2,
"selected": false,
"text": "<cfsilent>\n <!--- create some semi-complex test data --->\n <cfset data = StructNew() />\n <cfloop from=\"1\" to=\"50\" index=\"i\">\n <cfif variables.i mod 2 eq 0>\n <cfset variables.data[variables.i] = StructNew()/>\n <cfset tmp = variables.data[variables.i] />\n <cfloop from=\"1\" to=\"#variables.i#\" index=\"j\">\n <cfset variables.tmp[variables.j] = 1 - variables.j />\n </cfloop>\n <cfelseif variables.i mod 3 eq 0>\n <cfset variables.data[variables.i] = ArrayNew(1)/>\n <cfset tmp = variables.data[variables.i] />\n <cfloop from=\"1\" to=\"#variables.i#\" index=\"j\">\n <cfset variables.tmp[variables.j] = variables.j mod 6 />\n </cfloop>\n <cfset variables.data[variables.i] = variables.tmp />\n <cfelse>\n <cfset variables.data[variables.i] = variables.i />\n </cfif>\n </cfloop>\n</cfsilent>\n\n<cftimer label=\"JSON\" type=\"inline\">\n <cfset jsonData = serializeJson(variables.data) />\n <cfset jsonHash = hash(variables.jsonData) />\n <cfoutput>\n JSON: done.<br />\n len=#len(variables.jsonData)#<br/>\n hash=#variables.jsonHash#<br />\n </cfoutput>\n</cftimer>\n<br/><br/>\n<cftimer label=\"WDDX\" type=\"inline\">\n <cfwddx action=\"cfml2wddx\" input=\"#variables.data#\" output=\"wddx\" />\n <cfset wddxHash = hash(variables.wddx) />\n <cfoutput>\n WDDX: done.<br />\n len=#len(variables.wddx)#<br/>\n hash=#variables.wddxHash#<br />\n </cfoutput>\n</cftimer>\n JSON: done.\nlen=7460\nhash=5D0DC87FDF68ACA4F74F742528545B12\nJSON: 0ms\n\nWDDX: done.\nlen=33438\nhash=94D9B792546A4B1F2FAF9C04FE6A00E1\nWDDX: 47ms\n"
},
{
"answer_id": 130971,
"author": "ale",
"author_id": 21960,
"author_profile": "https://Stackoverflow.com/users/21960",
"pm_score": 3,
"selected": true,
"text": "<cfif arrayToList(arrayA) IS arrayToList(arrayB)>\n Arrays are equal!\n</cfif>\n"
}
] |
2008/08/27
|
[
"https://Stackoverflow.com/questions/30288",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3242/"
] |
30,302 |
<p>I'd like to ignore multiple wildcard routes. With asp.net mvc preview 4, they ship with:</p>
<pre><code>RouteTable.Routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
</code></pre>
<p>I'd also like to add something like:</p>
<pre><code>RouteTable.Routes.IgnoreRoute("Content/{*pathInfo}");
</code></pre>
<p>but that seems to break some of the helpers that generate urls in my program. Thoughts?</p>
|
[
{
"answer_id": 30551,
"author": "Haacked",
"author_id": 598,
"author_profile": "https://Stackoverflow.com/users/598",
"pm_score": 5,
"selected": true,
"text": "RouteTable.Routes.IgnoreRoute(\"{folder}/{*pathInfo}\", new {folder=\"content\"});\n"
}
] |
2008/08/27
|
[
"https://Stackoverflow.com/questions/30302",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3085/"
] |
30,307 |
<p>I'm doing some PHP stuff on an Ubuntu server.</p>
<p>The path I'm working in is <strong>/mnt/dev-windows-data/Staging/mbiek/test_list</strong> but the PHP call <code>getcwd()</code> is returning <strong>/mnt/dev-windows/Staging/mbiek/test_list</strong> (notice how it's dev-windows instead of dev-windows-data).</p>
<p>There aren't any symbolic links anywhere. </p>
<p>Are there any other causes for <code>getcwd()</code> returning a different path from a local <code>pwd</code> call?</p>
<p><strong><em>Edit</em></strong> </p>
<p>I figured it out. The <strong>DOCUMENT_ROOT</strong> in PHP is set to <strong>/mnt/dev-windows</strong> which throws everything off.</p>
|
[
{
"answer_id": 30313,
"author": "Ross",
"author_id": 2025,
"author_profile": "https://Stackoverflow.com/users/2025",
"pm_score": 2,
"selected": true,
"text": "<?php\n require_once('./includes/construct.php');\n //snip\n?>\n <?php\n //snip\n (!defined('DIR')) ? define('DIR', getcwd()) : NULL;\n\n require_once(DIR . '/includes/functions.php');\n //snip\n?>\n"
},
{
"answer_id": 30363,
"author": "Ross",
"author_id": 2025,
"author_profile": "https://Stackoverflow.com/users/2025",
"pm_score": 0,
"selected": false,
"text": "include_path"
}
] |
2008/08/27
|
[
"https://Stackoverflow.com/questions/30307",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/305/"
] |
30,310 |
<p>I'd like to have dashes separate words in my URLs. So instead of:</p>
<pre><code>/MyController/MyAction
</code></pre>
<p>I'd like:</p>
<pre><code>/My-Controller/My-Action
</code></pre>
<p>Is this possible?</p>
|
[
{
"answer_id": 540583,
"author": "ChadT",
"author_id": 23300,
"author_profile": "https://Stackoverflow.com/users/23300",
"pm_score": 8,
"selected": true,
"text": "[ActionName(\"My-Action\")]\npublic ActionResult MyAction() {\n return View();\n}\n public static void RegisterRoutes(RouteCollection routes)\n{\n routes.MapMvcAttributeRoutes();\n // routes.MapRoute...\n}\n [Route(\"My-Action\")]\n RoutePrefix [RoutePrefix(\"my-controller\")]\n RoutePrefix [RoutePrefix(\"clients/{clientId:int}\")]\npublic class ClientsController : Controller .....\n [Route(\"edit-client\")]\npublic ActionResult Edit(int clientId) // will match /clients/123/edit-client\n"
},
{
"answer_id": 2454016,
"author": "Andrew",
"author_id": 73228,
"author_profile": "https://Stackoverflow.com/users/73228",
"pm_score": 4,
"selected": false,
"text": "public class HyphenatedRouteHandler : MvcRouteHandler{\n protected override IHttpHandler GetHttpHandler(RequestContext requestContext)\n {\n requestContext.RouteData.Values[\"controller\"] = requestContext.RouteData.Values[\"controller\"].ToString().Replace(\"-\", \"_\");\n requestContext.RouteData.Values[\"action\"] = requestContext.RouteData.Values[\"action\"].ToString().Replace(\"-\", \"_\");\n return base.GetHttpHandler(requestContext);\n }\n }\n routes.Add(\n new Route(\"{controller}/{action}/{id}\", \n new RouteValueDictionary(\n new { controller = \"Default\", action = \"Index\", id = \"\" }),\n new HyphenatedRouteHandler())\n );\n"
},
{
"answer_id": 10488825,
"author": "Nexxas",
"author_id": 297656,
"author_profile": "https://Stackoverflow.com/users/297656",
"pm_score": 1,
"selected": false,
"text": "routes.MapRoute(\n \"TandC\", // Route controllerName\n \"CommonPath/{controller}/Terms-and-Conditions\", // URL with parameters\n new {\n controller = \"Home\",\n action = \"Terms_and_Conditions\"\n } // Parameter defaults\n);\n"
},
{
"answer_id": 13771284,
"author": "Cory Mawhorter",
"author_id": 670023,
"author_profile": "https://Stackoverflow.com/users/670023",
"pm_score": 0,
"selected": false,
"text": "<rewrite>\n <rules>\n <rule name=\"Dashes, damnit\">\n <match url=\"^my-controller(.*)\" />\n <action type=\"Rewrite\" url=\"MyController/Index{R:1}\" />\n </rule>\n </rules>\n</rewrite>\n"
},
{
"answer_id": 17454384,
"author": "gregtheross",
"author_id": 2528526,
"author_profile": "https://Stackoverflow.com/users/2528526",
"pm_score": 0,
"selected": false,
"text": "routes.MapRoute(\n name: \"ControllerName\",\n url: \"Controller-Name/{action}/{id}\",\n defaults: new { controller = \"ControllerName\", action = \"Index\", id = UrlParameter.Optional }\n);\n"
},
{
"answer_id": 18032530,
"author": "Ata S.",
"author_id": 1216609,
"author_profile": "https://Stackoverflow.com/users/1216609",
"pm_score": 4,
"selected": false,
"text": "Install-Package LowercaseDashedRoute routes.Add(new LowercaseDashedRoute(\"{controller}/{action}/{id}\",\n new RouteValueDictionary(\n new { controller = \"Home\", action = \"Index\", id = UrlParameter.Optional }),\n new DashedRouteHandler()\n )\n);\n"
},
{
"answer_id": 18043489,
"author": "Jim Geurts",
"author_id": 3085,
"author_profile": "https://Stackoverflow.com/users/3085",
"pm_score": 2,
"selected": false,
"text": "[RoutePrefix(\"dogs-and-cats\")]\npublic class DogsAndCatsController : Controller\n{\n [HttpGet(\"living-together\")]\n public ViewResult LivingTogether() { ... }\n\n [HttpPost(\"mass-hysteria\")]\n public ViewResult MassHysteria() { }\n}\n"
},
{
"answer_id": 21173406,
"author": "Daniel Eagle",
"author_id": 1727203,
"author_profile": "https://Stackoverflow.com/users/1727203",
"pm_score": 3,
"selected": false,
"text": " public static void RegisterRoutes(RouteCollection routes)\n {\n // add these to enable attribute routing and lowercase urls, if desired\n routes.MapMvcAttributeRoutes();\n routes.LowercaseUrls = true;\n\n // routes.MapRoute...\n }\n [RouteArea(\"SampleArea\", AreaPrefix = \"sample-area\")]\n[Route(\"{action}\")]\npublic class SampleAreaController: Controller\n{\n // ...\n\n [Route(\"my-action\")]\n public ViewResult MyAction()\n {\n // do something useful\n }\n}\n"
}
] |
2008/08/27
|
[
"https://Stackoverflow.com/questions/30310",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3085/"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.