qid int64 4 19.1M | question stringlengths 18 48.3k | answers list | date stringlengths 10 10 | metadata list |
|---|---|---|---|---|
308,456 | <p>I have a table containing the runtimes for generators on different sites, and I want to select the most recent entry for each site. Each generator is run once or twice a week.</p>
<p>I have a query that will do this, but I wonder if it's the best option. I can't help thinking that using WHERE x IN (SELECT ...) is lazy and not the best way to formulate the query - any query.</p>
<p>The table is as follows:</p>
<pre><code>CREATE TABLE generator_logs (
id integer NOT NULL,
site_id character varying(4) NOT NULL,
start timestamp without time zone NOT NULL,
"end" timestamp without time zone NOT NULL,
duration integer NOT NULL
);
</code></pre>
<p>And the query:</p>
<pre><code>SELECT id, site_id, start, "end", duration
FROM generator_logs
WHERE start IN (SELECT MAX(start) AS start
FROM generator_logs
GROUP BY site_id)
ORDER BY start DESC
</code></pre>
<p>There isn't a huge amount of data, so I'm not worried about optimizing the query. However, I do have to do similar things on tables with 10s of millions of rows, (big tables as far as I'm concerned!) and there optimisation is more important.</p>
<p>So is there a better query for this, and are inline queries generally a bad idea?</p>
| [
{
"answer_id": 308471,
"author": "Kent Fredric",
"author_id": 15614,
"author_profile": "https://Stackoverflow.com/users/15614",
"pm_score": 0,
"selected": false,
"text": "$maxids = 'SELECT MAX(start) AS start FROM generator_logs GROUP BY site_id';\n$q =\" \n SELECT id, site_id, start, \\\"end\\\", duration \n FROM generator_logs\n WHERE start IN ($maxids) \n ORDER BY start DESC\n\";\n"
},
{
"answer_id": 308505,
"author": "Tony Andrews",
"author_id": 18747,
"author_profile": "https://Stackoverflow.com/users/18747",
"pm_score": 2,
"selected": false,
"text": "SELECT id, site_id, start, \"end\", duration \nFROM generator_logs g1\nWHERE start = (SELECT MAX(g2.start) AS start \n FROM generator_logs g2\n WHERE g2.site_id = g1.site_id) \nORDER BY start DESC\n SELECT id, site_id, start, \"end\", duration \nFROM generator_logs g1\nWHERE (site_id, start) IN (SELECT site_id, MAX(g2.start) AS start \n FROM generator_logs g2\n GROUP BY site_id)\nORDER BY start DESC\n"
},
{
"answer_id": 308640,
"author": "kristof",
"author_id": 3241,
"author_profile": "https://Stackoverflow.com/users/3241",
"pm_score": 2,
"selected": true,
"text": "select gl.id, gl.site_id, gl.start, gl.\"end\", gl.duration \nfrom \n generator_logs gl\n inner join (\n select max(start) as start, site_id\n from generator_logs \n group by site_id\n ) gl2\n on gl.site_id = gl2.site_id\n and gl.start = gl2.start\n"
},
{
"answer_id": 24219355,
"author": "Nick Barnes",
"author_id": 1104979,
"author_profile": "https://Stackoverflow.com/users/1104979",
"pm_score": 0,
"selected": false,
"text": "MAX DISTINCT ON SELECT DISTINCT ON (site_id)\n id, site_id, start, \"end\", duration\nFROM generator_logs\nORDER BY site_id, start DESC;\n DISTINCT ON (site_id) site_id start"
},
{
"answer_id": 24219487,
"author": "wildplasser",
"author_id": 905902,
"author_profile": "https://Stackoverflow.com/users/905902",
"pm_score": 0,
"selected": false,
"text": "SELECT id, site_id, \"start\", \"end\", duration \nFROM generator_logs g1\nWHERE NOT EXISTS (\n SELECT 1\n FROM generator_logs g2\n WHERE g2.site_id = g1.site_id\n AND g2.\"start\" > g1.\"start\"\n );\n"
}
] | 2008/11/21 | [
"https://Stackoverflow.com/questions/308456",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/33161/"
] |
308,460 | <p>I have been going back and forth between C# and Java for the last 8 years. </p>
<p>One thing that strikes me is that I have completely stopped using the "Template Method" design pattern in C#. Actually, in C# I Have come to think of this pattern as an anti-pattern. </p>
<p><a href="http://en.wikipedia.org/wiki/Template_method_pattern" rel="nofollow noreferrer">http://en.wikipedia.org/wiki/Template_method_pattern</a></p>
<p>Coming back to Java, I find the pattern is alive and kicking. I still think it looks antique, but realise that there's no other way to do this in java. Java looks antique too ;)</p>
<p>Since this is going to come up anyway, Why is it an antipattern ?</p>
<ul>
<li>A lot of times it uses up your inheritance hierarchy for "the wrong reasons".</li>
<li>Base classes have a tendency to become littered with all sorts of unrelated code.</li>
<li>It forces you to lock down design, often quite early in the development process. (Premature lock down in a lot of cases)</li>
<li>Changing this at a later stage becomes just harder and harder.</li>
</ul>
<p>So with closures/delegates/function pointers, you normally pass around some function instead of subclassing.</p>
<p>So back to the question: </p>
<p>If your language has closures/delegates/function, do you use the Template Method, and when?</p>
| [
{
"answer_id": 3292618,
"author": "dsimcha",
"author_id": 23903,
"author_profile": "https://Stackoverflow.com/users/23903",
"pm_score": 2,
"selected": false,
"text": "doIt() beforeDoIt() afterDoIt()"
}
] | 2008/11/21 | [
"https://Stackoverflow.com/questions/308460",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23691/"
] |
308,466 | <p>I have to delete some rows from a data table. I've heard that it is not ok to change a collection while iterating through it. So instead of a for loop in which I check if a row meets the demands for deletion and then mark it as deleted, I should first iterate through the data table and add all of the rows in a list, then iterate through the list and mark the rows for deletions. What are the reasons for this, and what alternatives do I have (instead of using the rows list I mean)?.</p>
| [
{
"answer_id": 308486,
"author": "bruno conde",
"author_id": 31136,
"author_profile": "https://Stackoverflow.com/users/31136",
"pm_score": 5,
"selected": true,
"text": "for var l = new List<int>();\n\n l.Add(0);\n l.Add(1);\n l.Add(2);\n l.Add(3);\n l.Add(4);\n l.Add(5);\n l.Add(6);\n\n for (int i = 0; i < l.Count; i++)\n {\n if (l[i] % 2 == 0)\n {\n l.RemoveAt(i);\n i--;\n }\n }\n\n foreach (var i in l)\n {\n Console.WriteLine(i);\n }\n"
},
{
"answer_id": 308530,
"author": "Andy Rose",
"author_id": 1762,
"author_profile": "https://Stackoverflow.com/users/1762",
"pm_score": 2,
"selected": false,
"text": "int i = 0;\nwhile(i < list.Count)\n{\n if(<codition for removing element met>)\n {\n list.RemoveAt(i);\n }\n else\n {\n i++;\n }\n}\n"
},
{
"answer_id": 308550,
"author": "Philluminati",
"author_id": 25466,
"author_profile": "https://Stackoverflow.com/users/25466",
"pm_score": 2,
"selected": false,
"text": "ArrayList matches = new ArrayList(); //second list\n\nfor MyObject obj in my_list\n{\n\n if (obj.property == value_i_care_about)\n matches.addLast(obj);\n}\n\n//now modify\n\nfor MyObject m in matches\n{\n my_list.remove(m); //use second list to delete from first list\n}\n\n//finished.\n"
},
{
"answer_id": 308705,
"author": "MusiGenesis",
"author_id": 14606,
"author_profile": "https://Stackoverflow.com/users/14606",
"pm_score": 3,
"selected": false,
"text": "DataTable dt;\n// remove all rows where the last name starts with \"B\"\nforeach (DataRow row in dt.Rows)\n{\n if (row[\"LASTNAME\"].ToString().StartsWith(\"B\"))\n {\n // mark the row for deletion:\n row.Delete();\n }\n}\n foreach (DataRow row in dt.Rows)\n{\n if (row.RowState != DataRowState.Deleted)\n {\n // this row has not been deleted - go ahead and show it\n }\n}\n"
},
{
"answer_id": 308869,
"author": "Michael Stum",
"author_id": 91,
"author_profile": "https://Stackoverflow.com/users/91",
"pm_score": 6,
"selected": false,
"text": " List<int> test = new List<int>();\n test.Add(1);\n test.Add(2);\n test.Add(3);\n test.Add(4);\n test.Add(5);\n test.Add(6);\n test.Add(7);\n test.Add(8);\n for (int i = test.Count-1; i > -1; i--)\n {\n if(someCondition){\n test.RemoveAt(i);\n }\n }\n"
},
{
"answer_id": 310952,
"author": "chakrit",
"author_id": 3055,
"author_profile": "https://Stackoverflow.com/users/3055",
"pm_score": 5,
"selected": false,
"text": "var l = new List<int>(new int[] { 0, 1, 2, 3, 4, 5, 6 });\n\nfor (int i = l.Count - 1; i >= 0; i--)\n if (l[i] % 2 == 0)\n l.RemoveAt(i);\n\nforeach (var i in l)\n{\n Console.WriteLine(i);\n}\n var l = new List<int>(new int[] { 0, 1, 2, 3, 4, 5, 6 });\n\nl.RemoveAll(n => n % 2 == 0);\n"
},
{
"answer_id": 390708,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "public bool IsMatch(int item) {\n return (item % 3 == 1); // put whatever condition you want here\n}\npublic void RemoveMatching() {\n List<int> x = new List<int>();\n x.RemoveAll(new Predicate<int>(IsMatch));\n}\n"
}
] | 2008/11/21 | [
"https://Stackoverflow.com/questions/308466",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1360/"
] |
308,476 | <p>What is the fastest way to find out whether two <code>ICollection<T></code> collections contain precisely the same entries? Brute force is clear, I was wondering if there is a more elegant method.</p>
<p>We are using C# 2.0, so no extension methods if possible, please!</p>
<p>Edit: the answer would be interesting both for ordered and unordered collections, and would hopefully be different for each.</p>
| [
{
"answer_id": 308524,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 3,
"selected": true,
"text": "[Tested]\n\npublic virtual bool ContainsAll<U>(SCG.IEnumerable<U> items) where U : T\n{\n HashBag<T> res = new HashBag<T>(itemequalityComparer);\n\n foreach (T item in items)\n if (res.ContainsCount(item) < ContainsCount(item))\n res.Add(item);\n else\n return false;\n\n return true;\n}\n"
},
{
"answer_id": 308536,
"author": "Kent Boogaart",
"author_id": 5380,
"author_profile": "https://Stackoverflow.com/users/5380",
"pm_score": 2,
"selected": false,
"text": "SequenceEqual() System.Linq.Enumerable if (firstCollection.SequenceEqual(secondCollection))\n"
},
{
"answer_id": 1110651,
"author": "Marcus Griep",
"author_id": 28645,
"author_profile": "https://Stackoverflow.com/users/28645",
"pm_score": 1,
"selected": false,
"text": "C5.ICollection<T>.GetUnsequencedHashCode() C5.ICollection<T> System.Collections.Generic.ICollection<T>"
}
] | 2008/11/21 | [
"https://Stackoverflow.com/questions/308476",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6091/"
] |
308,477 | <p>How much do using smart pointers, particularly boost::shared_ptr cost more compared to bare pointers in terms of time and memory? Is using bare pointers better for performance intensive parts of gaming/embedded systems? Would you recommend using bare pointers or smart pointers for performance intensive components? </p>
| [
{
"answer_id": 308507,
"author": "Nicola Bonelli",
"author_id": 19630,
"author_profile": "https://Stackoverflow.com/users/19630",
"pm_score": 3,
"selected": false,
"text": "shared_ptr<> #include <iostream>\n#include <tr1/memory>\n\nint main()\n{\n#ifdef USE_SHARED_PTR\n std::tr1::shared_ptr<volatile int> i(new int(1));\n#else\n volatile int * i = new int(1);\n#endif\n\n long long int h = 0;\n\n for(long long int j=0;j < 10000000000LL; j++)\n {\n h += *i;\n }\n\n std::cout << h << std::endl;\n return 0;\n}\n"
},
{
"answer_id": 308661,
"author": "MSalters",
"author_id": 15416,
"author_profile": "https://Stackoverflow.com/users/15416",
"pm_score": 5,
"selected": true,
"text": "boost::scoped_ptr"
},
{
"answer_id": 662319,
"author": "timday",
"author_id": 24283,
"author_profile": "https://Stackoverflow.com/users/24283",
"pm_score": 2,
"selected": false,
"text": "std::vector<T*> std::vector<boost::shared_ptr<T> > boost::ptr_container std::auto_ptr"
}
] | 2008/11/21 | [
"https://Stackoverflow.com/questions/308477",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19501/"
] |
308,479 | <p>Can anybody help me out to know the possible reasons for which Apple store can reject or raise objection to submit any iPhone application.</p>
| [
{
"answer_id": 2624340,
"author": "sixtyfootersdude",
"author_id": 251589,
"author_profile": "https://Stackoverflow.com/users/251589",
"pm_score": 3,
"selected": false,
"text": "If (yes) reject if(yes) reject"
}
] | 2008/11/21 | [
"https://Stackoverflow.com/questions/308479",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/39599/"
] |
308,481 | <p>I often use this recursive 'visitor' in F#</p>
<pre><code>let rec visitor dir filter=
seq { yield! Directory.GetFiles(dir, filter)
for subdir in Directory.GetDirectories(dir) do yield! visitor subdir filter}
</code></pre>
<p>Recently I've started working on implementing some F# functionality in C#, and I'm trying to reproduce this as IEnumerable, but I'm having difficulty getting any further than this:</p>
<pre><code>static IEnumerable<string> Visitor(string root, string filter)
{
foreach (var file in Directory.GetFiles(root, filter))
yield return file;
foreach (var subdir in Directory.GetDirectories(root))
foreach (var file in Visitor(subdir, filter))
yield return file;
}
</code></pre>
<p>What I don't understand is why I have to do a double foreach in the C# version for the recursion, but not in F#... Does the seq {} implicitly do a 'concat'?</p>
| [
{
"answer_id": 308610,
"author": "Sunlight",
"author_id": 33650,
"author_profile": "https://Stackoverflow.com/users/33650",
"pm_score": 5,
"selected": true,
"text": "yield! foreach yield"
},
{
"answer_id": 309337,
"author": "Tomas Petricek",
"author_id": 33518,
"author_profile": "https://Stackoverflow.com/users/33518",
"pm_score": 2,
"selected": false,
"text": "type EnumerationResult<'a> = \n | One of 'a\n | Seq of seq<'a>\n static IEnumerable<EnumerationResult<string>> Visitor\n (string root, string filter) {\n foreach (var file in Directory.GetFiles(root, filter))\n yield return EnumerationResult.One(file);\n foreach (var subdir in Directory.GetDirectories(root))\n yield return EnumerationResult.Seq(Visitor(subdir, filter))\n }\n}\n IEnumerable<T> Flatten(this IEnumerable<EnumerationResult<T>> res);\n"
},
{
"answer_id": 327128,
"author": "Emperor XLII",
"author_id": 2495,
"author_profile": "https://Stackoverflow.com/users/2495",
"pm_score": 2,
"selected": false,
"text": "Directory.GetFiles static IEnumerable<string> Visitor( string root, string filter ) {\n return Directory.GetFiles( root, filter, SearchOption.AllDirectories );\n}\n static IEnumerable<T> Flatten<T>( T item, Func<T, IEnumerable<T>> next ) {\n yield return item;\n foreach( T child in next( item ) )\n foreach( T flattenedChild in Flatten( child, next ) )\n yield return flattenedChild;\n}\n static IEnumerable<string> Visitor( string root, string filter ) {\n return Flatten( root, dir => Directory.GetDirectories( dir ) )\n .SelectMany( dir => Directory.GetFiles( dir, filter ) );\n}\n"
},
{
"answer_id": 2716822,
"author": "Eamon Nerbonne",
"author_id": 42921,
"author_profile": "https://Stackoverflow.com/users/42921",
"pm_score": 2,
"selected": false,
"text": "public static IEnumerable<DirectoryInfo> TryGetDirectories(this DirectoryInfo dir) {\n return F.Swallow(() => dir.GetDirectories(), () => new DirectoryInfo[] { });\n}\npublic static IEnumerable<DirectoryInfo> DescendantDirs(this DirectoryInfo dir) {\n return Enumerable.Repeat(dir, 1).Concat(\n from kid in dir.TryGetDirectories()\n where (kid.Attributes & FileAttributes.ReparsePoint) == 0\n from desc in kid.DescendantDirs()\n select desc);\n}\n"
}
] | 2008/11/21 | [
"https://Stackoverflow.com/questions/308481",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11410/"
] |
308,491 | <p>Is it possible to get Mercurial to show progress of long-running push or pull operation? Google tells me basically "no", but does somebody know better? I was expecting something like <code>hg pull -v</code>...</p>
| [
{
"answer_id": 308515,
"author": "Kent Fredric",
"author_id": 15614,
"author_profile": "https://Stackoverflow.com/users/15614",
"pm_score": 6,
"selected": true,
"text": "hg pull -v \n hg --debug -v pull \n"
},
{
"answer_id": 901638,
"author": "Martin Geisler",
"author_id": 110204,
"author_profile": "https://Stackoverflow.com/users/110204",
"pm_score": 6,
"selected": false,
"text": "[extensions]\nprogress =\n [progress]\ndelay = 1.5\n hg help progress"
}
] | 2008/11/21 | [
"https://Stackoverflow.com/questions/308491",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6846/"
] |
308,492 | <p>In Postgresql you can create additional Aggregate Functions with </p>
<pre><code>CREATE AGGREGATE name(...);
</code></pre>
<p>But this gives an error if the aggregate already exists inside the database, so how can I check if a Aggregate already exists in the Postgres Database? </p>
| [
{
"answer_id": 308500,
"author": "Kent Fredric",
"author_id": 15614,
"author_profile": "https://Stackoverflow.com/users/15614",
"pm_score": 4,
"selected": true,
"text": "SELECT * FROM pg_proc WHERE proname = 'name' AND proisagg; \n"
},
{
"answer_id": 56543864,
"author": "gavenkoa",
"author_id": 173149,
"author_profile": "https://Stackoverflow.com/users/173149",
"pm_score": 0,
"selected": false,
"text": "drop aggregate if exists my_agg(varchar);\n\ncreate aggregate my_agg(varchar) (...);\n\nselect * from pg_aggregate\nwhere aggfnoid = 'my_agg'::regproc;\n"
}
] | 2008/11/21 | [
"https://Stackoverflow.com/questions/308492",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/39644/"
] |
308,499 | <p>I want to float a div to the right at the top of my page. It contains a 50px square image, but currently it impacts on the layout of the top 50px on the page.</p>
<p>Currently its:</p>
<pre><code><div style="float: right;">
...
</div>
</code></pre>
<p>I tried z-index as I thought that would be the answer, but I couldn't get it going.</p>
<p>I know it's something simple I'm missing, but I just can't seem to nail it.</p>
| [
{
"answer_id": 308519,
"author": "nickf",
"author_id": 9021,
"author_profile": "https://Stackoverflow.com/users/9021",
"pm_score": 2,
"selected": false,
"text": "position"
},
{
"answer_id": 308520,
"author": "Richard Garside",
"author_id": 31569,
"author_profile": "https://Stackoverflow.com/users/31569",
"pm_score": 7,
"selected": true,
"text": "z-index: 10; \nposition: absolute; \nright: 0; \ntop: 0;\n"
},
{
"answer_id": 308521,
"author": "EoghanM",
"author_id": 6691,
"author_profile": "https://Stackoverflow.com/users/6691",
"pm_score": 3,
"selected": false,
"text": "position:absolute;\nright:0;\ntop:0;\n position: relative"
}
] | 2008/11/21 | [
"https://Stackoverflow.com/questions/308499",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/39643/"
] |
308,501 | <p>I want to check that two passwords are the same using Dojo.</p>
<p>Here is the HTML I have:</p>
<p><code></p>
<blockquote>
<p><code><form id="form" action="." dojoType="dijit.form.Form" /</code>></p>
<p><code><p</code>>Password: <code><input type="password"<br>
name="password1"<br>
id="password1"<br>
dojoType="dijit.form.ValidationTextBox"<br>
required="true"<br>
invalidMessage="Please type a password" /</code>><code></p</code>></p>
<p><code><p</code>>Confirm: <code><input type="password"<br>
name="password2"<br>
id="password2"<br>
dojoType="dijit.form.ValidationTextBox"<br>
required="true"<br>
invalidMessage="This password doesn't match your first password" /</code>><code></p</code>></p>
<p><code><div dojoType="dijit.form.Button" onClick="onSave"</code>>Save<code></div</code>></p>
<p><code></form</code>>
</code></p>
</blockquote>
<p>Here is the JavaScript I have so far:</p>
<blockquote>
<p><code>
var onSave = function() {<br>
if(dijit.byId('form').validate()) { alert('Good form'); }<br>
else { alert('Bad form'); }<br>
}
</code></p>
</blockquote>
<p>Thanks for your help. I could do this in pure JavaScript, but I'm trying to find the Dojo way of doing it.</p>
| [
{
"answer_id": 308666,
"author": "Richard Garside",
"author_id": 31569,
"author_profile": "https://Stackoverflow.com/users/31569",
"pm_score": 1,
"selected": false,
"text": "\n <p>Confirm: <input type=\"password\"\n name=\"password2\"\n id=\"password2\"\n dojoType=\"dijit.form.ValidationTextBox\"\n required=\"true\"\n validator=\"return theSame(this, dijit.byId('password1'));\"\n invalidMessage=\"This password doesn't match your first password\" /></p>\n <p <input type=\"password\"\n name=\"password2\"\n id=\"password2\"\n dojoType=\"dijit.form.ValidationTextBox\"\n required=\"true\"\n validator=\"return theSame(this, dijit.byId('password1'));\"\n invalidMessage=\"This password doesn't match your first password\" / </p \n function(dojoTxt1, dojoTxt2) {\n return dojoTxt1.getValue() == dojoTxt2.getValue();\n }\n "
},
{
"answer_id": 312750,
"author": "Ed.",
"author_id": 12257,
"author_profile": "https://Stackoverflow.com/users/12257",
"pm_score": 3,
"selected": true,
"text": "\nfunction confirmPassword(value, constraints)\n{\n var isValid = false;\n if(constraints && constraints.other) {\n var otherInput = dijit.byId(constraints.other);\n if(otherInput) {\n var otherValue = otherInput.value;\n console.log(\"%s == %s ?\", value, otherValue);\n isValid = (value == otherValue);\n }\n }\n return isValid;\n}\nfunction onsubmit()\n{\n var p1 = dijit.byId('password1').value;\n var p2 = dijit.byId('password2').value;\n return p1 == p2;\n}\n \n<p>Password: <input type=\"password\"\n name=\"password1\"\n id=\"password1\"\n dojoType=\"dijit.form.ValidationTextBox\"\n required=\"true\"\n intermediateChanges=false\n invalidMessage=\"Please type a password\" /></p>\n\n<p>Confirm: <input type=\"password\"\n name=\"password2\"\n id=\"password2\"\n dojoType=\"dijit.form.ValidationTextBox\"\n required=\"true\"\n constraints=\"{'other': 'password1'}\"\n validator=confirmPassword\n intermediateChanges=false\n invalidMessage=\"This password doesn't match your first password\" /></p>\n"
}
] | 2008/11/21 | [
"https://Stackoverflow.com/questions/308501",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/31569/"
] |
308,511 | <p>I have a .Net 1.1 web application sitting in a folder called C:\inetpub\wwwroot\MyTestApp, where 'MyTestApp' is a virtual directory and is configured to be on ASP.Net version 1.1.4322 in IIS 5.1.</p>
<p>In the root directory (C:\inetpub\wwwroot) there is a web.config file for a .Net2.0 application, because the root folder contains some web pages written in .Net2.0.</p>
<p>Whenever I try to access 'MyTestApp' though I get an error...</p>
<pre><code>Parser Error Message: Unrecognized configuration section 'connectionStrings'
Source File: c:\inetpub\wwwroot\web.config Line: 17
</code></pre>
<p>The .Net1.1 application in the MyTestApp folder is trying to access the web.config file in the root folder, and getting upset because it is on a different version. How can I tell the MyTestApp folder NOT to use the web.config file in the root folder, but instead just use the web.config in its own folder?</p>
<p>Is such a thing possible, or is nesting a .Net 1.1 application in a sub-folder under a .Net 2.0 application a no-no?</p>
| [
{
"answer_id": 308542,
"author": "Rob Cooper",
"author_id": 832,
"author_profile": "https://Stackoverflow.com/users/832",
"pm_score": 1,
"selected": false,
"text": "Web.config Machine.config"
}
] | 2008/11/21 | [
"https://Stackoverflow.com/questions/308511",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7585/"
] |
308,514 | <p>In firefox when you add an onclick event handler to a method an event object is automatically passed to that method. This allows, among other things, the ability to detect which specific element was clicked. For example</p>
<pre><code>document.body.onclick = handleClick;
function handleClick(e)
{
// this works if FireFox
alert(e.target.className);
}
</code></pre>
<p>Is there any way to approximate this in IE? i need to be able to detect which element is clicked from an event handler on the body element.</p>
| [
{
"answer_id": 308523,
"author": "nickf",
"author_id": 9021,
"author_profile": "https://Stackoverflow.com/users/9021",
"pm_score": 0,
"selected": false,
"text": "event"
},
{
"answer_id": 308526,
"author": "Simon",
"author_id": 33036,
"author_profile": "https://Stackoverflow.com/users/33036",
"pm_score": 2,
"selected": false,
"text": "e.srcElement\n"
},
{
"answer_id": 308528,
"author": "Kent Fredric",
"author_id": 15614,
"author_profile": "https://Stackoverflow.com/users/15614",
"pm_score": 2,
"selected": false,
"text": "if (el.addEventListener){\n el.addEventListener('click', modifyText, false); \n} else if (el.attachEvent){\n el.attachEvent('onclick', modifyText);\n}\n function foo() { \n window.open(this.src, '_blank'); \n}\n"
},
{
"answer_id": 308540,
"author": "Atanas Korchev",
"author_id": 10141,
"author_profile": "https://Stackoverflow.com/users/10141",
"pm_score": 4,
"selected": true,
"text": "document.body.onclick = handleClick;\n\nfunction handleClick(e)\n{\n //If \"e\" is undefined use the global \"event\" variable\n e = e || event;\n\n var target = e.srcElement || e.target;\n alert(target.className);\n}\n $(document.body).click(function(e) {\n alert($(this).attr(\"class\"));\n});\n"
}
] | 2008/11/21 | [
"https://Stackoverflow.com/questions/308514",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/28882/"
] |
308,547 | <p>I am using a custom validator to compare value in two text box. This is comparing the values fine. But it says "025" and "25" are different.. can this do a float comparision.</p>
<p>the custom validator i am using is </p>
<pre><code><asp:CompareValidator id="compval" runat="server" ControlToValidate="txtBox1"
ErrorMessage="There values are not equal."
Enabled="False" ControlToCompare="txtBox2">*</asp:CompareValidator></TD>
</code></pre>
<p>Please let me know if this is possible.</p>
| [
{
"answer_id": 311875,
"author": "Stefan",
"author_id": 30604,
"author_profile": "https://Stackoverflow.com/users/30604",
"pm_score": 1,
"selected": false,
"text": "<asp:CompareValidator ID=\"cv1\" runat=\"server\" ControlToCompare=\"txt1\" ControlToValidate=\"txt2\" Operator=\"Equal\" Type=\"Integer\" ErrorMessage=\"integers in txt1 and txt2 are not equal\" />\n"
}
] | 2008/11/21 | [
"https://Stackoverflow.com/questions/308547",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20951/"
] |
308,555 | <p>I have this Java code (JPA):</p>
<pre><code>String queryString = "SELECT b , sum(v.votedPoints) as votedPoint " +
" FROM Bookmarks b " +
" LEFT OUTER JOIN Votes v " +
" on (v.organizationId = b.organizationId) " +
"WHERE b.userId = 101 " +
"GROUP BY b.organizationId " +
"ORDER BY votedPoint ascending ";
EntityManager em = getEntityManager();
Query query = em.createQuery(queryString);
query.setFirstResult(start);
query.setMaxResults(numRecords);
List results = query.getResultList();
</code></pre>
<p>I don't know what is wrong with my query because it gives me this error: </p>
<pre>
java.lang.NoSuchMethodError: org.hibernate.hql.antlr.HqlBaseParser.recover(Lantlr/RecognitionException;Lantlr/collections/impl/BitSet;)V
at org.hibernate.hql.antlr.HqlBaseParser.fromJoin(HqlBaseParser.java:1802)
at org.hibernate.hql.antlr.HqlBaseParser.fromClause(HqlBaseParser.java:1420)
at org.hibernate.hql.antlr.HqlBaseParser.selectFrom(HqlBaseParser.java:1130)
at org.hibernate.hql.antlr.HqlBaseParser.queryRule(HqlBaseParser.java:702)
at org.hibernate.hql.antlr.HqlBaseParser.selectStatement(HqlBaseParser.java:296)
at org.hibernate.hql.antlr.HqlBaseParser.statement(HqlBaseParser.java:159)
at org.hibernate.hql.ast.QueryTranslatorImpl.parse(QueryTranslatorImpl.java:271)
at org.hibernate.hql.ast.QueryTranslatorImpl.doCompile(QueryTranslatorImpl.java:180)
at org.hibernate.hql.ast.QueryTranslatorImpl.compile(QueryTranslatorImpl.java:134)
at org.hibernate.engine.query.HQLQueryPlan.(HQLQueryPlan.java:101)
at org.hibernate.engine.query.HQLQueryPlan.(HQLQueryPlan.java:80)
at org.hibernate.engine.query.QueryPlanCache.getHQLQueryPlan(QueryPlanCache.java:94)
at org.hibernate.impl.AbstractSessionImpl.getHQLQueryPlan(AbstractSessionImpl.java:156)
at org.hibernate.impl.AbstractSessionImpl.createQuery(AbstractSessionImpl.java:135)
at org.hibernate.impl.SessionImpl.createQuery(SessionImpl.java:1650)
</pre>
<p>Thanks.</p>
| [
{
"answer_id": 308568,
"author": "VonC",
"author_id": 6309,
"author_profile": "https://Stackoverflow.com/users/6309",
"pm_score": 1,
"selected": false,
"text": "\""
},
{
"answer_id": 308589,
"author": "JesperE",
"author_id": 13051,
"author_profile": "https://Stackoverflow.com/users/13051",
"pm_score": 0,
"selected": false,
"text": "recover(RecognitionException, Bitset) java.lang.NoSuchMethodError: org.hibernate.hql.antlr.HqlBaseParser.recover(Lantlr/RecognitionException;Lantlr/collections/impl/BitSet;)V\n"
},
{
"answer_id": 308591,
"author": "nicerobot",
"author_id": 23056,
"author_profile": "https://Stackoverflow.com/users/23056",
"pm_score": 1,
"selected": false,
"text": "Select b, ... Select b.organizationId, ..."
},
{
"answer_id": 309148,
"author": "Ionut",
"author_id": 39626,
"author_profile": "https://Stackoverflow.com/users/39626",
"pm_score": 2,
"selected": false,
"text": "@OneToMany(mappedBy = \"bookmarkId\")\nprivate Collection votesCollection;\n @JoinColumn(name = \"bookmark_id\", referencedColumnName = \"bookmark_id\")\n@ManyToOne\n[private Bookmarks bookmarkId;\n \ntring queryString = \"SELECT b, sum(v.votedPoints) \" +\n \"FROM Bookmarks b \" +\n \"LEFT OUTER JOIN b.votesCollection v \" + \n \"WHERE b.userId = 101 \" + \n \"GROUP BY b.organizationId \" +\n \"ORDER BY sum(v.votedPoints) asc \";\n"
},
{
"answer_id": 309932,
"author": "nicerobot",
"author_id": 23056,
"author_profile": "https://Stackoverflow.com/users/23056",
"pm_score": 0,
"selected": false,
"text": "b.* b.organizationId"
}
] | 2008/11/21 | [
"https://Stackoverflow.com/questions/308555",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/39626/"
] |
308,581 | <p>Is it better to have all the private members, then all the protected ones, then all the public ones? Or the reverse? Or should there be multiple private, protected and public labels so that the operations can be kept separate from the constructors and so on? What issues should I take into account when making this decision?</p>
| [
{
"answer_id": 308660,
"author": "David Rodríguez - dribeas",
"author_id": 36565,
"author_profile": "https://Stackoverflow.com/users/36565",
"pm_score": 2,
"selected": false,
"text": "class Example1 {\npublic:\n void publicOperation();\nprivate:\n void privateOperation1_();\n void privateOperation2_();\n\n Type1 data1_;\n Type2 data2_;\n};\n// example 2 header:\nclass Example2 {\n class Impl;\npublic:\n void publicOperation();\nprivate:\n std::auto_ptr<Example2Impl> impl_;\n};\n// example2 cpp:\nclass Example2::Impl\n{\npublic:\n void privateOperation1();\n void privateOperation2();\nprivate: // or public if Example2 needs access, or private + friendship:\n Type1 data1_;\n Type2 data2_;\n};\n"
},
{
"answer_id": 308691,
"author": "Dave Van den Eynde",
"author_id": 455874,
"author_profile": "https://Stackoverflow.com/users/455874",
"pm_score": 2,
"selected": false,
"text": "class Foo\n{\nprivate:\n int bar;\n\npublic:\n int GetBar() const\n {\n return bar;\n }\n};\n class Foo\n{\npublic:\n typedef int bar_type;\n\nprivate:\n bar_type bar;\n\npublic:\n bar_type GetBar() const\n {\n return bar;\n }\n};\n"
}
] | 2008/11/21 | [
"https://Stackoverflow.com/questions/308581",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11575/"
] |
308,588 | <p>I am struggling to get an Epson "ESC/POS" printer to print barcodes (Using Delphi) and want to test if the printer is not faulty. Do you know where I can find a program to print a barcode in "ESC/POS"? I suppose as a last resort an OPOS program will also be OK.</p>
<p>Also, a demo Delphi Program that works will also be fine. All the Delphi snippets I have so far is not working.</p>
<p>The printer I am using is an Epson TM-L60II</p>
| [
{
"answer_id": 308829,
"author": "Re0sless",
"author_id": 2098,
"author_profile": "https://Stackoverflow.com/users/2098",
"pm_score": 4,
"selected": true,
"text": "{**\n* @param a ean13 barcode numeric value\n* @return the escpos code for the barcode print\n* Description uses escpos code, return code needed to print a ean13 barcode\n*}\nfunction TPrintEscPosToPort.getBarcodeEscPosCode(l_ean13:String):String;\n var\n l_return:String;\nbegin\n l_return := CHR(29) + 'k' + CHR(67) + CHR(12);\n l_return := l_return + l_ean13; // Print bar code\n l_return := l_return + l_ean13; // Print bar code number under thge barcode\n\n Result := l_return\nend;\n {**\n* @param Printer Name, Item be printed, Cut the papers after the cut, #no of copies to print\n* @return boolen, true if it printed\n* Description prints a test page to the tysso printer\n*}\nfunction TPrintEscPosToPort.escPosPrint(const l_printer, l_textToPrint :String;l_cutPaper:Boolean=true;l_copies:integer=1): Boolean;\n var\n l_pPort,l_pName,l_tmp:String;\n i,x:integer;\n PrinterFile: TextFile;\nbegin\n // set result to false so any thing other then a good print will be false\n Result:= FALSE;\n\n try\n //Find if the printer exists, else set to defult -1\n i := Printer.Printers.IndexOf(l_printer);\n if (i > -1) then\n begin\n Printer.PrinterIndex := i;\n l_pName := Printer.Printers[i]; //Get the printer name (incase its the defult and not the one passed)\n l_pPort := Self.getPrinterPort(l_pName) ; // get the port name from the reg\n end;\n\n // If true add headers and footers to the passed text\n if (Self.aPrintHeadersFooters) then\n begin\n l_tmp := Self.getHeader()\n + l_textToPrint + Self.GetFooter();\n end\n else\n begin\n l_tmp := l_textToPrint;\n end;\n\n //Send the Document To the printer\n try\n for x:= 1 to l_copies do //Print multi-copies\n Begin \n //Assign the file to a tmp file in the printer port\n if (length(trim(l_pPort)) > 0) then AssignFile(PrinterFile,l_pPort)\n else\n begin \n //only use if we cant get the port \n //(may look bad as ctrl codes are still in place)\n AssignPrn(PrinterFile);\n l_tmp := Self.stripEscPos(l_tmp);\n end;\n\n Rewrite(PrinterFile);\n\n try\n //Send the passed Text to the printer \n WriteLn(PrinterFile,l_tmp);\n\n if (Self.aPrinterReset) then \n WriteLn(PrinterFile,escReset); // Reset the printer alignment\n\n if (l_cutPaper) then \n WriteLn(PrinterFile,escFeedAndCut); //Cut the paper if needed\n finally\n CloseFile(PrinterFile);\n Result:= true;\n end;\n end;\n except\n end;\n except\n end;\n\nend;\n const\n escNewLine = chr(10); // New line (LF line feed)\n escUnerlineOn = chr(27) + chr(45) + chr(1); // Unerline On\n escUnerlineOnx2 = chr(27) + chr(45) + chr(2); // Unerline On x 2\n escUnerlineOff = chr(27) + chr(45) + chr(0); // Unerline Off\n escBoldOn = chr(27) + chr(69) + chr(1); // Bold On\n escBoldOff = chr(27) + chr(69) + chr(0); // Bold Off\n escNegativeOn = chr(29) + chr(66) + chr(1); // White On Black On'\n escNegativeOff = chr(29) + chr(66) + chr(0); // White On Black Off\n esc8CpiOn = chr(29) + chr(33) + chr(16); // Font Size x2 On\n esc8CpiOff = chr(29) + chr(33) + chr(0); // Font Size x2 Off\n esc16Cpi = chr(27) + chr(77) + chr(48); // Font A - Normal Font\n esc20Cpi = chr(27) + chr(77) + chr(49); // Font B - Small Font\n escReset = chr(27) + chr(64); //chr(27) + chr(77) + chr(48); // Reset Printer\n escFeedAndCut = chr(29) + chr(86) + chr(65); // Partial Cut and feed\n\n escAlignLeft = chr(27) + chr(97) + chr(48); // Align Text to the Left\n escAlignCenter = chr(27) + chr(97) + chr(49); // Align Text to the Center\n escAlignRight = chr(27) + chr(97) + chr(50); // Align Text to the Right\n"
}
] | 2008/11/21 | [
"https://Stackoverflow.com/questions/308588",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3535708/"
] |
308,590 | <p>I'm running JBoss 4.0.5 on Windows 2003 x64 and wonder if there is any way to get a dump of all threads? </p>
<ul>
<li><p>It's stared with FireDaemon so I don't have a console windows in which to ctrl-break.</p></li>
<li><p>It's running under java 1.5 so jstack won't work.</p></li>
<li><p>I tried some program someone had made called sendsignal.exe, which I think actually crashed JBoss (not certain, but not going to try it again), if this was because JBoss runs under win x64 or because it runs as LocalSystem and I only have access to an "ordinary" user I don't know. It actually worked on my laptop, but it's 32-bit and I'm running as the same user as JBoss there.</p></li>
</ul>
<p>Someone has any other ideas that might work?</p>
| [
{
"answer_id": 308604,
"author": "Gowri",
"author_id": 3253,
"author_profile": "https://Stackoverflow.com/users/3253",
"pm_score": 0,
"selected": false,
"text": "Thread.getAllStackTraces()"
}
] | 2008/11/21 | [
"https://Stackoverflow.com/questions/308590",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/30354/"
] |
308,601 | <p>I am working on a Windows application which needs to be able to update itself. When a button is pressed it starts the installer and then the parent application exits. At some point during the installer, the installer attempts to rename the directory that the parent application was running from and fails with "Access Denied" If you run the installer from the desktop it works.</p>
<p>I am using CreateProcess to start the installer, is there some way of using this or another API to create the installer completely independantly from the parent application so that it doesn't retain some attachment to the directory.</p>
| [
{
"answer_id": 308604,
"author": "Gowri",
"author_id": 3253,
"author_profile": "https://Stackoverflow.com/users/3253",
"pm_score": 0,
"selected": false,
"text": "Thread.getAllStackTraces()"
}
] | 2008/11/21 | [
"https://Stackoverflow.com/questions/308601",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
308,605 | <p>I've got a Django application that works nicely. I'm adding REST services. I'm looking for some additional input on my REST strategy. </p>
<p>Here are some examples of things I'm wringing my hands over.</p>
<ul>
<li>Right now, I'm using the Django-REST API with a pile of patches. </li>
<li>I'm thinking of falling back to simply writing view functions in Django that return JSON results.</li>
<li>I can also see filtering the REST requests in Apache and routing them to a separate, non-Django server instance.</li>
</ul>
<p>Please nominate one approach per answer so we can vote them up or down.</p>
| [
{
"answer_id": 1510095,
"author": "yfeldblum",
"author_id": 12349,
"author_profile": "https://Stackoverflow.com/users/12349",
"pm_score": 5,
"selected": false,
"text": "GET /account/profile HTTP/1.1\nHost: example.com\nAccept: application/json\n GET /account/profile.json HTTP/1.1\nHost: example.com\n PUT /account/profile HTTP/1.1\nHost: example.com\n\nvar=value\n POST /account/profile HTTP/1.1\nHost: example.com\n\n_method=PUT&var=value\n"
}
] | 2008/11/21 | [
"https://Stackoverflow.com/questions/308605",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10661/"
] |
308,609 | <p>As as part of my daily routine, I have the misfortune of administering an ancient, once "just internal" JSP web application that relies on the following authentication schema:</p>
<pre><code>...
// Validate the user name and password.
if ((user != null) && (password != null) && (
(user.equals("brianmay") && password.equals("queen")) ||
(user.equals("rogertaylor") && password.equals("queen")) ||
(user.equals("freddiemercury") && password.equals("queen")) ||
(user.equals("johndeacon") && password.equals("queen"))
)) {
// Store the user name as a session variable.
session.putValue("user", user);
...
</code></pre>
<p>As much as I would like to, the Queen members have never been users of the system but anyway it does make a great example, does it not?</p>
<p>Despite that by policy this client enforces security by domain authentication among other things, therefore this issue isn't seen as a security risk, still, my idea is to at least obfuscate that plain text credentials using perhaps a simple MD5 or SHA1 method, so such sensitive data is not visible to the naked eye.</p>
<p>I'm a total newbie when it comes to JSP so I would really appreciate any piece of advice you'd be willing to share with me.</p>
<p>Thanks much in advance!</p>
| [
{
"answer_id": 308677,
"author": "carson",
"author_id": 25343,
"author_profile": "https://Stackoverflow.com/users/25343",
"pm_score": 3,
"selected": true,
"text": "try\n{\n String digestInput = \"queen\";\n\n MessageDigest messageDigest = MessageDigest.getInstance(\"MD5\");\n messageDigest.update(digestInput.getBytes());\n\n BASE64Encoder base64Encoder = new BASE64Encoder();\n String digestString = base64Encoder.encode(messageDigest.digest());\n\n // digestString now contains the md5 hashed password\n}\ncatch (Exception e)\n{\n // do some type of logging here\n}\n"
}
] | 2008/11/21 | [
"https://Stackoverflow.com/questions/308609",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6992/"
] |
308,615 | <p>Please feel free to correct me if I am wrong at any point...</p>
<p>I am trying to read a <a href="http://en.wikipedia.org/wiki/Comma-separated_values" rel="nofollow noreferrer">CSV</a> (comma separated values) file using .NET file I/O classes. Now the problem is, this CSV file may contain some fields with soft carriage returns (i.e. solitary \r or \n markers rather than the standard \r\n used in text files to end a line) within some fields and the standard text mode I/O class StreamReader does not respect the standard convention and treats the soft carriage returns as hard carriage returns thus compromising the integrity of the CSV file. </p>
<p>Now using the BinaryReader class seems to be the only option left but the BinaryReader does not have a ReadLine() function hence the need to implement a ReadLine() on my own. </p>
<p>My current approach reads one character from the stream at a time and fills a StringBuilder until a \r\n is obtained (ignoring all other characters including solitary \r or \n) and then returns a string representation of the StringBuilder (using ToString()). </p>
<p>But I wonder: is this is the most efficient way of implementing the ReadLine() function? Please enlighten me.</p>
| [
{
"answer_id": 308648,
"author": "configurator",
"author_id": 9536,
"author_profile": "https://Stackoverflow.com/users/9536",
"pm_score": 4,
"selected": true,
"text": "public class LineReader : IDisposable\n{\n private Stream stream;\n private BinaryReader reader;\n\n public LineReader(Stream stream) { reader = new BinaryReader(stream); }\n\n public string ReadLine()\n {\n StringBuilder result = new StringBuilder();\n char lastChar = reader.ReadChar();\n // an EndOfStreamException here would propogate to the caller\n\n try\n {\n char newChar = reader.ReadChar();\n if (lastChar == '\\r' && newChar == '\\n')\n return result.ToString();\n\n result.Append(lastChar);\n lastChar = newChar;\n }\n catch (EndOfStreamException)\n {\n result.Append(lastChar);\n return result.ToString();\n }\n }\n\n public void Dispose()\n {\n reader.Close();\n }\n}\n"
},
{
"answer_id": 9536963,
"author": "oazabir",
"author_id": 669105,
"author_profile": "https://Stackoverflow.com/users/669105",
"pm_score": 0,
"selected": false,
"text": "public class LineReader : BinaryReader\n{\n private Encoding _encoding;\n private Decoder _decoder;\n\n const int bufferSize = 1024;\n private char[] _LineBuffer = new char[bufferSize];\n\n public LineReader(Stream stream, int bufferSize, Encoding encoding)\n : base(stream, encoding)\n {\n this._encoding = encoding;\n this._decoder = encoding.GetDecoder();\n }\n\n public string ReadLine()\n {\n int pos = 0;\n\n char[] buf = new char[2];\n\n StringBuilder stringBuffer = null;\n bool lineEndFound = false;\n\n while(base.Read(buf, 0, 2) > 0)\n {\n if (buf[1] == '\\r')\n {\n // grab buf[0]\n this._LineBuffer[pos++] = buf[0];\n // get the '\\n'\n char ch = base.ReadChar();\n Debug.Assert(ch == '\\n');\n\n lineEndFound = true;\n }\n else if (buf[0] == '\\r')\n {\n lineEndFound = true;\n } \n else\n {\n this._LineBuffer[pos] = buf[0];\n this._LineBuffer[pos+1] = buf[1];\n pos += 2;\n\n if (pos >= bufferSize)\n {\n stringBuffer = new StringBuilder(bufferSize + 80);\n stringBuffer.Append(this._LineBuffer, 0, bufferSize);\n pos = 0;\n }\n }\n\n if (lineEndFound)\n {\n if (stringBuffer == null)\n {\n if (pos > 0)\n return new string(this._LineBuffer, 0, pos);\n else\n return string.Empty;\n }\n else\n {\n if (pos > 0)\n stringBuffer.Append(this._LineBuffer, 0, pos);\n return stringBuffer.ToString();\n }\n }\n }\n\n if (stringBuffer != null)\n {\n if (pos > 0)\n stringBuffer.Append(this._LineBuffer, 0, pos);\n return stringBuffer.ToString();\n }\n else\n {\n if (pos > 0)\n return new string(this._LineBuffer, 0, pos);\n else\n return null;\n }\n }\n\n}\n"
},
{
"answer_id": 27571627,
"author": "TermWay",
"author_id": 985714,
"author_profile": "https://Stackoverflow.com/users/985714",
"pm_score": 1,
"selected": false,
"text": "using System.IO;\nusing System.Text;\n\npublic static class BinaryReaderExtension\n{\n public static string ReadLine(this BinaryReader reader)\n {\n if (reader.IsEndOfStream())\n return null;\n\n StringBuilder result = new StringBuilder();\n char character;\n while(!reader.IsEndOfStream() && (character = reader.ReadChar()) != '\\n')\n if (character != '\\r' && character != '\\n')\n result.Append(character);\n\n return result.ToString();\n }\n\n public static bool IsEndOfStream(this BinaryReader reader)\n {\n return reader.BaseStream.Position == reader.BaseStream.Length; \n }\n}\n"
}
] | 2008/11/21 | [
"https://Stackoverflow.com/questions/308615",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/39648/"
] |
308,619 | <p>With a vector defined as <code>std::vector<std::string></code>,
Wondering why the following is valid:</p>
<pre><code>if ( vecMetaData[0] != "Some string" )
{
...
</code></pre>
<p>But not this:</p>
<pre><code>switch ( vecMetaData[1] )
{
...
</code></pre>
<p>Visual studio complains :</p>
<pre><code>error C2450: switch expression of type 'std::basic_string<_Elem,_Traits,_Ax>' is illegal
1> with
1> [
1> _Elem=char,
1> _Traits=std::char_traits<char>,
1> _Ax=std::allocator<char>
1> ]
1> No user-defined-conversion operator available that can perform this conversion, or the operator cannot be called
</code></pre>
| [
{
"answer_id": 308676,
"author": "MSalters",
"author_id": 15416,
"author_profile": "https://Stackoverflow.com/users/15416",
"pm_score": 1,
"selected": false,
"text": "std::map<std::string, boost::function> StringSwitch; StringSwitch[\"Some string\"](arguments...)"
},
{
"answer_id": 309152,
"author": "Reed Hedges",
"author_id": 39686,
"author_profile": "https://Stackoverflow.com/users/39686",
"pm_score": 1,
"selected": false,
"text": "for_each find_if for_each"
}
] | 2008/11/21 | [
"https://Stackoverflow.com/questions/308619",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18664/"
] |
308,620 | <p>I have a simple database with two tables. Users and Configurations. A user has a foreign key to link it to a particular configuration.</p>
<p>I am having a strange problem where the following query always causes an inner join to the Configuration table regardless of the second parameter value. As far as I can tell, even though the "UserConfiguration =" part of the object initialisation is conditional, LINQ doesn't see that and determines that a relationship is followed in any case.</p>
<p>If I actually remove that last initialisation, the whole thing works as expected. It doesn't inner join when loadConfiguration == false and it does join when loadConfiguration == true.</p>
<p>Anyone got any ideas about this? Is this syntax just not going to work? The only thought I have now is to wrap the return in a basic if statement - I just wanted to avoid the duplicated lines.</p>
<pre><code>public UserAccount GetByUsername(string username, bool loadConfiguration)
{
using (Database database = new Database())
{
if (loadConfiguration)
{
DataLoadOptions loadOptions = new DataLoadOptions();
loadOptions.LoadWith<User>(c => c.Configuration);
database.LoadOptions = loadOptions;
}
return (from c in database.Users
where c.Username == username
select new UserAccount
{
ID = c.ID,
ConfigurationID = c.ConfigurationID,
Username = c.Username,
Password = c.Password.ToArray(),
HashSalt = c.HashSalt,
FirstName = c.FirstName,
LastName = c.LastName,
EmailAddress = c.EmailAddress,
UserConfiguration = (loadConfiguration) ? new ApplicationConfiguration
{
ID = c.Configuration.ID,
MonthlyAccountPrice = c.Configuration.MonthlyAccountPrice,
TrialAccountDays = c.Configuration.TrialAccountDays,
VAT = c.Configuration.VAT,
DateCreated = c.Configuration.DateCreated
} : null
}).Single();
}
}
</code></pre>
<p>Thanks in advance,</p>
<p>Martin.</p>
| [
{
"answer_id": 308676,
"author": "MSalters",
"author_id": 15416,
"author_profile": "https://Stackoverflow.com/users/15416",
"pm_score": 1,
"selected": false,
"text": "std::map<std::string, boost::function> StringSwitch; StringSwitch[\"Some string\"](arguments...)"
},
{
"answer_id": 309152,
"author": "Reed Hedges",
"author_id": 39686,
"author_profile": "https://Stackoverflow.com/users/39686",
"pm_score": 1,
"selected": false,
"text": "for_each find_if for_each"
}
] | 2008/11/21 | [
"https://Stackoverflow.com/questions/308620",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
308,650 | <p>Anyone got any insight as to select x number of non-consecutive days worth of data? Dates are standard sql datetime. So for example I'd like to select 5 most recent days worth of data, but there could be many days gap between records, so just selecting records from 5 days ago and more recent will not do.</p>
| [
{
"answer_id": 308670,
"author": "Tony Andrews",
"author_id": 18747,
"author_profile": "https://Stackoverflow.com/users/18747",
"pm_score": 0,
"selected": false,
"text": "select *\nfrom data\nwhere datetime >=\n( select top 1 date\n from\n ( select top 5 date from\n ( select truncated(datetime) as date\n from data\n order by truncated(datetime) desc\n )\n order by date\n )\n)\n"
},
{
"answer_id": 308723,
"author": "Tomalak",
"author_id": 18771,
"author_profile": "https://Stackoverflow.com/users/18771",
"pm_score": 2,
"selected": true,
"text": "SELECT\n Value,\n ValueDate\nFROM\n Data\nWHERE\n ValueDate >= \n (\n SELECT \n CONVERT(DATETIME, MIN(TruncatedDate))\n FROM \n (\n SELECT DISTINCT TOP 5 \n CONVERT(VARCHAR, ValueDate, 102) TruncatedDate\n FROM \n Event\n ORDER BY \n TruncatedDate DESC\n ) d\n )\nORDER BY\n ValueDate DESC\n"
},
{
"answer_id": 309111,
"author": "Tom H",
"author_id": 5696608,
"author_profile": "https://Stackoverflow.com/users/5696608",
"pm_score": 0,
"selected": false,
"text": "SELECT TOP (@number_to_return)\n * -- Write out your columns here\nFROM\n dbo.MyTable\nORDER BY\n MyDateColumn DESC\n"
}
] | 2008/11/21 | [
"https://Stackoverflow.com/questions/308650",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/39655/"
] |
308,659 | <p>I have a login screen that I force to be ssl, so like this:
<a href="https://www.foobar.com/login" rel="noreferrer">https://www.foobar.com/login</a>
then after they login, they get moved to the homepage:
<a href="https://www.foobar.com/dashbaord" rel="noreferrer">https://www.foobar.com/dashbaord</a></p>
<p>However, I want to move people off of SSL once logged in (to save CPU), so just after checking that they are in fact logged in on <a href="https://www.foobar.com/dashbaord" rel="noreferrer">https://www.foobar.com/dashbaord</a> I move them to
<a href="http://www.foobar.com/dashbaord" rel="noreferrer">http://www.foobar.com/dashbaord</a></p>
<p>Well this always seems to wipe out the session variables, because when the page runs again, it confirms they are logged in (as all pages do) and session appears not to exist, so it moves them to the login screen.</p>
<p>Oddness/findings:</p>
<ol>
<li>List item</li>
<li>The second login always works, and happily gets me to <a href="http://www.foobar.com/dashbaord" rel="noreferrer">http://www.foobar.com/dashbaord</a></li>
<li>It successfully creates a cookie the first login</li>
<li>If I login twice, then logout, and login again, I don't need two logins (I seem to have traced this to the fact that the cookie exists). If I delete the cookie, I'm back to two logins.</li>
<li>After the second login, I can move from non-ssl from ssl and the session persists.</li>
<li>On the first login, the move to the non-ssl site wipes out the session entirely, manually moving back to the ssl site still forces me to login again.</li>
<li>The second login using the exact same mechanism as the first, over ssl</li>
</ol>
<p>What I tried:</p>
<ol>
<li>Playing with Cake's settings for security.level and session.checkagent - nothing</li>
<li>Having cake store the sessions in db (as opposed to file system) - nothing</li>
<li>Testing in FF, IE, Chrome on an XP machine.</li>
</ol>
<p>So I feel like this is something related to the cookie being created but not being read. </p>
<p>Environment:
1. Debian
2. Apache 2
3. Mysql 4
4. PHP 5
5. CakePHP
6. Sessions are being saved PHP default, as files</p>
| [
{
"answer_id": 308671,
"author": "Piskvor left the building",
"author_id": 19746,
"author_profile": "https://Stackoverflow.com/users/19746",
"pm_score": 2,
"selected": false,
"text": "Secure"
},
{
"answer_id": 2153433,
"author": "monmonja",
"author_id": 258648,
"author_profile": "https://Stackoverflow.com/users/258648",
"pm_score": 0,
"selected": false,
"text": "<br />ini_set('session.name', Configure::read('Session.cookie'));\n<br />\nfrom session.php (/cake/lib/session.php, line 480~)\n"
},
{
"answer_id": 4239315,
"author": "simmerman",
"author_id": 515253,
"author_profile": "https://Stackoverflow.com/users/515253",
"pm_score": 2,
"selected": false,
"text": " if (env('HTTPS')) {\n ini_set('session.name', Configure::read('Session.cookie').'-SECURE');\n }else{\n ini_set('session.name', Configure::read('Session.cookie'));\n } \n"
},
{
"answer_id": 18256575,
"author": "Quy Le",
"author_id": 2361258,
"author_profile": "https://Stackoverflow.com/users/2361258",
"pm_score": 1,
"selected": false,
"text": "Configure::write('Session', array(\n 'defaults' => 'php',\n 'ini' => array(\n 'session.cookie_secure' => false\n )\n));\n"
}
] | 2008/11/21 | [
"https://Stackoverflow.com/questions/308659",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/43/"
] |
308,667 | <p>I need to make a Control which shows only an outline, and I need to place it over a control that's showing a video. If I make my Control transparent, then the video is obscured, because transparent controls are painted by their parent control and the video isn't painted by the control; it's shown using DirectShow or another library, so instead the parent control paints its BackColor.</p>
<p>So - can I make a control that doesn't get painted <em>at all</em>, except where it's opaque? That way, the parent control wouldn't paint over the video.</p>
<p>I know I could make the border out of four controls (or more if I want it dashed) but is it possible to do what I want using just one control?</p>
<hr>
<p>rslite is right - although you don't even need to go so far as to use PInvoke like his example does - the Control.Region property is entirely sufficient.</p>
| [
{
"answer_id": 308708,
"author": "Skizz",
"author_id": 1898,
"author_profile": "https://Stackoverflow.com/users/1898",
"pm_score": -1,
"selected": false,
"text": "Form.TransparencyKey"
},
{
"answer_id": 20849282,
"author": "Pieterjan De Clippel",
"author_id": 3147047,
"author_profile": "https://Stackoverflow.com/users/3147047",
"pm_score": 0,
"selected": false,
"text": "createparams InvalidateEx Imports System.Windows.Forms.Design\nImports System.Reflection\n Public Class TransparentControl : Inherits Control\n Protected Overrides ReadOnly Property CreateParams As CreateParams\n Get\n Dim cp As CreateParams = MyBase.CreateParams()\n cp.ExStyle = cp.ExStyle Or 32 'WS_EX_TRANSPARENT\n Return cp\n End Get\n End Property\n Protected Sub InvalidateEx(rct As Rectangle)\n Me.Invalidate(rct)\n If IsNothing(Parent) Then Exit Sub\n Parent.Invalidate(New Rectangle(Me.Location, rct.Size), True)\n End Sub\n Protected Sub InvalidateEx()\n Me.Invalidate()\n If IsNothing(Parent) Then Exit Sub\n Parent.Invalidate(New Rectangle(Me.Location, Me.Size), True)\n End Sub\n Protected Overrides Sub OnPaintBackground(pevent As PaintEventArgs)\n 'MyBase.OnPaintBackground(pevent)\n End Sub\n\n Protected Overrides Sub OnPaint(e As PaintEventArgs)\n MyBase.OnPaint(e)\n 'draw the layout on e.Graphics\n End Sub\n End Class\n"
}
] | 2008/11/21 | [
"https://Stackoverflow.com/questions/308667",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15371/"
] |
308,683 | <p>When I create a new <code>Date</code> object, it is initialized to the current time but in the local timezone. How can I get the current date and time in GMT?</p>
| [
{
"answer_id": 308689,
"author": "Jon Skeet",
"author_id": 22656,
"author_profile": "https://Stackoverflow.com/users/22656",
"pm_score": 10,
"selected": true,
"text": "java.util.Date java.util.Date java.util.Date Date.toString() SimpleDateFormat"
},
{
"answer_id": 308704,
"author": "user2427",
"author_id": 1356709,
"author_profile": "https://Stackoverflow.com/users/1356709",
"pm_score": 2,
"selected": false,
"text": "Calendar cal = Calendar.getInstance();\n cal Calendar cal2 = Calendar.getInstance(TimeZone.getTimeZone(\"GMT-2\"));\n cal.get(Calendar.DATE);"
},
{
"answer_id": 2140824,
"author": "mjh2007",
"author_id": 208977,
"author_profile": "https://Stackoverflow.com/users/208977",
"pm_score": 3,
"selected": false,
"text": "Calendar aGMTCalendar = Calendar.getInstance(TimeZone.getTimeZone(\"GMT\"));\n"
},
{
"answer_id": 2453820,
"author": "Ahmad Nadeem",
"author_id": 294674,
"author_profile": "https://Stackoverflow.com/users/294674",
"pm_score": 6,
"selected": false,
"text": " Calendar c = Calendar.getInstance();\n System.out.println(\"current: \"+c.getTime());\n\n TimeZone z = c.getTimeZone();\n int offset = z.getRawOffset();\n if(z.inDaylightTime(new Date())){\n offset = offset + z.getDSTSavings();\n }\n int offsetHrs = offset / 1000 / 60 / 60;\n int offsetMins = offset / 1000 / 60 % 60;\n\n System.out.println(\"offset: \" + offsetHrs);\n System.out.println(\"offset: \" + offsetMins);\n\n c.add(Calendar.HOUR_OF_DAY, (-offsetHrs));\n c.add(Calendar.MINUTE, (-offsetMins));\n\n System.out.println(\"GMT Time: \"+c.getTime());\n"
},
{
"answer_id": 2528480,
"author": "Dan",
"author_id": 303071,
"author_profile": "https://Stackoverflow.com/users/303071",
"pm_score": 8,
"selected": false,
"text": "SimpleDateFormat dateFormatGmt = new SimpleDateFormat(\"yyyy-MMM-dd HH:mm:ss\");\ndateFormatGmt.setTimeZone(TimeZone.getTimeZone(\"GMT\"));\n\n//Local time zone \nSimpleDateFormat dateFormatLocal = new SimpleDateFormat(\"yyyy-MMM-dd HH:mm:ss\");\n\n//Time in GMT\nreturn dateFormatLocal.parse( dateFormatGmt.format(new Date()) );\n"
},
{
"answer_id": 2585570,
"author": "simpatico",
"author_id": 300248,
"author_profile": "https://Stackoverflow.com/users/300248",
"pm_score": 4,
"selected": false,
"text": "Calendar aGMTCalendar = Calendar.getInstance(TimeZone.getTimeZone(\"GMT\"));\naGMTCalendar.getTime(); //or getTimeInMillis()\n Calendar aNotGMTCalendar = Calendar.getInstance(TimeZone.getTimeZone(\"GMT-2\"));aNotGMTCalendar.getTime();\n new Date(); //it's not GMT.\n"
},
{
"answer_id": 4124699,
"author": "Anthony",
"author_id": 203204,
"author_profile": "https://Stackoverflow.com/users/203204",
"pm_score": 6,
"selected": false,
"text": "SimpleDateFormat f = new SimpleDateFormat(\"yyyy-MMM-dd HH:mm:ss\");\nf.setTimeZone(TimeZone.getTimeZone(\"UTC\"));\nSystem.out.println(f.format(new Date()));\n"
},
{
"answer_id": 4498814,
"author": "Justin",
"author_id": 549847,
"author_profile": "https://Stackoverflow.com/users/549847",
"pm_score": 3,
"selected": false,
"text": "SimpleDateFormat dateFormatGmt = new SimpleDateFormat(\"yyyy-MM-dd\");\ndateFormatGmt.setTimeZone(TimeZone.getTimeZone(\"GMT\"));\nSystem.out.println(dateFormatGmt.format(date));\n"
},
{
"answer_id": 6697884,
"author": "Someone Somewhere",
"author_id": 550471,
"author_profile": "https://Stackoverflow.com/users/550471",
"pm_score": 7,
"selected": false,
"text": "static final String DATE_FORMAT = \"yyyy-MM-dd HH:mm:ss\";\n\npublic static Date getUTCdatetimeAsDate() {\n // note: doesn't check for null\n return stringDateToDate(getUTCdatetimeAsString());\n}\n\npublic static String getUTCdatetimeAsString() {\n final SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT);\n sdf.setTimeZone(TimeZone.getTimeZone(\"UTC\"));\n final String utcTime = sdf.format(new Date());\n\n return utcTime;\n}\n\npublic static Date stringDateToDate(String StrDate) {\n Date dateToReturn = null;\n SimpleDateFormat dateFormat = new SimpleDateFormat(DATEFORMAT);\n\n try {\n dateToReturn = (Date)dateFormat.parse(StrDate);\n }\n catch (ParseException e) {\n e.printStackTrace();\n }\n\n return dateToReturn;\n}\n"
},
{
"answer_id": 7700729,
"author": "so_mv",
"author_id": 186858,
"author_profile": "https://Stackoverflow.com/users/186858",
"pm_score": 2,
"selected": false,
"text": "import java.text.SimpleDateFormat;\nimport java.util.Calendar;\nimport java.util.Date;\nimport java.util.TimeZone;\n\npublic class TimZoneTest {\n public static void main (String[] args){\n //<GMT><+/-><hour>:<minutes>\n // Any screw up in this format, timezone defaults to GMT QUIETLY. So test your format a few times.\n\n System.out.println(my_time_in(\"GMT-5:00\", \"MM/dd/yyyy HH:mm:ss\") );\n System.out.println(my_time_in(\"GMT+5:30\", \"'at' HH:mm a z 'on' MM/dd/yyyy\"));\n\n System.out.println(\"---------------------------------------------\");\n // Alternate format \n System.out.println(my_time_in(\"America/Los_Angeles\", \"'at' HH:mm a z 'on' MM/dd/yyyy\") );\n System.out.println(my_time_in(\"America/Buenos_Aires\", \"'at' HH:mm a z 'on' MM/dd/yyyy\") );\n\n\n }\n\n public static String my_time_in(String target_time_zone, String format){\n TimeZone tz = TimeZone.getTimeZone(target_time_zone);\n Date date = Calendar.getInstance().getTime();\n SimpleDateFormat date_format_gmt = new SimpleDateFormat(format);\n date_format_gmt.setTimeZone(tz);\n return date_format_gmt.format(date);\n }\n\n}\n 10/08/2011 21:07:21\nat 07:37 AM GMT+05:30 on 10/09/2011\nat 19:07 PM PDT on 10/08/2011\nat 23:07 PM ART on 10/08/2011\n"
},
{
"answer_id": 10186364,
"author": "nithinreddy",
"author_id": 583344,
"author_profile": "https://Stackoverflow.com/users/583344",
"pm_score": 3,
"selected": false,
"text": "SimpleDateFormat dateFormatGmt = new SimpleDateFormat(\"dd:MM:yyyy HH:mm:ss\");\ndateFormatGmt.setTimeZone(TimeZone.getTimeZone(\"GMT\"));\nSystem.out.println(dateFormatGmt.format(new Date())+\"\");\n"
},
{
"answer_id": 10447421,
"author": "huljas",
"author_id": 884141,
"author_profile": "https://Stackoverflow.com/users/884141",
"pm_score": 3,
"selected": false,
"text": "import org.joda.time.DateTimeZone;\nimport java.util.Date;\n\n...\n\nDate local = new Date();\nSystem.out.println(\"Local: \" + local);\nDateTimeZone zone = DateTimeZone.getDefault();\nlong utc = zone.convertLocalToUTC(local.getTime(), false);\nSystem.out.println(\"UTC: \" + new Date(utc));\n"
},
{
"answer_id": 10514345,
"author": "Rene",
"author_id": 1384339,
"author_profile": "https://Stackoverflow.com/users/1384339",
"pm_score": 3,
"selected": false,
"text": "import java.sql.Timestamp;\nimport java.util.Calendar;\n\n...\n\nprivate static Timestamp getGMT() {\n Calendar cal = Calendar.getInstance();\n return new Timestamp(cal.getTimeInMillis()\n -cal.get(Calendar.ZONE_OFFSET)\n -cal.get(Calendar.DST_OFFSET));\n}\n"
},
{
"answer_id": 10636276,
"author": "Ovidiu Latcu",
"author_id": 542091,
"author_profile": "https://Stackoverflow.com/users/542091",
"pm_score": 2,
"selected": false,
"text": "Date UTC Calendar Calendar.getInstance(TimeZone.getTimeZone(\"UTC\"));\n Calendar TimeZone Date getTime()"
},
{
"answer_id": 10707492,
"author": "Dana Wilson",
"author_id": 1410897,
"author_profile": "https://Stackoverflow.com/users/1410897",
"pm_score": 3,
"selected": false,
"text": "java.util.Date Date.toString() System.out.println(new java.util.Date().getHours() + \" hours\");\n Calendar SimpleDateFormat System.out.println(Calendar.getInstance(TimeZone.getTimeZone(\"GMT\"))\n .get(Calendar.HOUR_OF_DAY) + \" Hours\");\n getTime.getHours() Date()"
},
{
"answer_id": 12667316,
"author": "shahtapa",
"author_id": 1710772,
"author_profile": "https://Stackoverflow.com/users/1710772",
"pm_score": 3,
"selected": false,
"text": "String DATE_FORMAT = \"EEE, dd MMM yyyy HH:mm:ss z\" ;\nfinal SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT);\nsdf.setTimeZone(TimeZone.getTimeZone(\"GMT\"));\nString dateTimeString = sdf.format(new Date());\n"
},
{
"answer_id": 15615331,
"author": "Bogdan",
"author_id": 1809496,
"author_profile": "https://Stackoverflow.com/users/1809496",
"pm_score": 2,
"selected": false,
"text": " Date currDate;\n SimpleDateFormat dateFormatGmt = new SimpleDateFormat(\"yyyy-MMM-dd HH:mm:ss\");\n dateFormatGmt.setTimeZone(TimeZone.getTimeZone(\"GMT\"));\n SimpleDateFormat dateFormatLocal = new SimpleDateFormat(\"yyyy-MMM-dd HH:mm:ss\");\n\n long currTime = 0;\n try {\n\n currDate = dateFormatLocal.parse( dateFormatGmt.format(new Date()) );\n currTime = currDate.getTime();\n } catch (ParseException e) {\n // TODO Auto-generated catch block\n e.printStackTrace();\n }\n"
},
{
"answer_id": 16595970,
"author": "moberme",
"author_id": 901442,
"author_profile": "https://Stackoverflow.com/users/901442",
"pm_score": 4,
"selected": false,
"text": "Calendar c = Calendar.getInstance();\nint utcOffset = c.get(Calendar.ZONE_OFFSET) + c.get(Calendar.DST_OFFSET); \nLong utcMilliseconds = c.getTimeInMillis() + utcOffset;\n"
},
{
"answer_id": 19607953,
"author": "Adam",
"author_id": 226513,
"author_profile": "https://Stackoverflow.com/users/226513",
"pm_score": 4,
"selected": false,
"text": "import java.text.ParseException;\nimport java.text.SimpleDateFormat;\nimport java.util.Date;\nimport java.util.TimeZone;\n\n\npublic class Test\n{\n public static void main(final String[] args) throws ParseException\n {\n final SimpleDateFormat f = new SimpleDateFormat(\"yyyy-MM-dd HH:mm:ss z\");\n f.setTimeZone(TimeZone.getTimeZone(\"UTC\"));\n System.out.println(f.format(new Date()));\n }\n}\n 2013-10-26 14:37:48 UTC\n"
},
{
"answer_id": 19632076,
"author": "Basil Bourque",
"author_id": 642706,
"author_profile": "https://Stackoverflow.com/users/642706",
"pm_score": 9,
"selected": false,
"text": "Instant.now() // Capture the current moment in UTC. \n Instant.now().toString() \n toString java.util.Date j.u.Calendar java.text.SimpleDateFormat Instant instant = Instant.now();\n Instant Clock toString ZoneOffset.UTC OffsetDateTime OffsetDateTime now = OffsetDateTime.now( ZoneOffset.UTC );\n System.out.println( \"now.toString(): \" + now );\n now.toString(): 2014-01-21T23:42:03.522Z\n java.util.Date Calendar SimpleDateFormat java.sql.* Interval YearWeek YearQuarter System.out.println( \"UTC/GMT date-time in ISO 8601 format: \" + new org.joda.time.DateTime( org.joda.time.DateTimeZone.UTC ) );\n org.joda.time.DateTime now = new org.joda.time.DateTime(); // Default time zone.\norg.joda.time.DateTime zulu = now.toDateTime( org.joda.time.DateTimeZone.UTC );\n System.out.println( \"Local time in ISO 8601 format: \" + now );\nSystem.out.println( \"Same moment in UTC (Zulu): \" + zulu );\n Local time in ISO 8601 format: 2014-01-21T15:34:29.933-08:00\nSame moment in UTC (Zulu): 2014-01-21T23:34:29.933Z\n now() DateTimeZone DateTimeZone zoneMontréal = DateTimeZone.forID( \"America/Montreal\" );\nDateTime now = DateTime.now( zoneMontréal );\n DateTime now = DateTime.now( DateTimeZone.UTC );\n DateTimeZone zoneDefault = DateTimeZone.getDefault();\n toString"
},
{
"answer_id": 19735955,
"author": "Ingo",
"author_id": 2278668,
"author_profile": "https://Stackoverflow.com/users/2278668",
"pm_score": 1,
"selected": false,
"text": "import java.net.DatagramPacket;\nimport java.net.DatagramSocket;\nimport java.net.InetAddress;\n\n\nclass NTP_UTC_Time\n{\nprivate static final String TAG = \"SntpClient\";\n\nprivate static final int RECEIVE_TIME_OFFSET = 32;\nprivate static final int TRANSMIT_TIME_OFFSET = 40;\nprivate static final int NTP_PACKET_SIZE = 48;\n\nprivate static final int NTP_PORT = 123;\nprivate static final int NTP_MODE_CLIENT = 3;\nprivate static final int NTP_VERSION = 3;\n\n// Number of seconds between Jan 1, 1900 and Jan 1, 1970\n// 70 years plus 17 leap days\nprivate static final long OFFSET_1900_TO_1970 = ((365L * 70L) + 17L) * 24L * 60L * 60L;\n\nprivate long mNtpTime;\n\npublic boolean requestTime(String host, int timeout) {\n try {\n DatagramSocket socket = new DatagramSocket();\n socket.setSoTimeout(timeout);\n InetAddress address = InetAddress.getByName(host);\n byte[] buffer = new byte[NTP_PACKET_SIZE];\n DatagramPacket request = new DatagramPacket(buffer, buffer.length, address, NTP_PORT);\n\n buffer[0] = NTP_MODE_CLIENT | (NTP_VERSION << 3);\n\n writeTimeStamp(buffer, TRANSMIT_TIME_OFFSET);\n\n socket.send(request);\n\n // read the response\n DatagramPacket response = new DatagramPacket(buffer, buffer.length);\n socket.receive(response); \n socket.close();\n\n mNtpTime = readTimeStamp(buffer, RECEIVE_TIME_OFFSET); \n } catch (Exception e) {\n // if (Config.LOGD) Log.d(TAG, \"request time failed: \" + e);\n return false;\n }\n\n return true;\n}\n\n\npublic long getNtpTime() {\n return mNtpTime;\n}\n\n\n/**\n * Reads an unsigned 32 bit big endian number from the given offset in the buffer.\n */\nprivate long read32(byte[] buffer, int offset) {\n byte b0 = buffer[offset];\n byte b1 = buffer[offset+1];\n byte b2 = buffer[offset+2];\n byte b3 = buffer[offset+3];\n\n // convert signed bytes to unsigned values\n int i0 = ((b0 & 0x80) == 0x80 ? (b0 & 0x7F) + 0x80 : b0);\n int i1 = ((b1 & 0x80) == 0x80 ? (b1 & 0x7F) + 0x80 : b1);\n int i2 = ((b2 & 0x80) == 0x80 ? (b2 & 0x7F) + 0x80 : b2);\n int i3 = ((b3 & 0x80) == 0x80 ? (b3 & 0x7F) + 0x80 : b3);\n\n return ((long)i0 << 24) + ((long)i1 << 16) + ((long)i2 << 8) + (long)i3;\n}\n\n/**\n * Reads the NTP time stamp at the given offset in the buffer and returns \n * it as a system time (milliseconds since January 1, 1970).\n */ \nprivate long readTimeStamp(byte[] buffer, int offset) {\n long seconds = read32(buffer, offset);\n long fraction = read32(buffer, offset + 4);\n return ((seconds - OFFSET_1900_TO_1970) * 1000) + ((fraction * 1000L) / 0x100000000L); \n}\n\n/**\n * Writes 0 as NTP starttime stamp in the buffer. --> Then NTP returns Time OFFSET since 1900\n */ \nprivate void writeTimeStamp(byte[] buffer, int offset) { \n int ofs = offset++;\n\n for (int i=ofs;i<(ofs+8);i++)\n buffer[i] = (byte)(0); \n}\n\n}\n long now = 0;\n\n NTP_UTC_Time client = new NTP_UTC_Time();\n\n if (client.requestTime(\"pool.ntp.org\", 2000)) { \n now = client.getNtpTime();\n }\n private String get_UTC_Datetime_from_timestamp(long timeStamp){\n\n try{\n\n Calendar cal = Calendar.getInstance();\n TimeZone tz = cal.getTimeZone();\n\n int tzt = tz.getOffset(System.currentTimeMillis());\n\n timeStamp -= tzt;\n\n // DateFormat sdf = new SimpleDateFormat(\"yyyy-MM-dd HH:mm:ss\",Locale.getDefault());\n DateFormat sdf = new SimpleDateFormat();\n Date netDate = (new Date(timeStamp));\n return sdf.format(netDate);\n }\n catch(Exception ex){\n return \"\";\n }\n } \n String UTC_DateTime = get_UTC_Datetime_from_timestamp(now);\n"
},
{
"answer_id": 20996588,
"author": "My God",
"author_id": 1538553,
"author_profile": "https://Stackoverflow.com/users/1538553",
"pm_score": 2,
"selected": false,
"text": "DateTimeFormatter formatter = DateTimeFormat.forPattern(\"yyyy-MM-dd'T'HH:mm:ss.SSS'Z'\");\n\nDateTimeZone dateTimeZone = DateTimeZone.getDefault(); //Default Time Zone\n\nDateTime currDateTime = new DateTime(); //Current DateTime\n\nlong utcTime = dateTimeZone.convertLocalToUTC(currDateTime .getMillis(), false);\n\nString currTime = formatter.print(utcTime); //UTC time converted to string from long in format of formatter\n\ncurrDateTime = formatter.parseDateTime(currTime); //Converted to DateTime in UTC\n"
},
{
"answer_id": 23881937,
"author": "Gal Rom",
"author_id": 3093939,
"author_profile": "https://Stackoverflow.com/users/3093939",
"pm_score": 1,
"selected": false,
"text": "public static String GetCurrentTimeStamp()\n{\n Calendar cal=Calendar.getInstance();\n long offset = cal.getTimeZone().getOffset(System.currentTimeMillis());//if you want in UTC else remove it .\n return new java.sql.Timestamp(System.currentTimeMillis()+offset).toString(); \n}\n"
},
{
"answer_id": 31289752,
"author": "Managarm",
"author_id": 2061551,
"author_profile": "https://Stackoverflow.com/users/2061551",
"pm_score": 0,
"selected": false,
"text": "long instant = DateTimeZone.UTC.getMillisKeepLocal(DateTimeZone.getDefault(), System.currentTimeMillis());\n"
},
{
"answer_id": 31935095,
"author": "Matthias van der Vlies",
"author_id": 53702,
"author_profile": "https://Stackoverflow.com/users/53702",
"pm_score": 1,
"selected": false,
"text": "final Date gmt = new Timestamp(System.currentTimeMillis()\n - Calendar.getInstance().getTimeZone()\n .getOffset(System.currentTimeMillis()));\n"
},
{
"answer_id": 39253241,
"author": "Ashallar",
"author_id": 5669587,
"author_profile": "https://Stackoverflow.com/users/5669587",
"pm_score": 3,
"selected": false,
"text": " public static Date toUTC(Date date){\n long datems = date.getTime();\n long timezoneoffset = TimeZone.getDefault().getOffset(datems);\n datems -= timezoneoffset;\n return new Date(datems);\n}\n"
},
{
"answer_id": 40128836,
"author": "Arjun Singh",
"author_id": 7041660,
"author_profile": "https://Stackoverflow.com/users/7041660",
"pm_score": 2,
"selected": false,
"text": "public static void main(String args[]){\n LocalDate date=LocalDate.now(); \n System.out.println(\"Current date = \"+date);\n}\n"
},
{
"answer_id": 51165321,
"author": "santoshlokhande",
"author_id": 8659540,
"author_profile": "https://Stackoverflow.com/users/8659540",
"pm_score": 1,
"selected": false,
"text": "public class CurrentUtcDate \n{\n public static void main(String[] args) {\n Date date = new Date();\n SimpleDateFormat dateFormat = new SimpleDateFormat(\"dd-MM-yyyy HH:mm:ss\");\n dateFormat.setTimeZone(TimeZone.getTimeZone(\"UTC\"));\n System.out.println(\"UTC Time is: \" + dateFormat.format(date));\n }\n}\n UTC Time is: 22-01-2018 13:14:35\n"
},
{
"answer_id": 53110451,
"author": "Asif",
"author_id": 3792674,
"author_profile": "https://Stackoverflow.com/users/3792674",
"pm_score": 0,
"selected": false,
"text": "ZonedDateTime now = ZonedDateTime.now( ZoneOffset.UTC ); LocalDateTime now2 = LocalDateTime.now( ZoneOffset.UTC );"
},
{
"answer_id": 54978787,
"author": "Arefe",
"author_id": 2746110,
"author_profile": "https://Stackoverflow.com/users/2746110",
"pm_score": 1,
"selected": false,
"text": "Instant.now().toString().replaceAll(\"T.*\", \"\");\n"
},
{
"answer_id": 70783077,
"author": "JohnPan",
"author_id": 2149492,
"author_profile": "https://Stackoverflow.com/users/2149492",
"pm_score": 1,
"selected": false,
"text": " ZonedDateTime now = ZonedDateTime.now();\n Date nowUTC = new Date(1000 * (now.toEpochSecond() - now.getOffset().getTotalSeconds()));\n Date nowUTC = Date.from(ZonedDateTime.now().toInstant());\n"
},
{
"answer_id": 71626343,
"author": "Ammar",
"author_id": 14190819,
"author_profile": "https://Stackoverflow.com/users/14190819",
"pm_score": 2,
"selected": false,
"text": "private static final DateTimeFormatter FORMATTER\n = DateTimeFormatter.ofPattern(\"dd-MM-uuuu HH:mm:ss z\");\n\npublic static String getUtcDateTime() {\n return ZonedDateTime.now(ZoneId.of(\"Etc/UTC\")).format(FORMATTER);\n}\n 26-03-2022 17:38:55 UTC\n public String getUTC_DateTime() {\n SimpleDateFormat dateTimeFormat = new SimpleDateFormat(\"dd-MM-yyyy HH:mm:ss z\");\n dateTimeFormat.setTimeZone(TimeZone.getTimeZone(\"UTC\"));//gmt\n return dateTimeFormat.format(new Date());\n\n}\n 26-03-2022 08:07:21 UTC \n"
}
] | 2008/11/21 | [
"https://Stackoverflow.com/questions/308683",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19888/"
] |
308,695 | <p>I'm working in C, and I have to concatenate a few things.</p>
<p>Right now I have this:</p>
<pre><code>message = strcat("TEXT ", var);
message2 = strcat(strcat("TEXT ", foo), strcat(" TEXT ", bar));
</code></pre>
<p>Now if you have experience in C I'm sure you realize that this gives you a segmentation fault when you try to run it. So how do I work around that?</p>
| [
{
"answer_id": 308712,
"author": "Brian R. Bondy",
"author_id": 3153,
"author_profile": "https://Stackoverflow.com/users/3153",
"pm_score": 10,
"selected": true,
"text": "char strcat src dest char *strcat(char *dest, const char *src);\n char str[80];\nstrcpy(str, \"these \");\nstrcat(str, \"strings \");\nstrcat(str, \"are \");\nstrcat(str, \"concatenated.\");\n char buffer[1024]; strcpy_s strcat_s strcat strcat(strcat(str, foo), bar);\n char *foo = \"foo\";\nchar *bar = \"bar\";\nchar str[80];\nstrcpy(str, \"TEXT \");\nstrcat(str, foo);\nstrcat(str, bar);\n"
},
{
"answer_id": 308718,
"author": "paxdiablo",
"author_id": 14860,
"author_profile": "https://Stackoverflow.com/users/14860",
"pm_score": 3,
"selected": false,
"text": "strcat (\"Hello, \", name);\n name \"Hello, \" char message[1000];\nstrcpy (message, \"TEXT \");\nstrcat (message, var);\n const static char TEXT[] = \"TEXT \";\n\n// Make *sure* you have enough space.\n\nchar *message = malloc (sizeof(TEXT) + strlen(var) + 1);\nif (message == NULL)\n handleOutOfMemoryIntelligently();\nstrcpy (message, TEXT);\nstrcat (message, var);\n\n// Need to free message at some point after you're done with it.\n"
},
{
"answer_id": 308719,
"author": "Pieter",
"author_id": 5822,
"author_profile": "https://Stackoverflow.com/users/5822",
"pm_score": 2,
"selected": false,
"text": "char bigEnough[64] = \"\";\n\nstrcat(bigEnough, \"TEXT\");\nstrcat(bigEnough, foo);\n\n/* and so on */\n"
},
{
"answer_id": 308722,
"author": "Todd",
"author_id": 30841,
"author_profile": "https://Stackoverflow.com/users/30841",
"pm_score": 2,
"selected": false,
"text": "Pointer to the destination array, which should contain a C string, and be large enough to contain the concatenated resulting string.\n"
},
{
"answer_id": 308732,
"author": "Alex B",
"author_id": 23643,
"author_profile": "https://Stackoverflow.com/users/23643",
"pm_score": 8,
"selected": false,
"text": "strcat snprintf char buf[256];\nsnprintf(buf, sizeof(buf), \"%s%s%s%s\", str1, str2, str3, str4);\n"
},
{
"answer_id": 308761,
"author": "Ralf",
"author_id": 39645,
"author_profile": "https://Stackoverflow.com/users/39645",
"pm_score": 3,
"selected": false,
"text": "strcat message = strcat(\"TEXT \" + var);\n message2 = strcat(strcat(\"TEXT \", foo), strcat(\" TEXT \", bar));\n sprintf(message2, \"TEXT %s TEXT %s\", foo, bar);\n sprintf"
},
{
"answer_id": 308792,
"author": "David Rodríguez - dribeas",
"author_id": 36565,
"author_profile": "https://Stackoverflow.com/users/36565",
"pm_score": 3,
"selected": false,
"text": "char out[1024] = \"\"; // must be initialized\nstrcat( out, null_terminated_string ); \n// null_terminated_string has less than 1023 chars\n"
},
{
"answer_id": 309105,
"author": "Reed Hedges",
"author_id": 39686,
"author_profile": "https://Stackoverflow.com/users/39686",
"pm_score": 4,
"selected": false,
"text": "#include <stdio.h>\n#include <string.h>\n\nvoid example(const char *header, const char **words, size_t num_words)\n{\n size_t message_len = strlen(header) + 1; /* + 1 for terminating NULL */\n char *message = (char*) malloc(message_len);\n strncat(message, header, message_len);\n\n for(int i = 0; i < num_words; ++i)\n {\n message_len += 1 + strlen(words[i]); /* 1 + for separator ';' */\n message = (char*) realloc(message, message_len);\n strncat(strncat(message, \";\", message_len), words[i], message_len);\n }\n\n puts(message);\n\n free(message);\n}\n"
},
{
"answer_id": 8421784,
"author": "Nils",
"author_id": 44232,
"author_profile": "https://Stackoverflow.com/users/44232",
"pm_score": 3,
"selected": false,
"text": "#include <string.h>\n#include <stdio.h>\n#include <stdlib.h>\n\nvoid appendToHello(const char *s) {\n const char *const hello = \"hello \";\n\n const size_t sLength = strlen(s);\n const size_t helloLength = strlen(hello);\n const size_t totalLength = sLength + helloLength;\n\n char *const strBuf = malloc(totalLength + 1);\n if (strBuf == NULL) {\n fprintf(stderr, \"malloc failed\\n\");\n exit(EXIT_FAILURE);\n }\n\n strcpy(strBuf, hello);\n strcpy(strBuf + helloLength, s);\n\n puts(strBuf);\n\n free(strBuf);\n\n}\n\nint main (void) {\n appendToHello(\"blah blah\");\n return 0;\n}\n"
},
{
"answer_id": 15870295,
"author": "Nico Cvitak",
"author_id": 2255949,
"author_profile": "https://Stackoverflow.com/users/2255949",
"pm_score": 3,
"selected": false,
"text": "char* concat(const char* str1, const char* str2)\n{\n char* result;\n asprintf(&result, \"%s%s\", str1, str2);\n return result;\n}\n"
},
{
"answer_id": 22988390,
"author": "jksante",
"author_id": 3519509,
"author_profile": "https://Stackoverflow.com/users/3519509",
"pm_score": 1,
"selected": false,
"text": "#include <stdio.h>\n#include <string.h>\n\nint main(int argc, const char * argv[])\n{\n // Insert code here...\n char firstname[100], secondname[100];\n printf(\"Enter First Name: \");\n fgets(firstname, 100, stdin);\n printf(\"Enter Second Name: \");\n fgets(secondname,100,stdin);\n firstname[strlen(firstname)-1]= '\\0';\n printf(\"fullname is %s %s\", firstname, secondname);\n\n return 0;\n}\n"
},
{
"answer_id": 27467065,
"author": "technosaurus",
"author_id": 1162141,
"author_profile": "https://Stackoverflow.com/users/1162141",
"pm_score": 1,
"selected": false,
"text": "<<cout<<like *printf snprintf() #include <unistd.h> //for the write example\n//note: you should check if offset==sizeof(buf) after use\n#define strcpyALL(buf, offset, ...) do{ \\\n char *bp=(char*)(buf+offset); /*so we can add to the end of a string*/ \\\n const char *s, \\\n *a[] = { __VA_ARGS__,NULL}, \\\n **ss=a; \\\n while((s=*ss++)) \\\n while((*s)&&(++offset<(int)sizeof(buf))) \\\n *bp++=*s++; \\\n if (offset!=sizeof(buf))*bp=0; \\\n}while(0)\n\nchar buf[256];\nint len=0;\n\nstrcpyALL(buf,len,\n \"The config file is in:\\n\\t\",getenv(\"HOME\"),\"/.config/\",argv[0],\"/config.rc\\n\"\n);\nif (len<sizeof(buf))\n write(1,buf,len); //outputs our message to stdout\nelse\n write(2,\"error\\n\",6);\n\n//but we can keep adding on because we kept track of the length\n//this allows printf-like buffering to minimize number of syscalls to write\n//set len back to 0 if you don't want this behavior\nstrcpyALL(buf,len,\"Thanks for using \",argv[0],\"!\\n\");\nif (len<sizeof(buf))\n write(1,buf,len); //outputs both messages\nelse\n write(2,\"error\\n\",6);\n"
},
{
"answer_id": 32665978,
"author": "dbagnara",
"author_id": 5353133,
"author_profile": "https://Stackoverflow.com/users/5353133",
"pm_score": 6,
"selected": false,
"text": "#define SCHEMA \"test\"\n#define TABLE \"data\"\n\nconst char *table = SCHEMA \".\" TABLE ; // note no + or . or anything\nconst char *qry = // include comments in a string\n \" SELECT * \" // get all fields\n \" FROM \" SCHEMA \".\" TABLE /* the table */\n \" WHERE x = 1 \" /* the filter */ \n ;\n"
},
{
"answer_id": 38659116,
"author": "Donald Duck",
"author_id": 4284627,
"author_profile": "https://Stackoverflow.com/users/4284627",
"pm_score": 2,
"selected": false,
"text": "strcat() #define MAX_STRING_LENGTH 1000\nchar *strcat_const(const char *str1,const char *str2){\n static char buffer[MAX_STRING_LENGTH];\n strncpy(buffer,str1,MAX_STRING_LENGTH);\n if(strlen(str1) < MAX_STRING_LENGTH){\n strncat(buffer,str2,MAX_STRING_LENGTH - strlen(buffer));\n }\n buffer[MAX_STRING_LENGTH - 1] = '\\0';\n return buffer;\n}\n\nint main(int argc,char *argv[]){\n printf(\"%s\",strcat_const(\"Hello \",\"world\")); //Prints \"Hello world\"\n return 0;\n}\n MAX_STRING_LENGTH"
},
{
"answer_id": 40431747,
"author": "Miljan Rakita",
"author_id": 2001856,
"author_profile": "https://Stackoverflow.com/users/2001856",
"pm_score": 1,
"selected": false,
"text": "int main()\n{\n char input[100];\n gets(input);\n\n char str[101];\n strcpy(str, \" \");\n strcat(str, input);\n\n char *p = str;\n\n while(*p) {\n if(*p == ' ' && isalpha(*(p+1)) != 0)\n printf(\"%c\",*(p+1));\n p++;\n }\n\n return 0;\n}\n"
},
{
"answer_id": 41410139,
"author": "Naheel",
"author_id": 3825872,
"author_profile": "https://Stackoverflow.com/users/3825872",
"pm_score": 0,
"selected": false,
"text": "#include <stdlib.h>\n#include <stdarg.h>\n\nchar *strconcat(int num_args, ...) {\n int strsize = 0;\n va_list ap;\n va_start(ap, num_args);\n for (int i = 0; i < num_args; i++) \n strsize += strlen(va_arg(ap, char*));\n\n char *res = malloc(strsize+1);\n strsize = 0;\n va_start(ap, num_args);\n for (int i = 0; i < num_args; i++) {\n char *s = va_arg(ap, char*);\n strcpy(res+strsize, s);\n strsize += strlen(s);\n }\n va_end(ap);\n res[strsize] = '\\0';\n\n return res;\n}\n char *str = strconcat(3, \"testing \", \"this \", \"thing\");\n"
}
] | 2008/11/21 | [
"https://Stackoverflow.com/questions/308695",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2128/"
] |
308,703 | <p>Is there a way to change all the numeric keys to "Name" without looping through the array (so a php function)?</p>
<pre><code>[
0 => 'blabla',
1 => 'blabla',
2 => 'blblll',
// etc ...
]
</code></pre>
| [
{
"answer_id": 308731,
"author": "Kent Fredric",
"author_id": 15614,
"author_profile": "https://Stackoverflow.com/users/15614",
"pm_score": 5,
"selected": false,
"text": "$x =array(); \n$x['foo'] = 'bar' ; \n$x['foo'] = 'baz' ; #replaces 'bar'\n $x[0] --> $x['foo_0'] \n function rekey( $input , $prefix ) { \n $out = array(); \n foreach( $input as $i => $v ) { \n if ( is_numeric( $i ) ) { \n $out[$prefix . $i] = $v; \n continue; \n }\n $out[$i] = $v;\n }\n return $out;\n}\n <section> \n <foo_0></foo_0>\n <foo_1></foo_1>\n <bar></bar>\n <foo_2></foo_2>\n</section>\n <section> \n <foo></foo>\n <foo></foo>\n <bar></bar>\n <foo></foo>\n</section>\n section => { \n 0 => [ foo , {} ]\n 1 => [ foo , {} ]\n 2 => [ bar , {} ]\n 3 => [ foo , {} ] \n}\n"
},
{
"answer_id": 308757,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "XMLWriter PHP 5.2.x $xml->startElement('itemName');"
},
{
"answer_id": 308766,
"author": "Sebastian Hoitz",
"author_id": 9535,
"author_profile": "https://Stackoverflow.com/users/9535",
"pm_score": -1,
"selected": false,
"text": "<?php\n$array = array();\n$array['name'] = $oldArray;\n?>\n"
},
{
"answer_id": 308794,
"author": "Eric Goodwin",
"author_id": 1430,
"author_profile": "https://Stackoverflow.com/users/1430",
"pm_score": 7,
"selected": false,
"text": "array_combine $list = array_combine($keys, array_values($list));\n array_values foreach ($list as $k => $v) {\n unset ($list[$k]);\n\n $new_key = *some logic here*\n\n $list[$new_key] = $v;\n}\n"
},
{
"answer_id": 1642522,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "array_flip $array = array ( [1] => Sell [2] => Buy [3] => Rent [4] => Jobs )\nprint_r(array_flip($array));\nArray ( [Sell] => 1 [Buy] => 2 [Rent] => 3 [Jobs] => 4 ) \n"
},
{
"answer_id": 2549699,
"author": "intel",
"author_id": 305599,
"author_profile": "https://Stackoverflow.com/users/305599",
"pm_score": 2,
"selected": false,
"text": "$a = array(1=>'first_name', 2=>'last_name');\n$a = array_flip($a);\n\n$a['first_name'] = 3;\n$a = array_flip($a);\n\nprint_r($a);\n"
},
{
"answer_id": 10440168,
"author": "Darren Cato",
"author_id": 111291,
"author_profile": "https://Stackoverflow.com/users/111291",
"pm_score": 1,
"selected": false,
"text": "public function transform($key, $results)\n{\n foreach($results as $k=>$result)\n {\n if( property_exists($result, $key) )\n { \n $results[$result->$key] = $result;\n unset($results[$k]);\n }\n }\n\n return $results;\n}\n"
},
{
"answer_id": 14227644,
"author": "dingyuchi",
"author_id": 1244579,
"author_profile": "https://Stackoverflow.com/users/1244579",
"pm_score": 2,
"selected": false,
"text": "<?php\necho json_encode($data);\n\nfunction array_change_key_name( $orig, $new, &$array ) {\n foreach ( $array as $k => $v ) {\n $res[ $k === $orig ? $new : $k ] = ( (is_array($v)||is_object($v)) ? array_change_key_name( $orig, $new, $v ) : $v );\n }\n return $res;\n}\n\necho '<br>=====change \"group\" to \"children\"=====<br>';\n$new = array_change_key_name(\"group\" ,\"children\" , $data);\necho json_encode($new);\n?>\n {\"benchmark\":[{\"idText\":\"USGCB-Windows-7\",\"title\":\"USGCB: Guidance for Securing Microsoft Windows 7 Systems for IT Professional\",\"profile\":[{\"idText\":\"united_states_government_configuration_baseline_version_1.2.0.0\",\"title\":\"United States Government Configuration Baseline 1.2.0.0\",\"group\":[{\"idText\":\"security_components_overview\",\"title\":\"Windows 7 Security Components Overview\",\"group\":[{\"idText\":\"new_features\",\"title\":\"New Features in Windows 7\"}]},{\"idText\":\"usgcb_security_settings\",\"title\":\"USGCB Security Settings\",\"group\":[{\"idText\":\"account_policies_group\",\"title\":\"Account Policies group\"}]}]}]}]}\n\n=====change \"group\" to \"children\"=====\n\n{\"benchmark\":[{\"idText\":\"USGCB-Windows-7\",\"title\":\"USGCB: Guidance for Securing Microsoft Windows 7 Systems for IT Professional\",\"profile\":[{\"idText\":\"united_states_government_configuration_baseline_version_1.2.0.0\",\"title\":\"United States Government Configuration Baseline 1.2.0.0\",\"children\":[{\"idText\":\"security_components_overview\",\"title\":\"Windows 7 Security Components Overview\",\"children\":[{\"idText\":\"new_features\",\"title\":\"New Features in Windows 7\"}]},{\"idText\":\"usgcb_security_settings\",\"title\":\"USGCB Security Settings\",\"children\":[{\"idText\":\"account_policies_group\",\"title\":\"Account Policies group\"}]}]}]}]}\n"
},
{
"answer_id": 27720168,
"author": "Aurelien",
"author_id": 4408140,
"author_profile": "https://Stackoverflow.com/users/4408140",
"pm_score": 3,
"selected": false,
"text": "array_combine array_map $prefix = '_';\n$arr = array_combine(\n array_map(function($v) use ($prefix){\n return $prefix.$v;\n }, array_keys($arr)),\n array_values($arr)\n);\n"
},
{
"answer_id": 30805343,
"author": "Red Web",
"author_id": 2447633,
"author_profile": "https://Stackoverflow.com/users/2447633",
"pm_score": 1,
"selected": false,
"text": "<?php\n $array[$new_key] = $array[$old_key];\n unset($array[$old_key]);\n?>\n"
},
{
"answer_id": 30990779,
"author": "Ligemer",
"author_id": 2085469,
"author_profile": "https://Stackoverflow.com/users/2085469",
"pm_score": 3,
"selected": false,
"text": "$inputArray = array('app_test' => 'test', 'app_two' => 'two');\n\n/**\n * Used to remap keys of an array by removing the prefix passed in\n * \n * Example:\n * $inputArray = array('app_test' => 'test', 'app_two' => 'two');\n * $keys = array_keys($inputArray);\n * array_walk($keys, 'removePrefix', 'app_');\n * $remappedArray = array_combine($keys, $inputArray);\n *\n * @param $value - key value to replace, should be from array_keys\n * @param $omit - unused, needed for prefix call\n * @param $prefix - prefix to string replace in keys\n */\nfunction removePrefix(&$value, $omit, $prefix) {\n $value = str_replace($prefix, '', $value);\n}\n\n// first get all the keys to remap\n$keys = array_keys($inputArray);\n\n// perform internal iteration with prefix passed into walk function for dynamic replace of key\narray_walk($keys, 'removePrefix', 'app_');\n\n// combine the rewritten keys and overwrite the originals\n$remappedArray = array_combine($keys, $inputArray);\n\n// see full output of comparison\nvar_dump($inputArray);\nvar_dump($remappedArray);\n array(2) {\n 'attr_test' =>\n string(4) \"test\"\n 'attr_two' =>\n string(3) \"two\"\n}\narray(2) {\n 'test' =>\n string(4) \"test\"\n 'two' =>\n string(3) \"two\"\n}\n"
},
{
"answer_id": 44381156,
"author": "Jeffrey",
"author_id": 7352723,
"author_profile": "https://Stackoverflow.com/users/7352723",
"pm_score": 1,
"selected": false,
"text": "for ($i = 0; $i < count($array); $i++) {\n $newArray[] = ['name' => $array[$i]];\n};\n 0 => array:1 [\"name\" => \"blabla\"]\n1 => array:1 [\"name\" => \"blabla\"]\n2 => array:1 [\"name\" => \"blblll\"]\n"
}
] | 2008/11/21 | [
"https://Stackoverflow.com/questions/308703",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
308,739 | <p>Could some one tell me how to capture SOAP messages passed between the client and the server webservice applications.</p>
<p>I tried using both tools.
pocket soap
<a href="http://www.pocketsoap.com/pocketsoap/" rel="nofollow noreferrer">http://www.pocketsoap.com/pocketsoap/</a></p>
<p>Fiddler
<a href="http://www.fiddlertool.com/fiddler/" rel="nofollow noreferrer">http://www.fiddlertool.com/fiddler/</a></p>
<p>I may miss some settings, it is not working for me.</p>
<p>help will be more appreciated.</p>
| [
{
"answer_id": 10438793,
"author": "E.Bailo",
"author_id": 1373471,
"author_profile": "https://Stackoverflow.com/users/1373471",
"pm_score": 1,
"selected": false,
"text": ".\n.\n.\n Serializer->EndEnvelope();\n/* ___________________ */\n\n char * bufferxml = NULL;\n\n _variant_t punt = _variant_t((IUnknown*)Serializer);\n punt.lVal += 48;\n _variant_t punt1 = *punt.ppunkVal;\n punt1.lVal += 32;\n _variant_t punt2 = *punt1.ppunkVal;\n punt2.lVal += 4;\n memcpy(&bufferxml, (char *) *punt2.ppunkVal, sizeof(char *));\n\n punt2.lVal += 4;\n int lengxml = *(punt2.pintVal);\n bufferxml[lengxml] = '\\0';\n/* ___________________ */\n\n // Send the message to the web service\n Connector->EndMessage(); \n.\n.\n.\n punt.Detach();\n punt1.Detach();\n punt2.Detach();\n punt.Clear();\n punt1.Clear();\n punt2.Clear();\n\n Serializer.Release();\n.\n.\n.\n"
},
{
"answer_id": 13525666,
"author": "Rich",
"author_id": 1548977,
"author_profile": "https://Stackoverflow.com/users/1548977",
"pm_score": 2,
"selected": false,
"text": "@SuppressWarnings(\"rawtypes\")\npublic class MyHandler extends GenericSOAPHandler {\n\n private void print(InputStream input, OutputStream out) throws Exception {\n try {\n DocumentBuilder parser;\n DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();\n factory.setNamespaceAware(true);\n parser = factory.newDocumentBuilder();\n Document document = parser.parse(input);\n Transformer serializer = TransformerFactory.newInstance().newTransformer();\n serializer.setOutputProperty(OutputKeys.INDENT, \"yes\");\n serializer.setOutputProperty(\"{http://xml.apache.org/xslt}indent-amount\", \"2\");\n serializer.transform(new DOMSource(document), new StreamResult(out));\n } catch (TransformerException e) {\n // A fatal error occurred\n throw new Exception(e);\n }\n }\n\n\n @Override\n protected boolean handleInbound(MessageContext msgContext) {\n SOAPMessageContext soapMessageCtx = (SOAPMessageContext) msgContext;\n SOAPMessage soapMessage = soapMessageCtx.getMessage();\n ByteArrayOutputStream outputStream = new ByteArrayOutputStream();\n try {\n soapMessage.writeTo(outputStream);\n byte[] array = outputStream.toByteArray();\n ByteArrayInputStream inputStream = new ByteArrayInputStream(array);\n System.out.println(\"SOAP request message:\\n\");\n print(inputStream, System.out);\n } catch (SOAPException e) {\n e.printStackTrace();\n } catch (IOException e) {\n e.printStackTrace();\n } catch (Exception e) {\n e.printStackTrace();\n }\n return true;\n }\n\n @Override\n protected boolean handleOutbound(MessageContext msgContext) {\n SOAPMessageContext soapMessageCtx = (SOAPMessageContext) msgContext;\n SOAPMessage soapMessage = soapMessageCtx.getMessage();\n ByteArrayOutputStream outputStream = new ByteArrayOutputStream();\n try {\n soapMessage.writeTo(outputStream);\n byte[] array = outputStream.toByteArray();\n ByteArrayInputStream inputStream = new ByteArrayInputStream(array);\n System.out.println(\"SOAP response message:\\n\");\n print(inputStream, System.out);\n } catch (SOAPException e) {\n e.printStackTrace();\n } catch (IOException e) {\n e.printStackTrace();\n } catch (Exception e) {\n e.printStackTrace();\n }\n return true;\n }\n\n}\n <handler-chains xmlns=\"http://java.sun.com/xml/ns/javaee\"\nxmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\nxsi:schemaLocation=\"http://java.sun.com/xml/ns/javaee javaee_web_services_1_2.xsd\">\n <handler-chain>\n <protocol-bindings>##SOAP11_HTTP</protocol-bindings>\n <handler>\n <handler-name>DebugHandler</handler-name>\n <handler-class>handlers.MyHandler</handler-class>\n </handler>\n </handler-chain>\n</handler-chains>\n"
}
] | 2008/11/21 | [
"https://Stackoverflow.com/questions/308739",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/32670/"
] |
308,746 | <p>I'm getting a segmentation fault in the following C code:</p>
<pre><code>#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>
#include <netdb.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#define PORT 6667
#define MAXDATASIZE 1024
int bot_connect(char *hostname);
int bot_connect(char *hostname) {
int sockfd, numbytes, s;
char buf[MAXDATASIZE];
struct addrinfo hints, *servinfo, *p;
int rv;
char m[1024];
char *message;
char *nick = "Goo";
char *ident = "Goo";
char *realname = "Goo";
memset(&hints,0,sizeof hints);
hints.ai_family = AF_UNSPEC;
hints.ai_socktype = SOCK_STREAM;
rv = getaddrinfo(hostname, PORT, &hints, &servinfo);
if (rv != 0) {
fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(rv));
return 1;
}
for (p = servinfo; p != NULL; p = p->ai_next) {
sockfd = socket(p->ai_family, p->ai_socktype, p->ai_protocol);
if (sockfd == -1) {
perror("Client: socket");
continue;
}
if (connect(sockfd, p->ai_addr, p->ai_addrlen) == -1) {
close(sockfd);
perror("Client: connect");
continue;
}
break;
}
if (p == NULL) {
fprintf(stderr, "Client: failed to connect \n");
return 2;
}
freeaddrinfo(servinfo);
strcat(m, "NICK ");
strcat(m, nick);
message = m;
s = send(sockfd, message, strlen(message), 0);
strcat(m, "USER ");
strcat(m, ident);
strcat(m, " * * :");
strcat(m, realname);
message = m;
s = send(sockfd, message, strlen(message), 0);
message = "JOIN #C&T";
s = send(sockfd, message, strlen(message), 0);
close(sockfd);
}
</code></pre>
<p>I know that you get segmentation faults from trying to do something with memory that you are not allowed to do, like alter read only memory, but to my knowledge, this program doesn't do that. Does anyone have any clue where the segmentation fault is coming from?</p>
| [
{
"answer_id": 308763,
"author": "Graeme Perrow",
"author_id": 1821,
"author_profile": "https://Stackoverflow.com/users/1821",
"pm_score": 3,
"selected": false,
"text": "strcat( m, \"NICK\" ); m[0] = '\\0'; memset( m, 0, sizeof( m ) ); strcat strcpy strcat strcat strcpy"
},
{
"answer_id": 308808,
"author": "Graeme Perrow",
"author_id": 1821,
"author_profile": "https://Stackoverflow.com/users/1821",
"pm_score": 2,
"selected": false,
"text": "rv = getaddrinfo(hostname, PORT, &hints, &servinfo);\n const char * connect"
},
{
"answer_id": 308810,
"author": "Tyler McHenry",
"author_id": 39375,
"author_profile": "https://Stackoverflow.com/users/39375",
"pm_score": 3,
"selected": false,
"text": " char m[1024];\n"
},
{
"answer_id": 15396968,
"author": "Valeri Atamaniouk",
"author_id": 1405614,
"author_profile": "https://Stackoverflow.com/users/1405614",
"pm_score": 0,
"selected": false,
"text": "m strcpy(m, \"NICK \");\nstrcat(m, nick);\nmessage = m;\ns = send(sockfd, message, strlen(message), 0);\n\nstrcpy(m, \"USER \");\nstrcat(m, ident);\nstrcat(m, \" * * :\");\nstrcat(m, realname);\nmessage = m;\ns = send(sockfd, message, strlen(message), 0);\n sprintf(m, \"NICK %s\", nick);\nmessage = m;\ns = send(sockfd, message, strlen(message), 0);\n\nsprintf(m, \"USER %s * * :%s\", ident, realname);\ns = send(sockfd, message, strlen(message), 0);\n"
}
] | 2008/11/21 | [
"https://Stackoverflow.com/questions/308746",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2128/"
] |
308,749 | <p>In many languages there's a pair of functions, <code>chr()</code> and <code>ord()</code>, which convert between numbers and character values. In some languages, <code>ord()</code> is called <code>asc()</code>.</p>
<p>Ruby has <code>Integer#chr</code>, which works great:</p>
<pre><code>>> 65.chr
A
</code></pre>
<p>Fair enough. But how do you go the other way?</p>
<pre><code>"A".each_byte do |byte|
puts byte
end
</code></pre>
<p>prints:</p>
<pre><code>65
</code></pre>
<p>and that's pretty close to what I want. But I'd really rather avoid a loop -- I'm looking for something short enough to be readable when declaring a <code>const</code>.</p>
| [
{
"answer_id": 308804,
"author": "dylanfm",
"author_id": 38795,
"author_profile": "https://Stackoverflow.com/users/38795",
"pm_score": 4,
"selected": false,
"text": "'A'.unpack('c')\n"
},
{
"answer_id": 308812,
"author": "Kent Fredric",
"author_id": 15614,
"author_profile": "https://Stackoverflow.com/users/15614",
"pm_score": 2,
"selected": false,
"text": "puts 'Az'[0]\n=> 65\nputs 'Az'[1]\n=> 122\n"
},
{
"answer_id": 308904,
"author": "Robert Gamble",
"author_id": 25222,
"author_profile": "https://Stackoverflow.com/users/25222",
"pm_score": 5,
"selected": false,
"text": "puts ?A\n'A'[0]\n 'A'[0].ord\n ord"
},
{
"answer_id": 6146954,
"author": "Martin Dorey",
"author_id": 18096,
"author_profile": "https://Stackoverflow.com/users/18096",
"pm_score": 3,
"selected": false,
"text": "\n'A'.unpack('C')[0]\n"
},
{
"answer_id": 20501694,
"author": "Rob Cameron",
"author_id": 113347,
"author_profile": "https://Stackoverflow.com/users/113347",
"pm_score": 7,
"selected": true,
"text": "\"A\".ord #=> 65\n"
},
{
"answer_id": 22309665,
"author": "Eduardo Santana",
"author_id": 2040729,
"author_profile": "https://Stackoverflow.com/users/2040729",
"pm_score": 2,
"selected": false,
"text": "65.chr.ord\n'a'.ord.chr\n"
},
{
"answer_id": 22877143,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 3,
"selected": false,
"text": "chr [22] pry(main)> \"\\u0221\".ord.chr\nRangeError: 545 out of char range\nfrom (pry):2:in 'chr'\n[23] pry(main)> x = \"\\u0221\".unpack('U')[0]\n=> 545\n[24] pry(main)> [x].pack('U')\n=> \"ȡ\"\n[25] pry(main)>\n"
},
{
"answer_id": 23849989,
"author": "Clark",
"author_id": 2719837,
"author_profile": "https://Stackoverflow.com/users/2719837",
"pm_score": 2,
"selected": false,
"text": "\"A\".bytes"
},
{
"answer_id": 29608837,
"author": "hantscolin",
"author_id": 4764802,
"author_profile": "https://Stackoverflow.com/users/4764802",
"pm_score": 0,
"selected": false,
"text": "unless \"\".respond_to?(:ord)\n class Fixnum\n def ord\n return self\n end\n end\nend 'A'[0].ord"
}
] | 2008/11/21 | [
"https://Stackoverflow.com/questions/308749",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/39223/"
] |
308,752 | <p>I would like to know which one is the best material that I can hand out to my students about "<em>C# comments</em>".</p>
| [
{
"answer_id": 308762,
"author": "Patrick Desjardins",
"author_id": 13913,
"author_profile": "https://Stackoverflow.com/users/13913",
"pm_score": 2,
"selected": false,
"text": "//This is a single line comment\n /*\nMultiple lines\n*/\n /// <summary>\n /// This is a description\n /// </summary>\n /// <param name=\"sender\">Description of variable SENDER</param>\n /// <param name=\"e\">Description of variable E</param>\n"
},
{
"answer_id": 308770,
"author": "George Stocker",
"author_id": 16587,
"author_profile": "https://Stackoverflow.com/users/16587",
"pm_score": 4,
"selected": false,
"text": "//Connect to the Database\nDb.Connect();\n"
}
] | 2008/11/21 | [
"https://Stackoverflow.com/questions/308752",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18631/"
] |
308,756 | <p>Is it possible to check if a dynamically loaded assembly has been signed with a specific strong name?</p>
<p>Is it enough / secure to compare the values returned from <strong>AssemblyName.GetPublicKey()</strong> method?</p>
<pre><code>Assembly loaded = Assembly.LoadFile(path);
byte[] evidenceKey = loaded.GetName().GetPublicKey();
if (evidenceKey != null)
{
byte[] internalKey = Assembly.GetExecutingAssembly().GetName().GetPublicKey();
if (evidenceKey.SequenceEqual(internalKey))
{
return extension;
}
}
</code></pre>
<p>Can't this be spoofed? I am not sure if the SetPublicKey() method has any effect on a built assembly, but even the MSDN documentation shows how you can use this on a dynamically generated assembly (reflection emit) so that would mean you could extract the public key from the host application and inject it into an assembly of your own and run mallicious code if the above was the safe-guard, or am I missing something?</p>
<p>Is there a more correct and secure approach? I know if the reversed situation was the scenario, that is, where I wanted to secure the assembly from only being called by signed hosts then I could tag the assembly with the StrongNameIdentityPermission attribute.</p>
| [
{
"answer_id": 308762,
"author": "Patrick Desjardins",
"author_id": 13913,
"author_profile": "https://Stackoverflow.com/users/13913",
"pm_score": 2,
"selected": false,
"text": "//This is a single line comment\n /*\nMultiple lines\n*/\n /// <summary>\n /// This is a description\n /// </summary>\n /// <param name=\"sender\">Description of variable SENDER</param>\n /// <param name=\"e\">Description of variable E</param>\n"
},
{
"answer_id": 308770,
"author": "George Stocker",
"author_id": 16587,
"author_profile": "https://Stackoverflow.com/users/16587",
"pm_score": 4,
"selected": false,
"text": "//Connect to the Database\nDb.Connect();\n"
}
] | 2008/11/21 | [
"https://Stackoverflow.com/questions/308756",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/25319/"
] |
308,772 | <p>I'm creating a public internet facing website which contains the email address of their salespeople. </p>
<p>What kind of programming options do I have to generate the "mailto" and display the email from that address but limit the spambots from picking up the address? </p>
| [
{
"answer_id": 309220,
"author": "Brian C. Lane",
"author_id": 27461,
"author_profile": "https://Stackoverflow.com/users/27461",
"pm_score": 2,
"selected": false,
"text": "<script name=\"mailto\" language=\"JavaScript\">\n //<![CDATA[\n\n function load()\n {\n c1 = \"bcl\"\n c2 = \"brian\"\n c3 = \"lane\"\n c4 = \"com\"\n // Fill in the addresses\n document.getElementById(\"contact1\").innerHTML = \"<a href=\" + \"mail\" + \"to:\" + c1 + \"@\" + c2 + c3 + \".\" + c4 + \">\" + c1 + \"@\" + c2 + c3 + \".\" + c4 + \"</a>\";\n }\n //]]>\n\n</script>\n <body onload=\"load()\">\n <span id=\"contact1\"><a href=\"mailto:spam@brianlane.com\">spam@brianlane.com</a></span>\n"
},
{
"answer_id": 16200942,
"author": "vsync",
"author_id": 104380,
"author_profile": "https://Stackoverflow.com/users/104380",
"pm_score": 1,
"selected": false,
"text": ".email::after{ content:'myemail@gmail.com'; }\n"
},
{
"answer_id": 71794753,
"author": "Ivan_OFF",
"author_id": 17780003,
"author_profile": "https://Stackoverflow.com/users/17780003",
"pm_score": 0,
"selected": false,
"text": "function emptyMail() {\n let mail = document.querySelector('#your_mail');\n let mailValue = mail.href;\n\n mail.href = \"\";\n\n mail.addEventListener('mouseover', function() {\n mail.href= mailValue;\n })\n}\n"
}
] | 2008/11/21 | [
"https://Stackoverflow.com/questions/308772",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10352/"
] |
308,802 | <p>I'm using the <a href="http://code.msdn.microsoft.com/silverlightut/" rel="noreferrer">Silverlight UnitTest framerwork</a> does anyone have a good example have how to unit test an application with it?
I'm using it quite successfully to unit test a silverlight class library.</p>
<p>Any pointers and links would be greatly appreciated.</p>
<p>Thanks,
Nath</p>
| [
{
"answer_id": 16547022,
"author": "Michael",
"author_id": 986451,
"author_profile": "https://Stackoverflow.com/users/986451",
"pm_score": 2,
"selected": false,
"text": "using System;\nusing System.Net;\nusing System.Windows;\nusing System.Windows.Controls;\nusing System.Windows.Documents;\nusing System.Windows.Ink;\nusing System.Windows.Input;\nusing System.Windows.Media;\nusing System.Windows.Media.Animation;\nusing System.Windows.Shapes;\nusing Microsoft.Silverlight.Testing;\nusing Microsoft.VisualStudio.TestTools.UnitTesting;\n\nnamespace Test\n{\n[TestClass]\npublic class Test_Svc_Login \n{\n [TestMethod]\n public void Always_True()\n {\n Assert.IsTrue(true);\n }\n\n [TestMethod]\n public void Always_False()\n {\n Assert.IsTrue(false);\n }\n\n [TestMethod]\n public void Even_MoreAlways_False()\n {\n Assert.IsTrue(false);\n }\n}\n\n}\n this.RootVisual = new Gui.MainPage();\n #if DEBUG\n if (System.Diagnostics.Debugger.IsAttached)\n {\n //You hit F5 ONLY\n this.RootVisual = new Gui.MainPage();\n }\n else\n {\n //You hit CTRL + F5 \n RunUnitTests();\n }\n#else\n //You are in Release Mode. You hit whatever you want.\n this.RootVisual = new Gui.MainPage();\n#endif \n private void RunUnitTests()\n {\n\n#if DEBUG\n //You hit CTRL + F5 \n var settings = new UnitTestSettings();\n settings.TestHarness = new UnitTestHarness();\n settings.StartRunImmediately = true;\n settings.TestAssemblies.Add(Assembly.GetExecutingAssembly());\n this.RootVisual = UnitTestSystem.CreateTestPage(settings); \n#endif\n }\n"
}
] | 2008/11/21 | [
"https://Stackoverflow.com/questions/308802",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/39643/"
] |
308,813 | <p>I am using Apache Felix and its Declarative Services (SCR) to wire the service dependencies between bundles.</p>
<p>For example, if I need access to a java.util.Dictionary I can say the following to have SCR provide one:</p>
<pre><code>/**
* @scr.reference name=properties interface=java.util.Dictionary
*/
protected void bindProperties(Dictionary d) {
}
protected void unbindProperties(Dictionary d) {
}
</code></pre>
<p>Now, I have more than one Dictionary service available, and I want to filter them using the "name" service property (I only want "name=myDictionary"). I can do that with code (using a ServiceTracker), but I'd rather specify the filter in the @scr annotation instead.</p>
| [
{
"answer_id": 322471,
"author": "Danail Nachev",
"author_id": 3219,
"author_profile": "https://Stackoverflow.com/users/3219",
"pm_score": 1,
"selected": false,
"text": "\n(name=myDictionary)\n"
},
{
"answer_id": 367987,
"author": "Alexander Klimetschek",
"author_id": 2709,
"author_profile": "https://Stackoverflow.com/users/2709",
"pm_score": 3,
"selected": true,
"text": "target=\"(name=myDictionary)\"\n @scr.reference"
}
] | 2008/11/21 | [
"https://Stackoverflow.com/questions/308813",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14955/"
] |
308,820 | <p>I have big issue with url-rewriting for IIS 7.0.</p>
<p>I've written simple module for rewriting for my NET3.5/IIS7 web application. Here is a part of the code.</p>
<pre><code> public void Init(HttpApplication context)
{
context.BeginRequest += new EventHandler(context_BeginRequest);
}
void context_BeginRequest(object sender, EventArgs e)
{
HttpApplication app = sender as HttpApplication;
if (app.Request.Path.Contains("pagetorewrite.aspx"))
HttpContext.Current.RewritePath("~/otherpage.aspx");
}
</code></pre>
<p>And I register my module in web.config :</p>
<pre><code> <system.webServer>
<validation validateIntegratedModeConfiguration="false"/>
<modules>
<add name="MyModule" type="MyModule" preCondition="" />
</code></pre>
<p>Under IIS 7.0 (Vista) using Classic ASP Pipeline it works perfect, but when I change pipeline mode to Integrated, then it stops working. There are no exceptions, errors and anything in debugger/events/logfiles - only message in a browser that page was not found. The stragnest thing is that pagename looks like mispelled or merged from parts of original page and rewrte-to page.</p>
<p>I've deployed my code at another computer (also vista -but x64- and iis 7.0) and it works perfect in both modes.
It looks that there's an configuration issue or what?</p>
| [
{
"answer_id": 322471,
"author": "Danail Nachev",
"author_id": 3219,
"author_profile": "https://Stackoverflow.com/users/3219",
"pm_score": 1,
"selected": false,
"text": "\n(name=myDictionary)\n"
},
{
"answer_id": 367987,
"author": "Alexander Klimetschek",
"author_id": 2709,
"author_profile": "https://Stackoverflow.com/users/2709",
"pm_score": 3,
"selected": true,
"text": "target=\"(name=myDictionary)\"\n @scr.reference"
}
] | 2008/11/21 | [
"https://Stackoverflow.com/questions/308820",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/39656/"
] |
308,823 | <p>I have to define the grammar of a file like the one shown below.</p>
<p>//Sample file<br>
NameCount = 4<br>
Name = a<br>
Name = b<br>
Name = c<br>
Name = d<br>
//End of file<br></p>
<p>Now I am able to define tokens for <strong>NameCount</strong> and <strong>Name</strong>. But i have to define the file structure including the valid number of instances of token <strong>Name</strong> , which is the value after <strong>NameCount</strong>. I have the value parsed and converted into an integer and stored in a variable at global scope of the grammar (say in variable <strong>nc</strong>). </p>
<p>How to define in grammar that <strong>Name</strong> should repeat exactly <strong>nc</strong> times?</p>
| [
{
"answer_id": 335674,
"author": "tcurdt",
"author_id": 33165,
"author_profile": "https://Stackoverflow.com/users/33165",
"pm_score": 4,
"selected": true,
"text": "grammar test;\n\n@members {\n private int count = 0;\n private int names = 0;\n}\n\nfile\n : count (name)+\n {\n if (count != names) throw new Exception(\"\");\n }\n ;\n\ncount\n : 'NameCount' EQ Number\n {\n count = Integer.parseInt($Number.text);\n }\n ;\n\nname\n : 'Name' EQ Value\n {\n names++;\n }\n...\n"
}
] | 2008/11/21 | [
"https://Stackoverflow.com/questions/308823",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/27784/"
] |
308,826 | <p>The code below works. But if I comment out the line <code>Dim objRequest As MSXML2.XMLHTTP</code> and uncomment the line <code>Dim objRequest As Object</code> it fails with the error message :</p>
<blockquote>
<p>The parameter is incorrect</p>
</blockquote>
<p>Why, and what (if anything) can I do about it?</p>
<pre><code>Public Function GetSessionId(strApiId, strUserName, strPassword) As String
Dim strPostData As String
Dim objRequest As MSXML2.XMLHTTP
'Dim objRequest As Object '
strPostData = "api_id=" & strApiId & "&user=" & strUserName & "&password=" & strPassword
Set objRequest = New MSXML2.XMLHTTP
With objRequest
.Open "POST", "https://api.clickatell.com/http/auth", False
.setRequestHeader "Content-Type", "application/x-www-form-urlencoded"
.send strPostData
GetSessionId = .responseText
End With
End Function
</code></pre>
<hr>
<p>Corey, yes, I know I would have to do that in order for my code to work without a reference to the MSXML type library. That's not the issue here. The code fails when using <code>Dim objRequest As Object</code> regardless of whether I use </p>
<p><code>Set objRequest = NEW MSXML2.XMLHTTP</code> with the reference, or </p>
<p><code>Set objRequest = CreateObject("MSXML2.XMLHTTP")</code> without the reference.</p>
| [
{
"answer_id": 308920,
"author": "Tomalak",
"author_id": 18771,
"author_profile": "https://Stackoverflow.com/users/18771",
"pm_score": 5,
"selected": true,
"text": "Dim strPostData As String\nDim objRequest As Object\n\nstrPostData = \"api_id=\" & strApiId & \"&user=\" & strUserName & \"&password=\" & strPassword\n\nSet objRequest = New MSXML2.XMLHTTP\nWith objRequest\n .Open \"POST\", \"https://api.clickatell.com/http/auth\", False\n .setRequestHeader \"Content-Type\", \"application/x-www-form-urlencoded\"\n .send (strPostData)\n GetSessionId = .responseText\nEnd With\n strPostData strPostData = \"api_id=\" & URLEncode(strApiId) & _\n \"&user=\" & URLEncode(strUserName) & _\n \"&password=\" & URLEncode(strPassword)\n URLEncode()"
},
{
"answer_id": 2312332,
"author": "Alistair Collins",
"author_id": 201618,
"author_profile": "https://Stackoverflow.com/users/201618",
"pm_score": 0,
"selected": false,
"text": "Sub Button1_Click2()\n\nDim objXMLSendDoc As Object\nSet objXMLSendDoc = New MSXML2.DOMDocument\nobjXMLSendDoc.async = False\nDim myxml As String\nmyxml = \"<?xml version='1.0'?><Request>Do Something</Request>\"\nIf Not objXMLSendDoc.LoadXML(myxml) Then\n Err.Raise objXMLSendDoc.parseError.ErrorCode, , objXMLSendDoc.parseError.reason\nEnd If\n\nDim objRequest As MSXML2.XMLHTTP\nSet objRequest = New MSXML2.XMLHTTP\nWith objRequest\n .Open \"POST\", \"http://localhost/SISADraftCalcs/Test2.php\", False\n .setRequestHeader \"Content-Type\", \"application/xml;charset=UTF-16\"\n .setRequestHeader \"Cache-Control\", \"no-cache\"\n .send objXMLSendDoc\nEnd With\n\nDim objXMLDoc As MSXML2.DOMDocument\nSet objXMLDoc = objRequest.responseXML\nIf objXMLDoc.XML = \"\" Then\n objXMLDoc.LoadXML objRequest.responseText\n If objXMLDoc.parseError.ErrorCode <> 0 Then\n MsgBox objXMLDoc.parseError.reason\n End If\nEnd If\n\nDim rootNode As IXMLDOMElement\nSet rootNode = objXMLDoc.DocumentElement\n\nMsgBox rootNode.SelectNodes(\"text\").Item(0).text\n\nEnd Sub\n"
}
] | 2008/11/21 | [
"https://Stackoverflow.com/questions/308826",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/39665/"
] |
308,832 | <p>How do I detect when an iOS app is launched for the first time?</p>
| [
{
"answer_id": 308846,
"author": "Marc Charbonneau",
"author_id": 35136,
"author_profile": "https://Stackoverflow.com/users/35136",
"pm_score": 2,
"selected": false,
"text": "registerDefaults:"
},
{
"answer_id": 308861,
"author": "Noah Witherspoon",
"author_id": 30618,
"author_profile": "https://Stackoverflow.com/users/30618",
"pm_score": 7,
"selected": true,
"text": "// -applicationDidFinishLaunching:\n[[NSUserDefaults standardUserDefaults] registerDefaults:[NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithBool:YES],@\"firstLaunch\",nil]];\n// to check it:\n[[NSUserDefaults standardUserDefaults] boolForKey:@\"firstLaunch\"];\n// -applicationWillTerminate:\n[[NSUserDefaults standardUserDefaults] setBool:NO forKey:@\"firstLaunch\"];\n // -applicationDidFinishLaunching:\nUserDefaults.standard.register(defaults: [\"firstLaunch\":true])\n// to check it:\nUserDefaults.standard.bool(forKey: \"firstLaunch\")\n// -applicationWillTerminate:\nUserDefaults.standard.set(false, forKey: \"firstLaunch\")\n"
},
{
"answer_id": 3300358,
"author": "clint",
"author_id": 62694,
"author_profile": "https://Stackoverflow.com/users/62694",
"pm_score": 6,
"selected": false,
"text": "// Get current version (\"Bundle Version\") from the default Info.plist file\nNSString *currentVersion = (NSString*)[[NSBundle mainBundle] objectForInfoDictionaryKey:@\"CFBundleVersion\"];\nNSArray *prevStartupVersions = [[NSUserDefaults standardUserDefaults] arrayForKey:@\"prevStartupVersions\"];\nif (prevStartupVersions == nil) \n{\n // Starting up for first time with NO pre-existing installs (e.g., fresh \n // install of some version)\n [self firstStartAfterFreshInstall];\n [[NSUserDefaults standardUserDefaults] setObject:[NSArray arrayWithObject:currentVersion] forKey:@\"prevStartupVersions\"];\n}\nelse\n{\n if (![prevStartupVersions containsObject:currentVersion]) \n {\n // Starting up for first time with this version of the app. This\n // means a different version of the app was alread installed once \n // and started.\n [self firstStartAfterUpgradeDowngrade];\n NSMutableArray *updatedPrevStartVersions = [NSMutableArray arrayWithArray:prevStartupVersions];\n [updatedPrevStartVersions addObject:currentVersion];\n [[NSUserDefaults standardUserDefaults] setObject:updatedPrevStartVersions forKey:@\"prevStartupVersions\"];\n }\n}\n\n// Save changes to disk\n[[NSUserDefaults standardUserDefaults] synchronize];\n"
},
{
"answer_id": 10460054,
"author": "NSCoder",
"author_id": 1036945,
"author_profile": "https://Stackoverflow.com/users/1036945",
"pm_score": 2,
"selected": false,
"text": "// Check to see if its the first time\nif ([[NSUserDefaults standardUserDefaults] valueForKey:@\"firstTime\"] == NULL) {\n [[NSUserDefaults standardUserDefaults] setValue:@\"Not\" forKey:@\"firstTime\"];\n}\n"
}
] | 2008/11/21 | [
"https://Stackoverflow.com/questions/308832",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/36182/"
] |
308,833 | <p>I need to transform an Oracle SQL statement into a Stored Procedure therefore users with less privileges can access certain data field:</p>
<pre><code>SELECT
info_field, data_field
FROM
table_one
WHERE
some_id = '<id>' -- I need this <id> to be the procedure's parameter
UNION ALL
SELECT
info_field, data_field
FROM
table_two
WHERE
some_id = '<id>'
UNION ALL
SELECT
info_field, data_field
FROM
table_three
WHERE
some_id = '<id>'
UNION ALL
...
</code></pre>
<p>Given that I'm no SP expert I've been unable to figure out a good solution to loop through all the involved tables (12 aprox.).</p>
<p>Any ideas would be helpful. Thanks much!</p>
| [
{
"answer_id": 308883,
"author": "Dave Costa",
"author_id": 6568,
"author_profile": "https://Stackoverflow.com/users/6568",
"pm_score": 1,
"selected": false,
"text": "PROCEDURE get_fields( the_id NUMBER,\n info_field_out OUT table_one.info_field%TYPE,\n data_field_out OUT table_one.data_field%TYPE\n )\n IS\n BEGIN\n SELECT info_field, data_field\n INTO info_field_out, data_field_out\n FROM (\n ... put your full SQL query here, using 'the_id' as the value to match against ..\n );\n\n EXCEPTION\n\n WHEN no_data_found THEN\n -- What do you want to do here? Set the outputs to NULL? Raise an error?\n\n WHEN too_many_rows THEN\n -- Is this an invalid condition?\n\n END;\n"
},
{
"answer_id": 308929,
"author": "Tony Andrews",
"author_id": 18747,
"author_profile": "https://Stackoverflow.com/users/18747",
"pm_score": 3,
"selected": true,
"text": "CREATE VIEW info_and_data AS\n SELECT info_field, data_field \n FROM table_one\n UNION ALL\n SELECT info_field, data_field \n FROM table_two\n UNION ALL\n SELECT info_field, data_field \n FROM table_three\n ...\n SELECT info_field, data_field\nFROM info_and_data\nWHERE some_id = <id>\n"
}
] | 2008/11/21 | [
"https://Stackoverflow.com/questions/308833",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6992/"
] |
308,835 | <p>I'm finding myself doing a lot of things with associative arrays in PHP.</p>
<p>I was doing this:</p>
<pre><code> foreach ($item as $key=>$value) {
if ($arr[$key] == null) {
$arr[$key] = 0;
}
$arr[$key] += $other_arr[$value];
}
</code></pre>
<p>But then I realised that it works fine if I exclude the line that initializes $arr[$key], presumably since it's null which is treated as the same as 0.</p>
<p>Is making that kind of assumption safe in php? And if it's safe, is it a good idea?</p>
| [
{
"answer_id": 308852,
"author": "Greg",
"author_id": 24181,
"author_profile": "https://Stackoverflow.com/users/24181",
"pm_score": 4,
"selected": true,
"text": "if (!isset($arr[$key]))\n $arr[$key] = 0;\n"
},
{
"answer_id": 32802974,
"author": "ajon",
"author_id": 1068058,
"author_profile": "https://Stackoverflow.com/users/1068058",
"pm_score": 0,
"selected": false,
"text": "php 7 foreach ($item as $key=>$value) {\n $arr[$key] = ($arr[$key] ?? 0) + other_arr[$value];\n}\n"
}
] | 2008/11/21 | [
"https://Stackoverflow.com/questions/308835",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11522/"
] |
308,837 | <p>I have the following table</p>
<pre><code><td class="style2">
<asp:DropDownList ID="DropDownList1" runat="server">
<asp:ListItem>Location</asp:ListItem>
<asp:ListItem>Name</asp:ListItem>
<asp:ListItem>SSN</asp:ListItem>
</asp:DropDownList>
<asp:DropDownList ID="DropDownList2" runat="server">
<asp:ListItem>LIKE</asp:ListItem>
<asp:ListItem>=</asp:ListItem>
</asp:DropDownList>
<br />
<br />
</td>
<td valign="bottom">
<asp:Button ID="btnAdd" runat="server" Text="Add" />
</td>
</code></pre>
<p>When btnAdd is clicked I want to add another row of those filters. I assume I would create a panel and have these 3 controls and the add button would create a new panel or do I create all controls on the fly and then add them with code behind. </p>
<p>Edit::
When I click on btnAdd then I want to add another row as such</p>
<p>Before btnAdd Click</p>
<pre><code><td class="style2">
<asp:DropDownList ID="DropDownList1" runat="server">
<asp:ListItem>Location</asp:ListItem>
<asp:ListItem>Name</asp:ListItem>
<asp:ListItem>SSN</asp:ListItem>
</asp:DropDownList>
<asp:DropDownList ID="DropDownList2" runat="server">
<asp:ListItem>LIKE</asp:ListItem>
<asp:ListItem>=</asp:ListItem>
</asp:DropDownList>
<br />
<br />
</td>
</code></pre>
<p>After btnAdd:</p>
<pre><code><td class="style2">
<asp:DropDownList ID="DropDownList1" runat="server">
<asp:ListItem>Location</asp:ListItem>
<asp:ListItem>Name</asp:ListItem>
<asp:ListItem>SSN</asp:ListItem>
</asp:DropDownList>
<asp:DropDownList ID="DropDownList2" runat="server">
<asp:ListItem>LIKE</asp:ListItem>
<asp:ListItem>=</asp:ListItem>
</asp:DropDownList>
<br />
<br />
</td>
<tr>
<td class="style2">
<asp:DropDownList ID="DropDownList1" runat="server">
<asp:ListItem>Location</asp:ListItem>
<asp:ListItem>Name</asp:ListItem>
<asp:ListItem>SSN</asp:ListItem>
</asp:DropDownList>
<asp:DropDownList ID="DropDownList2" runat="server">
<asp:ListItem>LIKE</asp:ListItem>
<asp:ListItem>=</asp:ListItem>
</asp:DropDownList>
<br />
<br />
</td>
</tr>
</code></pre>
| [
{
"answer_id": 308852,
"author": "Greg",
"author_id": 24181,
"author_profile": "https://Stackoverflow.com/users/24181",
"pm_score": 4,
"selected": true,
"text": "if (!isset($arr[$key]))\n $arr[$key] = 0;\n"
},
{
"answer_id": 32802974,
"author": "ajon",
"author_id": 1068058,
"author_profile": "https://Stackoverflow.com/users/1068058",
"pm_score": 0,
"selected": false,
"text": "php 7 foreach ($item as $key=>$value) {\n $arr[$key] = ($arr[$key] ?? 0) + other_arr[$value];\n}\n"
}
] | 2008/11/21 | [
"https://Stackoverflow.com/questions/308837",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/38230/"
] |
308,850 | <p>Windows Forms:</p>
<p>For <code>System.Drawing</code> there is a way to get the font height. </p>
<pre><code>Font font = new Font("Arial", 10 , FontStyle.Regular);
float fontHeight = font.GetHeight();
</code></pre>
<p>But how do you get the other text metrics like average character width?</p>
| [
{
"answer_id": 308858,
"author": "Ramesh Soni",
"author_id": 191,
"author_profile": "https://Stackoverflow.com/users/191",
"pm_score": 3,
"selected": true,
"text": "private void MeasureStringMin(PaintEventArgs e)\n{\n\n // Set up string.\n string measureString = \"Measure String\";\n Font stringFont = new Font(\"Arial\", 16);\n\n // Measure string.\n SizeF stringSize = new SizeF();\n stringSize = e.Graphics.MeasureString(measureString, stringFont);\n\n // Draw rectangle representing size of string.\n e.Graphics.DrawRectangle(new Pen(Color.Red, 1), 0.0F, 0.0F, stringSize.Width, stringSize.Height);\n\n // Draw string to screen.\n e.Graphics.DrawString(measureString, stringFont, Brushes.Black, new PointF(0, 0));\n}\n"
},
{
"answer_id": 308907,
"author": "Ray Hayes",
"author_id": 7093,
"author_profile": "https://Stackoverflow.com/users/7093",
"pm_score": 2,
"selected": false,
"text": "StringBuilder sb = new StringBuilder();\n\n// Using the typical printable range\nfor(char i=32;i<127;i++)\n{\n sb.Append(i);\n} \n\nstring printableChars = sb.ToString();\n\n// Choose your font\nFont stringFont = new Font(\"Arial\", 16);\n\n// Now pass printableChars into MeasureString\nSizeF stringSize = new SizeF();\nstringSize = e.Graphics.MeasureString(printableChars, stringFont);\n\n// Work out average width of printable characters\ndouble average = stringSize.Width / (double) printableChars.Length;\n"
}
] | 2008/11/21 | [
"https://Stackoverflow.com/questions/308850",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/28343/"
] |
308,876 | <p>I am connecting to a MySQL DB trough a terminal who only have a program with an ODBC connection to a MySQL DB. I can put querys in the program, but not access MySQL directly.</p>
<p>I there a way to query the DB to obtain the list of fields in a table other than</p>
<pre><code>select * from table
</code></pre>
<p>??</p>
<p>(don't know why but the select returns a error)</p>
| [
{
"answer_id": 308882,
"author": "Sebastian Hoitz",
"author_id": 9535,
"author_profile": "https://Stackoverflow.com/users/9535",
"pm_score": 2,
"selected": true,
"text": "describe *tablename*\n"
},
{
"answer_id": 308890,
"author": "Tomalak",
"author_id": 18771,
"author_profile": "https://Stackoverflow.com/users/18771",
"pm_score": 2,
"selected": false,
"text": "SELECT\n COLUMN_NAME\nFROM\n INFORMATION_SCHEMA.COLUMNS\nWHERE\n TABLE_NAME = 'MyTable'\n AND TABLE_SCHEMA = 'SchemaName' /* added upon Bill Karwin's comment (thanks) */\n"
},
{
"answer_id": 1238801,
"author": "Waggers",
"author_id": 151039,
"author_profile": "https://Stackoverflow.com/users/151039",
"pm_score": 0,
"selected": false,
"text": "SHOW COLUMNS FROM Tablename\n"
}
] | 2008/11/21 | [
"https://Stackoverflow.com/questions/308876",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2385/"
] |
308,892 | <p>I'm looking for a good open source message bus that is suitable for embedded Linux devices (Linux and uClinux).</p>
<p>It needs to satisfy the following criteria:</p>
<ul>
<li>Must be free software and LGPL or a more liberal license due to uClinux only supporting static linking</li>
<li>Must have a C API</li>
<li>Must have a relatively small footprint and not depend on third party libraries</li>
<li>Must be compatible with Linux/uClinux 2.4.22+</li>
<li>Should be well tested and preferably have an existing test framework set up</li>
<li>Should have a well documented protocol</li>
<li>Should be portable to other platforms</li>
</ul>
<p>The message bus would primarily be used by applications on our system in order to communicate configuration parameters etc so it doesn't need to satisfy realtime requirements.</p>
| [
{
"answer_id": 309021,
"author": "Ben Collins",
"author_id": 3279,
"author_profile": "https://Stackoverflow.com/users/3279",
"pm_score": 4,
"selected": true,
"text": "man mq_overview"
}
] | 2008/11/21 | [
"https://Stackoverflow.com/questions/308892",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/22247/"
] |
308,893 | <p>I have a problem with an ASP.NET application that is driving me nuts.</p>
<p>When a user leaves a page inactive for a period of time the session was timing out and error were being thrown due to session variables not being resolvable (I will error trap this anyway but this is not the problem).
I coded a 'defribulator' which will perform an invisible postback after half of the session timeout has expired and this seemed to work fine - leaving the application for 30 mins did not cause an error even though the session timeout was set for 20 mins.
However, this morning one of the other Devs experienced a timeout - How is this possible?</p>
<p>On further investigation I think that the problem occurs when the Forms Authentication timeout is exceeded - even though the defribulator has been (apparently) keeping the session alive. I have read that the Authentication ticket will only be reissued if a postback occurs after half of the specified timeout period has elepsed and this can't the issue as the defrib will have issued requests during the second half of the timeout period - so why was it not reissued?</p>
<p>I suppose I could get around the problem by setting the authentication timeout to 8 hours or so but that is a poor fix.</p>
<p>Can anyone shed any light on this?</p>
<p>Thanks in advance</p>
<p>[Edit 24/11/2008] Reviewing the Log Files has proved enlightening and confusing. I can see the defribulator firing after 10 minutes of inactivity but while the Session_Id appears to be consitent throughout, the forms authentications ticket ID changes - not sure if it is supposed to or not. I'm formulating a test plan now and will post back when i have completed them.
Thanks to everyone who have provided feedback so far.</p>
<p>[Edit 24/11/2008] Well I'm stumped - everthing seems to be working fine at the moment! The Authentication ticket is being regenerated when the defrib runs (the ID changes) and the session is being maintained. Was it a server issue - can't tell. I have experienced this problem before and never got to the bottom of it and it is very frustrating - surely it should not be this difficult. I'm going to have to let this drop for the timebeing as I have to get on with some other aspects of the application. I'll just have to code around this issue - which may never occur on the customer site.</p>
<p>Thanks again for everyones input - if I make any progress I will post it back here.</p>
| [
{
"answer_id": 309033,
"author": "user39603",
"author_id": 39603,
"author_profile": "https://Stackoverflow.com/users/39603",
"pm_score": 1,
"selected": false,
"text": "slidingExpiration true"
}
] | 2008/11/21 | [
"https://Stackoverflow.com/questions/308893",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/31580/"
] |
308,905 | <p>I've been reading that some devs/dbas recommend using transactions in all database calls, even read-only calls. While I understand inserting/updating within a transaction what is the benefit of reading within a transaction?</p>
| [
{
"answer_id": 308910,
"author": "Greg",
"author_id": 24181,
"author_profile": "https://Stackoverflow.com/users/24181",
"pm_score": 7,
"selected": true,
"text": "myRows = query(SELECT * FROM A)\nmoreRows = query(SELECT * FROM B WHERE a_id IN myRows[id])\n"
}
] | 2008/11/21 | [
"https://Stackoverflow.com/questions/308905",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/34133/"
] |
308,908 | <p>I have a data set that is organized in the following manner:</p>
<pre><code>Timestamp|A0001|A0002|A0003|A0004|B0001|B0002|B0003|B0004 ...
---------+-----+-----+-----+-----+-----+-----+-----+-----
2008-1-1 | 1 | 2 | 10 | 6 | 20 | 35 | 300 | 8
2008-1-2 | 5 | 2 | 9 | 3 | 50 | 38 | 290 | 2
2008-1-4 | 7 | 7 | 11 | 0 | 30 | 87 | 350 | 0
2008-1-5 | 1 | 9 | 1 | 0 | 25 | 100 | 10 | 0
...
</code></pre>
<p>Where A0001 is Value A of item #1 and B0001 is Value B of item #1. There can be over 60 different items in a table, and each item has an A value column and a B value column, meaning a total of over 120 columns in the table.</p>
<p>Where I want to get to is a 3 column result (Item index, A Value, B Value) that sums the A and B values for each item:</p>
<pre><code>Index | A Value | B Value
------+---------+--------
0001 | 14 | 125
0002 | 20 | 260
0003 | 31 | 950
0004 | 9 | 10
....
</code></pre>
<p>As I am going from columns to rows I would expect a pivot in the solution, but I am not sure of how to flesh it out. Part of the issue is how to strip out the A's and B's to form the values for the Index column. The other part is that I have never had to use a Pivot before, so I am stumbling over the basic syntax as well.</p>
<p>I think that ultimately I need to have a multi step solution that first builds the summations as:</p>
<pre><code>ColName | Value
--------+------
A0001 | 14
A0002 | 20
A0003 | 31
A0004 | 9
B0001 | 125
B0002 | 260
B0003 | 950
B0004 | 10
</code></pre>
<p>Then modify the ColName data to strip out the index:</p>
<pre><code>ColName | Value | Index | Aspect
--------+-------+-------+-------
A0001 | 14 | 0001 | A
A0002 | 20 | 0002 | A
A0003 | 31 | 0003 | A
A0004 | 9 | 0004 | A
B0001 | 125 | 0001 | B
B0002 | 260 | 0002 | B
B0003 | 950 | 0003 | B
B0004 | 10 | 0004 | B
</code></pre>
<p>Finally self join to move the B values up next to the A Values.</p>
<p>This seems to be a long winded process to get what I want. So I am after advice as to whether I am headed down the right path, or is there another approach that I have over looked that will make my life so much easier.</p>
<p>Note 1) The solution has to be in T-SQL on MSSQL 2005.</p>
<p>Note 2) The format of the table cannot be changed.</p>
<p><strong>Edit</strong> Another method I have thought about uses UNIONs and individual SUM()s on each column:</p>
<pre><code>SELECT '0001' as Index, SUM(A0001) as A, SUM(B0001) as B FROM TABLE
UNION
SELECT '0002' as Index, SUM(A0002) as A, SUM(B0002) as B FROM TABLE
UNION
SELECT '0003' as Index, SUM(A0003) as A, SUM(B0003) as B FROM TABLE
UNION
SELECT '0004' as Index, SUM(A0004) as A, SUM(B0004) as B FROM TABLE
UNION
...
</code></pre>
<p>But this approach really doesn't look very nice either</p>
<p><strong>EDIT</strong> So far there are 2 great responses. But I would like to add two more conditions to the query :-) </p>
<p>1) I need to select the rows based on a range of timestamps (minv < timestamp < maxv). </p>
<p>2) I also need to conditionally select rows on a UDF that processes the timestamp</p>
<p>Using Brettski's table names, would the above translate to:</p>
<pre><code>...
(SELECT A0001, A0002, A0003, B0001, B0002, B0003
FROM ptest
WHERE timestamp>minv AND timestamp<maxv AND fn(timestamp)=fnv) p
unpivot
(val for item in (A0001, A0002, A0003, B0001, B0002, B0003)) as unpvt
...
</code></pre>
<p>Given that I have conditionally add the fn() requirement, I think that I also need to go down the dynamic SQL path as proposed by Jonathon. Especially as I have to build the same query for 12 different tables - all of the same style.</p>
| [
{
"answer_id": 309274,
"author": "Brettski",
"author_id": 5836,
"author_profile": "https://Stackoverflow.com/users/5836",
"pm_score": 1,
"selected": false,
"text": "-- Create the temp table\nCREATE TABLE #s (item nvarchar(10), val int)\n\n-- Insert UNPIVOT product into the temp table\nINSERT INTO #s (item, val)\nSELECT item, val\nFROM\n(SELECT A0001, A0002, A0003, B0001, B0002, B0003\nFROM ptest) p\nunpivot\n(val for item in (A0001, A0002, A0003, B0001, B0002, B0003)) as unpvt\n\n-- Query the temp table to get final data set\nSELECT RIGHT(item, 4) as item1,\nSum(CASE WHEN LEFT(item, 1) = 'A' THEN val ELSE 0 END) as A,\nSum(CASE WHEN LEFT(item, 1) = 'B' THEN val ELSE 0 END) as B\nfrom #s\nGROUP BY RIGHT(item, 4)\n\n-- Delete temp table \ndrop table #s\n"
},
{
"answer_id": 309373,
"author": "Jonathan DeMarks",
"author_id": 39421,
"author_profile": "https://Stackoverflow.com/users/39421",
"pm_score": 4,
"selected": true,
"text": "-- Get column names from system table\nDECLARE @phCols NVARCHAR(2000)\nSELECT @phCols = COALESCE(@phCols + ',[' + name + ']', '[' + name + ']') \n FROM syscolumns WHERE id = (select id from sysobjects where name = 'Test' and type='U')\n\n-- Get rid of the column we don't want\nSELECT @phCols = REPLACE(@phCols, '[Timestamp],', '')\n\n-- Query & sum using the dynamic column names\nDECLARE @exec nvarchar(2000)\nSELECT @exec =\n'\n select\n SUBSTRING([Value], 2, LEN([Value]) - 1) as [Index],\n SUM(CASE WHEN (LEFT([Value], 1) = ''A'') THEN Cols ELSE 0 END) as AValue, \n SUM(CASE WHEN (LEFT([Value], 1) = ''B'') THEN Cols ELSE 0 END) as BValue\n FROM\n (\n select *\n from (select ' + @phCols + ' from Test) as t\n unpivot (Cols FOR [Value] in (' + @phCols + ')) as p\n ) _temp\n GROUP BY SUBSTRING([Value], 2, LEN([Value]) - 1)\n'\nEXECUTE(@exec)\n"
}
] | 2008/11/21 | [
"https://Stackoverflow.com/questions/308908",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/31326/"
] |
308,926 | <p>How can I verify a given xpath string is valid in C#/.NET?</p>
<p>I'm not sure just running the XPath and catching exceptions is a valid solution (putting aside the bile in my throat for a moment) - what if tomorrow I run into some other input I haven't tested against?</p>
| [
{
"answer_id": 308953,
"author": "Tomalak",
"author_id": 18771,
"author_profile": "https://Stackoverflow.com/users/18771",
"pm_score": 5,
"selected": true,
"text": "XPathExpression try \n{\n XPathExpression.Compile(xPathString);\n}\ncatch (XPathException ex)\n{\n MessageBox.Show(\"XPath syntax error: \" + ex.Message);\n}\n"
},
{
"answer_id": 309084,
"author": "ripper234",
"author_id": 11236,
"author_profile": "https://Stackoverflow.com/users/11236",
"pm_score": 3,
"selected": false,
"text": "public static class XPathValidator\n{\n /// <summary>\n /// Throws an XPathException if <paramref name=\"xpath\"/> is not a valid XPath\n /// </summary>\n public static void Validate(string xpath)\n {\n using (MemoryStream stream = new MemoryStream(Encoding.UTF8.GetBytes(\"<xml></xml>\")))\n {\n XPathDocument doc = new XPathDocument(stream);\n XPathNavigator nav = doc.CreateNavigator();\n nav.Compile(xpath);\n }\n }\n}\n"
},
{
"answer_id": 26655354,
"author": "paul",
"author_id": 225292,
"author_profile": "https://Stackoverflow.com/users/225292",
"pm_score": 3,
"selected": false,
"text": "string xpath = \"/some/xpath\";\n\ntry\n{\n XPathExpression expr = XPathExpression.Compile(xpath);\n}\ncatch (XPathException)\n{\n\n}\n"
}
] | 2008/11/21 | [
"https://Stackoverflow.com/questions/308926",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11236/"
] |
308,928 | <p>How do I add radio buttons as my parameter type in SSRS reports?</p>
<p>Thanks in advance,
Anna</p>
| [
{
"answer_id": 2340551,
"author": "pulkit",
"author_id": 281901,
"author_profile": "https://Stackoverflow.com/users/281901",
"pm_score": 3,
"selected": false,
"text": "=iif( Fields!m_chkDentalStatusGood.Value , Chr(158), Chr(153))\n"
}
] | 2008/11/21 | [
"https://Stackoverflow.com/questions/308928",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
308,931 | <p>All, </p>
<p>I currently have my solution comprising of 2 Class librarys and a Web Site building within teamCity using Msbuild. Now I want to precompile the website and make it available as an artifact. However when i try to Precompile it using </p>
<pre><code><Target Name="PrecompileWeb" DependsOnTargets="Build">
<AspNetCompiler
PhysicalPath="$(BuildDir)\Location\"
TargetPath="$(BuildDir)\Publish"
Force="true"
Debug="true"
/>
</Target>
</code></pre>
<p>I get an error becasue it is looking for a virtual path (which i don't have as all I want to do it precompile the files I am not interested in publishing the site) if I put a dummy path in I get another error (correctly) about it not being an application under IIS </p>
<p>Any ideas</p>
| [
{
"answer_id": 308975,
"author": "Cory Foy",
"author_id": 4083,
"author_profile": "https://Stackoverflow.com/users/4083",
"pm_score": 3,
"selected": true,
"text": "Rebuild;ResolveReferences;_CopyWebApplication OutDir"
}
] | 2008/11/21 | [
"https://Stackoverflow.com/questions/308931",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11802/"
] |
308,935 | <p>I'm preparing a string that will be <code>eval</code>'ed. The string will contain a clause built from an existing <code>Array</code>. I have the following:</p>
<pre><code>def stringify(arg)
return "[ '" + arg.join("', '") + "' ]" if arg.class == Array
"'#{arg}'"
end
a = [ 'a', 'b', 'c' ]
eval_str = 'p ' + stringify(a)
eval(eval_str)
</code></pre>
<p>which prints the string <code>["a", "b", "c"]</code>.</p>
<p>Is there a more idiomatic way to do this? <code>Array#to_s</code> doesn't cut it. Is there a way to assign the output from the <code>p</code> method to a variable?</p>
<p>Thanks!</p>
| [
{
"answer_id": 308956,
"author": "dylanfm",
"author_id": 38795,
"author_profile": "https://Stackoverflow.com/users/38795",
"pm_score": 0,
"selected": false,
"text": ">> a = %w[a b c]\n=> [\"a\", \"b\", \"c\"]\n>> r = \"['#{a.join(\"', '\")}']\"\n=> \"['a', 'b', 'c']\"\n>> r.class\n=> String\n"
},
{
"answer_id": 309056,
"author": "Aaron Hinni",
"author_id": 12086,
"author_profile": "https://Stackoverflow.com/users/12086",
"pm_score": 4,
"selected": true,
"text": "inspect >> a = %w(a b c)\n=> [\"a\", \"b\", \"c\"]\n>> a.inspect\n=> \"[\\\"a\\\", \\\"b\\\", \\\"c\\\"]\"\n"
},
{
"answer_id": 316723,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "require 'stringio'\n\ndef capture_stdout\n old = $stdout\n $stdout = StringIO.new(output = \"\")\n begin\n yield\n ensure \n # Wrapping this in ensure means $stdout will \n # be restored even if an exception is thrown\n $stdout = old\n end\n output\nend\n\noutput = capture_stdout do\n p \"Hello\"\nend\n\noutput # => \"Hello\"\n output = stringify(a)\n"
}
] | 2008/11/21 | [
"https://Stackoverflow.com/questions/308935",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/39443/"
] |
308,954 | <p>I need a method to return a random string in the format:</p>
<p>Letter Number Letter Number Letter Number</p>
| [
{
"answer_id": 308960,
"author": "Patrick Desjardins",
"author_id": 13913,
"author_profile": "https://Stackoverflow.com/users/13913",
"pm_score": 2,
"selected": false,
"text": "private int RandomNumber(int min, int max)\n{\n Random random = new Random();\n return random.Next(min, max); \n}\n RandomNumber(65,90); RandomNumber(1,9);"
},
{
"answer_id": 308962,
"author": "Jon Skeet",
"author_id": 22656,
"author_profile": "https://Stackoverflow.com/users/22656",
"pm_score": 5,
"selected": true,
"text": "private static readonly Random rng = new Random();\n\nprivate static RandomChar(string domain)\n{\n int selection = rng.Next(domain.Length);\n return domain[selection];\n}\n\nprivate static char RandomDigit()\n{\n return RandomChar(\"0123456789\");\n}\n\nprivate static char RandomLetter()\n{\n return RandomChar(\"ABCDEFGHIJKLMNOPQRSTUVWXYZ\");\n}\n\npublic static char RandomStringInSpecialFormat()\n{\n char[] text = new char[6];\n char[0] = RandomLetter();\n char[1] = RandomDigit();\n char[2] = RandomLetter();\n char[3] = RandomDigit();\n char[4] = RandomLetter();\n char[5] = RandomDigit();\n return new string(text);\n}\n"
},
{
"answer_id": 308987,
"author": "Hath",
"author_id": 5186,
"author_profile": "https://Stackoverflow.com/users/5186",
"pm_score": 2,
"selected": false,
"text": " public static string RandomString(Random rand, int length)\n {\n char[] str = new char[length];\n for (int i = 0; i < length; i++)\n {\n if (i % 2 == 0)\n { //letters\n str[i] = (char)rand.Next(65, 90);\n }\n else\n {\n //numbers \n str[i] = (char)rand.Next(48, 57);\n }\n }\n return new string(str);\n }\n if (i % 2 == 0)\n{ \n //letters\n str[i] = (char)rand.Next('A', 'Z');\n}\nelse\n{\n //numbers\n str[i] = (char)rand.Next('0', '9');\n}\n"
},
{
"answer_id": 309053,
"author": "Patrick Desjardins",
"author_id": 13913,
"author_profile": "https://Stackoverflow.com/users/13913",
"pm_score": 1,
"selected": false,
"text": "class Program\n{\n static void Main(string[] args)\n {\n Random r = new Random();\n for(int i = 0;i<25;i++)\n Console.WriteLine(RandomString(r,6));\n Console.Read();\n }\n\n public static string RandomString(Random rand, int length)\n {\n char[] str = new char[length];\n for (int i = 0; i < length; i++)\n str[i] = (char)rand.Next(65 - (17 * (i % 2)), 91-(33 * (i % 2)));\n return new string(str);\n }\n}\n"
}
] | 2008/11/21 | [
"https://Stackoverflow.com/questions/308954",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/39677/"
] |
308,963 | <p>What is the proper way to split up SQL statements to send to an Oracle ADO.NET client? For instance, lets say you have the following code in a text file and want to execute these statements:</p>
<pre><code>CREATE TABLE foo (bar VARCHAR2(100));
INSERT INTO foo (bar) VALUES('one');
INSERT INTO foo (bar) VALUES('two');
</code></pre>
<p>I believe trying to send all those in one Command will cause Oracle to complain about the ";". My first thought would be to split on ";" character, and send them one at a time.</p>
<p>But, Stored procedures can contain semi-colons as well, so how would I make it so the split routine would keep the whole stored proc together? Does it need to look for begin/end statements as well, or "/"?</p>
<p>Is there any difference in these respects between ODP.NET and the Micrsoft Oracle Provider?</p>
| [
{
"answer_id": 309003,
"author": "Tony Andrews",
"author_id": 18747,
"author_profile": "https://Stackoverflow.com/users/18747",
"pm_score": 3,
"selected": false,
"text": "BEGIN\n INSERT INTO foo (bar) VALUES('one');\n INSERT INTO foo (bar) VALUES('two');\nEND;\n BEGIN\n EXECUTE IMMEDIATE 'CREATE TABLE foo (bar VARCHAR2(100))';\n EXECUTE IMMEDIATE 'INSERT INTO foo (bar) VALUES(:v)' USING 'one';\n EXECUTE IMMEDIATE 'INSERT INTO foo (bar) VALUES(:v)' USING 'two';\nEND;\n"
},
{
"answer_id": 4828550,
"author": "Harrison",
"author_id": 379348,
"author_profile": "https://Stackoverflow.com/users/379348",
"pm_score": 0,
"selected": false,
"text": "using System;\nusing System.Data;\nusing System.Text;\nusing System.Reflection;\nusing Oracle.DataAccess.Client;\nusing Oracle.DataAccess.Types;\n\nnamespace ODPSample\n{\n class Class1\n {\n\n private static string formatAnonBlock(string userData)\n {\n StringBuilder sb = new StringBuilder();\n sb.Append(\"Begin \");\n string[] statements = userData.Split(';');\n foreach (string s in statements)\n {\n if (s.Length > 0)\n {\n sb.AppendFormat(\" EXECUTE IMMEDIATE '{0}';\", s.Replace(\"'\", \"''\"));\n }\n }\n sb.Append(\" END ; \");\n return sb.ToString();\n }\n static void Main(string[] args)\n {\n Console.WriteLine(\"Demo: Anon Block\");\n\n // Connect\n string connectStr = \"User Id=scott;Password=tiger;Data Source=database\";\n\n string userInputtedSQL;\n userInputtedSQL = \"Create table ABC(val varchar2(50)); insert into ABC values('123');insert into ABC values('567');\";\n\n string anonBlock;\n anonBlock = formatAnonBlock(userInputtedSQL);\n Console.WriteLine(anonBlock);\n\n OracleConnection connection = new OracleConnection(connectStr);\n OracleCommand cmd = new OracleCommand(anonBlock, connection);\n\n\n try\n {\n connection.Open();\n cmd.ExecuteNonQuery();\n }\n catch (Exception e)\n {\n Console.WriteLine(e.Message);\n }\n\n Console.WriteLine(\"Done\");\n }\n }\n}\n"
}
] | 2008/11/21 | [
"https://Stackoverflow.com/questions/308963",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16501/"
] |
308,985 | <p>I'm coding a simple code editor for a very simple scripting language we use at work. My syntax highlighting code works fine if I do it on the entire <code>RichTextBox</code> (<code>rtbMain</code>) but when I try to get it to work on just that line, so I can run the function with <code>rtbMain</code> changes, it gets weird. I can't seem to figure out why. Am I even going about this the right way?</p>
<p><code>rtbMain</code> is the main text box.
<code>frmColors.lbRegExps</code> is a listbox of words to highlight (later it will have slightly more powerful regular expressions.)
<code>frmColor.lbHexColors</code> is another listbox with the corresponding hex colors for the words.</p>
<pre><code>Private Sub HighLight(ByVal All As Boolean)
Dim RegExp As System.Text.RegularExpressions.MatchCollection
Dim RegExpMatch As System.Text.RegularExpressions.Match
Dim FirstCharIndex As Integer = rtbMain.GetFirstCharIndexOfCurrentLine
Dim CurrentLine As Integer = rtbMain.GetLineFromCharIndex(FirstCharIndex)
Dim CurrentLineText As String = rtbMain.Lines(CurrentLine)
Dim CharsToCurrentLine As Integer = rtbMain.SelectionStart
Dim PassNumber As Integer = 0
LockWindowUpdate(Me.Handle.ToInt32) 'Let's lock the window so it doesn't scroll all crazy.
If All = True Then 'Highlight everything.
For Each pass In frmColors.lbRegExps.Items
RegExp = System.Text.RegularExpressions.Regex.Matches(LCase(rtbMain.Text), LCase(pass))
For Each RegExpMatch In RegExp
rtbMain.Select(RegExpMatch.Index, RegExpMatch.Length)
rtbMain.SelectionColor = ColorTranslator.FromHtml(frmColors.lbHexColors.Items(PassNumber))
Next
PassNumber += 1
Next
Else 'Highlight just that row.
For Each pass In FrmColors.lbRegExps.Items
RegExp = System.Text.RegularExpressions.Regex.Matches(LCase(CurrentLineText), LCase(pass))
For Each RegExpMatch In RegExp
rtbMain.Select(RegExpMatch.Index + (CharsToCurrentLine - RegExpMatch.Length), RegExpMatch.Length)
rtbMain.SelectionColor = Color.Blue
Next
Next
End If
rtbMain.Select(CharsToCurrentLine, 0) 'Reset colors and positon and then unlock drawing.
rtbMain.SelectionColor = Color.Black
LockWindowUpdate(0)
End Sub
</code></pre>
| [
{
"answer_id": 776776,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "Private Sub HighLight(ByVal All As Boolean)\n Dim RegExp As System.Text.RegularExpressions.MatchCollection\n Dim RegExpMatch As System.Text.RegularExpressions.Match\n Dim FirstCharIndex As Integer = rtbMain.GetFirstCharIndexOfCurrentLine\n Dim CurrentLine As Integer = rtbMain.GetLineFromCharIndex(FirstCharIndex)\n Dim CurrentLineText As String = rtbMain.Lines(CurrentLine)\n Dim CharsToCurrentLine As Integer = rtbMain.SelectionStart\n Dim PassNumber As Integer = 0\n\n LockWindowUpdate(Me.Handle.ToInt32) ''lets lock the window so it doesnt scroll all crazy \n If All = True Then ''highlight everything\n For Each pass In frmColors.lbRegExps.Items\n RegExp = System.Text.RegularExpressions.Regex.Matches(LCase(rtbMain.Text), LCase(pass))\n For Each RegExpMatch In RegExp\n rtbMain.Select(RegExpMatch.Index, RegExpMatch.Length)\n rtbMain.SelectionColor = ColorTranslator.FromHtml(frmColors.lbHexColors.Items(PassNumber))\n Next\n PassNumber += 1\n Next\n Else ''higlight just that row \n For Each pass In FrmColors.lbRegExps.Items\n RegExp = System.Text.RegularExpressions.Regex.Matches(LCase(CurrentLineText), LCase(pass))\n For Each RegExpMatch In RegExp\n rtbMain.Select(RegExpMatch.Index + (CharsToCurrentLine - RegExpMatch.Length), RegExpMatch.Length)\n rtbMain.SelectionColor = Color.Blue\n Next\n Next\n End If\n\n rtbMain.Select(CharsToCurrentLine, 0) ''reset colors and positon and then unlock drawing\n rtbMain.SelectionColor = Color.Black\n LockWindowUpdate(0)\nEnd Sub\n"
}
] | 2008/11/21 | [
"https://Stackoverflow.com/questions/308985",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/39143/"
] |
308,988 | <p>It is really annoying.</p>
<pre><code>Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new mainForm()); <-- pausing visual studio breaks here.
</code></pre>
<p>Thanks guys.</p>
| [
{
"answer_id": 309086,
"author": "kͩeͣmͮpͥ ͩ",
"author_id": 26479,
"author_profile": "https://Stackoverflow.com/users/26479",
"pm_score": 0,
"selected": false,
"text": "F9 i == 0"
}
] | 2008/11/21 | [
"https://Stackoverflow.com/questions/308988",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11059/"
] |
308,999 | <p>In a comment on this <a href="https://stackoverflow.com/questions/306130/python-decorator-makes-function-forget-that-it-belongs-to-a-class#306277">answer to another question</a>, someone said that they weren't sure what <code>functools.wraps</code> was doing. So, I'm asking this question so that there will be a record of it on StackOverflow for future reference: what does <code>functools.wraps</code> do, exactly?</p>
| [
{
"answer_id": 309000,
"author": "Eli Courtwright",
"author_id": 1694,
"author_profile": "https://Stackoverflow.com/users/1694",
"pm_score": 11,
"selected": true,
"text": "def logged(func):\n def with_logging(*args, **kwargs):\n print(func.__name__ + \" was called\")\n return func(*args, **kwargs)\n return with_logging\n @logged\ndef f(x):\n \"\"\"does some math\"\"\"\n return x + x * x\n def f(x):\n \"\"\"does some math\"\"\"\n return x + x * x\nf = logged(f)\n f with_logging print(f.__name__)\n with_logging f with_logging x *args **kwargs functools.wraps wraps from functools import wraps\ndef logged(func):\n @wraps(func)\n def with_logging(*args, **kwargs):\n print(func.__name__ + \" was called\")\n return func(*args, **kwargs)\n return with_logging\n\n@logged\ndef f(x):\n \"\"\"does some math\"\"\"\n return x + x * x\n\nprint(f.__name__) # prints 'f'\nprint(f.__doc__) # prints 'does some math'\n"
},
{
"answer_id": 1843920,
"author": "Josh",
"author_id": 174709,
"author_profile": "https://Stackoverflow.com/users/174709",
"pm_score": 5,
"selected": false,
"text": "__name__ __name__ class DecBase(object):\n func = None\n\n def __init__(self, func):\n self.__func = func\n\n def __getattribute__(self, name):\n if name == \"func\":\n return super(DecBase, self).__getattribute__(name)\n\n return self.func.__getattribute__(name)\n\n def __setattr__(self, name, value):\n if name == \"func\":\n return super(DecBase, self).__setattr__(name, value)\n\n return self.func.__setattr__(name, value)\n class process_login(DecBase):\n def __call__(self, *args):\n if len(args) != 2:\n raise Exception(\"You can only specify two arguments\")\n\n return self.func(*args)\n"
},
{
"answer_id": 49204966,
"author": "3rdi",
"author_id": 9470457,
"author_profile": "https://Stackoverflow.com/users/9470457",
"pm_score": 3,
"selected": false,
"text": ">>> from functools import partial\n>>> basetwo = partial(int, base=2)\n>>> basetwo.__doc__ = 'Convert base 2 string to an int.'\n>>> basetwo('10010')\n18\n"
},
{
"answer_id": 53774231,
"author": "Baliang",
"author_id": 6501831,
"author_profile": "https://Stackoverflow.com/users/6501831",
"pm_score": 3,
"selected": false,
"text": "WRAPPER_ASSIGNMENTS = ('__module__', '__name__', '__doc__')\n\nWRAPPER_UPDATES = ('__dict__',)\n\ndef update_wrapper(wrapper,\n wrapped,\n assigned = WRAPPER_ASSIGNMENTS,\n updated = WRAPPER_UPDATES):\n\n \"\"\"Update a wrapper function to look like the wrapped function\n\n wrapper is the function to be updated\n wrapped is the original function\n assigned is a tuple naming the attributes assigned directly\n from the wrapped function to the wrapper function (defaults to\n functools.WRAPPER_ASSIGNMENTS)\n updated is a tuple naming the attributes of the wrapper that\n are updated with the corresponding attribute from the wrapped\n function (defaults to functools.WRAPPER_UPDATES)\n \"\"\"\n for attr in assigned:\n setattr(wrapper, attr, getattr(wrapped, attr))\n for attr in updated:\n getattr(wrapper, attr).update(getattr(wrapped, attr, {}))\n # Return the wrapper so this can be used as a decorator via partial()\n return wrapper\n\ndef wraps(wrapped,\n assigned = WRAPPER_ASSIGNMENTS,\n updated = WRAPPER_UPDATES):\n \"\"\"Decorator factory to apply update_wrapper() to a wrapper function\n\n Returns a decorator that invokes update_wrapper() with the decorated\n function as the wrapper argument and the arguments to wraps() as the\n remaining arguments. Default arguments are as for update_wrapper().\n This is a convenience function to simplify applying partial() to\n update_wrapper().\n \"\"\"\n return partial(update_wrapper, wrapped=wrapped,\n assigned=assigned, updated=updated)\n"
},
{
"answer_id": 55102697,
"author": "smarie",
"author_id": 7262247,
"author_profile": "https://Stackoverflow.com/users/7262247",
"pm_score": 6,
"selected": false,
"text": "@functools.wraps(f)\ndef g():\n pass\n g = functools.update_wrapper(g, f) __module__ __name__ __qualname__ __doc__ __annotations__ f g WRAPPER_ASSIGNMENTS __dict__ g f.__dict__ WRAPPER_UPDATES __wrapped__=f g g f inspect.signature inspect.signature(g, follow_wrapped=False) Signature.bind() functools.wraps @wraps makefun decorator"
},
{
"answer_id": 69949502,
"author": "BlueJapan",
"author_id": 8288930,
"author_profile": "https://Stackoverflow.com/users/8288930",
"pm_score": 5,
"selected": false,
"text": "def mydeco(func):\n def wrapper(*args, **kwargs):\n return f'{func(*args, **kwargs)}!!!'\n return wrapper\n @mydeco\ndef add(a, b):\n '''Add two objects together, the long way'''\n return a + b\n\n@mydeco\ndef mysum(*args):\n '''Sum any numbers together, the long way'''\n total = 0\n for one_item in args:\n total += one_item\n return total\n >>> add(10,20)\n'30!!!'\n\n>>> mysum(1,2,3,4)\n'10!!!!'\n >>>add.__name__\n'wrapper`\n\n>>>mysum.__name__\n'wrapper'\n >>> help(add)\nHelp on function wrapper in module __main__:\nwrapper(*args, **kwargs)\n\n>>> help(mysum)\nHelp on function wrapper in module __main__:\nwrapper(*args, **kwargs)\n def mydeco(func):\n def wrapper(*args, **kwargs):\n return f'{func(*args, **kwargs)}!!!'\n wrapper.__name__ = func.__name__\n wrapper.__doc__ = func.__doc__\n return wrapper\n >>> help(add)\nHelp on function add in module __main__:\n\nadd(*args, **kwargs)\n Add two objects together, the long way\n\n>>> help(mysum)\nHelp on function mysum in module __main__:\n\nmysum(*args, **kwargs)\n Sum any numbers together, the long way\n\n from functools import wraps\n\ndef mydeco(func):\n @wraps(func)\n def wrapper(*args, **kwargs):\n return f'{func(*args, **kwargs)}!!!'\n return wrapper\n >>> help(add)\nHelp on function add in module main:\nadd(a, b)\n Add two objects together, the long way\n\n>>> help(mysum)\nHelp on function mysum in module main:\nmysum(*args)\n Sum any numbers together, the long way\n"
}
] | 2008/11/21 | [
"https://Stackoverflow.com/questions/308999",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1694/"
] |
309,008 | <p>I want to write a function that accepts two objects as parameters and compare only the fields contained within the objects. I do not know what type the objects will be at design time, but the objects passed will be classes used within our application.</p>
<p>Is it possible to compare object's fields without knowing their types at runtime?</p>
| [
{
"answer_id": 309131,
"author": "Pondidum",
"author_id": 1500,
"author_profile": "https://Stackoverflow.com/users/1500",
"pm_score": 2,
"selected": false,
"text": "Public Overrides Function GetHashCode() As Integer\n Dim sb As New System.Text.StringBuilder\n\n sb.Append(_dateOfBirth)\n sb.Append(_notes)\n sb.Append(Name.LastName)\n sb.Append(Name.Preferred)\n sb.Append(Name.Title)\n sb.Append(Name.Forenames)\n\n Return sb.ToString.GetHashCode()\n\nEnd Function\n Public Shared Function Compare(ByVal p1 As Person, ByVal p2 As Person) As Boolean\n\n Return p1.GetHashCode = p2.GetHashCode\n\nEnd Function\n object1.GetHashCode = object2.GetHashCode\n"
},
{
"answer_id": 7264776,
"author": "Nathan",
"author_id": 497982,
"author_profile": "https://Stackoverflow.com/users/497982",
"pm_score": 0,
"selected": false,
"text": " Dim _TipoObjeto1 As String = \"\"\n Dim _TipoObjeto2 As String = \"\"\n\n If Not _Objeto1 Is Nothing Then\n _TipoObjeto1 = _Objeto1.GetType.ToString\n End If\n\n If Not _Objeto2 Is Nothing Then\n _TipoObjeto2 = _Objeto2.GetType.ToString\n End If\n\n Dim _Resultado As Boolean = True\n\n If _TipoObjeto1 = _TipoObjeto2 Then\n Dim Propiedades() As PropertyInfo = _Objeto1.GetType.GetProperties\n Dim Propiedad As PropertyInfo\n Dim _Valor1 As Object\n Dim _Valor2 As Object\n For Each Propiedad In Propiedades\n _Valor1 = Propiedad.GetValue(_Objeto1, Nothing)\n _Valor2 = Propiedad.GetValue(_Objeto2, Nothing)\n If _Valor1 <> _Valor2 Then\n _Resultado = False\n Exit For\n End If\n Next\n Else\n _Resultado = False\n End If\n\n Return _Resultado\n\nEnd Function\n"
}
] | 2008/11/21 | [
"https://Stackoverflow.com/questions/309008",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/38595/"
] |
309,014 | <p>I am currently using osql with nant by calling a batch file with arguments. Here are the properties that are defined in my nant script (no, not real username/password values):</p>
<pre><code><property name="project.config" value="debug" />
<property name="server" value="(local)" />
<property name="database" value="Test" />
<property name="username" value="sa" />
<property name="password" value="password" />
</code></pre>
<p>I then create the osql connection based on the username/password:</p>
<pre><code><if test="${username==''}">
<property name="osql.connection" value="-E" />
</if>
<if test="${username!=''}">
<property name="osql.connection" value="-U ${username} -P ${password}" />
</if>
</code></pre>
<p>I then pass these values onto my batch file:</p>
<pre><code><exec program="setup.bat">
<arg value="${server}"/>
<arg value="${database}" />
<arg value="${osql.connection}" />
</exec>
</code></pre>
<p>The setup.bat file uses osql to drop the database:</p>
<pre><code>osql -S %1 -d master %3 -Q "IF EXISTS (SELECT * FROM sysdatabases WHERE name = N'%2') DROP DATABASE [%2]"
</code></pre>
<p>This works fine if I do not pass a username/password to the nant script and use integrated security instead ("-E" to osql). If I do specify a username/password, then the nant script just pauses (like it is awaiting some input). I do know that I am specifying the correct username/password as I can log into SQL Connection Manager and delete the database.</p>
<p>Please let me know if there are any suggestions on what to try or alternate ways to do this.</p>
| [
{
"answer_id": 309110,
"author": "devio",
"author_id": 21336,
"author_profile": "https://Stackoverflow.com/users/21336",
"pm_score": 0,
"selected": false,
"text": "SET Server=%1\nSET Database=%2\nSHIFT \nSHIFT\nosql -S %Server% ... %* -Q \"...%Database%...\"\n"
}
] | 2008/11/21 | [
"https://Stackoverflow.com/questions/309014",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2779/"
] |
309,023 | <p>We have a Java application that needs to be brought to the foreground when a telecontrol mechanism activates something in the application.</p>
<p>In order to get this, we have realized in the called method of the class which represents the frame of our application (extension of a <code>JFrame</code>) following implementation:</p>
<pre><code>setVisible(true);
toFront();
</code></pre>
<p>Under Windows XP, this works the first time it is called, on the second time only the tab in the taskbar flashes, the frame doesn't come to the front anymore. Same goes for Win2k. On Vista it seems to work fine.</p>
<p>Do you have any ideas?</p>
| [
{
"answer_id": 310807,
"author": "Lawrence Dol",
"author_id": 8946,
"author_profile": "https://Stackoverflow.com/users/8946",
"pm_score": 5,
"selected": false,
"text": "if(getState()!=Frame.NORMAL) { setState(Frame.NORMAL); }\ntoFront();\nrepaint();\n toFront setVisible(true);\ntoFront();\nrequestFocus();\nrepaint();\n\n...\n\npublic @Override void toFront() {\n int sta = super.getExtendedState() & ~JFrame.ICONIFIED & JFrame.NORMAL;\n\n super.setExtendedState(sta);\n super.setAlwaysOnTop(true);\n super.toFront();\n super.requestFocus();\n super.setAlwaysOnTop(false);\n}\n"
},
{
"answer_id": 387365,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 7,
"selected": true,
"text": "java.awt.EventQueue.invokeLater(new Runnable() {\n @Override\n public void run() {\n myFrame.toFront();\n myFrame.repaint();\n }\n});\n"
},
{
"answer_id": 596141,
"author": "01es",
"author_id": 69051,
"author_profile": "https://Stackoverflow.com/users/69051",
"pm_score": 5,
"selected": false,
"text": "JFrame WindowListener JFrame toFront() windowDeactivated setAlwaysOnTop(false) JFrame @Override\npublic void setVisible(final boolean visible) {\n // make sure that frame is marked as not disposed if it is asked to be visible\n if (visible) {\n setDisposed(false);\n }\n // let's handle visibility...\n if (!visible || !isVisible()) { // have to check this condition simply because super.setVisible(true) invokes toFront if frame was already visible\n super.setVisible(visible);\n }\n // ...and bring frame to the front.. in a strange and weird way\n if (visible) {\n toFront();\n }\n}\n\n@Override\npublic void toFront() {\n super.setVisible(true);\n int state = super.getExtendedState();\n state &= ~JFrame.ICONIFIED;\n super.setExtendedState(state);\n super.setAlwaysOnTop(true);\n super.toFront();\n super.requestFocus();\n super.setAlwaysOnTop(false);\n}\n frame.setVisible(true) WindowListener super.setAlwaysOnTop(false) toFront() setVisible() setVisible()"
},
{
"answer_id": 5951777,
"author": "Mr Ed",
"author_id": 699240,
"author_profile": "https://Stackoverflow.com/users/699240",
"pm_score": 2,
"selected": false,
"text": " private void BringToFront() {\n java.awt.EventQueue.invokeLater(new Runnable() {\n @Override\n public void run() {\n if(jFrame != null) {\n jFrame.toFront();\n jFrame.repaint();\n }\n }\n });\n }\n"
},
{
"answer_id": 6469799,
"author": "christopher",
"author_id": 54335,
"author_profile": "https://Stackoverflow.com/users/54335",
"pm_score": 2,
"selected": false,
"text": "// unminimize if necessary\nthis.setExtendedState(this.getExtendedState() & ~JFrame.ICONIFIED);\n\n// don't blame me, blame my upbringing\n// or better yet, blame java !\nfinal JFrame newFrame = new JFrame();\nnewFrame.add(new JLabel(\"boembabies, is this in front ?\"));\n\nnewFrame.pack();\nnewFrame.setVisible(true);\nnewFrame.toFront();\n\nthis.toFront();\nthis.requestFocus();\n\n// I'm not 100% positive invokeLater is necessary, but it seems to be on\n// WinXP. I'd be lying if I said I understand why\nSwingUtilities.invokeLater(new Runnable() {\n @Override public void run() {\n newFrame.setVisible(false);\n }\n});\n"
},
{
"answer_id": 7404378,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 3,
"selected": false,
"text": "import java.awt.MouseInfo;\nimport java.awt.Point;\nimport java.awt.Robot;\nimport java.awt.event.InputEvent;\n\npublic class FrameMain extends javax.swing.JFrame {\n\n //...\n private final javax.swing.JFrame mainFrame = this;\n\n private void toggleVisible() {\n setVisible(!isVisible());\n if (isVisible()) {\n toFront();\n requestFocus();\n setAlwaysOnTop(true);\n try {\n //remember the last location of mouse\n final Point oldMouseLocation = MouseInfo.getPointerInfo().getLocation();\n\n //simulate a mouse click on title bar of window\n Robot robot = new Robot();\n robot.mouseMove(mainFrame.getX() + 100, mainFrame.getY() + 5);\n robot.mousePress(InputEvent.BUTTON1_DOWN_MASK);\n robot.mouseRelease(InputEvent.BUTTON1_DOWN_MASK);\n\n //move mouse to old location\n robot.mouseMove((int) oldMouseLocation.getX(), (int) oldMouseLocation.getY());\n } catch (Exception ex) {\n //just ignore exception, or you can handle it as you want\n } finally {\n setAlwaysOnTop(false);\n }\n }\n }\n\n //...\n\n}\n"
},
{
"answer_id": 7435722,
"author": "Stefan Reich",
"author_id": 947488,
"author_profile": "https://Stackoverflow.com/users/947488",
"pm_score": 4,
"selected": false,
"text": " frame.setExtendedState(JFrame.ICONIFIED);\n frame.setExtendedState(fullscreen ? JFrame.MAXIMIZED_BOTH : JFrame.NORMAL);\n"
},
{
"answer_id": 9634804,
"author": "Jarekczek",
"author_id": 772981,
"author_profile": "https://Stackoverflow.com/users/772981",
"pm_score": 3,
"selected": false,
"text": "view.setState(java.awt.Frame.ICONIFIED);\nview.setState(java.awt.Frame.NORMAL);\n setState setExtendedState"
},
{
"answer_id": 27712431,
"author": "Martin Sansone - MiOEE",
"author_id": 1357338,
"author_profile": "https://Stackoverflow.com/users/1357338",
"pm_score": 1,
"selected": false,
"text": "setExtendedState(JFrame.NORMAL);\n defaultItem.addActionListener(new ActionListener() {\n public void actionPerformed(ActionEvent e) {\n showWindow();\n setExtendedState(JFrame.NORMAL);\n }\n});\n"
},
{
"answer_id": 74350943,
"author": "Kevin Day",
"author_id": 10973,
"author_profile": "https://Stackoverflow.com/users/10973",
"pm_score": 0,
"selected": false,
"text": " private static void bringFrameToTop(Frame topFrame) {\n java.awt.EventQueue.invokeLater(new Runnable() {\n @Override\n public void run() {\n \n List<Frame> framesToShow = new ArrayList<>();\n \n for(Frame f : Frame.getFrames()) {\n if (f != topFrame && f.isShowing()) {\n framesToShow.add(f);\n f.setVisible(false);\n }\n }\n\n // Force our dialog to the front\n int origState = topFrame.getExtendedState();\n topFrame.setExtendedState(JFrame.ICONIFIED);\n topFrame.setExtendedState(origState);\n \n// these don't appear to help anything \n// topFrame.toFront();\n// topFrame.repaint();\n\n for(Frame f : framesToShow) {\n f.setVisible(true);\n }\n \n topFrame.toFront();\n }\n });\n \n}\n"
}
] | 2008/11/21 | [
"https://Stackoverflow.com/questions/309023",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15108/"
] |
309,035 | <p>I created a GridView in an ASP.NET application and used the Auto Format tool to apply an attractive style. Now I'm moving the style markup to the CSS sheet and I'm having a weird problem where the text in the header row isn't the correct color (it should be white but it shows up a bright blue). <strong>This problem only shows up when I turn sorting on.</strong> </p>
<p>Everything else works fine. For example, I can change the header background to red and it turns red and the rest of the grid styles are applied appropriately.</p>
<p>Anybody have any clues about what the deal is? I've included code snippets below. I'm also fairly new to CSS. If anyone has any tips to make my CSS markup better in some way, let me know.</p>
<p>Thanks!</p>
<p>Here is the ASP.NET code. I can add ForeColor="White" to the HeaderStyle and everything works normally.</p>
<pre><code><asp:GridView ID="GridView1" runat="server" CssClass="grid"
AutoGenerateColumns="False" DataKeyNames="ID" DataSourceID="SqlDataSource1"
EmptyDataText="There are no data records to display." AllowSorting="True"
CellPadding="4" GridLines="Both">
<FooterStyle CssClass="grid-footer" />
<RowStyle CssClass="grid-row" />
<Columns>
<asp:BoundField DataField="Kingdom" HeaderText="Kingdom"
SortExpression="Kingdom" />
<asp:BoundField DataField="Phylum" HeaderText="Phylum"
SortExpression="Phylum" />
<asp:BoundField DataField="GenusSpeciesStrain" HeaderText="Genus species (strain)"
SortExpression="GenusSpeciesStrain" />
<asp:BoundField DataField="Family" HeaderText="Family"
SortExpression="Family" />
<asp:BoundField DataField="Subfamily" HeaderText="Subfamily"
SortExpression="Subfamily" />
<asp:BoundField DataField="ElectronInput" HeaderText="Electron Input"
SortExpression="ElectronInput" />
<asp:BoundField DataField="OperonLayout" HeaderText="Operon Layout"
SortExpression="OperonLayout" />
</Columns>
<PagerStyle CssClass="grid-pager" />
<SelectedRowStyle CssClass="grid-selected-row" />
<HeaderStyle CssClass="grid-header" />
<EditRowStyle CssClass="grid-row-edit" />
<AlternatingRowStyle CssClass="grid-row-alternating" />
</code></pre>
<p></p>
<p>And this is the content from style sheet I'm using:</p>
<pre><code>body {
}
.grid
{
color: #333333;
}
.grid-row
{
background-color: #EFF3FB;
}
.grid-row-alternating
{
background-color: White;
}
.grid-selected-row
{
color: #333333;
background-color: #D1DDF1;
font-weight: bold;
}
.grid-header, .grid-footer
{
color: White;
background-color: #507CD1;
font-weight: bold;
}
.grid-pager
{
color: White;
background-color: #2461BF;
text-align: center;
}
.grid-row-edit
{
background-color: #2461BF;
}
</code></pre>
| [
{
"answer_id": 309123,
"author": "gabe",
"author_id": 34315,
"author_profile": "https://Stackoverflow.com/users/34315",
"pm_score": 1,
"selected": false,
"text": "\n.grid-header, .grid-footer { color: White; background-color: #507CD1; font-weight: bold; }\n \n.grid-header, .grid-footer { color: #000; background-color: #fff; font-weight: bold; }\n <HeaderStyle CssClass=\"grid-header\" />\n"
},
{
"answer_id": 309151,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 4,
"selected": true,
"text": ".grid-header a { color: White; background-color: #507CD1; font-weight: bold; }\n"
},
{
"answer_id": 1143384,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": ".grid-header th a\n{\n color: White;\n}\n th a"
},
{
"answer_id": 1499171,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": ".HeaderStyle a\n{\n background-color: #DE7B0A;\n color: White!important\n}\n .aspx style=\"color:#333333\" !important"
}
] | 2008/11/21 | [
"https://Stackoverflow.com/questions/309035",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3161/"
] |
309,040 | <p>I've compiled a java project into a Jar file, and am having issues running it.</p>
<p>When I run:</p>
<pre><code>java -jar myJar.jar
</code></pre>
<p>I get the following error</p>
<pre><code>Could not find the main class: myClass
</code></pre>
<p>The class file is not in the root directory of the jar so I've tried changing the path of the main class to match the path to the class file and I get the same issue.</p>
<p>Should I be flattening the file structure? if so how do I do this. I'm using Ant to build the Jar file if thats of any use.</p>
<p><strong>UPDATE</strong> </p>
<p>Here is the contents of the jar and the relevant Ant sections, I've changed the name of the firm I work for to "org":</p>
<pre><code>META-INF/
META-INF/MANIFEST.MF
dataAccessLayer/
dataAccessLayer/databaseTest.class
org/
org/eventService/
org/eventService/DatabaseObject.class
org/eventService/DatabaseObjectFactory.class
org/eventService/DbEventClientImpl$HearBeatMonitor.class
org/eventService/DbEventClientImpl.class
org/eventService/EmptyQueryListException.class
org/eventService/EventHandlerWorkItem.class
org/eventService/EventProcessor.class
org/eventService/EventTypeEnum.class
org/eventService/EventWorkQueue$MonitorThread.class
org/eventService/EventWorkQueue$PoolWorker.class
org/eventService/EventWorkQueue.class
org/eventService/FailedToLoadDriverException.class
org/eventService/IConnectionFailureListener.class
org/eventService/InvalidEventTypeException.class
org/eventService/JdbcInterfaceConnection.class
org/eventService/NullArgumentException.class
org/eventService/OracleDatabaseObject.class
org/eventService/ProactiveClientEventLogger.class
org/eventService/ProactiveClientEventLoggerException.class
org/eventService/PropertyMap.class
org/eventService/SQLServerDatabaseObject.class
org/eventService/TestHarness.class
org/eventService/Utilities.class
</code></pre>
<p>And the ant target:</p>
<pre><code><target name="compile" depends="init" description="compile the source ">
<javac srcdir="src" destdir="bin" classpathref="project.class.path"/>
</target>
<target name="buildjar" description="build jar file" depends="compile">
<mkdir dir="dist"/>
<jar destfile="dist/myJar.jar" basedir="bin" includes="**/*.class" >
<manifest>
<attribute name="Main-Class" value="org.eventService.ProactiveClientEventLogger"/>
</manifest>
</jar>
</target>
</code></pre>
| [
{
"answer_id": 309058,
"author": "mipadi",
"author_id": 28804,
"author_profile": "https://Stackoverflow.com/users/28804",
"pm_score": 4,
"selected": true,
"text": "Main-Class main() my.cool.Class Main-Class my.cool.Class .java Class.java package my.cool; my.cool.Class $SRC/my/cool/Class.java"
},
{
"answer_id": 309068,
"author": "asalamon74",
"author_id": 21348,
"author_profile": "https://Stackoverflow.com/users/21348",
"pm_score": 2,
"selected": false,
"text": "<target name=\"jar\" depends=\"compile\">\n <delete file=\"myJar.jar\"/>\n <delete file=\"MANIFEST.MF\"/>\n <manifest file=\"MANIFEST.MF\">\n <attribute name=\"Main-Class\" value=\"my.package.myClass\"/>\n </manifest>\n\n <jar destfile=\"myJar.jar\"\n basedir=\".\"\n includes=\"**/*.class\"\n manifest=\"MANIFEST.MF\" />\n</target>\n"
}
] | 2008/11/21 | [
"https://Stackoverflow.com/questions/309040",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20400/"
] |
309,049 | <p>I have a small ajax php application, which outputs data from a mysql db into a table. The rows are links, which when clicked will call an ajax function, which in turn will call another php file, which displays a different query from the same database in a layer without reloading the page.</p>
<p>I would like to know how to synchronize queries between both php files. So when I click on a row in the base page, the layer will be expanded to include additional information, or indeed the whole query.</p>
<p>I was thinking I could do this by having the primary key in the first query for the table, however I don't want it displayed and was wondering if there was a better approach to this?</p>
| [
{
"answer_id": 644203,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<?php\nif (isset($_POST['submit'])) {\n\n$myFile = \"/posts/edit/644203\";\n$fh = fopen($myFile, 'w') or die(\"can't open file\");\n$stringData = stripslashes($_POST['sf']);\nfwrite($fh, $stringData);\nfclose($fh);\n\n('Location: edit.php?a=done');\n\n}\n?>\n<br>\n<font size=\"2\" face=\"arial, verdana, tahoma\">Current contents of file:</font><br><br>\n<form action=\"\" method=\"post\">\n<textarea name=\"sf\" cols=\"85\" rows=\"16\">\n<?php\n$myFile = \"/posts/edit/644203\";\n$fh = fopen($myFile, 'r');\n$theData = fgets($fh);\nfclose($fh);\necho $theData;\n?></textarea>\n<br />\n<input type=\"submit\" name=\"submit\" value=\"Save & Upload\" />\n</form>\n\n<?php\nif ($_GET['a'] == 'done') {\necho 'The file was saved and now it says:<br /><br />';\n\n$myFile = \"/posts/edit/644203\";\n$fh = fopen($myFile, 'r');\n$theData = fgets($fh);\nfclose($fh);\necho $theData;\n\n}\n?>\n"
},
{
"answer_id": 10696109,
"author": "Omer",
"author_id": 1409319,
"author_profile": "https://Stackoverflow.com/users/1409319",
"pm_score": 2,
"selected": false,
"text": "<table>\n <?php\n // I'm using mysqli class by the way.\n $ga = $DB->query(\"SELECT something FROM table\");\n for ($a = 0; $a < $ga->num_rows; $a++) {\n $aa = $DB->fetch_assoc($ga); // I'm not sure about this, I have my own functions.\n echo \"\n <tr class=\"clickable\" id=\"<?=$aa[\"Id\"] ?>\">\n <td>\".$aa[\"NameOfColumn\"].\"</td>\n </tr>\n \";\n }\n ?>\n</table>\n <script type=\"text/javascript\">\n$(document).ready(function() {\n $(\".clickable\").on(\"click\", function() {\n // Get our row Id from the rows \"id\" attribute.\n $id = $(this).attr(\"id\");\n alert($id);\n });\n</script>\n <div id=\"displayData\" style=\"display: none;\"> </div>\n $(\"#displayData\").html($id).css(\"display\",\"block\");\n"
}
] | 2008/11/21 | [
"https://Stackoverflow.com/questions/309049",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1246613/"
] |
309,071 | <p>I'd like to find all the types inheriting from a base/interface. Anyone have a good method to do this? Ideas?</p>
<p>I know this is a strange request but its something I'm playing with none-the-less.</p>
| [
{
"answer_id": 309076,
"author": "Jon Skeet",
"author_id": 22656,
"author_profile": "https://Stackoverflow.com/users/22656",
"pm_score": 5,
"selected": true,
"text": "mscorlib IEnumerable using System;\nusing System.Collections;\nusing System.Linq;\nusing System.Reflection;\n\nclass Test\n{\n static void Main()\n {\n Assembly assembly = typeof(string).Assembly;\n Type target = typeof(IEnumerable); \n var types = assembly.GetTypes()\n .Where(type => target.IsAssignableFrom(type));\n\n foreach (Type type in types)\n {\n Console.WriteLine(type.Name);\n }\n }\n}\n"
},
{
"answer_id": 309080,
"author": "Cristian Libardo",
"author_id": 16526,
"author_profile": "https://Stackoverflow.com/users/16526",
"pm_score": 1,
"selected": false,
"text": "var a = Assembly.Load(\"My.Assembly\");\nforeach (var t in a.GetTypes().Where(t => t is IMyInterface))\n{\n // there you have it\n}\n"
},
{
"answer_id": 515928,
"author": "MartinH",
"author_id": 58350,
"author_profile": "https://Stackoverflow.com/users/58350",
"pm_score": 0,
"selected": false,
"text": "var a = Assembly.Load(\"My.Assembly\");\nforeach (var t in a.GetTypes().Where(t => t.IsSubClassOf(typeof(MyType)))\n{\n // there you have it\n}\n"
}
] | 2008/11/21 | [
"https://Stackoverflow.com/questions/309071",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1946/"
] |
309,081 | <p>I want to create a toggle button in html using css. I want it so that when you click on it , it stays pushed in and than when you click it on it again it pops out. </p>
<p>If theres no way of doing it just using css. Is there a way to do it using jQuery?</p>
| [
{
"answer_id": 309112,
"author": "Anand",
"author_id": 12649,
"author_profile": "https://Stackoverflow.com/users/12649",
"pm_score": 2,
"selected": false,
"text": "<a></a> var flag = 0;\nfunction toggle(){\nif(flag==0){\n document.getElementById(\"toggleDiv\").style.backgroundImage=\"path/to/img/img1.gif\";\n flag=1;\n}\nelse if(flag==1){\n document.getElementById(\"toggleDiv\").style.backgroundImage=\"path/to/img/img2.gif\";\n flag=0;\n}\n}\n <div id=\"toggleDiv\" onclick=\"toggle()\">Some thing</div>"
},
{
"answer_id": 309130,
"author": "pilsetnieks",
"author_id": 6615,
"author_profile": "https://Stackoverflow.com/users/6615",
"pm_score": 0,
"selected": false,
"text": "a:active\n{\n ...desired style here...\n}\n"
},
{
"answer_id": 309260,
"author": "monkey do",
"author_id": 29951,
"author_profile": "https://Stackoverflow.com/users/29951",
"pm_score": 3,
"selected": false,
"text": "<html>\n<head>\n<style type=\"text/css\">\n.on { \nborder:1px outset;\ncolor:#369;\nbackground:#efefef; \n}\n\n.off {\nborder:1px outset;\ncolor:#369;\nbackground:#f9d543; \n}\n</style>\n\n<script language=\"javascript\">\nfunction togglestyle(el){\n if(el.className == \"on\") {\n el.className=\"off\";\n } else {\n el.className=\"on\";\n }\n}\n</script>\n\n</head>\n\n<body>\n<input type=\"button\" id=\"btn\" value=\"button\" class=\"off\" onclick=\"togglestyle(this)\" />\n</body>\n</html>\n"
},
{
"answer_id": 309318,
"author": "alexmeia",
"author_id": 36587,
"author_profile": "https://Stackoverflow.com/users/36587",
"pm_score": 8,
"selected": true,
"text": "$(document).ready(function() {\n $('a#button').click(function() {\n $(this).toggleClass(\"down\");\n });\n}); a {\n background: #ccc;\n cursor: pointer;\n border-top: solid 2px #eaeaea;\n border-left: solid 2px #eaeaea;\n border-bottom: solid 2px #777;\n border-right: solid 2px #777;\n padding: 5px 5px;\n}\n\na.down {\n background: #bbb;\n border-top: solid 2px #777;\n border-left: solid 2px #777;\n border-bottom: solid 2px #eaeaea;\n border-right: solid 2px #eaeaea;\n} <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js\"></script>\n<a id=\"button\" title=\"button\">Press Me</a>"
},
{
"answer_id": 3286066,
"author": "bkdraper",
"author_id": 396334,
"author_profile": "https://Stackoverflow.com/users/396334",
"pm_score": 6,
"selected": false,
"text": "<label for=\"myToggleButton\">my toggle button caption</label>\n<input type=\"checkbox\" id=\"myToggleButton\" />\n onLoad $.ready() init() $(\"#myToggleButton\").button()\n < label for=...> input=\"checkbox"
},
{
"answer_id": 7150477,
"author": "Ivar",
"author_id": 906265,
"author_profile": "https://Stackoverflow.com/users/906265",
"pm_score": 0,
"selected": false,
"text": "<input type=\"checkbox\"> opacity filter"
},
{
"answer_id": 11169747,
"author": "Titouan de Bailleul",
"author_id": 1044591,
"author_profile": "https://Stackoverflow.com/users/1044591",
"pm_score": 2,
"selected": false,
"text": "<fieldset class=\"toggle\">\n <input id=\"data-policy\" type=\"checkbox\" checked=\"checked\" />\n <label for=\"data-policy\">\n <div class=\"toggle-button\">\n <div class=\"toggle-tab\"></div>\n </div>\n Toggle\n </label>\n</fieldset>\n .toggle label {\n color: #444;\n float: left;\n line-height: 26px;\n}\n.toggle .toggle-button {\n margin: 0px 10px 0px 0px;\n float: left;\n width: 70px;\n height: 26px;\n background-color: #eeeeee;\n background-image: -webkit-gradient(linear, left top, left bottom, from(#eeeeee), to(#fafafa));\n background-image: -webkit-linear-gradient(top, #eeeeee, #fafafa);\n background-image: -moz-linear-gradient(top, #eeeeee, #fafafa);\n background-image: -o-linear-gradient(top, #eeeeee, #fafafa);\n background-image: -ms-linear-gradient(top, #eeeeee, #fafafa);\n background-image: linear-gradient(top, #eeeeee, #fafafa);\n filter: progid:dximagetransform.microsoft.gradient(GradientType=0, StartColorStr='#eeeeee', EndColorStr='#fafafa');\n border-radius: 4px;\n -webkit-border-radius: 4px;\n -moz-border-radius: 4px;\n border: 1px solid #D1D1D1;\n}\n.toggle .toggle-button .toggle-tab {\n width: 30px;\n height: 26px;\n background-color: #fafafa;\n background-image: -webkit-gradient(linear, left top, left bottom, from(#fafafa), to(#eeeeee));\n background-image: -webkit-linear-gradient(top, #fafafa, #eeeeee);\n background-image: -moz-linear-gradient(top, #fafafa, #eeeeee);\n background-image: -o-linear-gradient(top, #fafafa, #eeeeee);\n background-image: -ms-linear-gradient(top, #fafafa, #eeeeee);\n background-image: linear-gradient(top, #fafafa, #eeeeee);\n filter: progid:dximagetransform.microsoft.gradient(GradientType=0, StartColorStr='#fafafa', EndColorStr='#eeeeee');\n border: 1px solid #CCC;\n margin-left: -1px;\n margin-top: -1px;\n border-radius: 4px;\n -webkit-border-radius: 4px;\n -moz-border-radius: 4px;\n -webkit-box-shadow: 5px 0px 4px -5px #000000, 0px 0px 0px 0px #000000;\n -moz-box-shadow: 5px 0px 4px -5px rgba(0, 0, 0, 0.3), 0px 0px 0px 0px #000000;\n box-shadow: 5px 0px 4px -5px rgba(0, 0, 0, 0.3), 0px 0px 0px 0px #000000;\n}\n.toggle input[type=checkbox] {\n display: none;\n}\n.toggle input[type=checkbox]:checked ~ label .toggle-button {\n background-color: #2d71c2;\n background-image: -webkit-gradient(linear, left top, left bottom, from(#2d71c2), to(#4ea1db));\n background-image: -webkit-linear-gradient(top, #2d71c2, #4ea1db);\n background-image: -moz-linear-gradient(top, #2d71c2, #4ea1db);\n background-image: -o-linear-gradient(top, #2d71c2, #4ea1db);\n background-image: -ms-linear-gradient(top, #2d71c2, #4ea1db);\n background-image: linear-gradient(top, #2d71c2, #4ea1db);\n filter: progid:dximagetransform.microsoft.gradient(GradientType=0, StartColorStr='#2d71c2', EndColorStr='#4ea1db');\n}\n.toggle input[type=checkbox]:checked ~ label .toggle-button .toggle-tab {\n margin-left: 39px;\n -webkit-box-shadow: -5px 0px 4px -5px #000000, 0px 0px 0px 0px #000000;\n -moz-box-shadow: -5px 0px 4px -5px rgba(0, 0, 0, 0.3), 0px 0px 0px 0px #000000;\n box-shadow: -5px 0px 4px -5px rgba(0, 0, 0, 0.3), 0px 0px 0px 0px #000000;\n}\n"
},
{
"answer_id": 11634428,
"author": "Paul T. Rawkeen",
"author_id": 1548719,
"author_profile": "https://Stackoverflow.com/users/1548719",
"pm_score": 0,
"selected": false,
"text": "<label for=\"input\"> <input> <label> <span>\n <input type=\"checkbox\" value=\"1\" name=\"some_feature_to_select\" id=\"feature_cb\" style=\"display: none;\"> <!-- We can hide checkbox bec. we want <label> to be a ToggleButton, so we don't need to show it. It is used as our value holder -->\n <label for=\"feature_cb\" id=\"label_for_some_feature\">\n <img alt=\"Stylish image\" src=\"/images/icons/feature.png\">\n </label>\n</span>\n <label> function toggleButton(button) {\n\nvar _for = button.getAttribute('for'); // defining for which element this label is (suppose element is a checkbox (bec. we are making ToggleButton ;) )\nvar _toggleID = 'input#'+_for; // composing selector ID string to select our toggle element (checkbox)\nvar _toggle = $( _toggleID ); // selecting checkbox to work on\nvar isChecked = !_toggle.is(':checked'); // defining the state with negation bec. change value event will have place later, so we negating current state to retrieve inverse (next).\n\nif (isChecked)\n $(button).addClass('SelectedButtonClass'); // if it is checked -> adding nice class to our button (<label> in our case) to show that value was toggled\nelse\n $(button).removeClass('SelectedButtonClass'); // if value (or feature) was unselected by clicking the button (<label>) -> removing .SelectedButtonClass (or simply removing all classes from element)\n}\n <label> click checkbox change <label> $(document).ready(function(){\n\n $(\"#some_feature_label\").click(function () {\n toggleButton(this); // call function with transmitting instance of a clicked label and let the script decide what was toggled and what to do with it\n });\n\n $(\"#some_other_feature_label\").click(function () {\n toggleButton(this); // doing the same for any other feature we want to represent in a way of ToggleButton\n });\n\n});\n backgorund-image border <label>"
},
{
"answer_id": 11670724,
"author": "Pierre de LESPINAY",
"author_id": 305189,
"author_profile": "https://Stackoverflow.com/users/305189",
"pm_score": 4,
"selected": false,
"text": "<a href=\"#\" class=\"toggler\"> </a>\n<a href=\"#\" class=\"toggler off\"> </a>\n<a href=\"#\" class=\"toggler\"> </a>\n a.toggler {\n background: green;\n cursor: pointer;\n border: 2px solid black;\n border-right-width: 15px;\n padding: 0 5px;\n border-radius: 5px;\n text-decoration: none;\n transition: all .5s ease;\n}\n\na.toggler.off {\n background: red;\n border-right-width: 2px;\n border-left-width: 15px;\n}\n $(document).ready(function(){\n $('a.toggler').click(function(){\n $(this).toggleClass('off');\n });\n});\n"
},
{
"answer_id": 12692489,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<li>Text To go with Toggle Button<span class = 'toggle'><input type = 'checkbox' class = 'toggle' name = 'somename' id = 'someid' /></span></li>\n <head><link rel = 'stylesheet' src = 'theme.css'> (from jqtouch - downloadable online)\n <link rel = 'text/javascript' src = 'jquery.js'> (also from jqtouch)\n</head>\n somename someid"
},
{
"answer_id": 19671730,
"author": "tim",
"author_id": 967943,
"author_profile": "https://Stackoverflow.com/users/967943",
"pm_score": 3,
"selected": false,
"text": "toggleClass() $(\"button.toggler\").click( function() {\n $me = $(this);\n $me.toggleClass('off');\n if($me.is(\".off\")){\n alert('hi');\n }else {\n alert('bye');\n }\n});\n button <button class=\"toggler\">Toggle me</button>\n"
},
{
"answer_id": 20993148,
"author": "Peter",
"author_id": 3172850,
"author_profile": "https://Stackoverflow.com/users/3172850",
"pm_score": 1,
"selected": false,
"text": "input type=\"button\" \n data-bind=\"css:{on:toggleButton, off:toggleButton!=true},value:toggleButton,click: function() { $data.toggleButton(!($data.toggleButton()))}\" />\n\nin viewModel\nself.toggleButton = ko.observable(false);\n"
},
{
"answer_id": 27181789,
"author": "suhailvs",
"author_id": 2351696,
"author_profile": "https://Stackoverflow.com/users/2351696",
"pm_score": 5,
"selected": false,
"text": "pure css .cmn-toggle {\n position: absolute;\n margin-left: -9999px;\n visibility: hidden;\n }\n .cmn-toggle + label {\n display: block;\n position: relative;\n cursor: pointer;\n outline: none;\n user-select: none;\n }\n input.cmn-toggle-round + label {\n padding: 2px;\n width: 120px;\n height: 60px;\n background-color: #dddddd;\n border-radius: 60px;\n }\n input.cmn-toggle-round + label:before,\n input.cmn-toggle-round + label:after {\n display: block;\n position: absolute;\n top: 1px;\n left: 1px;\n bottom: 1px;\n content: \"\";\n }\n input.cmn-toggle-round + label:before {\n right: 1px;\n background-color: #f1f1f1;\n border-radius: 60px;\n transition: background 0.4s;\n }\n input.cmn-toggle-round + label:after {\n width: 58px;\n background-color: #fff;\n border-radius: 100%;\n box-shadow: 0 2px 5px rgba(0, 0, 0, 0.3);\n transition: margin 0.4s;\n }\n input.cmn-toggle-round:checked + label:before {\n background-color: #8ce196;\n }\n input.cmn-toggle-round:checked + label:after {\n margin-left: 60px;\n } <div class=\"switch\">\n <input id=\"cmn-toggle-1\" class=\"cmn-toggle cmn-toggle-round\" type=\"checkbox\">\n <label for=\"cmn-toggle-1\"></label>\n</div>"
},
{
"answer_id": 70410909,
"author": "Mori",
"author_id": 478018,
"author_profile": "https://Stackoverflow.com/users/478018",
"pm_score": 2,
"selected": false,
"text": "input {\n -webkit-appearance: none;\n appearance: none;\n padding: 16px 30px;\n border-radius: 16px;\n background: radial-gradient(circle 12px, white 100%, transparent calc(100% + 1px)) #ccc -14px;\n transition: 0.3s ease-in-out;\n}\n\n:checked {\n background-color: dodgerBlue;\n background-position: 14px;\n} <input type=\"checkbox\">"
},
{
"answer_id": 71026864,
"author": "willy wonka",
"author_id": 6508528,
"author_profile": "https://Stackoverflow.com/users/6508528",
"pm_score": 1,
"selected": false,
"text": "#mycbid\n{\n display:none;\n}\n\n#mycbid:checked + #mylabelid\n{\n background: grey;\n border: inset;\n}\n\n#mylabelid\n{\n background: lightgray;\n border: outset;\n} <input type=\"checkbox\" id=\"mycbid\">\n <label for=\"mycbid\" id=\"mylabelid\">Text of the label</label> #mycbid:checked + #mylabelid #mylabelid"
},
{
"answer_id": 73053185,
"author": "Basj",
"author_id": 1422096,
"author_profile": "https://Stackoverflow.com/users/1422096",
"pm_score": 0,
"selected": false,
"text": ".switch {\n appearance: none;\n height: 30px;\n width: 52px;\n background-image: linear-gradient(to bottom, transparent 0 22px, dodgerBlue 22px), \n linear-gradient(to right, white 0 22px, dodgerBlue 22px 60px);\n transition: 0.2s ease-in-out;\n background-position: 4px 4px;\n}\n.switch:checked {\n background-position: 26px 4px;\n} <input type=\"checkbox\" class=\"switch\"> .switch {\n appearance: none;\n padding: 16px 30px;\n border-radius: 16px;\n background: radial-gradient(circle 12px, white 100%, transparent calc(100% + 1px)) dodgerBlue -14px;\n transition: 0.3s ease-in-out;\n}\n\n.switch:checked {\n background-position: 14px;\n} <input type=\"checkbox\" class=\"switch\">"
}
] | 2008/11/21 | [
"https://Stackoverflow.com/questions/309081",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1231/"
] |
309,098 | <p>How (i.e. using which API) is the virtual keyboard opened on Symbian S60 5th edition? The documentation seems to lack information about this.</p>
| [
{
"answer_id": 4315560,
"author": "tihi",
"author_id": 525309,
"author_profile": "https://Stackoverflow.com/users/525309",
"pm_score": 2,
"selected": false,
"text": "// lineEdit is an instance of QLineEdit \nQApplication::postEvent(lineEdit, new QEvent(QEvent::RequestSoftwareInputPanel));\n"
},
{
"answer_id": 4588208,
"author": "brunoabinader",
"author_id": 229714,
"author_profile": "https://Stackoverflow.com/users/229714",
"pm_score": 1,
"selected": false,
"text": "QApplication::postEvent(lineEdit, new QEvent(QEvent::CloseSoftwareInputPanel));\n"
}
] | 2008/11/21 | [
"https://Stackoverflow.com/questions/309098",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/39684/"
] |
309,101 | <p>How do I get the <code>GridView</code> control to render the <code><thead></code> <code><tbody></code> tags? I know <code>.UseAccessibleHeaders</code> makes it put <code><th></code> instead of <code><td></code>, but I cant get the <code><thead></code> to appear.</p>
| [
{
"answer_id": 309119,
"author": "Phil Jenkins",
"author_id": 35496,
"author_profile": "https://Stackoverflow.com/users/35496",
"pm_score": 9,
"selected": true,
"text": "gv.HeaderRow.TableSection = TableRowSection.TableHeader;\n"
},
{
"answer_id": 808819,
"author": "ASalvo",
"author_id": 58535,
"author_profile": "https://Stackoverflow.com/users/58535",
"pm_score": 3,
"selected": false,
"text": "Page_Load GridView_PreRender Page_Load NullReferenceException"
},
{
"answer_id": 15830304,
"author": "Rajpurohit",
"author_id": 859558,
"author_profile": "https://Stackoverflow.com/users/859558",
"pm_score": 2,
"selected": false,
"text": "PageLoad private void MakeGridViewPrinterFriendly(GridView gridView) { \n if (gridView.Rows.Count > 0) { \n gridView.UseAccessibleHeader = true; \n gridView.HeaderRow.TableSection = TableRowSection.TableHeader; \n } \n} \n PageLoad protected void Page_Load(object sender, EventArgs e) {\n if (!IsPostBack)\n {\n MakeGridViewPrinterFriendly(grddata);\n }\n}\n"
},
{
"answer_id": 19846059,
"author": "MikeTeeVee",
"author_id": 555798,
"author_profile": "https://Stackoverflow.com/users/555798",
"pm_score": 3,
"selected": false,
"text": "if protected override void OnPreRender(EventArgs e)\n{\n if ( (this.ShowHeader == true && this.Rows.Count > 0)\n || (this.ShowHeaderWhenEmpty == true))\n {\n //Force GridView to use <thead> instead of <tbody> - 11/03/2013 - MCR.\n this.HeaderRow.TableSection = TableRowSection.TableHeader;\n }\n if (this.ShowFooter == true && this.Rows.Count > 0)\n {\n //Force GridView to use <tfoot> instead of <tbody> - 11/03/2013 - MCR.\n this.FooterRow.TableSection = TableRowSection.TableFooter;\n }\n base.OnPreRender(e);\n}\n this"
},
{
"answer_id": 24373384,
"author": "Felipe Delgado",
"author_id": 3768709,
"author_profile": "https://Stackoverflow.com/users/3768709",
"pm_score": 3,
"selected": false,
"text": "protected void GrdPagosRowCreated(object sender, GridViewRowEventArgs e)\n{\n if (e.Row.RowType == DataControlRowType.DataRow)\n {\n e.Row.TableSection = TableRowSection.TableBody;\n }\n else if (e.Row.RowType == DataControlRowType.Header)\n {\n e.Row.TableSection = TableRowSection.TableHeader;\n }\n else if (e.Row.RowType == DataControlRowType.Footer)\n {\n e.Row.TableSection = TableRowSection.TableFooter;\n }\n}\n"
},
{
"answer_id": 27847351,
"author": "Neto Kuhn",
"author_id": 4434211,
"author_profile": "https://Stackoverflow.com/users/4434211",
"pm_score": 5,
"selected": false,
"text": "OnRowDataBound protected void GridViewResults_OnRowDataBound(object sender, GridViewRowEventArgs e) {\n if (e.Row.RowType == DataControlRowType.Header) {\n e.Row.TableSection = TableRowSection.TableHeader;\n }\n}\n"
},
{
"answer_id": 40747798,
"author": "Jonathan Harris",
"author_id": 1015557,
"author_profile": "https://Stackoverflow.com/users/1015557",
"pm_score": 2,
"selected": false,
"text": "<asp:GridView ID=\"GridView1\" runat=\"server\" \n OnPreRender=\"GridView_PreRender\">\n protected void GridView_PreRender(object sender, EventArgs e)\n {\n GridView gv = (GridView)sender;\n\n if ((gv.ShowHeader == true && gv.Rows.Count > 0)\n || (gv.ShowHeaderWhenEmpty == true))\n {\n //Force GridView to use <thead> instead of <tbody> - 11/03/2013 - MCR.\n gv.HeaderRow.TableSection = TableRowSection.TableHeader;\n }\n if (gv.ShowFooter == true && gv.Rows.Count > 0)\n {\n //Force GridView to use <tfoot> instead of <tbody> - 11/03/2013 - MCR.\n gv.FooterRow.TableSection = TableRowSection.TableFooter;\n }\n\n }\n"
},
{
"answer_id": 57225224,
"author": "Michael",
"author_id": 295011,
"author_profile": "https://Stackoverflow.com/users/295011",
"pm_score": 0,
"selected": false,
"text": "$('#myTableId').prepend($(\"<thead></thead>\").append($(this).find(\"#myTableId tr:first\")));"
}
] | 2008/11/21 | [
"https://Stackoverflow.com/questions/309101",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/28543/"
] |
309,115 | <p>I am creating a small app to teach myself ASP.NET MVC and JQuery, and one of the pages is a list of items in which some can be selected. Then I would like to press a button and send a List (or something equivalent) to my controller containing the ids of the items that were selected, using JQuery's Post function.</p>
<p>I managed to get an array with the ids of the elements that were selected, and now I want to post that. One way I could do this is to have a dummy form in my page, with a hidden value, and then set the hidden value with the selected items, and post that form; this looks crufty, though. </p>
<p>Is there a cleaner way to achieve this, by sending the array directly to the controller? I've tried a few different things but it looks like the controller can't map the data it's receiving. Here's the code so far:</p>
<pre><code>function generateList(selectedValues) {
var s = {
values: selectedValues //selectedValues is an array of string
};
$.post("/Home/GenerateList", $.toJSON(s), function() { alert("back") }, "json");
}
</code></pre>
<p>And then my Controller looks like this</p>
<pre><code>public ActionResult GenerateList(List<string> values)
{
//do something
}
</code></pre>
<p>All I managed to get is a "null" in the controller parameter...</p>
<p>Any tips?</p>
| [
{
"answer_id": 310136,
"author": "MrDustpan",
"author_id": 34720,
"author_profile": "https://Stackoverflow.com/users/34720",
"pm_score": 9,
"selected": true,
"text": "function test()\n{\n var stringArray = new Array();\n stringArray[0] = \"item1\";\n stringArray[1] = \"item2\";\n stringArray[2] = \"item3\";\n var postData = { values: stringArray };\n \n $.ajax({\n type: \"POST\",\n url: \"/Home/SaveList\",\n data: postData,\n success: function(data){\n alert(data.Result);\n },\n dataType: \"json\",\n traditional: true\n });\n}\n public JsonResult SaveList(List<String> values)\n{\n return Json(new { Result = String.Format(\"Fist item in list: '{0}'\", values[0]) });\n}\n"
},
{
"answer_id": 2527206,
"author": "Dustin Davis",
"author_id": 302908,
"author_profile": "https://Stackoverflow.com/users/302908",
"pm_score": 7,
"selected": false,
"text": "{ Values : [\"1\", \"2\", \"3\"] }\n Values[]=1&Values[]=2&Values[]=3\n Values=1&Values=2&Values=3\n"
},
{
"answer_id": 7037251,
"author": "Evgenii",
"author_id": 297131,
"author_profile": "https://Stackoverflow.com/users/297131",
"pm_score": 5,
"selected": false,
"text": "$.post(\"/your/url\", $.param(yourJsonObject,true));\n"
},
{
"answer_id": 12777893,
"author": "Mohsen Afshin",
"author_id": 191148,
"author_profile": "https://Stackoverflow.com/users/191148",
"pm_score": 1,
"selected": false,
"text": "public string GetData() {\n // InputStream contains the JSON object you've sent\n String jsonString = new StreamReader(this.Request.InputStream).ReadToEnd();\n\n // Deserialize it to a dictionary\n var dic =\n Newtonsoft.Json.JsonConvert.DeserializeObject < Dictionary < String,\n dynamic >> (jsonString);\n\n string result = \"\";\n\n result += dic[\"firstname\"] + dic[\"lastname\"];\n\n // You can even cast your object to their original type because of 'dynamic' keyword\n result += \", Age: \" + (int) dic[\"age\"];\n\n if ((bool) dic[\"married\"])\n result += \", Married\";\n\n return result;\n}\n public static Dictionary < string, dynamic > GetDic(HttpRequestBase request) {\n String jsonString = new StreamReader(request.InputStream).ReadToEnd();\n return Newtonsoft.Json.JsonConvert.DeserializeObject < Dictionary < string, dynamic >> (jsonString);\n}\n"
},
{
"answer_id": 27963533,
"author": "Matas Vaitkevicius",
"author_id": 1509764,
"author_profile": "https://Stackoverflow.com/users/1509764",
"pm_score": 3,
"selected": false,
"text": ".NET4.5 MVC 5 $('.button-green-large').click(function() {\n $.ajax({\n url: 'Quote',\n type: \"POST\",\n dataType: \"json\",\n data: JSON.stringify(document.selectedProduct),\n contentType: 'application/json; charset=utf-8',\n });\n });\n public class WillsQuoteViewModel\n{\n public string Product { get; set; }\n\n public List<ClaimedFee> ClaimedFees { get; set; }\n}\n\npublic partial class ClaimedFee //Generated by EF6\n{\n public long Id { get; set; }\n public long JourneyId { get; set; }\n public string Title { get; set; }\n public decimal Net { get; set; }\n public decimal Vat { get; set; }\n public string Type { get; set; }\n\n public virtual Journey Journey { get; set; }\n}\n [AcceptVerbs(HttpVerbs.Post)]\npublic ActionResult Quote(WillsQuoteViewModel data)\n{\n....\n}\n"
},
{
"answer_id": 28116832,
"author": "d.popov",
"author_id": 1407302,
"author_profile": "https://Stackoverflow.com/users/1407302",
"pm_score": 3,
"selected": false,
"text": "var postData = {};\npostData[values] = selectedValues ;\n\n$.ajax({\n url: \"/Home/SaveList\",\n type: \"POST\",\n data: JSON.stringify(postData),\n dataType: \"json\",\n contentType: \"application/json; charset=utf-8\",\n success: function(data){\n alert(data.Result);\n }\n});\n public JsonResult SaveList(List<ViewModel> values)\n{ \n return Json(new { \n Result = String.Format(\"Fist item in list: '{0}'\", values[0].Name) \n });\n}\n"
},
{
"answer_id": 48190761,
"author": "mr_squall",
"author_id": 1071162,
"author_profile": "https://Stackoverflow.com/users/1071162",
"pm_score": 0,
"selected": false,
"text": "jQuery.ajaxSettings.traditional = true;\n"
}
] | 2008/11/21 | [
"https://Stackoverflow.com/questions/309115",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/79101/"
] |
309,129 | <p>I got the following class :</p>
<pre><code>class ConstraintFailureSet(dict, Exception) :
"""
Container for constraint failures. It act as a constraint failure itself
but can contain other constraint failures that can be accessed with a dict syntax.
"""
def __init__(self, **failures) :
dict.__init__(self, failures)
Exception.__init__(self)
print isinstance(ConstraintFailureSet(), Exception)
True
raise ConstraintFailureSet()
TypeError: exceptions must be classes, instances, or strings (deprecated), not ConstraintFailureSet
</code></pre>
<p>What the heck ?</p>
<p>And the worst is that I can't try super() since Exception are old based class...</p>
<p>EDIT : And, yes, I've tried to switch the order of inheritance / init.</p>
<p>EDIT2 : I am using CPython 2.4 on Ubuntu8.10. You newer know is this kind of infos is usefull ;-). Anyway, this little riddle has shut the mouth of 3 of my collegues. You'd be my best-friend-of-the day...</p>
| [
{
"answer_id": 309196,
"author": "Dave Costa",
"author_id": 6568,
"author_profile": "https://Stackoverflow.com/users/6568",
"pm_score": 2,
"selected": false,
"text": "dict Exception >>> class foo(dict, Exception):\n... pass\n... \nTraceback (most recent call last):\n File \"<stdin>\", line 1, in <module>\nTypeError: Error when calling the metaclass bases\n multiple bases have instance lay-out conflict\n"
},
{
"answer_id": 309211,
"author": "e-satis",
"author_id": 9951,
"author_profile": "https://Stackoverflow.com/users/9951",
"pm_score": 2,
"selected": false,
"text": "UserDict.UserDict"
},
{
"answer_id": 309563,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 5,
"selected": true,
"text": "Exception dict >>> class C(object): pass\n...\n>>> '__module__' in C.__dict__\nTrue\n>>> '__module__' in dict.__dict__\nFalse\n>>> '__module__' in Exception.__dict__\nFalse\n Exception dict >>> class foo(dict, Exception):\n... pass\n... \nTraceback (most recent call last):\n File \"<stdin>\", line 1, in <module>\nTypeError: Error when calling the metaclass bases\n multiple bases have instance lay-out conflict\n"
},
{
"answer_id": 310273,
"author": "S.Lott",
"author_id": 10661,
"author_profile": "https://Stackoverflow.com/users/10661",
"pm_score": 2,
"selected": false,
"text": "class ConstraintFailure( Exception ):\n def __init__( self, **failures ):\n self.failures= failures # already a dict, don't need to do anything\n def __getitem__( self, key ):\n return self.failures.get(key)\n failures try:\n raise ConstraintFailure( x=ValueError, y=Exception )\nexcept ConstraintFailure, e:\n print e['x']\n print e['y']\n\n\n<type 'exceptions.ValueError'>\n<type 'exceptions.Exception'>\n"
},
{
"answer_id": 924952,
"author": "lispmachine",
"author_id": 82091,
"author_profile": "https://Stackoverflow.com/users/82091",
"pm_score": 0,
"selected": false,
"text": "$ python2.4\nPython 2.4.4 (#1, Feb 19 2009, 09:13:34)\n>>> type(dict)\n<type 'type'>\n>>> type(Exception)\n<type 'classobj'>\n>>> type(Exception())\n<type 'instance'>\n\n$ python2.5\nPython 2.5.4 (r254:67916, Feb 17 2009, 23:11:16)\n>>> type(Exception)\n<type 'type'>\n>>> type(Exception())\n<type 'exceptions.Exception'>\n"
},
{
"answer_id": 34334644,
"author": "codeMonkey",
"author_id": 1098683,
"author_profile": "https://Stackoverflow.com/users/1098683",
"pm_score": 0,
"selected": false,
"text": "collections.UserDict class ConstraintFailureSet(coll.UserDict, Exception):\n \"\"\"\n Container for constraint failures. It act as a constraint failure itself\n but can contain other constraint failures that can be accessed with a dict syntax.\n \"\"\"\n\n def __init__(self, **failures) :\n coll.UserDict.__init__(self, failures)\n Exception.__init__(self)\n\n\nprint( isinstance(ConstraintFailureSet(), Exception)) #True\nraise ConstraintFailureSet()\n"
}
] | 2008/11/21 | [
"https://Stackoverflow.com/questions/309129",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9951/"
] |
309,149 | <p>When generating graphs and showing different sets of data it usually a good idea to difference the sets by color. So one line is red and the next is green and so on. The problem is then that when the number of datasets is unknown one needs to randomly generate these colors and often they end up very close to each other (green, light green for example). </p>
<p>Any ideas on how this could be solved and how it would be possibler to generate distinctly different colors? </p>
<p>I'd be great if any examples (feel free to just discuss the problem and solution without examples if you find that easier) were in C# and RGB based colors.</p>
| [
{
"answer_id": 309193,
"author": "Sam Meldrum",
"author_id": 16005,
"author_profile": "https://Stackoverflow.com/users/16005",
"pm_score": 8,
"selected": true,
"text": "0, 0, 255\n0, 255, 0\n255, 0, 0\n 0, 255, 255\n255, 0, 255\n255, 255, 0\n 0, 0, 128\n0, 128, 0\n128, 0, 0\n0, 128, 128\n128, 0, 128\n128, 128, 0\n 255, 255, 255\n128, 128, 128 \n static string[] ColourValues = new string[] { \n \"FF0000\", \"00FF00\", \"0000FF\", \"FFFF00\", \"FF00FF\", \"00FFFF\", \"000000\", \n \"800000\", \"008000\", \"000080\", \"808000\", \"800080\", \"008080\", \"808080\", \n \"C00000\", \"00C000\", \"0000C0\", \"C0C000\", \"C000C0\", \"00C0C0\", \"C0C0C0\", \n \"400000\", \"004000\", \"000040\", \"404000\", \"400040\", \"004040\", \"404040\", \n \"200000\", \"002000\", \"000020\", \"202000\", \"200020\", \"002020\", \"202020\", \n \"600000\", \"006000\", \"000060\", \"606000\", \"600060\", \"006060\", \"606060\", \n \"A00000\", \"00A000\", \"0000A0\", \"A0A000\", \"A000A0\", \"00A0A0\", \"A0A0A0\", \n \"E00000\", \"00E000\", \"0000E0\", \"E0E000\", \"E000E0\", \"00E0E0\", \"E0E0E0\", \n };\n using System;\n\nclass Program {\n static void Main(string[] args) {\n ColourGenerator generator = new ColourGenerator();\n for (int i = 0; i < 896; i++) {\n Console.WriteLine(string.Format(\"{0}: {1}\", i, generator.NextColour()));\n }\n }\n}\n\npublic class ColourGenerator {\n\n private int index = 0;\n private IntensityGenerator intensityGenerator = new IntensityGenerator();\n\n public string NextColour() {\n string colour = string.Format(PatternGenerator.NextPattern(index),\n intensityGenerator.NextIntensity(index));\n index++;\n return colour;\n }\n}\n\npublic class PatternGenerator {\n public static string NextPattern(int index) {\n switch (index % 7) {\n case 0: return \"{0}0000\";\n case 1: return \"00{0}00\";\n case 2: return \"0000{0}\";\n case 3: return \"{0}{0}00\";\n case 4: return \"{0}00{0}\";\n case 5: return \"00{0}{0}\";\n case 6: return \"{0}{0}{0}\";\n default: throw new Exception(\"Math error\");\n }\n }\n}\n\npublic class IntensityGenerator {\n private IntensityValueWalker walker;\n private int current;\n\n public string NextIntensity(int index) {\n if (index == 0) {\n current = 255;\n }\n else if (index % 7 == 0) {\n if (walker == null) {\n walker = new IntensityValueWalker();\n }\n else {\n walker.MoveNext();\n }\n current = walker.Current.Value;\n }\n string currentText = current.ToString(\"X\");\n if (currentText.Length == 1) currentText = \"0\" + currentText;\n return currentText;\n }\n}\n\npublic class IntensityValue {\n\n private IntensityValue mChildA;\n private IntensityValue mChildB;\n\n public IntensityValue(IntensityValue parent, int value, int level) {\n if (level > 7) throw new Exception(\"There are no more colours left\");\n Value = value;\n Parent = parent;\n Level = level;\n }\n\n public int Level { get; set; }\n public int Value { get; set; }\n public IntensityValue Parent { get; set; }\n\n public IntensityValue ChildA {\n get {\n return mChildA ?? (mChildA = new IntensityValue(this, this.Value - (1<<(7-Level)), Level+1));\n }\n }\n\n public IntensityValue ChildB {\n get {\n return mChildB ?? (mChildB = new IntensityValue(this, Value + (1<<(7-Level)), Level+1));\n }\n }\n}\n\npublic class IntensityValueWalker {\n\n public IntensityValueWalker() {\n Current = new IntensityValue(null, 1<<7, 1);\n }\n\n public IntensityValue Current { get; set; }\n\n public void MoveNext() {\n if (Current.Parent == null) {\n Current = Current.ChildA;\n }\n else if (Current.Parent.ChildA == Current) {\n Current = Current.Parent.ChildB;\n }\n else {\n int levelsUp = 1;\n Current = Current.Parent;\n while (Current.Parent != null && Current == Current.Parent.ChildB) {\n Current = Current.Parent;\n levelsUp++;\n }\n if (Current.Parent != null) {\n Current = Current.Parent.ChildB;\n }\n else {\n levelsUp++;\n }\n for (int i = 0; i < levelsUp; i++) {\n Current = Current.ChildA;\n }\n\n }\n }\n}\n"
},
{
"answer_id": 3881380,
"author": "Filip Rooms",
"author_id": 469040,
"author_profile": "https://Stackoverflow.com/users/469040",
"pm_score": 1,
"selected": false,
"text": "void ColorValue::SetColorValue( double r, double g, double b, ColorType myType )\n{\n this->c[0] = r;\n this->c[1] = g;\n this->c[2] = b;\n\n this->type = myType;\n}\n\n\nDistinctColorGenerator::DistinctColorGenerator()\n{\n mFactor = 255;\n mColorsGenerated = 0;\n mpColorCycle = new ColorValue[6];\n mpColorCycle[0].SetColorValue( 1.0, 0.0, 0.0, TYPE_RGB);\n mpColorCycle[1].SetColorValue( 0.0, 1.0, 0.0, TYPE_RGB);\n mpColorCycle[2].SetColorValue( 0.0, 0.0, 1.0, TYPE_RGB);\n mpColorCycle[3].SetColorValue( 1.0, 1.0, 0.0, TYPE_RGB);\n mpColorCycle[4].SetColorValue( 1.0, 0.0, 1.0, TYPE_RGB);\n mpColorCycle[5].SetColorValue( 0.0, 1.0, 1.0, TYPE_RGB);\n}\n\n//----------------------------------------------------------\n\nColorValue DistinctColorGenerator::GenerateNewColor()\n{\n int innerCycleNr = mColorsGenerated % 6;\n int outerCycleNr = mColorsGenerated / 6;\n int cycleSize = pow( 2, (int)(log((double)(outerCycleNr)) / log( 2.0 ) ) );\n int insideCycleCounter = outerCycleNr % cyclesize;\n\n if ( outerCycleNr == 0)\n {\n mFactor = 255;\n }\n else\n {\n mFactor = ( 256 / ( 2 * cycleSize ) ) + ( insideCycleCounter * ( 256 / cycleSize ) );\n }\n\n ColorValue newColor = mpColorCycle[innerCycleNr] * mFactor;\n\n mColorsGenerated++;\n return newColor;\n}\n"
},
{
"answer_id": 4341012,
"author": "Tom Hamming",
"author_id": 412107,
"author_profile": "https://Stackoverflow.com/users/412107",
"pm_score": 0,
"selected": false,
"text": "int num = (number to convert);\nint baseConvert = (desired base, 255 in this case);\n(array of ints) nums = new (array of ints);\nint x = num;\ndouble digits = Math.Log(num, baseConvert); //or ln(num) / ln(baseConvert)\nint numDigits = (digits - Math.Ceiling(digits) == 0 ? (int)(digits + 1) : (int)Math.Ceiling(digits)); //go up one if it turns out even\nfor (int i = 0; i < numDigits; i++)\n{\n int toAdd = ((int)Math.Floor(x / Math.Pow((double)convertBase, (double)(numDigits - i - 1))));\n //Formula for 0th digit: d = num / (convertBase^(numDigits - 1))\n //Then subtract (d * convertBase^(numDigits - 1)) from the num and continue\n nums.Add(toAdd);\n x -= toAdd * (int)Math.Pow((double)convertBase, (double)(numDigits - i - 1));\n}\nreturn nums;\n"
},
{
"answer_id": 7451886,
"author": "deancutlet",
"author_id": 813249,
"author_profile": "https://Stackoverflow.com/users/813249",
"pm_score": 2,
"selected": false,
"text": "#006600\n#330000\n#FF00FF\n #336600\n#FF0066\n#33FF66\n max = 255\nsegs = int(num**(Decimal(\"1.0\")/3))\nstep = int(max/segs)\np = [(i*step) for i in xrange(segs)]\nvalues = [max]\nvalues.extend(p)\n total = 0\nfor red in values:\n for green in values:\n for blue in values:\n if total <= N:\n print color(red, green, blue)\n total += 1\n"
},
{
"answer_id": 12224359,
"author": "Tatarize",
"author_id": 631911,
"author_profile": "https://Stackoverflow.com/users/631911",
"pm_score": 7,
"selected": false,
"text": "public Color getColor(int i) {\n return new Color(getRGB(i));\n}\n\npublic int getRGB(int index) {\n int[] p = getPattern(index);\n return getElement(p[0]) << 16 | getElement(p[1]) << 8 | getElement(p[2]);\n}\n\npublic int getElement(int index) {\n int value = index - 1;\n int v = 0;\n for (int i = 0; i < 8; i++) {\n v = v | (value & 1);\n v <<= 1;\n value >>= 1;\n }\n v >>= 1;\n return v & 0xFF;\n}\n\npublic int[] getPattern(int index) {\n int n = (int)Math.cbrt(index);\n index -= (n*n*n);\n int[] p = new int[3];\n Arrays.fill(p,n);\n if (index == 0) {\n return p;\n }\n index--;\n int v = index % 3;\n index = index / 3;\n if (index < n) {\n p[v] = index % n;\n return p;\n }\n index -= n;\n p[v ] = index / n;\n p[++v % 3] = index % n;\n return p;\n}\n #FFFFFF \n#000000 \n#FF0000 \n#00FF00 \n#0000FF \n#FFFF00 \n#00FFFF \n#FF00FF \n#808080 \n#FF8080 \n#80FF80 \n#8080FF \n#008080 \n#800080 \n#808000 \n#FFFF80 \n#80FFFF \n#FF80FF \n#FF0080 \n#80FF00 \n#0080FF \n#00FF80 \n#8000FF \n#FF8000 \n#000080 \n#800000 \n#008000 \n#404040 \n#FF4040 \n#40FF40 \n#4040FF \n#004040 \n#400040 \n#404000 \n#804040 \n#408040 \n#404080 \n#FFFF40 \n#40FFFF \n#FF40FF \n#FF0040 \n#40FF00 \n#0040FF \n#FF8040 \n#40FF80 \n#8040FF \n#00FF40 \n#4000FF \n#FF4000 \n#000040 \n#400000 \n#004000 \n#008040 \n#400080 \n#804000 \n#80FF40 \n#4080FF \n#FF4080 \n#800040 \n#408000 \n#004080 \n#808040 \n#408080 \n#804080 \n#C0C0C0 \n#FFC0C0 \n#C0FFC0 \n#C0C0FF \n#00C0C0 \n#C000C0 \n#C0C000 \n#80C0C0 \n#C080C0 \n#C0C080 \n#40C0C0 \n#C040C0 \n#C0C040 \n#FFFFC0 \n#C0FFFF \n#FFC0FF \n#FF00C0 \n#C0FF00 \n#00C0FF \n#FF80C0 \n#C0FF80 \n#80C0FF \n#FF40C0 \n#C0FF40 \n#40C0FF \n#00FFC0 \n#C000FF \n#FFC000 \n#0000C0 \n#C00000 \n#00C000 \n#0080C0 \n#C00080 \n#80C000 \n#0040C0 \n#C00040 \n#40C000 \n#80FFC0 \n#C080FF \n#FFC080 \n#8000C0 \n#C08000 \n#00C080 \n#8080C0 \n#C08080 \n#80C080 \n#8040C0 \n#C08040 \n#40C080 \n#40FFC0 \n#C040FF \n#FFC040 \n#4000C0 \n#C04000 \n#00C040 \n#4080C0 \n#C04080 \n#80C040 \n#4040C0 \n#C04040 \n#40C040 \n#202020 \n#FF2020 \n#20FF20 \n #9BC4E5\n#310106\n#04640D\n#FEFB0A\n#FB5514\n#E115C0\n#00587F\n#0BC582\n#FEB8C8\n#9E8317\n#01190F\n#847D81\n#58018B\n#B70639\n#703B01\n#F7F1DF\n#118B8A\n#4AFEFA\n#FCB164\n#796EE6\n#000D2C\n#53495F\n#F95475\n#61FC03\n#5D9608\n#DE98FD\n#98A088\n#4F584E\n#248AD0\n#5C5300\n#9F6551\n#BCFEC6\n#932C70\n#2B1B04\n#B5AFC4\n#D4C67A\n#AE7AA1\n#C2A393\n#0232FD\n#6A3A35\n#BA6801\n#168E5C\n#16C0D0\n#C62100\n#014347\n#233809\n#42083B\n#82785D\n#023087\n#B7DAD2\n#196956\n#8C41BB\n#ECEDFE\n#2B2D32\n#94C661\n#F8907D\n#895E6B\n#788E95\n#FB6AB8\n#576094\n#DB1474\n#8489AE\n#860E04\n#FBC206\n#6EAB9B\n#F2CDFE\n#645341\n#760035\n#647A41\n#496E76\n#E3F894\n#F9D7CD\n#876128\n#A1A711\n#01FB92\n#FD0F31\n#BE8485\n#C660FB\n#120104\n#D48958\n#05AEE8\n#C3C1BE\n#9F98F8\n#1167D9\n#D19012\n#B7D802\n#826392\n#5E7A6A\n#B29869\n#1D0051\n#8BE7FC\n#76E0C1\n#BACFA7\n#11BA09\n#462C36\n#65407D\n#491803\n#F5D2A8\n#03422C\n#72A46E\n#128EAC\n#47545E\n#B95C69\n#A14D12\n#C4C8FA\n#372A55\n#3F3610\n#D3A2C6\n#719FFA\n#0D841A\n#4C5B32\n#9DB3B7\n#B14F8F\n#747103\n#9F816D\n#D26A5B\n#8B934B\n#F98500\n#002935\n#D7F3FE\n#FCB899\n#1C0720\n#6B5F61\n#F98A9D\n#9B72C2\n#A6919D\n#2C3729\n#D7C70B\n#9F9992\n#EFFBD0\n#FDE2F1\n#923A52\n#5140A7\n#BC14FD\n#6D706C\n#0007C4\n#C6A62F\n#000C14\n#904431\n#600013\n#1C1B08\n#693955\n#5E7C99\n#6C6E82\n#D0AFB3\n#493B36\n#AC93CE\n#C4BA9C\n#09C4B8\n#69A5B8\n#374869\n#F868ED\n#E70850\n#C04841\n#C36333\n#700366\n#8A7A93\n#52351D\n#B503A2\n#D17190\n#A0F086\n#7B41FC\n#0EA64F\n#017499\n#08A882\n#7300CD\n#A9B074\n#4E6301\n#AB7E41\n#547FF4\n#134DAC\n#FDEC87\n#056164\n#FE12A0\n#C264BA\n#939DAD\n#0BCDFA\n#277442\n#1BDE4A\n#826958\n#977678\n#BAFCE8\n#7D8475\n#8CCF95\n#726638\n#FEA8EB\n#EAFEF0\n#6B9279\n#C2FE4B\n#304041\n#1EA6A7\n#022403\n#062A47\n#054B17\n#F4C673\n#02FEC7\n#9DBAA8\n#775551\n#835536\n#565BCC\n#80D7D2\n#7AD607\n#696F54\n#87089A\n#664B19\n#242235\n#7DB00D\n#BFC7D6\n#D5A97E\n#433F31\n#311A18\n#FDB2AB\n#D586C9\n#7A5FB1\n#32544A\n#EFE3AF\n#859D96\n#2B8570\n#8B282D\n#E16A07\n#4B0125\n#021083\n#114558\n#F707F9\n#C78571\n#7FB9BC\n#FC7F4B\n#8D4A92\n#6B3119\n#884F74\n#994E4F\n#9DA9D3\n#867B40\n#CED5C4\n#1CA2FE\n#D9C5B4\n#FEAA00\n#507B01\n#A7D0DB\n#53858D\n#588F4A\n#FBEEEC\n#FC93C1\n#D7CCD4\n#3E4A02\n#C8B1E2\n#7A8B62\n#9A5AE2\n#896C04\n#B1121C\n#402D7D\n#858701\n#D498A6\n#B484EF\n#5C474C\n#067881\n#C0F9FC\n#726075\n#8D3101\n#6C93B2\n#A26B3F\n#AA6582\n#4F4C4F\n#5A563D\n#E83005\n#32492D\n#FC7272\n#B9C457\n#552A5B\n#B50464\n#616E79\n#DCE2E4\n#CF8028\n#0AE2F0\n#4F1E24\n#FD5E46\n#4B694E\n#C5DEFC\n#5DC262\n#022D26\n#7776B8\n#FD9F66\n#B049B8\n#988F73\n#BE385A\n#2B2126\n#54805A\n#141B55\n#67C09B\n#456989\n#DDC1D9\n#166175\n#C1E29C\n#A397B5\n#2E2922\n#ABDBBE\n#B4A6A8\n#A06B07\n#A99949\n#0A0618\n#B14E2E\n#60557D\n#D4A556\n#82A752\n#4A005B\n#3C404F\n#6E6657\n#7E8BD5\n#1275B8\n#D79E92\n#230735\n#661849\n#7A8391\n#FE0F7B\n#B0B6A9\n#629591\n#D05591\n#97B68A\n#97939A\n#035E38\n#53E19E\n#DFD7F9\n#02436C\n#525A72\n#059A0E\n#3E736C\n#AC8E87\n#D10C92\n#B9906E\n#66BDFD\n#C0ABFD\n#0734BC\n#341224\n#8AAAC1\n#0E0B03\n#414522\n#6A2F3E\n#2D9A8A\n#4568FD\n#FDE6D2\n#FEE007\n#9A003C\n#AC8190\n#DCDD58\n#B7903D\n#1F2927\n#9B02E6\n#827A71\n#878B8A\n#8F724F\n#AC4B70\n#37233B\n#385559\n#F347C7\n#9DB4FE\n#D57179\n#DE505A\n#37F7DD\n#503500\n#1C2401\n#DD0323\n#00A4BA\n#955602\n#FA5B94\n#AA766C\n#B8E067\n#6A807E\n#4D2E27\n#73BED7\n#D7BC8A\n#614539\n#526861\n#716D96\n#829A17\n#210109\n#436C2D\n#784955\n#987BAB\n#8F0152\n#0452FA\n#B67757\n#A1659F\n#D4F8D8\n#48416F\n#DEBAAF\n#A5A9AA\n#8C6B83\n#403740\n#70872B\n#D9744D\n#151E2C\n#5C5E5E\n#B47C02\n#F4CBD0\n#E49D7D\n#DD9954\n#B0A18B\n#2B5308\n#EDFD64\n#9D72FC\n#2A3351\n#68496C\n#C94801\n#EED05E\n#826F6D\n#E0D6BB\n#5B6DB4\n#662F98\n#0C97CA\n#C1CA89\n#755A03\n#DFA619\n#CD70A8\n#BBC9C7\n#F6BCE3\n#A16462\n#01D0AA\n#87C6B3\n#E7B2FA\n#D85379\n#643AD5\n#D18AAE\n#13FD5E\n#B3E3FD\n#C977DB\n#C1A7BB\n#9286CB\n#A19B6A\n#8FFED7\n#6B1F17\n#DF503A\n#10DDD7\n#9A8457\n#60672F\n#7D327D\n#DD8782\n#59AC42\n#82FDB8\n#FC8AE7\n#909F6F\n#B691AE\n#B811CD\n#BCB24E\n#CB4BD9\n#2B2304\n#AA9501\n#5D5096\n#403221\n#F9FAB4\n#3990FC\n#70DE7F\n#95857F\n#84A385\n#50996F\n#797B53\n#7B6142\n#81D5FE\n#9CC428\n#0B0438\n#3E2005\n#4B7C91\n#523854\n#005EA9\n#F0C7AD\n#ACB799\n#FAC08E\n#502239\n#BFAB6A\n#2B3C48\n#0EB5D8\n#8A5647\n#49AF74\n#067AE9\n#F19509\n#554628\n#4426A4\n#7352C9\n#3F4287\n#8B655E\n#B480BF\n#9BA74C\n#5F514C\n#CC9BDC\n#BA7942\n#1C4138\n#3C3C3A\n#29B09C\n#02923F\n#701D2B\n#36577C\n#3F00EA\n#3D959E\n#440601\n#8AEFF3\n#6D442A\n#BEB1A8\n#A11C02\n#8383FE\n#A73839\n#DBDE8A\n#0283B3\n#888597\n#32592E\n#F5FDFA\n#01191B\n#AC707A\n#B6BD03\n#027B59\n#7B4F08\n#957737\n#83727D\n#035543\n#6F7E64\n#C39999\n#52847A\n#925AAC\n#77CEDA\n#516369\n#E0D7D0\n#FCDD97\n#555424\n#96E6B6\n#85BB74\n#5E2074\n#BD5E48\n#9BEE53\n#1A351E\n#3148CD\n#71575F\n#69A6D0\n#391A62\n#E79EA0\n#1C0F03\n#1B1636\n#D20C39\n#765396\n#7402FE\n#447F3E\n#CFD0A8\n#3A2600\n#685AFC\n#A4B3C6\n#534302\n#9AA097\n#FD5154\n#9B0085\n#403956\n#80A1A7\n#6E7A9A\n#605E6A\n#86F0E2\n#5A2B01\n#7E3D43\n#ED823B\n#32331B\n#424837\n#40755E\n#524F48\n#B75807\n#B40080\n#5B8CA1\n#FDCFE5\n#CCFEAC\n#755847\n#CAB296\n#C0D6E3\n#2D7100\n#D5E4DE\n#362823\n#69C63C\n#AC3801\n#163132\n#4750A6\n#61B8B2\n#FCC4B5\n#DEBA2E\n#FE0449\n#737930\n#8470AB\n#687D87\n#D7B760\n#6AAB86\n#8398B8\n#B7B6BF\n#92C4A1\n#B6084F\n#853B5E\n#D0BCBA\n#92826D\n#C6DDC6\n#BE5F5A\n#280021\n#435743\n#874514\n#63675A\n#E97963\n#8F9C9E\n#985262\n#909081\n#023508\n#DDADBF\n#D78493\n#363900\n#5B0120\n#603C47\n#C3955D\n#AC61CB\n#FD7BA7\n#716C74\n#8D895B\n#071001\n#82B4F2\n#B6BBD8\n#71887A\n#8B9FE3\n#997158\n#65A6AB\n#2E3067\n#321301\n#FEECCB\n#3B5E72\n#C8FE85\n#A1DCDF\n#CB49A6\n#B1C5E4\n#3E5EB0\n#88AEA7\n#04504C\n#975232\n#6786B9\n#068797\n#9A98C4\n#A1C3C2\n#1C3967\n#DBEA07\n#789658\n#E7E7C6\n#A6C886\n#957F89\n#752E62\n#171518\n#A75648\n#01D26F\n#0F535D\n#047E76\n#C54754\n#5D6E88\n#AB9483\n#803B99\n#FA9C48\n#4A8A22\n#654A5C\n#965F86\n#9D0CBB\n#A0E8A0\n#D3DBFA\n#FD908F\n#AEAB85\n#A13B89\n#F1B350\n#066898\n#948A42\n#C8BEDE\n#19252C\n#7046AA\n#E1EEFC\n#3E6557\n#CD3F26\n#2B1925\n#DDAD94\n#C0B109\n#37DFFE\n#039676\n#907468\n#9E86A5\n#3A1B49\n#BEE5B7\n#C29501\n#9E3645\n#DC580A\n#645631\n#444B4B\n#FD1A63\n#DDE5AE\n#887800\n#36006F\n#3A6260\n#784637\n#FEA0B7\n#A3E0D2\n#6D6316\n#5F7172\n#B99EC7\n#777A7E\n#E0FEFD\n#E16DC5\n#01344B\n#F8F8FC\n#9F9FB5\n#182617\n#FE3D21\n#7D0017\n#822F21\n#EFD9DC\n#6E68C4\n#35473E\n#007523\n#767667\n#A6825D\n#83DC5F\n#227285\n#A95E34\n#526172\n#979730\n#756F6D\n#716259\n#E8B2B5\n#B6C9BB\n#9078DA\n#4F326E\n#B2387B\n#888C6F\n#314B5F\n#E5B678\n#38A3C6\n#586148\n#5C515B\n#CDCCE1\n#C8977F\n #000000\n#00FF00\n#0000FF\n#FF0000\n#01FFFE\n#FFA6FE\n#FFDB66\n#006401\n#010067\n#95003A\n#007DB5\n#FF00F6\n#FFEEE8\n#774D00\n#90FB92\n#0076FF\n#D5FF00\n#FF937E\n#6A826C\n#FF029D\n#FE8900\n#7A4782\n#7E2DD2\n#85A900\n#FF0056\n#A42400\n#00AE7E\n#683D3B\n#BDC6FF\n#263400\n#BDD393\n#00B917\n#9E008E\n#001544\n#C28C9F\n#FF74A3\n#01D0FF\n#004754\n#E56FFE\n#788231\n#0E4CA1\n#91D0CB\n#BE9970\n#968AE8\n#BB8800\n#43002C\n#DEFF74\n#00FFC6\n#FFE502\n#620E00\n#008F9C\n#98FF52\n#7544B1\n#B500FF\n#00FF78\n#FF6E41\n#005F39\n#6B6882\n#5FAD4E\n#A75740\n#A5FFD2\n#FFB167\n#009BFF\n#E85EBE\n public static final String[] indexcolors = new String[]{\n \"#000000\", \"#FFFF00\", \"#1CE6FF\", \"#FF34FF\", \"#FF4A46\", \"#008941\", \"#006FA6\", \"#A30059\",\n \"#FFDBE5\", \"#7A4900\", \"#0000A6\", \"#63FFAC\", \"#B79762\", \"#004D43\", \"#8FB0FF\", \"#997D87\",\n \"#5A0007\", \"#809693\", \"#FEFFE6\", \"#1B4400\", \"#4FC601\", \"#3B5DFF\", \"#4A3B53\", \"#FF2F80\",\n \"#61615A\", \"#BA0900\", \"#6B7900\", \"#00C2A0\", \"#FFAA92\", \"#FF90C9\", \"#B903AA\", \"#D16100\",\n \"#DDEFFF\", \"#000035\", \"#7B4F4B\", \"#A1C299\", \"#300018\", \"#0AA6D8\", \"#013349\", \"#00846F\",\n \"#372101\", \"#FFB500\", \"#C2FFED\", \"#A079BF\", \"#CC0744\", \"#C0B9B2\", \"#C2FF99\", \"#001E09\",\n \"#00489C\", \"#6F0062\", \"#0CBD66\", \"#EEC3FF\", \"#456D75\", \"#B77B68\", \"#7A87A1\", \"#788D66\",\n \"#885578\", \"#FAD09F\", \"#FF8A9A\", \"#D157A0\", \"#BEC459\", \"#456648\", \"#0086ED\", \"#886F4C\",\n \"#34362D\", \"#B4A8BD\", \"#00A6AA\", \"#452C2C\", \"#636375\", \"#A3C8C9\", \"#FF913F\", \"#938A81\",\n \"#575329\", \"#00FECF\", \"#B05B6F\", \"#8CD0FF\", \"#3B9700\", \"#04F757\", \"#C8A1A1\", \"#1E6E00\",\n \"#7900D7\", \"#A77500\", \"#6367A9\", \"#A05837\", \"#6B002C\", \"#772600\", \"#D790FF\", \"#9B9700\",\n \"#549E79\", \"#FFF69F\", \"#201625\", \"#72418F\", \"#BC23FF\", \"#99ADC0\", \"#3A2465\", \"#922329\",\n \"#5B4534\", \"#FDE8DC\", \"#404E55\", \"#0089A3\", \"#CB7E98\", \"#A4E804\", \"#324E72\", \"#6A3A4C\",\n \"#83AB58\", \"#001C1E\", \"#D1F7CE\", \"#004B28\", \"#C8D0F6\", \"#A3A489\", \"#806C66\", \"#222800\",\n \"#BF5650\", \"#E83000\", \"#66796D\", \"#DA007C\", \"#FF1A59\", \"#8ADBB4\", \"#1E0200\", \"#5B4E51\",\n \"#C895C5\", \"#320033\", \"#FF6832\", \"#66E1D3\", \"#CFCDAC\", \"#D0AC94\", \"#7ED379\", \"#012C58\",\n \"#7A7BFF\", \"#D68E01\", \"#353339\", \"#78AFA1\", \"#FEB2C6\", \"#75797C\", \"#837393\", \"#943A4D\",\n \"#B5F4FF\", \"#D2DCD5\", \"#9556BD\", \"#6A714A\", \"#001325\", \"#02525F\", \"#0AA3F7\", \"#E98176\",\n \"#DBD5DD\", \"#5EBCD1\", \"#3D4F44\", \"#7E6405\", \"#02684E\", \"#962B75\", \"#8D8546\", \"#9695C5\",\n \"#E773CE\", \"#D86A78\", \"#3E89BE\", \"#CA834E\", \"#518A87\", \"#5B113C\", \"#55813B\", \"#E704C4\",\n \"#00005F\", \"#A97399\", \"#4B8160\", \"#59738A\", \"#FF5DA7\", \"#F7C9BF\", \"#643127\", \"#513A01\",\n \"#6B94AA\", \"#51A058\", \"#A45B02\", \"#1D1702\", \"#E20027\", \"#E7AB63\", \"#4C6001\", \"#9C6966\",\n \"#64547B\", \"#97979E\", \"#006A66\", \"#391406\", \"#F4D749\", \"#0045D2\", \"#006C31\", \"#DDB6D0\",\n \"#7C6571\", \"#9FB2A4\", \"#00D891\", \"#15A08A\", \"#BC65E9\", \"#FFFFFE\", \"#C6DC99\", \"#203B3C\",\n \"#671190\", \"#6B3A64\", \"#F5E1FF\", \"#FFA0F2\", \"#CCAA35\", \"#374527\", \"#8BB400\", \"#797868\",\n \"#C6005A\", \"#3B000A\", \"#C86240\", \"#29607C\", \"#402334\", \"#7D5A44\", \"#CCB87C\", \"#B88183\",\n \"#AA5199\", \"#B5D6C3\", \"#A38469\", \"#9F94F0\", \"#A74571\", \"#B894A6\", \"#71BB8C\", \"#00B433\",\n \"#789EC9\", \"#6D80BA\", \"#953F00\", \"#5EFF03\", \"#E4FFFC\", \"#1BE177\", \"#BCB1E5\", \"#76912F\",\n \"#003109\", \"#0060CD\", \"#D20096\", \"#895563\", \"#29201D\", \"#5B3213\", \"#A76F42\", \"#89412E\",\n \"#1A3A2A\", \"#494B5A\", \"#A88C85\", \"#F4ABAA\", \"#A3F3AB\", \"#00C6C8\", \"#EA8B66\", \"#958A9F\",\n \"#BDC9D2\", \"#9FA064\", \"#BE4700\", \"#658188\", \"#83A485\", \"#453C23\", \"#47675D\", \"#3A3F00\",\n \"#061203\", \"#DFFB71\", \"#868E7E\", \"#98D058\", \"#6C8F7D\", \"#D7BFC2\", \"#3C3E6E\", \"#D83D66\",\n \"#2F5D9B\", \"#6C5E46\", \"#D25B88\", \"#5B656C\", \"#00B57F\", \"#545C46\", \"#866097\", \"#365D25\",\n \"#252F99\", \"#00CCFF\", \"#674E60\", \"#FC009C\", \"#92896B\", \"#1E2324\", \"#DEC9B2\", \"#9D4948\",\n \"#85ABB4\", \"#342142\", \"#D09685\", \"#A4ACAC\", \"#00FFFF\", \"#AE9C86\", \"#742A33\", \"#0E72C5\",\n \"#AFD8EC\", \"#C064B9\", \"#91028C\", \"#FEEDBF\", \"#FFB789\", \"#9CB8E4\", \"#AFFFD1\", \"#2A364C\",\n \"#4F4A43\", \"#647095\", \"#34BBFF\", \"#807781\", \"#920003\", \"#B3A5A7\", \"#018615\", \"#F1FFC8\",\n \"#976F5C\", \"#FF3BC1\", \"#FF5F6B\", \"#077D84\", \"#F56D93\", \"#5771DA\", \"#4E1E2A\", \"#830055\",\n \"#02D346\", \"#BE452D\", \"#00905E\", \"#BE0028\", \"#6E96E3\", \"#007699\", \"#FEC96D\", \"#9C6A7D\",\n \"#3FA1B8\", \"#893DE3\", \"#79B4D6\", \"#7FD4D9\", \"#6751BB\", \"#B28D2D\", \"#E27A05\", \"#DD9CB8\",\n \"#AABC7A\", \"#980034\", \"#561A02\", \"#8F7F00\", \"#635000\", \"#CD7DAE\", \"#8A5E2D\", \"#FFB3E1\",\n \"#6B6466\", \"#C6D300\", \"#0100E2\", \"#88EC69\", \"#8FCCBE\", \"#21001C\", \"#511F4D\", \"#E3F6E3\",\n \"#FF8EB1\", \"#6B4F29\", \"#A37F46\", \"#6A5950\", \"#1F2A1A\", \"#04784D\", \"#101835\", \"#E6E0D0\",\n \"#FF74FE\", \"#00A45F\", \"#8F5DF8\", \"#4B0059\", \"#412F23\", \"#D8939E\", \"#DB9D72\", \"#604143\",\n \"#B5BACE\", \"#989EB7\", \"#D2C4DB\", \"#A587AF\", \"#77D796\", \"#7F8C94\", \"#FF9B03\", \"#555196\",\n \"#31DDAE\", \"#74B671\", \"#802647\", \"#2A373F\", \"#014A68\", \"#696628\", \"#4C7B6D\", \"#002C27\",\n \"#7A4522\", \"#3B5859\", \"#E5D381\", \"#FFF3FF\", \"#679FA0\", \"#261300\", \"#2C5742\", \"#9131AF\",\n \"#AF5D88\", \"#C7706A\", \"#61AB1F\", \"#8CF2D4\", \"#C5D9B8\", \"#9FFFFB\", \"#BF45CC\", \"#493941\",\n \"#863B60\", \"#B90076\", \"#003177\", \"#C582D2\", \"#C1B394\", \"#602B70\", \"#887868\", \"#BABFB0\",\n \"#030012\", \"#D1ACFE\", \"#7FDEFE\", \"#4B5C71\", \"#A3A097\", \"#E66D53\", \"#637B5D\", \"#92BEA5\",\n \"#00F8B3\", \"#BEDDFF\", \"#3DB5A7\", \"#DD3248\", \"#B6E4DE\", \"#427745\", \"#598C5A\", \"#B94C59\",\n \"#8181D5\", \"#94888B\", \"#FED6BD\", \"#536D31\", \"#6EFF92\", \"#E4E8FF\", \"#20E200\", \"#FFD0F2\",\n \"#4C83A1\", \"#BD7322\", \"#915C4E\", \"#8C4787\", \"#025117\", \"#A2AA45\", \"#2D1B21\", \"#A9DDB0\",\n \"#FF4F78\", \"#528500\", \"#009A2E\", \"#17FCE4\", \"#71555A\", \"#525D82\", \"#00195A\", \"#967874\",\n \"#555558\", \"#0B212C\", \"#1E202B\", \"#EFBFC4\", \"#6F9755\", \"#6F7586\", \"#501D1D\", \"#372D00\",\n \"#741D16\", \"#5EB393\", \"#B5B400\", \"#DD4A38\", \"#363DFF\", \"#AD6552\", \"#6635AF\", \"#836BBA\",\n \"#98AA7F\", \"#464836\", \"#322C3E\", \"#7CB9BA\", \"#5B6965\", \"#707D3D\", \"#7A001D\", \"#6E4636\",\n \"#443A38\", \"#AE81FF\", \"#489079\", \"#897334\", \"#009087\", \"#DA713C\", \"#361618\", \"#FF6F01\",\n \"#006679\", \"#370E77\", \"#4B3A83\", \"#C9E2E6\", \"#C44170\", \"#FF4526\", \"#73BE54\", \"#C4DF72\",\n \"#ADFF60\", \"#00447D\", \"#DCCEC9\", \"#BD9479\", \"#656E5B\", \"#EC5200\", \"#FF6EC2\", \"#7A617E\",\n \"#DDAEA2\", \"#77837F\", \"#A53327\", \"#608EFF\", \"#B599D7\", \"#A50149\", \"#4E0025\", \"#C9B1A9\",\n \"#03919A\", \"#1B2A25\", \"#E500F1\", \"#982E0B\", \"#B67180\", \"#E05859\", \"#006039\", \"#578F9B\",\n \"#305230\", \"#CE934C\", \"#B3C2BE\", \"#C0BAC0\", \"#B506D3\", \"#170C10\", \"#4C534F\", \"#224451\",\n \"#3E4141\", \"#78726D\", \"#B6602B\", \"#200441\", \"#DDB588\", \"#497200\", \"#C5AAB6\", \"#033C61\",\n \"#71B2F5\", \"#A9E088\", \"#4979B0\", \"#A2C3DF\", \"#784149\", \"#2D2B17\", \"#3E0E2F\", \"#57344C\",\n \"#0091BE\", \"#E451D1\", \"#4B4B6A\", \"#5C011A\", \"#7C8060\", \"#FF9491\", \"#4C325D\", \"#005C8B\",\n \"#E5FDA4\", \"#68D1B6\", \"#032641\", \"#140023\", \"#8683A9\", \"#CFFF00\", \"#A72C3E\", \"#34475A\",\n \"#B1BB9A\", \"#B4A04F\", \"#8D918E\", \"#A168A6\", \"#813D3A\", \"#425218\", \"#DA8386\", \"#776133\",\n \"#563930\", \"#8498AE\", \"#90C1D3\", \"#B5666B\", \"#9B585E\", \"#856465\", \"#AD7C90\", \"#E2BC00\",\n \"#E3AAE0\", \"#B2C2FE\", \"#FD0039\", \"#009B75\", \"#FFF46D\", \"#E87EAC\", \"#DFE3E6\", \"#848590\",\n \"#AA9297\", \"#83A193\", \"#577977\", \"#3E7158\", \"#C64289\", \"#EA0072\", \"#C4A8CB\", \"#55C899\",\n \"#E78FCF\", \"#004547\", \"#F6E2E3\", \"#966716\", \"#378FDB\", \"#435E6A\", \"#DA0004\", \"#1B000F\",\n \"#5B9C8F\", \"#6E2B52\", \"#011115\", \"#E3E8C4\", \"#AE3B85\", \"#EA1CA9\", \"#FF9E6B\", \"#457D8B\",\n \"#92678B\", \"#00CDBB\", \"#9CCC04\", \"#002E38\", \"#96C57F\", \"#CFF6B4\", \"#492818\", \"#766E52\",\n \"#20370E\", \"#E3D19F\", \"#2E3C30\", \"#B2EACE\", \"#F3BDA4\", \"#A24E3D\", \"#976FD9\", \"#8C9FA8\",\n \"#7C2B73\", \"#4E5F37\", \"#5D5462\", \"#90956F\", \"#6AA776\", \"#DBCBF6\", \"#DA71FF\", \"#987C95\",\n \"#52323C\", \"#BB3C42\", \"#584D39\", \"#4FC15F\", \"#A2B9C1\", \"#79DB21\", \"#1D5958\", \"#BD744E\",\n \"#160B00\", \"#20221A\", \"#6B8295\", \"#00E0E4\", \"#102401\", \"#1B782A\", \"#DAA9B5\", \"#B0415D\",\n \"#859253\", \"#97A094\", \"#06E3C4\", \"#47688C\", \"#7C6755\", \"#075C00\", \"#7560D5\", \"#7D9F00\",\n \"#C36D96\", \"#4D913E\", \"#5F4276\", \"#FCE4C8\", \"#303052\", \"#4F381B\", \"#E5A532\", \"#706690\",\n \"#AA9A92\", \"#237363\", \"#73013E\", \"#FF9079\", \"#A79A74\", \"#029BDB\", \"#FF0169\", \"#C7D2E7\",\n \"#CA8869\", \"#80FFCD\", \"#BB1F69\", \"#90B0AB\", \"#7D74A9\", \"#FCC7DB\", \"#99375B\", \"#00AB4D\",\n \"#ABAED1\", \"#BE9D91\", \"#E6E5A7\", \"#332C22\", \"#DD587B\", \"#F5FFF7\", \"#5D3033\", \"#6D3800\",\n \"#FF0020\", \"#B57BB3\", \"#D7FFE6\", \"#C535A9\", \"#260009\", \"#6A8781\", \"#A8ABB4\", \"#D45262\",\n \"#794B61\", \"#4621B2\", \"#8DA4DB\", \"#C7C890\", \"#6FE9AD\", \"#A243A7\", \"#B2B081\", \"#181B00\",\n \"#286154\", \"#4CA43B\", \"#6A9573\", \"#A8441D\", \"#5C727B\", \"#738671\", \"#D0CFCB\", \"#897B77\",\n \"#1F3F22\", \"#4145A7\", \"#DA9894\", \"#A1757A\", \"#63243C\", \"#ADAAFF\", \"#00CDE2\", \"#DDBC62\",\n \"#698EB1\", \"#208462\", \"#00B7E0\", \"#614A44\", \"#9BBB57\", \"#7A5C54\", \"#857A50\", \"#766B7E\",\n \"#014833\", \"#FF8347\", \"#7A8EBA\", \"#274740\", \"#946444\", \"#EBD8E6\", \"#646241\", \"#373917\",\n \"#6AD450\", \"#81817B\", \"#D499E3\", \"#979440\", \"#011A12\", \"#526554\", \"#B5885C\", \"#A499A5\",\n \"#03AD89\", \"#B3008B\", \"#E3C4B5\", \"#96531F\", \"#867175\", \"#74569E\", \"#617D9F\", \"#E70452\",\n \"#067EAF\", \"#A697B6\", \"#B787A8\", \"#9CFF93\", \"#311D19\", \"#3A9459\", \"#6E746E\", \"#B0C5AE\",\n \"#84EDF7\", \"#ED3488\", \"#754C78\", \"#384644\", \"#C7847B\", \"#00B6C5\", \"#7FA670\", \"#C1AF9E\",\n \"#2A7FFF\", \"#72A58C\", \"#FFC07F\", \"#9DEBDD\", \"#D97C8E\", \"#7E7C93\", \"#62E674\", \"#B5639E\",\n \"#FFA861\", \"#C2A580\", \"#8D9C83\", \"#B70546\", \"#372B2E\", \"#0098FF\", \"#985975\", \"#20204C\",\n \"#FF6C60\", \"#445083\", \"#8502AA\", \"#72361F\", \"#9676A3\", \"#484449\", \"#CED6C2\", \"#3B164A\",\n \"#CCA763\", \"#2C7F77\", \"#02227B\", \"#A37E6F\", \"#CDE6DC\", \"#CDFFFB\", \"#BE811A\", \"#F77183\",\n \"#EDE6E2\", \"#CDC6B4\", \"#FFE09E\", \"#3A7271\", \"#FF7B59\", \"#4E4E01\", \"#4AC684\", \"#8BC891\",\n \"#BC8A96\", \"#CF6353\", \"#DCDE5C\", \"#5EAADD\", \"#F6A0AD\", \"#E269AA\", \"#A3DAE4\", \"#436E83\",\n \"#002E17\", \"#ECFBFF\", \"#A1C2B6\", \"#50003F\", \"#71695B\", \"#67C4BB\", \"#536EFF\", \"#5D5A48\",\n \"#890039\", \"#969381\", \"#371521\", \"#5E4665\", \"#AA62C3\", \"#8D6F81\", \"#2C6135\", \"#410601\",\n \"#564620\", \"#E69034\", \"#6DA6BD\", \"#E58E56\", \"#E3A68B\", \"#48B176\", \"#D27D67\", \"#B5B268\",\n \"#7F8427\", \"#FF84E6\", \"#435740\", \"#EAE408\", \"#F4F5FF\", \"#325800\", \"#4B6BA5\", \"#ADCEFF\",\n \"#9B8ACC\", \"#885138\", \"#5875C1\", \"#7E7311\", \"#FEA5CA\", \"#9F8B5B\", \"#A55B54\", \"#89006A\",\n \"#AF756F\", \"#2A2000\", \"#576E4A\", \"#7F9EFF\", \"#7499A1\", \"#FFB550\", \"#00011E\", \"#D1511C\",\n \"#688151\", \"#BC908A\", \"#78C8EB\", \"#8502FF\", \"#483D30\", \"#C42221\", \"#5EA7FF\", \"#785715\",\n \"#0CEA91\", \"#FFFAED\", \"#B3AF9D\", \"#3E3D52\", \"#5A9BC2\", \"#9C2F90\", \"#8D5700\", \"#ADD79C\",\n \"#00768B\", \"#337D00\", \"#C59700\", \"#3156DC\", \"#944575\", \"#ECFFDC\", \"#D24CB2\", \"#97703C\",\n \"#4C257F\", \"#9E0366\", \"#88FFEC\", \"#B56481\", \"#396D2B\", \"#56735F\", \"#988376\", \"#9BB195\",\n \"#A9795C\", \"#E4C5D3\", \"#9F4F67\", \"#1E2B39\", \"#664327\", \"#AFCE78\", \"#322EDF\", \"#86B487\",\n \"#C23000\", \"#ABE86B\", \"#96656D\", \"#250E35\", \"#A60019\", \"#0080CF\", \"#CAEFFF\", \"#323F61\",\n \"#A449DC\", \"#6A9D3B\", \"#FF5AE4\", \"#636A01\", \"#D16CDA\", \"#736060\", \"#FFBAAD\", \"#D369B4\",\n \"#FFDED6\", \"#6C6D74\", \"#927D5E\", \"#845D70\", \"#5B62C1\", \"#2F4A36\", \"#E45F35\", \"#FF3B53\",\n \"#AC84DD\", \"#762988\", \"#70EC98\", \"#408543\", \"#2C3533\", \"#2E182D\", \"#323925\", \"#19181B\",\n \"#2F2E2C\", \"#023C32\", \"#9B9EE2\", \"#58AFAD\", \"#5C424D\", \"#7AC5A6\", \"#685D75\", \"#B9BCBD\",\n \"#834357\", \"#1A7B42\", \"#2E57AA\", \"#E55199\", \"#316E47\", \"#CD00C5\", \"#6A004D\", \"#7FBBEC\",\n \"#F35691\", \"#D7C54A\", \"#62ACB7\", \"#CBA1BC\", \"#A28A9A\", \"#6C3F3B\", \"#FFE47D\", \"#DCBAE3\",\n \"#5F816D\", \"#3A404A\", \"#7DBF32\", \"#E6ECDC\", \"#852C19\", \"#285366\", \"#B8CB9C\", \"#0E0D00\",\n \"#4B5D56\", \"#6B543F\", \"#E27172\", \"#0568EC\", \"#2EB500\", \"#D21656\", \"#EFAFFF\", \"#682021\",\n \"#2D2011\", \"#DA4CFF\", \"#70968E\", \"#FF7B7D\", \"#4A1930\", \"#E8C282\", \"#E7DBBC\", \"#A68486\",\n \"#1F263C\", \"#36574E\", \"#52CE79\", \"#ADAAA9\", \"#8A9F45\", \"#6542D2\", \"#00FB8C\", \"#5D697B\",\n \"#CCD27F\", \"#94A5A1\", \"#790229\", \"#E383E6\", \"#7EA4C1\", \"#4E4452\", \"#4B2C00\", \"#620B70\",\n \"#314C1E\", \"#874AA6\", \"#E30091\", \"#66460A\", \"#EB9A8B\", \"#EAC3A3\", \"#98EAB3\", \"#AB9180\",\n \"#B8552F\", \"#1A2B2F\", \"#94DDC5\", \"#9D8C76\", \"#9C8333\", \"#94A9C9\", \"#392935\", \"#8C675E\",\n \"#CCE93A\", \"#917100\", \"#01400B\", \"#449896\", \"#1CA370\", \"#E08DA7\", \"#8B4A4E\", \"#667776\",\n \"#4692AD\", \"#67BDA8\", \"#69255C\", \"#D3BFFF\", \"#4A5132\", \"#7E9285\", \"#77733C\", \"#E7A0CC\",\n \"#51A288\", \"#2C656A\", \"#4D5C5E\", \"#C9403A\", \"#DDD7F3\", \"#005844\", \"#B4A200\", \"#488F69\",\n \"#858182\", \"#D4E9B9\", \"#3D7397\", \"#CAE8CE\", \"#D60034\", \"#AA6746\", \"#9E5585\", \"#BA6200\"\n };\n"
},
{
"answer_id": 14660261,
"author": "sai siva sundar",
"author_id": 1906525,
"author_profile": "https://Stackoverflow.com/users/1906525",
"pm_score": 0,
"selected": false,
"text": "for(int col=1;col<CLUSTER_COUNT+1;col++){\nswitch(col%6)\n {\n case 1:cout<<Scalar(0,0,(int)(255/(int)(col/6+1)))<<endl;break;\n case 2:cout<<Scalar(0,(int)(255/(int)(col/6+1)),0)<<endl;break;\n case 3:cout<<Scalar((int)(255/(int)(col/6+1)),0,0)<<endl;break;\n case 4:cout<<Scalar(0,(int)(255/(int)(col/6+1)),(int)(255/(int)(col/6+1)))<<endl;break;\n case 5:cout<<Scalar((int)(255/(int)(col/6+1)),0,(int)(255/(int)(col/6+1)))<<endl;break;\n case 0:cout<<Scalar((int)(255/(int)(col/6)),(int)(255/(int)(col/6)),0)<<endl;break;\n }\n}\n"
},
{
"answer_id": 38087571,
"author": "Mich",
"author_id": 2056201,
"author_profile": "https://Stackoverflow.com/users/2056201",
"pm_score": 2,
"selected": false,
"text": " private System.Drawing.Color GetRandColor(int index)\n {\n byte red = 0;\n byte green = 0;\n byte blue = 0;\n\n for (int t = 0; t <= index / 8; t++)\n {\n int index_a = (index+t) % 8;\n int index_b = index_a / 2;\n\n //Color writers, take on values of 0 and 1\n int color_red = index_a % 2;\n int color_blue = index_b % 2;\n int color_green = ((index_b + 1) % 3) % 2;\n\n int add = 255 / (t + 1);\n\n red = (byte)(red+color_red * add);\n green = (byte)(green + color_green * add);\n blue = (byte)(blue + color_blue * add);\n }\n\n Color color = Color.FromArgb(red, green, blue);\n return color;\n }\n int skip_index = 0;\n private System.Drawing.Color GetRandColor(int index)\n {\n index += skip_index;\n byte red = 0;\n byte green = 0;\n byte blue = 0;\n\n for (int t = 0; t <= index / 8; t++)\n {\n int index_a = (index+t) % 8;\n int index_b = index_a / 2;\n\n //Color writers, take on values of 0 and 1\n int color_red = index_a % 2;\n int color_blue = index_b % 2;\n int color_green = ((index_b + 1) % 3) % 2;\n\n int add = 255 / (t + 1);\n\n red = (byte)(red + color_red * add);\n green = (byte)(green + color_green * add);\n blue = (byte)(blue + color_blue * add);\n }\n\n if(red > 200 && green > 200)\n {\n skip_index++;\n return GetRandColor(index);\n }\n\n Color color = Color.FromArgb(red, green, blue);\n return color;\n }\n"
},
{
"answer_id": 56848413,
"author": "Krish",
"author_id": 2417445,
"author_profile": "https://Stackoverflow.com/users/2417445",
"pm_score": 1,
"selected": false,
"text": "[DllImport(\"shlwapi.dll\")]\npublic static extern int ColorHLSToRGB(int H, int L, int S);\n\npublic static string GetRandomDarkColor()\n{\n int h = 0, s = 0, l = 0;\n h = (RandomObject.Next(1, 2) % 2 == 0) ? RandomObject.Next(0, 180) : iApp.RandomObject.Next(181, 360);\n s = RandomObject.Next(90, 160);\n l = RandomObject.Next(80, 130);\n\n return System.Drawing.ColorTranslator.FromWin32(ColorHLSToRGB(h, l, s)).ToHex();\n}\n\nprivate static string ToHex(this System.Drawing.Color c)\n{\n return \"#\" + c.R.ToString(\"X2\") + c.G.ToString(\"X2\") + c.B.ToString(\"X2\");\n}\n RandomObject Random"
}
] | 2008/11/21 | [
"https://Stackoverflow.com/questions/309149",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/298/"
] |
309,153 | <p>Is there a way to link to a chm file, and therein to a certain topic, from a Microsoft Word docx document? Something in the lines of:</p>
<blockquote>
<p>"For more information about this Property see [link ref="./SomeDirectory/somedocument.chm!Sometopic.Somesubtopic" text="MyClass.MyProperty"]</p>
</blockquote>
| [
{
"answer_id": 310510,
"author": "Frank V",
"author_id": 18196,
"author_profile": "https://Stackoverflow.com/users/18196",
"pm_score": 0,
"selected": false,
"text": "C:\\Helpfiles\\Help.chm#Topic\n"
},
{
"answer_id": 320800,
"author": "Dirk Vollmar",
"author_id": 40347,
"author_profile": "https://Stackoverflow.com/users/40347",
"pm_score": 2,
"selected": false,
"text": "Declare Function HtmlHelp Lib \"HHCtrl.ocx\" Alias \"HtmlHelpA\" _\n (ByVal hwndCaller As Long, _\n ByVal pszFile As String, _\n ByVal uCommand As Long, _\n dwData As Any) As Long\n\nPrivate Declare Function FindWindow Lib \"user32\" Alias \"FindWindowA\" (ByVal lpClassName As String, ByVal lpWindowName As String) As Long\n\nPublic Function GetWindowHandle() As Long\n 'obtain Word's hwnd\n 'NOTE: there is a possibility of getting the wrong hwnd. If two word windows\n 'are open with the same caption, this *could* happen. In order to prevent this,\n 'you can either change the caption to something strange before trying to find it,\n 'or you can compare processId's with GetCurrentProcessId and GetWindowThreadProcessId\n 'You can always search the top level windows yourself.\n\n GetWindowHandle = FindWindow(Word8ClassName, ActiveDocument.Windows(1) & \" - \" & ActiveDocument.Application.Caption)\n\nEnd Function\n\nPublic Function ShowHelp(strPage As String)\n\n On Error Resume Next\n\n HtmlHelp GetWindowHandle, \"fullpathtohelpfile.chm\", HH_DISPLAY_TOPIC, ByVal strPage\n\nEnd Function\n"
}
] | 2008/11/21 | [
"https://Stackoverflow.com/questions/309153",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4227/"
] |
309,159 | <p>I'm trying to do some abstraction in Haskell98 but doen't know how to do it.</p>
<p>What I want to do is to define a class for types that may be converted into lists.</p>
<pre><code>toList :: a -> [b]
</code></pre>
<p>But I don't know how to define a class for this method. I brought up the following three ideas:</p>
<pre><code>class ToList a b where
toList :: a -> [b]
class ToList a where
toList :: a -> [b]
class ToList a where
toList :: a b -> [b]
</code></pre>
<p>The first one doesn't work because Haskell98 doesn't allow multiple parameter classes.</p>
<p>The second one doesn't work because b depends on a and can't be implemented for every b.</p>
<p>The third doesn't work either because I don't know how to instanciate the class with a type where 'b' isn't the last type-parameter.</p>
<pre><code>data HTree a b = Nil | Node a b (HTree a b) (HTree a b)
toList Nil = []
toList Node x y l r = toList l ++ [(x,y)] ++ toList r
</code></pre>
<p>or</p>
<pre><code>toList Nil = []
toList Node x y l r = toList l ++ [x] ++ toList r
</code></pre>
<p>How would I do something like that?</p>
| [
{
"answer_id": 311234,
"author": "mattiast",
"author_id": 8272,
"author_profile": "https://Stackoverflow.com/users/8272",
"pm_score": -1,
"selected": false,
"text": "(HTree a) toList (HTree a b) -> [b] (HTree a b) -> [(a,b)] class ToList a where\n toList :: a b -> [b]\n\ndata HTree a b = Nil | Node a b (HTree a b) (HTree a b)\n\ninstance ToList (HTree a) where\n toList Nil = []\n toList (Node x y l r) = toList l ++ [y] ++ toList r\n\ntest = toList (Node \"a\" 1 (Node \"b\" 2 Nil Nil) Nil)\n-- test == [2,1]\n"
},
{
"answer_id": 312250,
"author": "luqui",
"author_id": 33796,
"author_profile": "https://Stackoverflow.com/users/33796",
"pm_score": 4,
"selected": true,
"text": "toList Foldable Foldable HTree HTree data HTree a = Nil | Node a (HTree a) (HTree a)\n HTree (a,b) HTree a b Functor"
}
] | 2008/11/21 | [
"https://Stackoverflow.com/questions/309159",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9632/"
] |
309,161 | <p>Is it a simple case of just never using the this.XYZ construct?</p>
| [
{
"answer_id": 309182,
"author": "Kent Boogaart",
"author_id": 5380,
"author_profile": "https://Stackoverflow.com/users/5380",
"pm_score": 4,
"selected": true,
"text": "this public MyType(int arg)\n{\n this.arg = arg;\n}\n public MyType(int arg)\n{\n _arg = arg;\n}\n"
},
{
"answer_id": 309183,
"author": "Jon Skeet",
"author_id": 22656,
"author_profile": "https://Stackoverflow.com/users/22656",
"pm_score": 1,
"selected": false,
"text": "this.foo public Person (string name, string occupation)\n{\n this.name = name;\n this.occupation = occupation;\n}\n"
}
] | 2008/11/21 | [
"https://Stackoverflow.com/questions/309161",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11538/"
] |
309,165 | <p>Let's say I have an int with the value of 1. How can I convert that int to a zero padded string, such as <code>00000001</code>?</p>
| [
{
"answer_id": 309194,
"author": "Mitch Wheat",
"author_id": 16076,
"author_profile": "https://Stackoverflow.com/users/16076",
"pm_score": 5,
"selected": false,
"text": "DECLARE @iVal int = 1\nselect REPLACE(STR(@iVal, 8, 0), ' ', '0')\n"
},
{
"answer_id": 309207,
"author": "Charles Bretana",
"author_id": 32632,
"author_profile": "https://Stackoverflow.com/users/32632",
"pm_score": 7,
"selected": true,
"text": "Declare @MyInt integer Set @MyInt = 123\nDeclare @StrLen TinyInt Set @StrLen = 8\n\nSelect Replace(Str(@MyInt, @StrLen), ' ' , '0')\n"
},
{
"answer_id": 309252,
"author": "user39603",
"author_id": 39603,
"author_profile": "https://Stackoverflow.com/users/39603",
"pm_score": 0,
"selected": false,
"text": "declare @int int\nset @int = 1\n\ndeclare @string varchar(max)\nset @string = cast(@int as varchar(max))\n\ndeclare @length int\nset @length = len(@string)\n\ndeclare @MAX int\nset @MAX = 8\n\nif @length < @MAX\nbegin\n declare @zeros varchar(8)\n set @zeros = ''\n\n declare @counter int\n set @counter = 0\n\n while (@counter < (@MAX - @length))\n begin\n set @zeros = @zeros + '0'\n set @counter = @counter + 1\n end\n set @string = @zeros + @string\nend\nprint @string\n"
},
{
"answer_id": 309278,
"author": "Steve Brouillard",
"author_id": 26516,
"author_profile": "https://Stackoverflow.com/users/26516",
"pm_score": 1,
"selected": false,
"text": "DECLARE @INT INT\nDECLARE @UNPADDED VARCHAR(3)\nDECLARE @PADDED VARCHAR(3)\n\nSET @INT = 2\nSET @UNPADDED = CONVERT(VARCHAR(3),@INT)\nSET @PADDED = REPLICATE('0', 3 - DATALENGTH(@UNPADDED)) + @UNPADDED\nSELECT @INT, @UNPADDED, @PADDED\n"
},
{
"answer_id": 439709,
"author": "Amy B",
"author_id": 8155,
"author_profile": "https://Stackoverflow.com/users/8155",
"pm_score": 1,
"selected": false,
"text": "SET @padded = RIGHT('z0000000000000'\n + convert(varchar(30), @myInt), 8)\n"
},
{
"answer_id": 439881,
"author": "Jim Birchall",
"author_id": 989,
"author_profile": "https://Stackoverflow.com/users/989",
"pm_score": 1,
"selected": false,
"text": "DECLARE @iVal int \nset @iVal = -1\n select \n case \n when @ival >= 0 then right(replicate('0',8) + cast(@ival as nvarchar(8)),8)\n else '-' + right(replicate('0',8) + cast(@ival*-1 as nvarchar(8)),8)\n end\n"
},
{
"answer_id": 2397140,
"author": "RicardoBalda",
"author_id": 194721,
"author_profile": "https://Stackoverflow.com/users/194721",
"pm_score": 3,
"selected": false,
"text": "SELECT RIGHT('000' + CAST(Table.Field AS VARCHAR(3)),3) FROM Table\n CREATE FUNCTION CIntToChar(@intVal Int, @intLen Int) RETURNS nvarchar(24) AS BEGIN\n\nIF @intlen > 24\n SET @intlen = 24\n\nRETURN REPLICATE('0',@intLen-LEN(RTRIM(CONVERT(nvarchar(24),@intVal)))) \n + CONVERT(nvarchar(24),@intVal) END\n"
},
{
"answer_id": 18347049,
"author": "gordy",
"author_id": 99691,
"author_profile": "https://Stackoverflow.com/users/99691",
"pm_score": 5,
"selected": false,
"text": "format(@int, '0000#')\n"
},
{
"answer_id": 26289026,
"author": "BobRodes",
"author_id": 490454,
"author_profile": "https://Stackoverflow.com/users/490454",
"pm_score": 0,
"selected": false,
"text": "SELECT REPLICATE('0', 7) + '1'\n SELECT REPLICATE('0', 8 - LEN(CONVERT(nvarchar, @myInt))) + CONVERT(nvarchar, @myInt)\n SELECT COALESCE(REPLICATE('0', 8 - LEN(CONVERT(nvarchar, @myInt))) + CONVERT(nvarchar, @myInt), CONVERT(nvarchar, @myInt))\n"
},
{
"answer_id": 30137029,
"author": "Jenna Leaf",
"author_id": 4170504,
"author_profile": "https://Stackoverflow.com/users/4170504",
"pm_score": 1,
"selected": false,
"text": " select RIGHT( '0000'+ Convert(varchar, @_int), 4) as txtnum\n select RIGHT( '000'+ Convert(varchar, @_int), 3) as txtnum\n declare @_int int\nset @_int = 1\nwhile @_int < 100 Begin\n select BldgName + '.Floor_' + RIGHT( '00'+ Convert(varchar, @_int), 2) \n + '.balcony' from dbo.tbl_FloorInfo group by BldgName\n set @_int = @_int +1\nEnd\n 'BldgA.Floor_01.balcony'\n 'BldgB.Floor_01.balcony'\n 'BldgC.Floor_01.balcony'\n ..\n ..\n 'BldgA.Floor_10.balcony'\n 'BldgB.Floor_10.balcony'\n 'BldgC.Floor_10.balcony'\n ..\n ..\n ..\n 'BldgA.Floor_99.balcony'\n 'BldgB.Floor_99.balcony'\n 'BldgC.Floor_99.balcony'\n"
},
{
"answer_id": 49864758,
"author": "Diego",
"author_id": 498609,
"author_profile": "https://Stackoverflow.com/users/498609",
"pm_score": 0,
"selected": false,
"text": "STR SELECT REPLACE(REVERSE(\n CONVERT(CHAR(5 /*<= Target length*/)\n , REVERSE(CONVERT(VARCHAR(100), @MyInt)))\n ), ' ', '0')\n"
},
{
"answer_id": 50696896,
"author": "Ilia Gilmijarow",
"author_id": 6631196,
"author_profile": "https://Stackoverflow.com/users/6631196",
"pm_score": 3,
"selected": false,
"text": "FORMAT(<your number>,'00000000')"
}
] | 2008/11/21 | [
"https://Stackoverflow.com/questions/309165",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/470/"
] |
309,203 | <p>I used a new Date() object to fill a field in a MySQL DB, but the actual value stored in that field is in my local timezone.</p>
<p>How can I configure MySQL to store it in the UTC/GMT timezone?</p>
<p>I think, configuring the connection string will help but I don't know how. There are many properties in the connection string like useTimezone, serverTimzone, useGmtMillisForDatetimes, useLegacyDatetimeCode, ...</p>
| [
{
"answer_id": 309316,
"author": "Powerlord",
"author_id": 15880,
"author_profile": "https://Stackoverflow.com/users/15880",
"pm_score": 1,
"selected": false,
"text": "PreparedStatement stmt.setDate(2, date, Calendar.getInstance(TimeZone.getTimeZone(\"GMT\")));\n"
},
{
"answer_id": 13405155,
"author": "Ted Bigham",
"author_id": 868121,
"author_profile": "https://Stackoverflow.com/users/868121",
"pm_score": 2,
"selected": false,
"text": "long originalTime = originalDate.getTime();\nDate newDate = new Date(originalTime - TimeZone.getDefault().getOffset(originalTime));\nps.setDate(1, newDate);\n long dbTime = rs.getTimestamp(1).getTime();\nDate originalDate = new Date(dbTime + TimeZone.getDefault().getOffset(dbTime));\n"
},
{
"answer_id": 15533663,
"author": "Chris M.",
"author_id": 2141229,
"author_profile": "https://Stackoverflow.com/users/2141229",
"pm_score": 2,
"selected": false,
"text": " String startTime = \"2013-02-01T04:00:00.000Z\";\n DateTime dt = ISODateTimeFormat.dateTimeParser().parseDateTime(startTime); \n\n PreparedStatement stmt = connection.prepareStatement(insertStatementTemplate);\n\n Timestamp ts = new Timestamp(dt.getMillis());\n stmt.setTimestamp(1, ts, Calendar.getInstance(TimeZone.getTimeZone(\"UTC\"))); \n private final static String DatabaseName =\n \"jdbc:mysql://foo/?useLegacyDatetimeCode=false\";\n"
}
] | 2008/11/21 | [
"https://Stackoverflow.com/questions/309203",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19888/"
] |
309,205 | <p>Since C# is strongly typed, do we really need to prefix variables anymore?</p>
<p>e.g.</p>
<pre><code>iUserAge
iCounter
strUsername
</code></pre>
<p>I used to prefix in the past, but <b>going forward I don't see any benefit</b>.</p>
| [
{
"answer_id": 309228,
"author": "George Stocker",
"author_id": 16587,
"author_profile": "https://Stackoverflow.com/users/16587",
"pm_score": 2,
"selected": false,
"text": "I ILoadable"
},
{
"answer_id": 309239,
"author": "Todd Smith",
"author_id": 31624,
"author_profile": "https://Stackoverflow.com/users/31624",
"pm_score": 0,
"selected": false,
"text": "public class Test\n{\n private int _id;\n}\n"
},
{
"answer_id": 309265,
"author": "Dan C.",
"author_id": 26391,
"author_profile": "https://Stackoverflow.com/users/26391",
"pm_score": 5,
"selected": false,
"text": "txtWhatever _whatever"
},
{
"answer_id": 309812,
"author": "scobi",
"author_id": 14582,
"author_profile": "https://Stackoverflow.com/users/14582",
"pm_score": 5,
"selected": false,
"text": "i_ // input-only function parameter (most are these)\no_ // output-only function parameter (so a non-const & or * type)\nio_ // bidirectional func param\n_ // private member var (c#)\nm_ // private member var (c++)\ns_ // static member var (c++)\ng_ // global (rare, typically a singleton accessor macro)\n"
},
{
"answer_id": 831559,
"author": "Luc M",
"author_id": 14673,
"author_profile": "https://Stackoverflow.com/users/14673",
"pm_score": 2,
"selected": false,
"text": "t_ for table name\nv_ for view name\ni_ for index name\ntrig_ for trigger\n\n\nsp_ for stored procedure name\np_ for parameter \nv_ for variable\nc_ for cursor\nr_ for record\n"
}
] | 2008/11/21 | [
"https://Stackoverflow.com/questions/309205",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/39677/"
] |
309,206 | <p>At the risk of becoming the village idiot, can someone explain to me why generics are called generics? I understand their usage and benefits, but if the <a href="http://dictionary.reference.com/browse/generic" rel="noreferrer">definition of generic</a> is "general" and generic collections are type safe, then why isn't this a misnomer?</p>
<p>For example, an ArrayList can hold anything that's an object:</p>
<pre><code>ArrayList myObjects = new ArrayList();
myObjects.Add("one");
myObjects.Add(1);
</code></pre>
<p>while a generic collection of type string can only hold strings:</p>
<pre><code>var myStrings = new List<string>();
myStrings.Add("one");
myStrings.Add("1");
</code></pre>
<p>I'm just not clear on why it's called "generic". If the answer is "...which make it possible to design classes and methods that defer the specification of one or more types until the class or method is declared and instantiated by client code." from <a href="http://msdn.microsoft.com/en-us/library/512aeb7t(VS.80).aspx" rel="noreferrer">here</a>, then I suppose that makes sense. Perhaps I'm having this mental lapse because I only began programming after Java introduced generics, so I don't recall a time before them. But still...</p>
<p>Any help is appreciated.</p>
| [
{
"answer_id": 1793614,
"author": "Jason Orendorff",
"author_id": 94977,
"author_profile": "https://Stackoverflow.com/users/94977",
"pm_score": 4,
"selected": false,
"text": "generic"
},
{
"answer_id": 1793677,
"author": "Pavel Minaev",
"author_id": 111335,
"author_profile": "https://Stackoverflow.com/users/111335",
"pm_score": 2,
"selected": false,
"text": "bool Equals(int x, int y)\n bool Equals<T>(T x, T y);\n"
}
] | 2008/11/21 | [
"https://Stackoverflow.com/questions/309206",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2034/"
] |
309,255 | <p>Does anyone know how to add a an MSBuild .proj file to my solution?</p>
<p>I was just given existing code from a vendor with a solution that references an MSBuild .proj file as one of its projects. When I open the solution, the project shows as (unavailable). It appears that I need to install some sort of project template to get this project to open correctly. I installed the <a href="http://www.codeplex.com/MSBuildTemplate" rel="nofollow noreferrer">Codeplex MSBuild Template</a>, but this doesn't appear to be it. </p>
<p>Any ideas?</p>
| [
{
"answer_id": 6822820,
"author": "ShadowChaser",
"author_id": 497666,
"author_profile": "https://Stackoverflow.com/users/497666",
"pm_score": 2,
"selected": false,
"text": "<Project xmlns=\"http://schemas.microsoft.com/developer/msbuild/2003\">\n <ItemGroup>\n <ProjectReference Include=\"CustomProject\\CustomProject.proj\">\n <AdditionalProperties>Configuration=$(Configuration); Platform=AnyCPU</AdditionalProperties>\n <Configuration>$(Configuration)</Configuration>\n <Platform>AnyCPU</Platform>\n </ProjectReference>\n </ItemGroup>\n</Project>\n"
}
] | 2008/11/21 | [
"https://Stackoverflow.com/questions/309255",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12497/"
] |
309,291 | <p>I'm writing an error handling module for a fairly complex system architected into layers. Sometimes our data layer throws obscure exceptions.</p>
<p>It would be really handy to log out the <i>values</i> of the parameters of the method that threw the exception. </p>
<p>I can reflect on the TargetSite property of the exception to find the method's parameter types and names, but I don't seem to be able to get the values... am I missing something?</p>
<hr>
<p>Dupe</p>
<p><a href="https://stackoverflow.com/questions/157911/in-a-net-exception-how-to-get-a-stacktrace-with-argument-values">In a .net Exception how to get a stacktrace with argument values</a></p>
| [
{
"answer_id": 309331,
"author": "Charles Bretana",
"author_id": 32632,
"author_profile": "https://Stackoverflow.com/users/32632",
"pm_score": 2,
"selected": false,
"text": "throw new ArgumentOutOfRangeException(string parameterName, \n object actualValue, string message);\n"
}
] | 2008/11/21 | [
"https://Stackoverflow.com/questions/309291",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3546/"
] |
309,292 | <p>I have an ARM kit beside me and a Linux kernel source code patched with Xenomai on my machine. I understand I can send data to the kit through an USB cable and a (windows-based, of course) software, but I'm stumped as to exactly <em>what</em> I should be sending that would make the kit run Linux.</p>
<p>(clarifications from comments: It is an Atmel AT91SAM9260-EK kit. It uses SAM-BA and SAM-PROG for the loading and unloading of data through either a serial or USB cable.)</p>
| [
{
"answer_id": 309331,
"author": "Charles Bretana",
"author_id": 32632,
"author_profile": "https://Stackoverflow.com/users/32632",
"pm_score": 2,
"selected": false,
"text": "throw new ArgumentOutOfRangeException(string parameterName, \n object actualValue, string message);\n"
}
] | 2008/11/21 | [
"https://Stackoverflow.com/questions/309292",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/39702/"
] |
309,303 | <p>Currently this expression <code>"I ([a-zA-z]\d]{3} "</code> returns when the following pattern is true:</p>
<pre>
I AAA
I Z99
</pre>
<p>I need to modify this so it will return a range of alphanumerics after the I from 2 to 13 that do not have a space.</p>
<p>Example:</p>
<pre>
I AAA
I A321
I ASHG310310
</pre>
<p>Thanks,</p>
<p>Dave</p>
| [
{
"answer_id": 309335,
"author": "Raymond Martineau",
"author_id": 33952,
"author_profile": "https://Stackoverflow.com/users/33952",
"pm_score": 2,
"selected": false,
"text": "I ([a-zA-Z]|\\d){2,13}\n"
}
] | 2008/11/21 | [
"https://Stackoverflow.com/questions/309303",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/38349/"
] |
309,322 | <p>For my personal stuff I just use the <code>svnadmin hotcopy</code> command once a week but for more mission critical repositories that include many developers, is that enough? Or should I spend the time to put together a more rigorous backup strategy that includes full backups and incremental backups?</p>
<p><code>hotcopy</code> seems like the easiest way to go, but I want to be able to restore a repo if, for some reason, it becomes corrupted. Will just doing a dump via <code>hotcopy</code> allow me to do this?</p>
| [
{
"answer_id": 309463,
"author": "Ken Gentle",
"author_id": 8709,
"author_profile": "https://Stackoverflow.com/users/8709",
"pm_score": 2,
"selected": false,
"text": "python svn-backup-dumps.py svn-backup-dump.py post-commit schtasks"
},
{
"answer_id": 1667123,
"author": "Aaron Newton",
"author_id": 201648,
"author_profile": "https://Stackoverflow.com/users/201648",
"pm_score": 2,
"selected": false,
"text": "svnadmin dump c:\\svn\\project > c:\\dumps\\project.bak\n\nsvnadmin load c:\\svn\\project < c:\\dumps\\project.bak\n svnadmin create c:\\svn\\project\n\nsvnadmin load c:\\svn\\project < c:\\dumps\\project.bak\n"
}
] | 2008/11/21 | [
"https://Stackoverflow.com/questions/309322",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13841/"
] |
309,333 | <p>I have an enum construct like this:</p>
<pre><code>public enum EnumDisplayStatus
{
None = 1,
Visible = 2,
Hidden = 3,
MarkedForDeletion = 4
}
</code></pre>
<p>In my database, the enumerations are referenced by value. My question is, how can I turn the number representation of the enum back to the string name. </p>
<p>For example, given <code>2</code> the result should be <code>Visible</code>.</p>
| [
{
"answer_id": 309339,
"author": "Kent Boogaart",
"author_id": 5380,
"author_profile": "https://Stackoverflow.com/users/5380",
"pm_score": 10,
"selected": true,
"text": "int ToString() int value = GetValueFromDb();\nvar enumDisplayStatus = (EnumDisplayStatus)value;\nstring stringValue = enumDisplayStatus.ToString();\n"
},
{
"answer_id": 309345,
"author": "Hath",
"author_id": 5186,
"author_profile": "https://Stackoverflow.com/users/5186",
"pm_score": 5,
"selected": false,
"text": "int dbValue = 2;\nEnumDisplayStatus enumValue = (EnumDisplayStatus)dbValue;\nstring stringName = enumValue.ToString(); //Visible\n"
},
{
"answer_id": 309349,
"author": "lacop",
"author_id": 894,
"author_profile": "https://Stackoverflow.com/users/894",
"pm_score": 2,
"selected": false,
"text": "EnumDisplayStatus status = (EnumDisplayStatus) statusFromDatabase;\nstring statusString = status.ToString();\n"
},
{
"answer_id": 309363,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 4,
"selected": false,
"text": "EnumDisplayStatus status = (EnumDisplayStatus)int.Parse(GetValueFromDb());\n string dbStatus = ((int)status).ToString();\n"
},
{
"answer_id": 8699002,
"author": "Mandoleen",
"author_id": 192355,
"author_profile": "https://Stackoverflow.com/users/192355",
"pm_score": 8,
"selected": false,
"text": "string m = Enum.GetName(typeof(MyEnumClass), value);\n"
},
{
"answer_id": 13879305,
"author": "algreat",
"author_id": 755223,
"author_profile": "https://Stackoverflow.com/users/755223",
"pm_score": 8,
"selected": false,
"text": "\"Visible\" EnumDisplayStatus int dbValue = GetDBValue();\nstring stringValue = Enum.GetName(typeof(EnumDisplayStatus), dbValue);\n"
},
{
"answer_id": 50865659,
"author": "James Cooke",
"author_id": 6240731,
"author_profile": "https://Stackoverflow.com/users/6240731",
"pm_score": 6,
"selected": false,
"text": "string bob = nameof(EnumDisplayStatus.Visible);\n"
},
{
"answer_id": 53539389,
"author": "Al3x_M",
"author_id": 4149929,
"author_profile": "https://Stackoverflow.com/users/4149929",
"pm_score": 3,
"selected": false,
"text": "string stringName = EnumDisplayStatus.Visible.ToString(\"f\");\n// stringName == \"Visible\"\n"
},
{
"answer_id": 54823079,
"author": "Naveen Kumar V",
"author_id": 5276297,
"author_profile": "https://Stackoverflow.com/users/5276297",
"pm_score": 4,
"selected": false,
"text": "int enumValue = 2; // The value for which you want to get string \nstring enumName = Enum.GetName(typeof(EnumDisplayStatus), enumValue);\n Stopwatch sw = new Stopwatch (); sw.Start (); sw.Stop (); sw.Reset ();\ndouble sum = 0;\nint n = 1000;\nConsole.WriteLine (\"\\nGetName method way:\");\nfor (int i = 0; i < n; i++) {\n sw.Start ();\n string t = Enum.GetName (typeof (Roles), roleValue);\n sw.Stop ();\n sum += sw.Elapsed.TotalMilliseconds;\n sw.Reset ();\n}\nConsole.WriteLine ($\"Average of {n} runs using Getname method casting way: {sum / n}\");\nConsole.WriteLine (\"\\nExplicit casting way:\");\nfor (int i = 0; i < n; i++) {\n sw.Start ();\n string t = ((Roles)roleValue).ToString ();\n sw.Stop ();\n sum += sw.Elapsed.TotalMilliseconds;\n sw.Reset ();\n}\nConsole.WriteLine ($\"Average of {n} runs using Explicit casting way: {sum / n}\");\n GetName method way:\nAverage of 1000 runs using Getname method casting way: 0.000186899999999998\nExplicit casting way:\nAverage of 1000 runs using Explicit casting way: 0.000627900000000002\n"
},
{
"answer_id": 55625154,
"author": "Muhammad Aqib",
"author_id": 5941789,
"author_profile": "https://Stackoverflow.com/users/5941789",
"pm_score": 3,
"selected": false,
"text": "EnumDisplayStatus enumDisplayStatus = (EnumDisplayStatus)GetDBValue();\nstring stringValue = $\"{enumDisplayStatus:G}\"; \n string stringValue = $\"{enumDisplayStatus:D}\";\nSetDBValue(Convert.ToInt32(stringValue ));\n"
},
{
"answer_id": 56983177,
"author": "Biddut",
"author_id": 9323947,
"author_profile": "https://Stackoverflow.com/users/9323947",
"pm_score": 3,
"selected": false,
"text": " CustomerType = ((EnumCustomerType)(cus.CustomerType)).ToString()\n"
},
{
"answer_id": 59777759,
"author": "Reap",
"author_id": 8705563,
"author_profile": "https://Stackoverflow.com/users/8705563",
"pm_score": 5,
"selected": false,
"text": "nameof class struct variable public enum MyEnum {\n CSV,\n Excel\n}\n\n\nstring enumAsString = nameof(MyEnum.CSV)\n// enumAsString = \"CSV\"\n nameof"
},
{
"answer_id": 69227197,
"author": "Biddut",
"author_id": 9323947,
"author_profile": "https://Stackoverflow.com/users/9323947",
"pm_score": 1,
"selected": false,
"text": "string stringValue=( (MyEnum)(MyEnum.CSV)).ToString();\n"
},
{
"answer_id": 71090888,
"author": "StackOverflowUser",
"author_id": 1470798,
"author_profile": "https://Stackoverflow.com/users/1470798",
"pm_score": 2,
"selected": false,
"text": "enum Colors {\n Red = 1,\n Green = 2,\n Blue = 3\n};\n Console.WriteLine( Enum.GetName( typeof(Colors), Colors.Green ) );\nConsole.WriteLine( Enum.GetName( typeof(Colors), 3 ) );\n Green\nBlue\n Console.WriteLine( Enum.GetName( Colors.Green ) );\nConsole.WriteLine( Enum.GetName( (Colors)3 ) );\n Green\nBlue\n"
}
] | 2008/11/21 | [
"https://Stackoverflow.com/questions/309333",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/39655/"
] |
309,334 | <p>What features do you wish were in common languages? More precisely, I mean features which generally don't exist at all but would be nice to see, rather than, "I wish dynamic typing was popular."</p>
| [
{
"answer_id": 309365,
"author": "Brian",
"author_id": 18192,
"author_profile": "https://Stackoverflow.com/users/18192",
"pm_score": 0,
"selected": false,
"text": "type datafoobak = item.datafoobak\nitem.datafoobak = 'tootle'\nitem.handledata()\nitem.datafoobak = datafoobak\n item.datafoobar @=@ 'tootle'\nitem.handledata()\n itemclone = item.shallowclone\nitemclone.datafoobak='tootle'\nitemclone.handledata()\n"
},
{
"answer_id": 309384,
"author": "benjismith",
"author_id": 22979,
"author_profile": "https://Stackoverflow.com/users/22979",
"pm_score": 4,
"selected": false,
"text": "GameState {\n observable int CurrentScore;\n}\n ScoreDisplay {\n observe GameState.CurrentScore(int oldValue, int newValue) {\n ...do stuff...\n }\n}\n"
},
{
"answer_id": 309417,
"author": "mipadi",
"author_id": 28804,
"author_profile": "https://Stackoverflow.com/users/28804",
"pm_score": 3,
"selected": false,
"text": "data Tree a = Node a (Tree a) (Tree a) | Nothing\n"
},
{
"answer_id": 309442,
"author": "benjismith",
"author_id": 22979,
"author_profile": "https://Stackoverflow.com/users/22979",
"pm_score": 0,
"selected": false,
"text": "interface Addable<T> --> HasOperator( T = T + T)\n\ninterface Splittable<T> --> HasMethod( T[] = T.Split(T) )\n"
},
{
"answer_id": 309488,
"author": "Kent Fredric",
"author_id": 15614,
"author_profile": "https://Stackoverflow.com/users/15614",
"pm_score": 3,
"selected": false,
"text": "my $y = \"world\"; \n\nmy $x = sub { print @_ , $y }; \n\n&$x( 'hello' ); #helloworld \n my $adder = sub {\n my $reg = $_[0];\n my $result = {};\n return sub { return $reg + $_[0]; }\n};\n\nprint $adder->(4)->(3);\n"
},
{
"answer_id": 10771257,
"author": "user",
"author_id": 512251,
"author_profile": "https://Stackoverflow.com/users/512251",
"pm_score": 2,
"selected": false,
"text": "immutable class JustAClass \n{\n private int readonly id; \n private MyClass readonly obj;\n public MyClass \n { \n get \n {\n return obj;\n }\n }\n}\n JustAClass obj immutable immutable"
}
] | 2008/11/21 | [
"https://Stackoverflow.com/questions/309334",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18192/"
] |
309,382 | <p>Say I have a xml document that looks like this</p>
<pre><code><foo>
<bar id="9" />
<bar id="4" />
<bar id="3" />
</foo>
</code></pre>
<p>I would like to use linq to reset the id's to 0, 1 ,2.
What would be the easiest way to do this?</p>
<p>Thanks</p>
| [
{
"answer_id": 309407,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 3,
"selected": true,
"text": "XElement xml = GetXml();\nvar i = 0;\nforeach (var e in xml.Elements(\"bar\"))\n e.SetAttributeValue(\"id\", i++);\n"
},
{
"answer_id": 309828,
"author": "Amy B",
"author_id": 8155,
"author_profile": "https://Stackoverflow.com/users/8155",
"pm_score": 0,
"selected": false,
"text": "XElement xml = GetXml();\nint updatedElements = xml.Elements(\"bar\")\n .Select((x, i) =>\n {\n x.SetAttributeValue(\"id\", i);\n return x;\n })\n .Count();\n XElement xml = GetXml();\nxml.Elements(\"bar\")\n .Select( (x, i) => new {x, i})\n .ToList()\n .ForEach(a => a.x.SetAttributeValue(\"id\", a.i));\n"
}
] | 2008/11/21 | [
"https://Stackoverflow.com/questions/309382",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/29961/"
] |
309,396 | <p>I've got a few methods that should call <code>System.exit()</code> on certain inputs. Unfortunately, testing these cases causes JUnit to terminate! Putting the method calls in a new Thread doesn't seem to help, since <code>System.exit()</code> terminates the JVM, not just the current thread. Are there any common patterns for dealing with this? For example, can I subsitute a stub for <code>System.exit()</code>? </p>
<p>[EDIT] The class in question is actually a command-line tool which I'm attempting to test inside JUnit. Maybe JUnit is simply not the right tool for the job? Suggestions for complementary regression testing tools are welcome (preferably something that integrates well with JUnit and EclEmma).</p>
| [
{
"answer_id": 309427,
"author": "VonC",
"author_id": 6309,
"author_profile": "https://Stackoverflow.com/users/6309",
"pm_score": 9,
"selected": true,
"text": "System.exit() System.exit() public class NoExitTestCase extends TestCase \n{\n\n protected static class ExitException extends SecurityException \n {\n public final int status;\n public ExitException(int status) \n {\n super(\"There is no escape!\");\n this.status = status;\n }\n }\n\n private static class NoExitSecurityManager extends SecurityManager \n {\n @Override\n public void checkPermission(Permission perm) \n {\n // allow anything.\n }\n @Override\n public void checkPermission(Permission perm, Object context) \n {\n // allow anything.\n }\n @Override\n public void checkExit(int status) \n {\n super.checkExit(status);\n throw new ExitException(status);\n }\n }\n\n @Override\n protected void setUp() throws Exception \n {\n super.setUp();\n System.setSecurityManager(new NoExitSecurityManager());\n }\n\n @Override\n protected void tearDown() throws Exception \n {\n System.setSecurityManager(null); // or save and restore original\n super.tearDown();\n }\n\n public void testNoExit() throws Exception \n {\n System.out.println(\"Printing works\");\n }\n\n public void testExit() throws Exception \n {\n try \n {\n System.exit(42);\n } catch (ExitException e) \n {\n assertEquals(\"Exit status\", 42, e.status);\n }\n }\n}\n java.lang.System System.exit(…)\n ExpectedSystemExit System.exit(…) public void MyTest {\n @Rule\n public final ExpectedSystemExit exit = ExpectedSystemExit.none();\n\n @Test\n public void noSystemExit() {\n //passes\n }\n\n @Test\n public void systemExitWithArbitraryStatusCode() {\n exit.expectSystemExit();\n System.exit(0);\n }\n\n @Test\n public void systemExitWithSelectedStatusCode0() {\n exit.expectSystemExitWithStatus(0);\n System.exit(0);\n }\n}\n"
},
{
"answer_id": 309435,
"author": "Scott Bale",
"author_id": 2495576,
"author_profile": "https://Stackoverflow.com/users/2495576",
"pm_score": 4,
"selected": false,
"text": "private static final Runnable DEFAULT_ACTION = new Runnable(){\n public void run(){\n System.exit(0);\n }\n};\n\npublic void foo(){ \n this.foo(DEFAULT_ACTION);\n}\n\n/* package-visible only for unit testing */\nvoid foo(Runnable action){ \n // ...some stuff... \n action.run(); \n}\n public void testFoo(){ \n final AtomicBoolean actionWasCalled = new AtomicBoolean(false); \n fooObject.foo(new Runnable(){\n public void run(){\n actionWasCalled.set(true);\n } \n }); \n assertTrue(actionWasCalled.get()); \n}\n"
},
{
"answer_id": 309451,
"author": "Marc Novakowski",
"author_id": 27020,
"author_profile": "https://Stackoverflow.com/users/27020",
"pm_score": 2,
"selected": false,
"text": "SecurityManager securityManager = new SecurityManager() {\n public void checkPermission(Permission permission) {\n if (\"exitVM\".equals(permission.getName())) {\n throw new SecurityException(\"System.exit attempted and blocked.\");\n }\n }\n};\nSystem.setSecurityManager(securityManager);\n"
},
{
"answer_id": 309467,
"author": "EricSchaefer",
"author_id": 8976,
"author_profile": "https://Stackoverflow.com/users/8976",
"pm_score": 5,
"selected": false,
"text": "public interface ExitManager {\n void exit(int exitCode);\n}\n\npublic class ExitManagerImpl implements ExitManager {\n public void exit(int exitCode) {\n System.exit(exitCode);\n }\n}\n\npublic class ExitManagerMock implements ExitManager {\n public bool exitWasCalled;\n public int exitCode;\n public void exit(int exitCode) {\n exitWasCalled = true;\n this.exitCode = exitCode;\n }\n}\n\npublic class MethodsCallExit {\n public void CallsExit(ExitManager exitManager) {\n // whatever\n if (foo) {\n exitManager.exit(42);\n }\n // whatever\n }\n}\n"
},
{
"answer_id": 309705,
"author": "Jeffrey Fredrick",
"author_id": 35894,
"author_profile": "https://Stackoverflow.com/users/35894",
"pm_score": 3,
"selected": false,
"text": "public class Foo {\n public void bar(int i) {\n if (i < 0) {\n System.exit(i);\n }\n }\n}\n public class Foo {\n public void bar(int i) {\n if (i < 0) {\n exit(i);\n }\n }\n\n void exit(int i) {\n System.exit(i);\n }\n}\n public class TestFoo extends TestCase {\n\n public void testShouldExitWithNegativeNumbers() {\n TestFoo foo = new TestFoo();\n foo.bar(-1);\n assertTrue(foo.exitCalled);\n assertEquals(-1, foo.exitValue);\n }\n\n private class TestFoo extends Foo {\n boolean exitCalled;\n int exitValue;\n void exit(int i) {\n exitCalled = true;\n exitValue = i;\n }\n}\n"
},
{
"answer_id": 1185204,
"author": "Rogério",
"author_id": 2326914,
"author_profile": "https://Stackoverflow.com/users/2326914",
"pm_score": 5,
"selected": false,
"text": "System.exit @Test\npublic void mockSystemExit(@Mocked(\"exit\") System mockSystem)\n{\n // Called by code under test:\n System.exit(); // will not exit the program\n}\n System.exit(n) @Test(expected = EOFException.class)\npublic void checkingForSystemExitWhileNotAllowingCodeToContinueToRun() {\n new Expectations(System.class) {{ System.exit(anyInt); result = new EOFException(); }};\n\n // From the code under test:\n System.exit(1);\n System.out.println(\"This will never run (and not exit either)\");\n}\n"
},
{
"answer_id": 2172642,
"author": "Jeow Li Huan",
"author_id": 263003,
"author_profile": "https://Stackoverflow.com/users/263003",
"pm_score": 3,
"selected": false,
"text": "protected static class ExitException extends SecurityException {\n private static final long serialVersionUID = -1982617086752946683L;\n public final int status;\n\n public ExitException(int status) {\n super(\"There is no escape!\");\n this.status = status;\n }\n}\n\nprivate static class NoExitSecurityManager extends SecurityManager {\n @Override\n public void checkPermission(Permission perm) {\n // allow anything.\n }\n\n @Override\n public void checkPermission(Permission perm, Object context) {\n // allow anything.\n }\n\n @Override\n public void checkExit(int status) {\n super.checkExit(status);\n throw new ExitException(status);\n }\n}\n\nprivate SecurityManager securityManager;\n\n@Before\npublic void setUp() {\n securityManager = System.getSecurityManager();\n System.setSecurityManager(new NoExitSecurityManager());\n}\n\n@After\npublic void tearDown() {\n System.setSecurityManager(securityManager);\n}\n"
},
{
"answer_id": 3977267,
"author": "Alexei",
"author_id": 481614,
"author_profile": "https://Stackoverflow.com/users/481614",
"pm_score": 1,
"selected": false,
"text": "Runtime.exec(String command)"
},
{
"answer_id": 8658497,
"author": "Stefan Birkner",
"author_id": 557091,
"author_profile": "https://Stackoverflow.com/users/557091",
"pm_score": 7,
"selected": false,
"text": "catchSystemExit public class MyTest {\n @Test\n public void systemExitWithArbitraryStatusCode() {\n SystemLambda.catchSystemExit(() -> {\n //the code under test, which calls System.exit(...);\n });\n }\n\n\n @Test\n public void systemExitWithSelectedStatusCode0() {\n int status = SystemLambda.catchSystemExit(() -> {\n //the code under test, which calls System.exit(0);\n });\n\n assertEquals(0, status);\n }\n}\n public class MyTest {\n @Rule\n public final ExpectedSystemExit exit = ExpectedSystemExit.none();\n\n @Test\n public void systemExitWithArbitraryStatusCode() {\n exit.expectSystemExit();\n //the code under test, which calls System.exit(...);\n }\n\n @Test\n public void systemExitWithSelectedStatusCode0() {\n exit.expectSystemExitWithStatus(0);\n //the code under test, which calls System.exit(0);\n }\n}\n"
},
{
"answer_id": 8669826,
"author": "Arend v. Reinersdorff",
"author_id": 78973,
"author_profile": "https://Stackoverflow.com/users/78973",
"pm_score": 3,
"selected": false,
"text": "// do thing1\nif(someCondition) {\n System.exit(1);\n}\n// do thing2\nSystem.exit(0)\n Sytem.exit() thing2 // do thing1\nif(someCondition) {\n return 1;\n}\n// do thing2\nreturn 0;\n System.exit(status) System.exit() main() System.exit() public class SystemExit {\n\n public void exit(int status) {\n System.exit(status);\n }\n}\n public class Main {\n\n private final SystemExit systemExit;\n\n\n Main(SystemExit systemExit) {\n this.systemExit = systemExit;\n }\n\n\n public static void main(String[] args) {\n SystemExit aSystemExit = new SystemExit();\n Main main = new Main(aSystemExit);\n\n main.executeAndExit(args);\n }\n\n\n void executeAndExit(String[] args) {\n int status = execute(args);\n systemExit.exit(status);\n }\n\n\n private int execute(String[] args) {\n System.out.println(\"First argument:\");\n if (args.length == 0) {\n return 1;\n }\n System.out.println(args[0]);\n return 0;\n }\n}\n public class MainTest {\n\n private Main main;\n\n private SystemExit systemExit;\n\n\n @Before\n public void setUp() {\n systemExit = mock(SystemExit.class);\n main = new Main(systemExit);\n }\n\n\n @Test\n public void executeCallsSystemExit() {\n String[] emptyArgs = {};\n\n // test\n main.executeAndExit(emptyArgs);\n\n verify(systemExit).exit(1);\n }\n}\n"
},
{
"answer_id": 9899322,
"author": "cayhorstmann",
"author_id": 375317,
"author_profile": "https://Stackoverflow.com/users/375317",
"pm_score": 1,
"selected": false,
"text": "SecurityManager JFrame.exitOnClose SecurityManager.checkExit Class[] stack = getClassContext();\nif (stack[1] != JFrame.class && !okToExit) throw new ExitException();\nsuper.checkExit(status);\n"
},
{
"answer_id": 17052539,
"author": "ursa",
"author_id": 2078908,
"author_profile": "https://Stackoverflow.com/users/2078908",
"pm_score": 2,
"selected": false,
"text": "public class ConsoleTest {\n /** Original runtime. */\n private Runtime originalRuntime;\n\n /** Mocked runtime. */\n private Runtime spyRuntime;\n\n @BeforeMethod\n public void setUp() {\n originalRuntime = Runtime.getRuntime();\n spyRuntime = spy(originalRuntime);\n\n // Replace original runtime with a spy (via reflection).\n Utils.setField(Runtime.class, \"currentRuntime\", spyRuntime);\n }\n\n @AfterMethod\n public void tearDown() {\n // Recover original runtime.\n Utils.setField(Runtime.class, \"currentRuntime\", originalRuntime);\n }\n\n @Test\n public void testSystemExit() {\n // Or anything you want as an answer.\n doNothing().when(spyRuntime).exit(anyInt());\n\n System.exit(1);\n\n verify(spyRuntime).exit(1);\n }\n}\n"
},
{
"answer_id": 59930938,
"author": "Christian Hujer",
"author_id": 3554264,
"author_profile": "https://Stackoverflow.com/users/3554264",
"pm_score": 2,
"selected": false,
"text": "System.exit() SecurityManager System.exit() assertAll() assertExits(int expectedStatus, Executable executable) System.exit() status assertThrows SecurityManager import java.security.Permission;\n\nimport static java.lang.System.getSecurityManager;\nimport static java.lang.System.setSecurityManager;\nimport static org.junit.jupiter.api.Assertions.assertEquals;\nimport static org.junit.jupiter.api.Assertions.fail;\n\npublic enum ExitAssertions {\n ;\n\n public static <E extends Throwable> void assertExits(final int expectedStatus, final ThrowingExecutable<E> executable) throws E {\n final SecurityManager originalSecurityManager = getSecurityManager();\n setSecurityManager(new SecurityManager() {\n @Override\n public void checkPermission(final Permission perm) {\n if (originalSecurityManager != null)\n originalSecurityManager.checkPermission(perm);\n }\n\n @Override\n public void checkPermission(final Permission perm, final Object context) {\n if (originalSecurityManager != null)\n originalSecurityManager.checkPermission(perm, context);\n }\n\n @Override\n public void checkExit(final int status) {\n super.checkExit(status);\n throw new ExitException(status);\n }\n });\n try {\n executable.run();\n fail(\"Expected System.exit(\" + expectedStatus + \") to be called, but it wasn't called.\");\n } catch (final ExitException e) {\n assertEquals(expectedStatus, e.status, \"Wrong System.exit() status.\");\n } finally {\n setSecurityManager(originalSecurityManager);\n }\n }\n\n public interface ThrowingExecutable<E extends Throwable> {\n void run() throws E;\n }\n\n private static class ExitException extends SecurityException {\n final int status;\n\n private ExitException(final int status) {\n this.status = status;\n }\n }\n}\n @Test\n void example() {\n assertExits(0, () -> System.exit(0)); // succeeds\n assertExits(1, () -> System.exit(1)); // succeeds\n assertExits(2, () -> System.exit(1)); // fails\n }\n Rule assertExits()"
},
{
"answer_id": 64983262,
"author": "Ashley Frieze",
"author_id": 1355930,
"author_profile": "https://Stackoverflow.com/users/1355930",
"pm_score": 2,
"selected": false,
"text": "System.exit @ExtendWith(SystemStubsExtension.class)\nclass SystemExitUseCase {\n // the presence of this in the test means System.exit becomes an exception\n @SystemStub\n private SystemExit systemExit;\n\n @Test\n void doSomethingThatAccidentallyCallsSystemExit() {\n // this test would have stopped the JVM, now it ends in `AbortExecutionException`\n // System.exit(1);\n }\n\n @Test\n void canCatchSystemExit() {\n assertThatThrownBy(() -> System.exit(1))\n .isInstanceOf(AbortExecutionException.class);\n\n assertThat(systemExit.getExitCode()).isEqualTo(1);\n }\n}\n assertThat(catchSystemExit(() -> {\n //the code under test\n System.exit(123);\n})).isEqualTo(123);\n"
},
{
"answer_id": 68323093,
"author": "Jool",
"author_id": 1329426,
"author_profile": "https://Stackoverflow.com/users/1329426",
"pm_score": 1,
"selected": false,
"text": "package mainmocked;\nclass MainRunner {\n void run(final String[] args) {\n new MainMocked().run(args); \n }\n void exit(final int status) {\n System.exit(status);\n }\n}\n package mainmocked;\n\npublic class MainMocked {\n private static MainRunner runner = new MainRunner();\n\n static void altMain(final String[] args, final MainRunner inRunner) {\n runner = inRunner;\n main(args);\n }\n\n public static void main(String[] args) {\n try {\n runner.run(args);\n } catch (Throwable ex) {\n // Log(\"error: \", ex);\n runner.exit(1);\n }\n runner.exit(0);\n } // main\n\n\n public void run(String[] args) {\n // do things ...\n }\n} // class\n @Test\npublic void testAltMain() {\n String[] args0 = {};\n MainRunner mockRunner = mock(MainRunner.class);\n MainMocked.altMain(args0, mockRunner);\n\n verify(mockRunner).run(args0);\n verify(mockRunner).exit(0);\n }\n private class FakeRunnerRuns extends MainRunner {\n @Override\n void run(String[] args){\n new MainMocked().run(args);\n }\n @Override\n void exit(final int status) {\n if (status == 0) {\n throw new MyMockExitExceptionOK(\"exit(0) success\");\n }\n else {\n throw new MyMockExitExceptionFail(\"Unexpected Exception\");\n } // ok\n } // exit\n} // class\n"
}
] | 2008/11/21 | [
"https://Stackoverflow.com/questions/309396",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1412/"
] |
309,402 | <p>In my php script which connects to mysql, I have to query 2 databases in the same script to get different information. More specifically Faxarchives in one database and Faxusers in the other. </p>
<p>In my code I query faxusers and then foreach user, I query Faxarchives to get the user history. </p>
<p>I might do something like: </p>
<pre><code>function getUserarchive( $userid) {
$out= "";
$dbname = 'Faxarchive';
$db = mysql_select_db($dbname);
$sql = "select sent, received from faxarchivetable where userid = '" . $userid . "'";
if ( $rs = mysql_query($sql) {
while ($row = mysql_fetch_array($rs) ) {
$out = $row['sent'] . " " . $row['received'];
}//end while
}//end if query
return ($out);
}//end function
$conn = mysql_connect($dbhost, $dbuser, $dbpass) or die ('Error connecting to mysql');
$dbname = 'Faxusers';
$db = mysql_select_db($dbname);
$sql="select distinct userid from faxuserstable";
if ( $rs = mysql_query($sql) {
while ($row = mysql_fetch_array($rs) ) {
$out = $row['userid'] . ":" . getuserarchive($row['userid']);
}//end while
}//end if query
</code></pre>
<p>I'm guessing the switching between databases for each user is causing the slowness. Anyways how i can improve the speed of the processing? </p>
<p>thanks in advance.</p>
| [
{
"answer_id": 309552,
"author": "Bill Karwin",
"author_id": 20860,
"author_profile": "https://Stackoverflow.com/users/20860",
"pm_score": 0,
"selected": false,
"text": "SELECT sent, received \nFROM Faxarchive.faxarchivetable\nWHERE userid IN ( SELECT DISTINCT userid FROM Faxusers.faxuserstable );\n"
}
] | 2008/11/21 | [
"https://Stackoverflow.com/questions/309402",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18853/"
] |
309,405 | <p>Currently, we're storing the user's HTTP_REFERER so we can redirect the user back to the previous page they were browsing before they logged in.</p>
<p>Http Referer comes from the client and can be spoofed or blank. Is there a more secure/reliable method to deliver this handy user redirect?</p>
| [
{
"answer_id": 309418,
"author": "Andrew Bullock",
"author_id": 28543,
"author_profile": "https://Stackoverflow.com/users/28543",
"pm_score": 2,
"selected": false,
"text": "history.go(-1);\n"
},
{
"answer_id": 309428,
"author": "Greg",
"author_id": 24181,
"author_profile": "https://Stackoverflow.com/users/24181",
"pm_score": 0,
"selected": false,
"text": "<form action=\"login\" method=\"post\">\n<input type=\"hidden\" name=\"url\" value=\"... whatever the current url is ...\">\n<input type=\"text\" name=\"username\">\n<input type=\"text\" name=\"password\">\n</form>\n"
},
{
"answer_id": 309487,
"author": "Ryan Smith",
"author_id": 10420,
"author_profile": "https://Stackoverflow.com/users/10420",
"pm_score": 0,
"selected": false,
"text": "Protected Sub doRedirect(ByVal sender As Object, ByVal e As System.EventArgs)\n If Not Request.QueryString(\"rtn\") Is Nothing Then\n Response.Redirect(Request.QueryString(\"rtn\").ToString)\n ElseIf Me.hidden_return.Value <> \"\" Then\n Response.Redirect(Me.hidden_return.Value)\n ElseIf Not Request.UrlReferrer Is Nothing AndAlso Request.UrlReferrer.Segments(Request.UrlReferrer.Segments.Length - 1) <> \"login.aspx\" Then\n Response.Redirect(Request.UrlReferrer.ToString)\n Else\n Response.Redirect(\"default.aspx\")\n End If\nEnd Sub\n"
}
] | 2008/11/21 | [
"https://Stackoverflow.com/questions/309405",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/26180/"
] |
309,412 | <p>Is there any way to install Setuptools for Python 2.6 in Windows without having an exe installer? </p>
<p>There isn't one built at the moment, and the maintainer of Setuptools has stated that it will probably be a while before he'll get to it. </p>
<p>Does anyone know of a way to install it anyway?</p>
| [
{
"answer_id": 380007,
"author": "will-mvn",
"author_id": 47632,
"author_profile": "https://Stackoverflow.com/users/47632",
"pm_score": 3,
"selected": false,
"text": "python.exe setup.py bdist_wininst\n dist\\setuptools-0.6c9.win32.exe"
},
{
"answer_id": 2755659,
"author": "Tommy B",
"author_id": 331062,
"author_profile": "https://Stackoverflow.com/users/331062",
"pm_score": 1,
"selected": false,
"text": "setuptools"
},
{
"answer_id": 22721532,
"author": "ewerybody",
"author_id": 469322,
"author_profile": "https://Stackoverflow.com/users/469322",
"pm_score": 0,
"selected": false,
"text": "import urllib\nurl = 'https://bitbucket.org/pypa/setuptools/raw/bootstrap/ez_setup.py'\nezcode = urllib.urlopen(url).read()\nexec(ezcode)\n"
}
] | 2008/11/21 | [
"https://Stackoverflow.com/questions/309412",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/349836/"
] |
309,424 | <p>If you have a <code>java.io.InputStream</code> object, how should you process that object and produce a <code>String</code>?</p>
<hr />
<p>Suppose I have an <code>InputStream</code> that contains text data, and I want to convert it to a <code>String</code>, so for example I can write that to a log file.</p>
<p>What is the easiest way to take the <code>InputStream</code> and convert it to a <code>String</code>?</p>
<pre><code>public String convertStreamToString(InputStream is) {
// ???
}
</code></pre>
| [
{
"answer_id": 309448,
"author": "Harry Lime",
"author_id": 21590,
"author_profile": "https://Stackoverflow.com/users/21590",
"pm_score": 12,
"selected": true,
"text": "IOUtils InputStream StringWriter StringWriter writer = new StringWriter();\nIOUtils.copy(inputStream, writer, encoding);\nString theString = writer.toString();\n // NB: does not close inputStream, you'll have to use try-with-resources for that\nString theString = IOUtils.toString(inputStream, encoding); \n ByteArrayOutputStream"
},
{
"answer_id": 309718,
"author": "Paul de Vrieze",
"author_id": 4100,
"author_profile": "https://Stackoverflow.com/users/4100",
"pm_score": 8,
"selected": false,
"text": "java.io.Reader StringBuilder StringBuffer StringBuilder public static String slurp(final InputStream is, final int bufferSize) {\n final char[] buffer = new char[bufferSize];\n final StringBuilder out = new StringBuilder();\n try (Reader in = new InputStreamReader(is, \"UTF-8\")) {\n for (;;) {\n int rsz = in.read(buffer, 0, buffer.length);\n if (rsz < 0)\n break;\n out.append(buffer, 0, rsz);\n }\n }\n catch (UnsupportedEncodingException ex) {\n /* ... */\n }\n catch (IOException ex) {\n /* ... */\n }\n return out.toString();\n}\n"
},
{
"answer_id": 350723,
"author": "Chinnery",
"author_id": 31892,
"author_profile": "https://Stackoverflow.com/users/31892",
"pm_score": 10,
"selected": false,
"text": "String myString = IOUtils.toString(myInputStream, \"UTF-8\");\n"
},
{
"answer_id": 978162,
"author": "Jon Moore",
"author_id": 57541,
"author_profile": "https://Stackoverflow.com/users/57541",
"pm_score": 6,
"selected": false,
"text": "import java.io.BufferedInputStream;\nimport java.io.ByteArrayOutputStream;\nimport java.io.InputStream;\nimport java.io.IOException;\n\npublic static String readInputStreamAsString(InputStream in)\n throws IOException {\n\n BufferedInputStream bis = new BufferedInputStream(in);\n ByteArrayOutputStream buf = new ByteArrayOutputStream();\n int result = bis.read();\n while(result != -1) {\n byte b = (byte)result;\n buf.write(b);\n result = bis.read();\n }\n return buf.toString();\n}\n"
},
{
"answer_id": 2857414,
"author": "DJDaveMark",
"author_id": 344029,
"author_profile": "https://Stackoverflow.com/users/344029",
"pm_score": 5,
"selected": false,
"text": "public class StringFromFile {\n public static void main(String[] args) /*throws UnsupportedEncodingException*/ {\n InputStream is = StringFromFile.class.getResourceAsStream(\"file.txt\");\n BufferedReader br = new BufferedReader(new InputStreamReader(is/*, \"UTF-8\"*/));\n final int CHARS_PER_PAGE = 5000; //counting spaces\n StringBuilder builder = new StringBuilder(CHARS_PER_PAGE);\n try {\n for(String line=br.readLine(); line!=null; line=br.readLine()) {\n builder.append(line);\n builder.append('\\n');\n }\n } \n catch (IOException ignore) { }\n\n String text = builder.toString();\n System.out.println(text);\n }\n}\n public class StringFromFileFast {\n public static void main(String[] args) /*throws UnsupportedEncodingException*/ {\n InputStream is = StringFromFileFast.class.getResourceAsStream(\"file.txt\");\n InputStreamReader input = new InputStreamReader(is/*, \"UTF-8\"*/);\n final int CHARS_PER_PAGE = 5000; //counting spaces\n final char[] buffer = new char[CHARS_PER_PAGE];\n StringBuilder output = new StringBuilder(CHARS_PER_PAGE);\n try {\n for(int read = input.read(buffer, 0, buffer.length);\n read != -1;\n read = input.read(buffer, 0, buffer.length)) {\n output.append(buffer, 0, read);\n }\n } catch (IOException ignore) { }\n\n String text = output.toString();\n System.out.println(text);\n }\n}\n"
},
{
"answer_id": 3238954,
"author": "Sakuraba",
"author_id": 151614,
"author_profile": "https://Stackoverflow.com/users/151614",
"pm_score": 8,
"selected": false,
"text": "InputStream stream = ...\nString content = CharStreams.toString(new InputStreamReader(stream, Charsets.UTF_8));\nCloseables.closeQuietly(stream);\n InputStreamReader"
},
{
"answer_id": 5445161,
"author": "Pavel Repin",
"author_id": 43151,
"author_profile": "https://Stackoverflow.com/users/43151",
"pm_score": 11,
"selected": false,
"text": "static String convertStreamToString(java.io.InputStream is) {\n java.util.Scanner s = new java.util.Scanner(is).useDelimiter(\"\\\\A\");\n return s.hasNext() ? s.next() : \"\";\n}\n Scanner"
},
{
"answer_id": 6938341,
"author": "sampathpremarathna",
"author_id": 559185,
"author_profile": "https://Stackoverflow.com/users/559185",
"pm_score": 8,
"selected": false,
"text": "InputStream in = /* Your InputStream */;\nStringBuilder sb = new StringBuilder();\nBufferedReader br = new BufferedReader(new InputStreamReader(in));\nString read;\n\nwhile ((read=br.readLine()) != null) {\n //System.out.println(read);\n sb.append(read);\n}\n\nbr.close();\nreturn sb.toString();\n"
},
{
"answer_id": 7743991,
"author": "Brett H",
"author_id": 370547,
"author_profile": "https://Stackoverflow.com/users/370547",
"pm_score": 5,
"selected": false,
"text": " String response;\n String url = \"www.blah.com/path?key=value\";\n GetMethod method = new GetMethod(url);\n int status = client.executeMethod(method);\n response = method.getResponseBodyAsString();\n InputStream resp = method.getResponseBodyAsStream();\nInputStreamReader is=new InputStreamReader(resp);\nBufferedReader br=new BufferedReader(is);\nString read = null;\nStringBuffer sb = new StringBuffer();\nwhile((read = br.readLine()) != null) {\n sb.append(read);\n}\nresponse = sb.toString();\n InputStream iStream = method.getResponseBodyAsStream();\nStringWriter writer = new StringWriter();\nIOUtils.copy(iStream, writer, \"UTF-8\");\nresponse = writer.toString();\n"
},
{
"answer_id": 9597413,
"author": "Jack",
"author_id": 828757,
"author_profile": "https://Stackoverflow.com/users/828757",
"pm_score": 5,
"selected": false,
"text": "scala.io.Source.fromInputStream(is).mkString(\"\")\n"
},
{
"answer_id": 9949592,
"author": "TKH",
"author_id": 458244,
"author_profile": "https://Stackoverflow.com/users/458244",
"pm_score": 5,
"selected": false,
"text": "String streamToString(InputStream in) throws IOException {\n StringBuilder out = new StringBuilder();\n BufferedReader br = new BufferedReader(new InputStreamReader(in));\n for(String line = br.readLine(); line != null; line = br.readLine()) \n out.append(line);\n br.close();\n return out.toString();\n}\n"
},
{
"answer_id": 10505933,
"author": "TacB0sS",
"author_id": 348189,
"author_profile": "https://Stackoverflow.com/users/348189",
"pm_score": 7,
"selected": false,
"text": "public String readFullyAsString(InputStream inputStream, String encoding)\n throws IOException {\n return readFully(inputStream).toString(encoding);\n}\n\npublic byte[] readFullyAsBytes(InputStream inputStream)\n throws IOException {\n return readFully(inputStream).toByteArray();\n}\n\nprivate ByteArrayOutputStream readFully(InputStream inputStream)\n throws IOException {\n ByteArrayOutputStream baos = new ByteArrayOutputStream();\n byte[] buffer = new byte[1024];\n int length = 0;\n while ((length = inputStream.read(buffer)) != -1) {\n baos.write(buffer, 0, length);\n }\n return baos;\n}\n"
},
{
"answer_id": 11566262,
"author": "soBinary",
"author_id": 772549,
"author_profile": "https://Stackoverflow.com/users/772549",
"pm_score": -1,
"selected": false,
"text": "String result = (String)new ObjectInputStream( inputStream ).readObject();\n"
},
{
"answer_id": 11628754,
"author": "Anand N",
"author_id": 1548325,
"author_profile": "https://Stackoverflow.com/users/1548325",
"pm_score": 3,
"selected": false,
"text": "URL url = MyClass.class.getResource(\"/\" + configFileName);\nBufferedInputStream bi = (BufferedInputStream) url.getContent();\nbyte[] buffer = new byte[bi.available() ];\nint bytesRead = bi.read(buffer);\nString out = new String(buffer);\n available() InputStream BufferedInputStream available() URL url = MyClass.class.getResource(\"/\" + configFileName);\nBufferedInputStream bi = (BufferedInputStream) url.getContent();\nFile f = new File(url.getPath());\nbyte[] buffer = new byte[ (int) f.length()];\nint bytesRead = bi.read(buffer);\nString out = new String(buffer);\n"
},
{
"answer_id": 13195413,
"author": "Matt Shannon",
"author_id": 1794244,
"author_profile": "https://Stackoverflow.com/users/1794244",
"pm_score": 4,
"selected": false,
"text": "IOUtils.copy() byte[] char[] Reader InputStream import java.io.ByteArrayOutputStream;\nimport java.io.InputStream;\n\n...\n\nInputStream is = ....\nByteArrayOutputStream baos = new ByteArrayOutputStream(8192);\nbyte[] buffer = new byte[8192];\nint count = 0;\ntry {\n while ((count = is.read(buffer)) != -1) {\n baos.write(buffer, 0, count);\n }\n}\nfinally {\n try {\n is.close();\n }\n catch (Exception ignore) {\n }\n}\n\nString charset = \"UTF-8\";\nString inputStreamAsString = baos.toString(charset);\n"
},
{
"answer_id": 13430647,
"author": "Thamme Gowda",
"author_id": 1506477,
"author_profile": "https://Stackoverflow.com/users/1506477",
"pm_score": 4,
"selected": false,
"text": "private String readStream(InputStream iStream) throws IOException {\n //build a Stream Reader, it can read char by char\n InputStreamReader iStreamReader = new InputStreamReader(iStream);\n //build a buffered Reader, so that i can read whole line at once\n BufferedReader bReader = new BufferedReader(iStreamReader);\n String line = null;\n StringBuilder builder = new StringBuilder();\n while((line = bReader.readLine()) != null) { //Read till end\n builder.append(line);\n builder.append(\"\\n\"); // append new line to preserve lines\n }\n bReader.close(); //close all opened stuff\n iStreamReader.close();\n //iStream.close(); //EDIT: Let the creator of the stream close it!\n // some readers may auto close the inner stream\n return builder.toString();\n}\n /**\n * Reads the stream into a string\n * @param iStream the input stream\n * @return the string read from the stream\n * @throws IOException when an IO error occurs\n */\nprivate String readStream(InputStream iStream) throws IOException {\n\n //Buffered reader allows us to read line by line\n try (BufferedReader bReader =\n new BufferedReader(new InputStreamReader(iStream))){\n StringBuilder builder = new StringBuilder();\n String line;\n while((line = bReader.readLine()) != null) { //Read till end\n builder.append(line);\n builder.append(\"\\n\"); // append new line to preserve lines\n }\n return builder.toString();\n }\n}\n"
},
{
"answer_id": 14107694,
"author": "Drew Noakes",
"author_id": 24874,
"author_profile": "https://Stackoverflow.com/users/24874",
"pm_score": 6,
"selected": false,
"text": "public static String fromStream(InputStream in) throws IOException\n{\n BufferedReader reader = new BufferedReader(new InputStreamReader(in));\n StringBuilder out = new StringBuilder();\n String newLine = System.getProperty(\"line.separator\");\n String line;\n while ((line = reader.readLine()) != null) {\n out.append(line);\n out.append(newLine);\n }\n return out.toString();\n}\n"
},
{
"answer_id": 15315403,
"author": "Victor",
"author_id": 903998,
"author_profile": "https://Stackoverflow.com/users/903998",
"pm_score": 3,
"selected": false,
"text": "String Inputstream2String (InputStream is) throws IOException\n {\n final int PKG_SIZE = 1024;\n byte[] data = new byte [PKG_SIZE];\n StringBuilder buffer = new StringBuilder(PKG_SIZE * 10);\n int size;\n\n size = is.read(data, 0, data.length);\n while (size > 0)\n {\n String str = new String(data, 0, size);\n buffer.append(str);\n size = is.read(data, 0, data.length);\n }\n return buffer.toString();\n }\n"
},
{
"answer_id": 16487716,
"author": "FK386",
"author_id": 2370932,
"author_profile": "https://Stackoverflow.com/users/2370932",
"pm_score": -1,
"selected": false,
"text": " InputStream IS=new URL(\"http://www.petrol.si/api/gas_prices.json\").openStream(); \n\n ByteArrayOutputStream BAOS=new ByteArrayOutputStream();\n IOUtils.copy(IS, BAOS);\n String d= new String(BAOS.toByteArray(),\"UTF-8\"); \n\nSystem.out.println(d);\n"
},
{
"answer_id": 16839350,
"author": "Omkar Khot",
"author_id": 2435085,
"author_profile": "https://Stackoverflow.com/users/2435085",
"pm_score": 2,
"selected": false,
"text": "InputStreamReader i = new InputStreamReader(s);\nBufferedReader str = new BufferedReader(i);\nString msg = str.readLine();\nSystem.out.println(msg);\n InputStream String"
},
{
"answer_id": 20407168,
"author": "voidmain",
"author_id": 428594,
"author_profile": "https://Stackoverflow.com/users/428594",
"pm_score": 3,
"selected": false,
"text": "StringBuilder build = new StringBuilder();\nbyte[] buf = new byte[1024];\nint length;\ntry (InputStream is = getInputStream()) {\n while ((length = is.read(buf)) != -1) {\n build.append(new String(buf, 0, length));\n }\n}\n"
},
{
"answer_id": 21163930,
"author": "Rys",
"author_id": 2217011,
"author_profile": "https://Stackoverflow.com/users/2217011",
"pm_score": 2,
"selected": false,
"text": "public static String toString(InputStream input) throws IOException {\n return toString(input, Charset.defaultCharset());\n}\n\npublic static String toString(InputStream input) throws IOException {\n return toString(input, Charset.defaultCharset());\n}\n\npublic static String toString(InputStream input, String encoding)\n throws IOException {\n return toString(input, Charsets.toCharset(encoding));\n}\n"
},
{
"answer_id": 21619906,
"author": "JavaTechnical",
"author_id": 2534090,
"author_profile": "https://Stackoverflow.com/users/2534090",
"pm_score": 2,
"selected": false,
"text": "String += char String String st st public String convertStreamToString(InputStream is)\n{\n int k;\n StringBuffer sb=new StringBuffer();\n while((k=fin.read()) != -1)\n {\n sb.append((char)k);\n }\n return sb.toString();\n}\n public String convertStreamToString(InputStream is) { \n int k;\n String st=\"\";\n while((k=is.read()) != -1)\n {\n st+=(char)k;\n }\n return st;\n}\n"
},
{
"answer_id": 21912248,
"author": "Fred",
"author_id": 2470524,
"author_profile": "https://Stackoverflow.com/users/2470524",
"pm_score": 0,
"selected": false,
"text": "/** Reads an InputStream and converts it to a String.\n * @param stream InputStream containing HTML from targeted site.\n * @param len Length of string that this method returns.\n * @return String concatenated according to len parameter.\n * @throws java.io.IOException\n * @throws java.io.UnsupportedEncodingException\n */\nprivate String readIt(InputStream stream, int len) throws IOException, UnsupportedEncodingException {\n Reader reader = null;\n reader = new InputStreamReader(stream, \"UTF-8\");\n char[] buffer = new char[len];\n reader.read(buffer);\n return new String(buffer);\n}\n"
},
{
"answer_id": 21915153,
"author": "Ben Barkay",
"author_id": 1055284,
"author_profile": "https://Stackoverflow.com/users/1055284",
"pm_score": 3,
"selected": false,
"text": "// Read from InputStream\nString data = new ReaderSink(inputStream, Charset.forName(\"UTF-8\")).drain();\n\n// Read from File\ndata = new ReaderSink(file, Charset.forName(\"UTF-8\")).drain();\n\n// Drain input stream to console\nnew ReaderSink(inputStream, Charset.forName(\"UTF-8\")).drainTo(System.out);\n import java.io.*;\nimport java.nio.charset.Charset;\n\n/**\n * A simple sink class that drains a {@link Reader} to a {@link String} or\n * to a {@link Writer}.\n *\n * @author Ben Barkay\n * @version 2/20/2014\n */\npublic class ReaderSink {\n /**\n * The default buffer size to use if no buffer size was specified.\n */\n public static final int DEFAULT_BUFFER_SIZE = 1024;\n\n /**\n * The {@link Reader} that will be drained.\n */\n private final Reader in;\n\n /**\n * Constructs a new {@code ReaderSink} for the specified file and charset.\n * @param file The file to read from.\n * @param charset The charset to use.\n * @throws FileNotFoundException If the file was not found on the filesystem.\n */\n public ReaderSink(File file, Charset charset) throws FileNotFoundException {\n this(new FileInputStream(file), charset);\n }\n\n /**\n * Constructs a new {@code ReaderSink} for the specified {@link InputStream}.\n * @param in The {@link InputStream} to drain.\n * @param charset The charset to use.\n */\n public ReaderSink(InputStream in, Charset charset) {\n this(new InputStreamReader(in, charset));\n }\n\n /**\n * Constructs a new {@code ReaderSink} for the specified {@link Reader}.\n * @param in The reader to drain.\n */\n public ReaderSink(Reader in) {\n this.in = in;\n }\n\n /**\n * Drains the data from the underlying {@link Reader}, returning a {@link String} containing\n * all of the read information. This method will use {@link #DEFAULT_BUFFER_SIZE} for\n * its buffer size.\n * @return A {@link String} containing all of the information that was read.\n */\n public String drain() throws IOException {\n return drain(DEFAULT_BUFFER_SIZE);\n }\n\n /**\n * Drains the data from the underlying {@link Reader}, returning a {@link String} containing\n * all of the read information.\n * @param bufferSize The size of the buffer to use when reading.\n * @return A {@link String} containing all of the information that was read.\n */\n public String drain(int bufferSize) throws IOException {\n StringWriter stringWriter = new StringWriter();\n drainTo(stringWriter, bufferSize);\n return stringWriter.toString();\n }\n\n /**\n * Drains the data from the underlying {@link Reader}, writing it to the\n * specified {@link Writer}. This method will use {@link #DEFAULT_BUFFER_SIZE} for\n * its buffer size.\n * @param out The {@link Writer} to write to.\n */\n public void drainTo(Writer out) throws IOException {\n drainTo(out, DEFAULT_BUFFER_SIZE);\n }\n\n /**\n * Drains the data from the underlying {@link Reader}, writing it to the\n * specified {@link Writer}.\n * @param out The {@link Writer} to write to.\n * @param bufferSize The size of the buffer to use when reader.\n */\n public void drainTo(Writer out, int bufferSize) throws IOException {\n char[] buffer = new char[bufferSize];\n int read;\n while ((read = in.read(buffer)) > -1) {\n out.write(buffer, 0, read);\n }\n }\n}\n"
},
{
"answer_id": 22960005,
"author": "laksys",
"author_id": 978136,
"author_profile": "https://Stackoverflow.com/users/978136",
"pm_score": 4,
"selected": false,
"text": "InputStream String StringBuilder StringBuffer public static String getString( InputStream is) throws IOException {\n int ch;\n StringBuilder sb = new StringBuilder();\n while((ch = is.read()) != -1)\n sb.append((char)ch);\n return sb.toString();\n}\n"
},
{
"answer_id": 23615823,
"author": "Dinis Cruz",
"author_id": 262379,
"author_profile": "https://Stackoverflow.com/users/262379",
"pm_score": -1,
"selected": false,
"text": "String result = new String(StreamUtils.getBytes(inputStream));\n"
},
{
"answer_id": 24104048,
"author": "Daniel De León",
"author_id": 980442,
"author_profile": "https://Stackoverflow.com/users/980442",
"pm_score": 4,
"selected": false,
"text": "public static String convertStreamToString(InputStream is) throws IOException {\n StringBuilder sb = new StringBuilder(2048); // Define a size if you have an idea of it.\n char[] read = new char[128]; // Your buffer size.\n try (InputStreamReader ir = new InputStreamReader(is, StandardCharsets.UTF_8)) {\n for (int i; -1 != (i = ir.read(read)); sb.append(read, 0, i));\n }\n return sb.toString();\n}\n public static String inputStreamString(InputStream inputStream) throws IOException {\n try (inputStream) {\n return new String(inputStream.readAllBytes(), StandardCharsets.UTF_8);\n }\n}\n"
},
{
"answer_id": 24810414,
"author": "Simon Kuang",
"author_id": 3040627,
"author_profile": "https://Stackoverflow.com/users/3040627",
"pm_score": 5,
"selected": false,
"text": "public static String streamToString(final InputStream inputStream) throws Exception {\n // buffering optional\n try\n (\n final BufferedReader br\n = new BufferedReader(new InputStreamReader(inputStream))\n ) {\n // parallel optional\n return br.lines().parallel().collect(Collectors.joining(\"\\n\"));\n } catch (final IOException e) {\n throw new RuntimeException(e);\n // whatever.\n }\n}\n"
},
{
"answer_id": 25103484,
"author": "Hai Zhang",
"author_id": 2420519,
"author_profile": "https://Stackoverflow.com/users/2420519",
"pm_score": 4,
"selected": false,
"text": "org.apache.commons.io.IOUtils private static final int BUFFER_SIZE = 4 * 1024;\n\npublic static String inputStreamToString(InputStream inputStream, String charsetName)\n throws IOException {\n StringBuilder builder = new StringBuilder();\n InputStreamReader reader = new InputStreamReader(inputStream, charsetName);\n char[] buffer = new char[BUFFER_SIZE];\n int length;\n while ((length = reader.read(buffer)) != -1) {\n builder.append(buffer, 0, length);\n }\n return builder.toString();\n}\n"
},
{
"answer_id": 25486003,
"author": "Vaishali Sutariya",
"author_id": 3129572,
"author_profile": "https://Stackoverflow.com/users/3129572",
"pm_score": 2,
"selected": false,
"text": "InputStream is = Context.openFileInput(someFileName); // whatever format you have\n\nByteArrayOutputStream bos = new ByteArrayOutputStream();\n\nbyte[] b = new byte[8192];\nfor (int bytesRead; (bytesRead = is.read(b)) != -1;) {\n bos.write(b, 0, bytesRead);\n}\n\nString output = bos.toString(someEncoding);\n"
},
{
"answer_id": 25782577,
"author": "Luke Hutchison",
"author_id": 3950982,
"author_profile": "https://Stackoverflow.com/users/3950982",
"pm_score": 1,
"selected": false,
"text": "String line = null;\nwhile((line = reader.readLine()) != null) {\n // ...\n}\n for(String line = reader.readLine(); line != null; line = reader.readLine()) {\n // ...\n}\n for (String line; (line = reader.readLine()) != null; ) {\n //...\n}\n"
},
{
"answer_id": 28311797,
"author": "Alex",
"author_id": 159679,
"author_profile": "https://Stackoverflow.com/users/159679",
"pm_score": 4,
"selected": false,
"text": "println(InputStreamReader(is).readText())\n readText()\n"
},
{
"answer_id": 28750240,
"author": "czerny",
"author_id": 639687,
"author_profile": "https://Stackoverflow.com/users/639687",
"pm_score": 5,
"selected": false,
"text": "import java.io.BufferedReader;\nimport java.io.IOException;\nimport java.io.InputStream;\nimport java.io.InputStreamReader;\nimport java.util.stream.Collectors;\n\n// ...\npublic static String inputStreamToString(InputStream is) throws IOException {\n try (BufferedReader br = new BufferedReader(new InputStreamReader(is))) {\n return br.lines().collect(Collectors.joining(System.lineSeparator()));\n }\n}\n new InputStreamReader(is, Charset.forName(\"UTF-8\"))\n"
},
{
"answer_id": 31318764,
"author": "Vadzim",
"author_id": 603516,
"author_profile": "https://Stackoverflow.com/users/603516",
"pm_score": 2,
"selected": false,
"text": "byte[] bytes = Resources.toByteArray(classLoader.getResource(path));\n String text = Resources.toString(classLoader.getResource(path), StandardCharsets.UTF_8);\n String content = Files.asCharSource(new File(\"robots.txt\"), StandardCharsets.UTF_8).read();\nbyte[] data = Files.asByteSource(new File(\"favicon.ico\")).read();\n String content = Files.toString(new File(\"robots.txt\"), StandardCharsets.UTF_8);\nbyte[] data = Files.toByteArray(new File(\"favicon.ico\"));\n"
},
{
"answer_id": 32351730,
"author": "Christian Rädel",
"author_id": 1684528,
"author_profile": "https://Stackoverflow.com/users/1684528",
"pm_score": 3,
"selected": false,
"text": "InputStream public static String toString(InputStream inputStream) {\n BufferedReader reader = new BufferedReader(\n new InputStreamReader(inputStream));\n return reader.lines().collect(Collectors.joining(\n System.getProperty(\"line.separator\")));\n}\n"
},
{
"answer_id": 32352386,
"author": "Tagir Valeev",
"author_id": 4856258,
"author_profile": "https://Stackoverflow.com/users/4856258",
"pm_score": 7,
"selected": false,
"text": "public static String toString(InputStream input) throws IOException {\n return new String(input.readAllBytes(), StandardCharsets.UTF_8);\n}\n readAllBytes"
},
{
"answer_id": 33748600,
"author": "hyper-neutrino",
"author_id": 8200485,
"author_profile": "https://Stackoverflow.com/users/8200485",
"pm_score": -1,
"selected": false,
"text": "StackOverflowError public String read (InputStream is) {\n byte next = is.read();\n return next == -1 ? \"\" : next + read(is); // Recursive part: reads next byte recursively\n}\n"
},
{
"answer_id": 34451847,
"author": "Steve Chambers",
"author_id": 1063716,
"author_profile": "https://Stackoverflow.com/users/1063716",
"pm_score": 3,
"selected": false,
"text": " String theString;\n try {\n theString = IOUtils.toString(inputStream, encoding);\n } finally {\n IOUtils.closeQuietly(inputStream);\n }\n"
},
{
"answer_id": 34926427,
"author": "libnull-dev",
"author_id": 4515400,
"author_profile": "https://Stackoverflow.com/users/4515400",
"pm_score": 3,
"selected": false,
"text": "reduce concat String fromFile = new BufferedReader(new \nInputStreamReader(inputStream)).lines().reduce(String::concat).get();\n"
},
{
"answer_id": 35066091,
"author": "jmehrens",
"author_id": 2428802,
"author_profile": "https://Stackoverflow.com/users/2428802",
"pm_score": 5,
"selected": false,
"text": "public static String gobble(InputStream in, String charsetName) throws IOException {\n ByteArrayOutputStream bos = new ByteArrayOutputStream();\n in.transferTo(bos);\n return bos.toString(charsetName);\n}\n"
},
{
"answer_id": 35446009,
"author": "Slava Vedenin",
"author_id": 4318868,
"author_profile": "https://Stackoverflow.com/users/4318868",
"pm_score": 12,
"selected": false,
"text": "IOUtils.toString String result = IOUtils.toString(inputStream, StandardCharsets.UTF_8);\n CharStreams String result = CharStreams.toString(new InputStreamReader(\n inputStream, Charsets.UTF_8));\n Scanner Scanner s = new Scanner(inputStream).useDelimiter(\"\\\\A\");\n String result = s.hasNext() ? s.next() : \"\";\n \\r\\n \\n String result = new BufferedReader(new InputStreamReader(inputStream))\n .lines().collect(Collectors.joining(\"\\n\"));\n \\r\\n \\n String result = new BufferedReader(new InputStreamReader(inputStream))\n .lines().parallel().collect(Collectors.joining(\"\\n\"));\n InputStreamReader StringBuilder int bufferSize = 1024;\n char[] buffer = new char[bufferSize];\n StringBuilder out = new StringBuilder();\n Reader in = new InputStreamReader(stream, StandardCharsets.UTF_8);\n for (int numRead; (numRead = in.read(buffer, 0, buffer.length)) > 0; ) {\n out.append(buffer, 0, numRead);\n }\n return out.toString();\n StringWriter IOUtils.copy StringWriter writer = new StringWriter();\n IOUtils.copy(inputStream, writer, \"UTF-8\");\n return writer.toString();\n ByteArrayOutputStream inputStream.read ByteArrayOutputStream result = new ByteArrayOutputStream();\n byte[] buffer = new byte[1024];\n for (int length; (length = inputStream.read(buffer)) != -1; ) {\n result.write(buffer, 0, length);\n }\n // StandardCharsets.UTF_8.name() > JDK 7\n return result.toString(\"UTF-8\");\n BufferedReader \\n\\r line.separator String newLine = System.getProperty(\"line.separator\");\n BufferedReader reader = new BufferedReader(\n new InputStreamReader(inputStream));\n StringBuilder result = new StringBuilder();\n for (String line; (line = reader.readLine()) != null; ) {\n if (result.length() > 0) {\n result.append(newLine);\n }\n result.append(line);\n }\n return result.toString();\n BufferedInputStream ByteArrayOutputStream BufferedInputStream bis = new BufferedInputStream(inputStream);\nByteArrayOutputStream buf = new ByteArrayOutputStream();\nfor (int result = bis.read(); result != -1; result = bis.read()) {\n buf.write((byte) result);\n}\n// StandardCharsets.UTF_8.name() > JDK 7\nreturn buf.toString(\"UTF-8\");\n inputStream.read() StringBuilder StringBuilder sb = new StringBuilder();\nfor (int ch; (ch = inputStream.read()) != -1; ) {\n sb.append((char) ch);\n}\nreturn sb.toString();\n String Benchmark Mode Cnt Score Error Units\n 8. ByteArrayOutputStream and read (JDK) avgt 10 1,343 ± 0,028 us/op\n 6. InputStreamReader and StringBuilder (JDK) avgt 10 6,980 ± 0,404 us/op\n10. BufferedInputStream, ByteArrayOutputStream avgt 10 7,437 ± 0,735 us/op\n11. InputStream.read() and StringBuilder (JDK) avgt 10 8,977 ± 0,328 us/op\n 7. StringWriter and IOUtils.copy (Apache) avgt 10 10,613 ± 0,599 us/op\n 1. IOUtils.toString (Apache Utils) avgt 10 10,605 ± 0,527 us/op\n 3. Scanner (JDK) avgt 10 12,083 ± 0,293 us/op\n 2. CharStreams (guava) avgt 10 12,999 ± 0,514 us/op\n 4. Stream Api (Java 8) avgt 10 15,811 ± 0,605 us/op\n 9. BufferedReader (JDK) avgt 10 16,038 ± 0,711 us/op\n 5. parallel Stream Api (Java 8) avgt 10 21,544 ± 0,583 us/op\n String Benchmark Mode Cnt Score Error Units\n 8. ByteArrayOutputStream and read (JDK) avgt 10 200,715 ± 18,103 us/op\n 1. IOUtils.toString (Apache Utils) avgt 10 300,019 ± 8,751 us/op\n 6. InputStreamReader and StringBuilder (JDK) avgt 10 347,616 ± 130,348 us/op\n 7. StringWriter and IOUtils.copy (Apache) avgt 10 352,791 ± 105,337 us/op\n 2. CharStreams (guava) avgt 10 420,137 ± 59,877 us/op\n 9. BufferedReader (JDK) avgt 10 632,028 ± 17,002 us/op\n 5. parallel Stream Api (Java 8) avgt 10 662,999 ± 46,199 us/op\n 4. Stream Api (Java 8) avgt 10 701,269 ± 82,296 us/op\n10. BufferedInputStream, ByteArrayOutputStream avgt 10 740,837 ± 5,613 us/op\n 3. Scanner (JDK) avgt 10 751,417 ± 62,026 us/op\n11. InputStream.read() and StringBuilder (JDK) avgt 10 2919,350 ± 1101,942 us/op\n length 182 546 1092 3276 9828 29484 58968\n\n test8 0.38 0.938 1.868 4.448 13.412 36.459 72.708\n test4 2.362 3.609 5.573 12.769 40.74 81.415 159.864\n test5 3.881 5.075 6.904 14.123 50.258 129.937 166.162\n test9 2.237 3.493 5.422 11.977 45.98 89.336 177.39\n test6 1.261 2.12 4.38 10.698 31.821 86.106 186.636\n test7 1.601 2.391 3.646 8.367 38.196 110.221 211.016\n test1 1.529 2.381 3.527 8.411 40.551 105.16 212.573\n test3 3.035 3.934 8.606 20.858 61.571 118.744 235.428\n test2 3.136 6.238 10.508 33.48 43.532 118.044 239.481\n test10 1.593 4.736 7.527 20.557 59.856 162.907 323.147\n test11 3.913 11.506 23.26 68.644 207.591 600.444 1211.545\n"
},
{
"answer_id": 35705517,
"author": "Jitender Chahar",
"author_id": 5735806,
"author_profile": "https://Stackoverflow.com/users/5735806",
"pm_score": 0,
"selected": false,
"text": "public static String getStringFromInputStream(InputStream inputStream) {\n\n BufferedReader bufferedReader = null;\n StringBuilder stringBuilder = new StringBuilder();\n String line;\n\n try {\n bufferedReader = new BufferedReader(new InputStreamReader(\n inputStream));\n while ((line = bufferedReader.readLine()) != null) {\n stringBuilder.append(line);\n }\n } catch (IOException e) {\n logger.error(e.getMessage());\n } finally {\n if (bufferedReader != null) {\n try {\n bufferedReader.close();\n } catch (IOException e) {\n logger.error(e.getMessage());\n }\n }\n }\n return stringBuilder.toString();\n}\n"
},
{
"answer_id": 35908771,
"author": "Harsh",
"author_id": 1586864,
"author_profile": "https://Stackoverflow.com/users/1586864",
"pm_score": 0,
"selected": false,
"text": "InputStream inputStream = null;\nBufferedReader bufferedReader = null;\ntry {\n BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));\n String stringBuilder = new StringBuilder();\n String content;\n while((content = bufferedReader.readLine()) != null){\n stringBuilder.append(content);\n }\n System.out.println(\"content of file::\" + stringBuilder.toString());\n}\ncatch (IOException e) {\n e.printStackTrace();\n }finally{ \n if(bufferedReader != null){\n try{\n bufferedReader.close();\n }catch(IoException ex){\n ex.printStackTrace();\n }\n"
},
{
"answer_id": 37452030,
"author": "Ravi",
"author_id": 625114,
"author_profile": "https://Stackoverflow.com/users/625114",
"pm_score": 0,
"selected": false,
"text": "public static InputStream getResourceAsStream(String path)\n{\n InputStream myiInputStream = ClassName.class.getResourceAsStream(path);\n if (null == myiInputStream)\n {\n mylogger.info(\"Can't find path = \", path);\n }\n\n return myiInputStream;\n}\n public static URL getResource(String path)\n{\n URL myURL = ClassName.class.getResource(path);\n if (null == myURL)\n {\n mylogger.info(\"Can't find resource path = \", path);\n }\n return myURL;\n}\n"
},
{
"answer_id": 38667387,
"author": "James",
"author_id": 285288,
"author_profile": "https://Stackoverflow.com/users/285288",
"pm_score": 4,
"selected": false,
"text": "import java.nio.charset.StandardCharsets;\nimport org.springframework.util.FileCopyUtils;\n\npublic String convertStreamToString(InputStream is) throws IOException { \n return new String(FileCopyUtils.copyToByteArray(is), StandardCharsets.UTF_8);\n}\n org.springframework.util.StreamUtils FileCopyUtils"
},
{
"answer_id": 38859690,
"author": "Raghu K Nair",
"author_id": 2194364,
"author_profile": "https://Stackoverflow.com/users/2194364",
"pm_score": 3,
"selected": false,
"text": "String convertToString(InputStream in){\n String resource = new Scanner(in).useDelimiter(\"\\\\Z\").next();\n return resource;\n}\n"
},
{
"answer_id": 41541671,
"author": "Hao Zheng",
"author_id": 550742,
"author_profile": "https://Stackoverflow.com/users/550742",
"pm_score": 2,
"selected": false,
"text": "public String read(InputStream in) throws IOException {\n try (BufferedReader buffer = new BufferedReader(new InputStreamReader(in))) {\n return buffer.lines().collect(Collectors.joining(\"\\n\"));\n }\n}\n"
},
{
"answer_id": 41881604,
"author": "Snekse",
"author_id": 378151,
"author_profile": "https://Stackoverflow.com/users/378151",
"pm_score": 2,
"selected": false,
"text": "inputStream.getText()\n"
},
{
"answer_id": 43891396,
"author": "Halfacht",
"author_id": 6926281,
"author_profile": "https://Stackoverflow.com/users/6926281",
"pm_score": 2,
"selected": false,
"text": "String convertToString(InputStream in){\n Scanner scanner = new Scanner(in)\n scanner.useDelimiter(\"\\\\A\");\n\n boolean hasInput = scanner.hasNext();\n if (hasInput) {\n return scanner.next();\n } else {\n return null;\n }\n\n}\n"
},
{
"answer_id": 45535091,
"author": "yegor256",
"author_id": 187141,
"author_profile": "https://Stackoverflow.com/users/187141",
"pm_score": 2,
"selected": false,
"text": "String text = new TextOf(inputStream).asString();\n String text = new TextOf(inputStream, \"UTF-16\").asString();\n"
},
{
"answer_id": 46861979,
"author": "gil.fernandes",
"author_id": 2735286,
"author_profile": "https://Stackoverflow.com/users/2735286",
"pm_score": 1,
"selected": false,
"text": "public static String streamToStringChannel(InputStream in, String encoding, int bufSize) throws IOException {\n ReadableByteChannel channel = Channels.newChannel(in);\n ByteBuffer byteBuffer = ByteBuffer.allocate(bufSize);\n ByteArrayOutputStream bout = new ByteArrayOutputStream();\n WritableByteChannel outChannel = Channels.newChannel(bout);\n while (channel.read(byteBuffer) > 0 || byteBuffer.position() > 0) {\n byteBuffer.flip(); //make buffer ready for write\n outChannel.write(byteBuffer);\n byteBuffer.compact(); //make buffer ready for reading\n }\n channel.close();\n outChannel.close();\n return bout.toString(encoding);\n}\n try (InputStream in = new FileInputStream(\"/tmp/large_file.xml\")) {\n String x = streamToStringChannel(in, \"UTF-8\", 1);\n System.out.println(x);\n}\n"
},
{
"answer_id": 48775964,
"author": "Ilya Gazman",
"author_id": 1129332,
"author_profile": "https://Stackoverflow.com/users/1129332",
"pm_score": 6,
"selected": false,
"text": "ByteArrayOutputStream public String inputStreamToString(InputStream inputStream) throws IOException {\n try(ByteArrayOutputStream result = new ByteArrayOutputStream()) {\n byte[] buffer = new byte[1024];\n int length;\n while ((length = inputStream.read(buffer)) != -1) {\n result.write(buffer, 0, length);\n }\n\n return result.toString(UTF_8);\n }\n}\n import com.google.common.io.CharStreams;\nimport org.apache.commons.io.IOUtils;\n\nimport java.io.*;\nimport java.nio.ByteBuffer;\nimport java.nio.channels.Channels;\nimport java.nio.channels.ReadableByteChannel;\nimport java.nio.channels.WritableByteChannel;\nimport java.util.Arrays;\nimport java.util.List;\nimport java.util.Random;\nimport java.util.stream.Collectors;\n\n/**\n * Created by Ilya Gazman on 2/13/18.\n */\npublic class InputStreamToString {\n\n\n private static final String UTF_8 = \"UTF-8\";\n\n public static void main(String... args) {\n log(\"App started\");\n byte[] bytes = new byte[1024 * 1024];\n new Random().nextBytes(bytes);\n log(\"Stream is ready\\n\");\n\n try {\n test(bytes);\n } catch (IOException e) {\n e.printStackTrace();\n }\n }\n\n private static void test(byte[] bytes) throws IOException {\n List<Stringify> tests = Arrays.asList(\n new ApacheStringWriter(),\n new ApacheStringWriter2(),\n new NioStream(),\n new ScannerReader(),\n new ScannerReaderNoNextTest(),\n new GuavaCharStreams(),\n new StreamApi(),\n new ParallelStreamApi(),\n new ByteArrayOutputStreamTest(),\n new BufferReaderTest(),\n new BufferedInputStreamVsByteArrayOutputStream(),\n new InputStreamAndStringBuilder(),\n new Java9ISTransferTo(),\n new Java9ISReadAllBytes()\n );\n\n String solution = new String(bytes, \"UTF-8\");\n\n for (Stringify test : tests) {\n try (ByteArrayInputStream inputStream = new ByteArrayInputStream(bytes)) {\n String s = test.inputStreamToString(inputStream);\n if (!s.equals(solution)) {\n log(test.name() + \": Error\");\n continue;\n }\n }\n long startTime = System.currentTimeMillis();\n for (int i = 0; i < 20; i++) {\n try (ByteArrayInputStream inputStream = new ByteArrayInputStream(bytes)) {\n test.inputStreamToString(inputStream);\n }\n }\n log(test.name() + \": \" + (System.currentTimeMillis() - startTime));\n }\n }\n\n private static void log(String message) {\n System.out.println(message);\n }\n\n interface Stringify {\n String inputStreamToString(InputStream inputStream) throws IOException;\n\n default String name() {\n return this.getClass().getSimpleName();\n }\n }\n\n static class ApacheStringWriter implements Stringify {\n\n @Override\n public String inputStreamToString(InputStream inputStream) throws IOException {\n StringWriter writer = new StringWriter();\n IOUtils.copy(inputStream, writer, UTF_8);\n return writer.toString();\n }\n }\n\n static class ApacheStringWriter2 implements Stringify {\n\n @Override\n public String inputStreamToString(InputStream inputStream) throws IOException {\n return IOUtils.toString(inputStream, UTF_8);\n }\n }\n\n static class NioStream implements Stringify {\n\n @Override\n public String inputStreamToString(InputStream in) throws IOException {\n ReadableByteChannel channel = Channels.newChannel(in);\n ByteBuffer byteBuffer = ByteBuffer.allocate(1024 * 16);\n ByteArrayOutputStream bout = new ByteArrayOutputStream();\n WritableByteChannel outChannel = Channels.newChannel(bout);\n while (channel.read(byteBuffer) > 0 || byteBuffer.position() > 0) {\n byteBuffer.flip(); //make buffer ready for write\n outChannel.write(byteBuffer);\n byteBuffer.compact(); //make buffer ready for reading\n }\n channel.close();\n outChannel.close();\n return bout.toString(UTF_8);\n }\n }\n\n static class ScannerReader implements Stringify {\n\n @Override\n public String inputStreamToString(InputStream is) throws IOException {\n java.util.Scanner s = new java.util.Scanner(is).useDelimiter(\"\\\\A\");\n return s.hasNext() ? s.next() : \"\";\n }\n }\n\n static class ScannerReaderNoNextTest implements Stringify {\n\n @Override\n public String inputStreamToString(InputStream is) throws IOException {\n java.util.Scanner s = new java.util.Scanner(is).useDelimiter(\"\\\\A\");\n return s.next();\n }\n }\n\n static class GuavaCharStreams implements Stringify {\n\n @Override\n public String inputStreamToString(InputStream is) throws IOException {\n return CharStreams.toString(new InputStreamReader(\n is, UTF_8));\n }\n }\n\n static class StreamApi implements Stringify {\n\n @Override\n public String inputStreamToString(InputStream inputStream) throws IOException {\n return new BufferedReader(new InputStreamReader(inputStream))\n .lines().collect(Collectors.joining(\"\\n\"));\n }\n }\n\n static class ParallelStreamApi implements Stringify {\n\n @Override\n public String inputStreamToString(InputStream inputStream) throws IOException {\n return new BufferedReader(new InputStreamReader(inputStream)).lines()\n .parallel().collect(Collectors.joining(\"\\n\"));\n }\n }\n\n static class ByteArrayOutputStreamTest implements Stringify {\n\n @Override\n public String inputStreamToString(InputStream inputStream) throws IOException {\n try(ByteArrayOutputStream result = new ByteArrayOutputStream()) {\n byte[] buffer = new byte[1024];\n int length;\n while ((length = inputStream.read(buffer)) != -1) {\n result.write(buffer, 0, length);\n }\n\n return result.toString(UTF_8);\n }\n }\n }\n\n static class BufferReaderTest implements Stringify {\n\n @Override\n public String inputStreamToString(InputStream inputStream) throws IOException {\n String newLine = System.getProperty(\"line.separator\");\n BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));\n StringBuilder result = new StringBuilder(UTF_8);\n String line;\n boolean flag = false;\n while ((line = reader.readLine()) != null) {\n result.append(flag ? newLine : \"\").append(line);\n flag = true;\n }\n return result.toString();\n }\n }\n\n static class BufferedInputStreamVsByteArrayOutputStream implements Stringify {\n\n @Override\n public String inputStreamToString(InputStream inputStream) throws IOException {\n BufferedInputStream bis = new BufferedInputStream(inputStream);\n ByteArrayOutputStream buf = new ByteArrayOutputStream();\n int result = bis.read();\n while (result != -1) {\n buf.write((byte) result);\n result = bis.read();\n }\n\n return buf.toString(UTF_8);\n }\n }\n\n static class InputStreamAndStringBuilder implements Stringify {\n\n @Override\n public String inputStreamToString(InputStream inputStream) throws IOException {\n int ch;\n StringBuilder sb = new StringBuilder(UTF_8);\n while ((ch = inputStream.read()) != -1)\n sb.append((char) ch);\n return sb.toString();\n }\n }\n\n static class Java9ISTransferTo implements Stringify {\n\n @Override\n public String inputStreamToString(InputStream inputStream) throws IOException {\n ByteArrayOutputStream bos = new ByteArrayOutputStream();\n inputStream.transferTo(bos);\n return bos.toString(UTF_8);\n }\n }\n\n static class Java9ISReadAllBytes implements Stringify {\n\n @Override\n public String inputStreamToString(InputStream inputStream) throws IOException {\n return new String(inputStream.readAllBytes(), UTF_8);\n }\n }\n\n}\n"
},
{
"answer_id": 49707572,
"author": "drakeet",
"author_id": 2764007,
"author_profile": "https://Stackoverflow.com/users/2764007",
"pm_score": 2,
"selected": false,
"text": "String result = Okio.buffer(Okio.source(inputStream)).readUtf8();\n"
},
{
"answer_id": 51083322,
"author": "13hola",
"author_id": 8558398,
"author_profile": "https://Stackoverflow.com/users/8558398",
"pm_score": 2,
"selected": false,
"text": "String Stream Stream String import java.io.ByteArrayInputStream;\nimport java.io.InputStream;\n\npublic class STRINGTOSTREAM {\n\n public static void main(String[] args)\n {\n String text = \"Hello Bhola..!\\nMy Name Is Kishan \";\n\n InputStream strm = new ByteArrayInputStream(text.getBytes()); // Convert String to Stream\n\n String data = streamTostring(strm);\n\n System.out.println(data);\n }\n\n static String streamTostring(InputStream stream)\n {\n String data = \"\";\n\n try\n {\n StringBuilder stringbuld = new StringBuilder();\n int i;\n while ((i=stream.read())!=-1)\n {\n stringbuld.append((char)i);\n }\n data = stringbuld.toString();\n }\n catch(Exception e)\n {\n data = \"No data Streamed.\";\n }\n return data;\n }\n"
},
{
"answer_id": 53199396,
"author": "Hans Brende",
"author_id": 2599133,
"author_profile": "https://Stackoverflow.com/users/2599133",
"pm_score": 2,
"selected": false,
"text": "StringWriter StringBuffer InputStreamReader StringBuilder char public static String iso_8859_1(InputStream is) throws IOException {\n StringBuilder chars = new StringBuilder(Math.max(is.available(), 4096));\n byte[] buffer = new byte[4096];\n int n;\n while ((n = is.read(buffer)) != -1) {\n for (int i = 0; i < n; i++) {\n chars.append((char)(buffer[i] & 0xFF));\n }\n }\n return chars.toString();\n}\n public static String utf8(InputStream is) throws IOException {\n StringBuilder chars = new StringBuilder(Math.max(is.available(), 4096));\n byte[] buffer = new byte[4096];\n int n;\n int state = 0;\n while ((n = is.read(buffer)) != -1) {\n for (int i = 0; i < n; i++) {\n if ((state = nextStateUtf8(state, buffer[i])) >= 0) {\n chars.appendCodePoint(state);\n } else if (state == -1) { //error\n state = 0;\n chars.append('\\uFFFD'); //replacement char\n }\n }\n }\n return chars.toString();\n}\n nextStateUtf8() /**\n * Returns the next UTF-8 state given the next byte of input and the current state.\n * If the input byte is the last byte in a valid UTF-8 byte sequence,\n * the returned state will be the corresponding unicode character (in the range of 0 through 0x10FFFF).\n * Otherwise, a negative integer is returned. A state of -1 is returned whenever an\n * invalid UTF-8 byte sequence is detected.\n */\nstatic int nextStateUtf8(int currentState, byte nextByte) {\n switch (currentState & 0xF0000000) {\n case 0:\n if ((nextByte & 0x80) == 0) { //0 trailing bytes (ASCII)\n return nextByte;\n } else if ((nextByte & 0xE0) == 0xC0) { //1 trailing byte\n if (nextByte == (byte) 0xC0 || nextByte == (byte) 0xC1) { //0xCO & 0xC1 are overlong\n return -1;\n } else {\n return nextByte & 0xC000001F;\n }\n } else if ((nextByte & 0xF0) == 0xE0) { //2 trailing bytes\n if (nextByte == (byte) 0xE0) { //possibly overlong\n return nextByte & 0xA000000F;\n } else if (nextByte == (byte) 0xED) { //possibly surrogate\n return nextByte & 0xB000000F;\n } else {\n return nextByte & 0x9000000F;\n }\n } else if ((nextByte & 0xFC) == 0xF0) { //3 trailing bytes\n if (nextByte == (byte) 0xF0) { //possibly overlong\n return nextByte & 0x80000007;\n } else {\n return nextByte & 0xE0000007;\n }\n } else if (nextByte == (byte) 0xF4) { //3 trailing bytes, possibly undefined\n return nextByte & 0xD0000007;\n } else {\n return -1;\n }\n case 0xE0000000: //3rd-to-last continuation byte\n return (nextByte & 0xC0) == 0x80 ? currentState << 6 | nextByte & 0x9000003F : -1;\n case 0x80000000: //3rd-to-last continuation byte, check overlong\n return (nextByte & 0xE0) == 0xA0 || (nextByte & 0xF0) == 0x90 ? currentState << 6 | nextByte & 0x9000003F : -1;\n case 0xD0000000: //3rd-to-last continuation byte, check undefined\n return (nextByte & 0xF0) == 0x80 ? currentState << 6 | nextByte & 0x9000003F : -1;\n case 0x90000000: //2nd-to-last continuation byte\n return (nextByte & 0xC0) == 0x80 ? currentState << 6 | nextByte & 0xC000003F : -1;\n case 0xA0000000: //2nd-to-last continuation byte, check overlong\n return (nextByte & 0xE0) == 0xA0 ? currentState << 6 | nextByte & 0xC000003F : -1;\n case 0xB0000000: //2nd-to-last continuation byte, check surrogate\n return (nextByte & 0xE0) == 0x80 ? currentState << 6 | nextByte & 0xC000003F : -1;\n case 0xC0000000: //last continuation byte\n return (nextByte & 0xC0) == 0x80 ? currentState << 6 | nextByte & 0x3F : -1;\n default:\n return -1;\n }\n}\n public static String autoDetect(InputStream is) throws IOException {\n StringBuilder chars = new StringBuilder(Math.max(is.available(), 4096));\n byte[] buffer = new byte[4096];\n int n;\n int state = 0;\n boolean ascii = true;\n while ((n = is.read(buffer)) != -1) {\n for (int i = 0; i < n; i++) {\n if ((state = nextStateUtf8(state, buffer[i])) > 0x7F)\n ascii = false;\n chars.append((char)(buffer[i] & 0xFF));\n }\n }\n\n if (ascii || state < 0) { //probably not UTF-8\n return chars.toString();\n }\n //probably UTF-8\n int pos = 0;\n char[] charBuf = new char[2];\n for (int i = 0, len = chars.length(); i < len; i++) {\n if ((state = nextStateUtf8(state, (byte)chars.charAt(i))) >= 0) {\n boolean hi = Character.toChars(state, charBuf, 0) == 2;\n chars.setCharAt(pos++, charBuf[0]);\n if (hi) {\n chars.setCharAt(pos++, charBuf[1]);\n }\n }\n }\n return chars.substring(0, pos);\n}\n"
},
{
"answer_id": 55393395,
"author": "Hasee Amarathunga",
"author_id": 7484853,
"author_profile": "https://Stackoverflow.com/users/7484853",
"pm_score": 0,
"selected": false,
"text": "StringWriter wt= new StringWriter();\nIOUtils.copy(inputStream, wt, encoding);\nString st= wt.toString();\n"
},
{
"answer_id": 58954758,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "private String textDataFromFile;\n\npublic String getFromFile(InputStream myInputStream) throws FileNotFoundException, IOException {\n\n BufferedReader bufferReader = new BufferedReader(new InputStreamReader(myInputStream));\n\n StringBuilder stringBuilder = new StringBuilder();\n\n String eachStringLine;\n\n while ((eachStringLine = bufferReader.readLine()) != null) {\n stringBuilder.append(eachStringLine).append(\"\\n\");\n }\n textDataFromFile = stringBuilder.toString();\n\n return textDataFromFile;\n}\n"
},
{
"answer_id": 61036395,
"author": "czerny",
"author_id": 639687,
"author_profile": "https://Stackoverflow.com/users/639687",
"pm_score": 4,
"selected": false,
"text": "String inputStreamToString(InputStream inputStream, Charset charset) throws IOException {\n try (\n final StringWriter writer = new StringWriter();\n final InputStreamReader reader = new InputStreamReader(inputStream, charset)\n ) {\n reader.transferTo(writer);\n return writer.toString();\n }\n}\n"
},
{
"answer_id": 65265664,
"author": "Kaplan",
"author_id": 11199879,
"author_profile": "https://Stackoverflow.com/users/11199879",
"pm_score": 2,
"selected": false,
"text": "public String convertStreamToString(InputStream is) throws IOException {\n try (ByteArrayOutputStream baos = new ByteArrayOutputStream();) {\n is.transferTo(baos);\n return baos.toString(StandardCharsets.UTF_8);\n }\n}\n"
},
{
"answer_id": 69865898,
"author": "somayaj",
"author_id": 17287795,
"author_profile": "https://Stackoverflow.com/users/17287795",
"pm_score": -1,
"selected": false,
"text": " public static void main(String... args) throws IOException {\n System.out.println(new String(Files.readAllBytes(Paths.get(\"csv.txt\"))));\n }\n"
},
{
"answer_id": 72002358,
"author": "hertzsprung",
"author_id": 150884,
"author_profile": "https://Stackoverflow.com/users/150884",
"pm_score": 1,
"selected": false,
"text": "public String convertStreamToString(InputStream is) {\n return IoUtils.toUtf8String(is);\n}\n"
}
] | 2008/11/21 | [
"https://Stackoverflow.com/questions/309424",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16616/"
] |
309,438 | <p>We have a JavaScript construct that will play .wav files within Firefox on Windows and MacOSX, but it does not work for Red Hat Linux. What extension do I need?</p>
| [
{
"answer_id": 309611,
"author": "luiscubal",
"author_id": 32775,
"author_profile": "https://Stackoverflow.com/users/32775",
"pm_score": 2,
"selected": false,
"text": "<audio>"
}
] | 2008/11/21 | [
"https://Stackoverflow.com/questions/309438",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13930/"
] |
309,485 | <p>I recently have been moving a bunch of MP3s from various locations into a repository. I had been constructing the new file names using the ID3 tags (thanks, TagLib-Sharp!), and I noticed that I was getting a <code>System.NotSupportedException</code>: </p>
<blockquote>
<p><em>"The given path's format is not supported."</em></p>
</blockquote>
<p>This was generated by either <code>File.Copy()</code> or <code>Directory.CreateDirectory()</code>.</p>
<p>It didn't take long to realize that my file names needed to be sanitized. So I did the obvious thing:</p>
<pre><code>public static string SanitizePath_(string path, char replaceChar)
{
string dir = Path.GetDirectoryName(path);
foreach (char c in Path.GetInvalidPathChars())
dir = dir.Replace(c, replaceChar);
string name = Path.GetFileName(path);
foreach (char c in Path.GetInvalidFileNameChars())
name = name.Replace(c, replaceChar);
return dir + name;
}
</code></pre>
<p>To my surprise, I continued to get exceptions. It turned out that ':' is not in the set of <code>Path.GetInvalidPathChars()</code>, because it is valid in a path root. I suppose that makes sense - but this has to be a pretty common problem. Does anyone have some short code that sanitizes a path? The most thorough I've come up with this, but it feels like it is probably overkill.</p>
<pre><code> // replaces invalid characters with replaceChar
public static string SanitizePath(string path, char replaceChar)
{
// construct a list of characters that can't show up in filenames.
// need to do this because ":" is not in InvalidPathChars
if (_BadChars == null)
{
_BadChars = new List<char>(Path.GetInvalidFileNameChars());
_BadChars.AddRange(Path.GetInvalidPathChars());
_BadChars = Utility.GetUnique<char>(_BadChars);
}
// remove root
string root = Path.GetPathRoot(path);
path = path.Remove(0, root.Length);
// split on the directory separator character. Need to do this
// because the separator is not valid in a filename.
List<string> parts = new List<string>(path.Split(new char[]{Path.DirectorySeparatorChar}));
// check each part to make sure it is valid.
for (int i = 0; i < parts.Count; i++)
{
string part = parts[i];
foreach (char c in _BadChars)
{
part = part.Replace(c, replaceChar);
}
parts[i] = part;
}
return root + Utility.Join(parts, Path.DirectorySeparatorChar.ToString());
}
</code></pre>
<p>Any improvements to make this function faster and less baroque would be much appreciated.</p>
| [
{
"answer_id": 310797,
"author": "Dour High Arch",
"author_id": 22437,
"author_profile": "https://Stackoverflow.com/users/22437",
"pm_score": 2,
"selected": false,
"text": "Path.GetDirectoryName public static string SanitizePath(string path, char replaceChar)\n{\n int filenamePos = path.LastIndexOf(Path.DirectorySeparatorChar) + 1;\n var sb = new System.Text.StringBuilder();\n sb.Append(path.Substring(0, filenamePos));\n for (int i = filenamePos; i < path.Length; i++)\n {\n char filenameChar = path[i];\n foreach (char c in Path.GetInvalidFileNameChars())\n if (filenameChar.Equals(c))\n {\n filenameChar = replaceChar;\n break;\n }\n\n sb.Append(filenameChar);\n }\n\n return sb.ToString();\n}"
},
{
"answer_id": 847251,
"author": "Andre",
"author_id": 104672,
"author_profile": "https://Stackoverflow.com/users/104672",
"pm_score": 8,
"selected": false,
"text": "private static string MakeValidFileName( string name )\n{\n string invalidChars = System.Text.RegularExpressions.Regex.Escape( new string( System.IO.Path.GetInvalidFileNameChars() ) );\n string invalidRegStr = string.Format( @\"([{0}]*\\.+$)|([{0}]+)\", invalidChars );\n\n return System.Text.RegularExpressions.Regex.Replace( name, invalidRegStr, \"_\" );\n}\n"
},
{
"answer_id": 8825072,
"author": "Ralf",
"author_id": 1143930,
"author_profile": "https://Stackoverflow.com/users/1143930",
"pm_score": -1,
"selected": false,
"text": "using System;\nusing System.IO;\nusing System.Linq;\nusing System.Text;\n\npublic class Program\n{\n public static void Main()\n {\n try\n {\n var badString = \"ABC\\\\DEF/GHI<JKL>MNO:PQR\\\"STU\\tVWX|YZA*BCD?EFG\";\n Console.WriteLine(badString);\n Console.WriteLine(SanitizeFileName(badString, '.'));\n Console.WriteLine(SanitizeFileName(badString));\n }\n catch (Exception ex)\n {\n Console.WriteLine(ex.ToString());\n }\n }\n\n private static string SanitizeFileName(string fileName, char? replacement = null)\n {\n if (fileName == null) { return null; }\n if (fileName.Length == 0) { return \"\"; }\n\n var sb = new StringBuilder();\n var badChars = Path.GetInvalidFileNameChars().ToList();\n\n foreach (var @char in fileName)\n {\n if (badChars.Contains(@char)) \n {\n if (replacement.HasValue)\n {\n sb.Append(replacement.Value);\n }\n continue; \n }\n sb.Append(@char);\n }\n return sb.ToString();\n }\n}\n"
},
{
"answer_id": 10382121,
"author": "Helix 88",
"author_id": 681819,
"author_profile": "https://Stackoverflow.com/users/681819",
"pm_score": 2,
"selected": false,
"text": " public static string returnSafeString(string s)\n {\n foreach (char character in Path.GetInvalidFileNameChars())\n {\n s = s.Replace(character.ToString(),string.Empty);\n }\n\n foreach (char character in Path.GetInvalidPathChars())\n {\n s = s.Replace(character.ToString(), string.Empty);\n }\n\n return (s);\n }\n"
},
{
"answer_id": 12924582,
"author": "fiat",
"author_id": 1141876,
"author_profile": "https://Stackoverflow.com/users/1141876",
"pm_score": 7,
"selected": false,
"text": "/// <summary>\n/// Strip illegal chars and reserved words from a candidate filename (should not include the directory path)\n/// </summary>\n/// <remarks>\n/// http://stackoverflow.com/questions/309485/c-sharp-sanitize-file-name\n/// </remarks>\npublic static string CoerceValidFileName(string filename)\n{\n var invalidChars = Regex.Escape(new string(Path.GetInvalidFileNameChars()));\n var invalidReStr = string.Format(@\"[{0}]+\", invalidChars);\n\n var reservedWords = new []\n {\n \"CON\", \"PRN\", \"AUX\", \"CLOCK$\", \"NUL\", \"COM0\", \"COM1\", \"COM2\", \"COM3\", \"COM4\",\n \"COM5\", \"COM6\", \"COM7\", \"COM8\", \"COM9\", \"LPT0\", \"LPT1\", \"LPT2\", \"LPT3\", \"LPT4\",\n \"LPT5\", \"LPT6\", \"LPT7\", \"LPT8\", \"LPT9\"\n };\n\n var sanitisedNamePart = Regex.Replace(filename, invalidReStr, \"_\");\n foreach (var reservedWord in reservedWords)\n {\n var reservedWordPattern = string.Format(\"^{0}\\\\.\", reservedWord);\n sanitisedNamePart = Regex.Replace(sanitisedNamePart, reservedWordPattern, \"_reservedWord_.\", RegexOptions.IgnoreCase);\n }\n\n return sanitisedNamePart;\n}\n [Test]\npublic void CoerceValidFileName_SimpleValid()\n{\n var filename = @\"thisIsValid.txt\";\n var result = PathHelper.CoerceValidFileName(filename);\n Assert.AreEqual(filename, result);\n}\n\n[Test]\npublic void CoerceValidFileName_SimpleInvalid()\n{\n var filename = @\"thisIsNotValid\\3\\\\_3.txt\";\n var result = PathHelper.CoerceValidFileName(filename);\n Assert.AreEqual(\"thisIsNotValid_3__3.txt\", result);\n}\n\n[Test]\npublic void CoerceValidFileName_InvalidExtension()\n{\n var filename = @\"thisIsNotValid.t\\xt\";\n var result = PathHelper.CoerceValidFileName(filename);\n Assert.AreEqual(\"thisIsNotValid.t_xt\", result);\n}\n\n[Test]\npublic void CoerceValidFileName_KeywordInvalid()\n{\n var filename = \"aUx.txt\";\n var result = PathHelper.CoerceValidFileName(filename);\n Assert.AreEqual(\"_reservedWord_.txt\", result);\n}\n\n[Test]\npublic void CoerceValidFileName_KeywordValid()\n{\n var filename = \"auxillary.txt\";\n var result = PathHelper.CoerceValidFileName(filename);\n Assert.AreEqual(\"auxillary.txt\", result);\n}\n"
},
{
"answer_id": 13617375,
"author": "DenNukem",
"author_id": 118878,
"author_profile": "https://Stackoverflow.com/users/118878",
"pm_score": 7,
"selected": false,
"text": "var invalids = System.IO.Path.GetInvalidFileNameChars();\nvar newName = String.Join(\"_\", origFileName.Split(invalids, StringSplitOptions.RemoveEmptyEntries) ).TrimEnd('.');\n"
},
{
"answer_id": 16188376,
"author": "data",
"author_id": 221042,
"author_profile": "https://Stackoverflow.com/users/221042",
"pm_score": 5,
"selected": false,
"text": "string clean = String.Concat(dirty.Split(Path.GetInvalidFileNameChars()));\n"
},
{
"answer_id": 17928649,
"author": "André Leal",
"author_id": 2087196,
"author_profile": "https://Stackoverflow.com/users/2087196",
"pm_score": 3,
"selected": false,
"text": "System.IO.Path.GetInvalidFileNameChars() foreach( char invalidchar in System.IO.Path.GetInvalidFileNameChars())\n{\n filename = filename.Replace(invalidchar, '_');\n}\n"
},
{
"answer_id": 23750635,
"author": "Valamas",
"author_id": 511438,
"author_profile": "https://Stackoverflow.com/users/511438",
"pm_score": 3,
"selected": false,
"text": "private static Dictionary<string, string> EncodeMapping()\n{\n //-- Following characters are invalid for windows file and folder names.\n //-- \\/:*?\"<>|\n Dictionary<string, string> dic = new Dictionary<string, string>();\n dic.Add(@\"\\\", \"Ì\"); // U+OOCC\n dic.Add(\"/\", \"Í\"); // U+OOCD\n dic.Add(\":\", \"¦\"); // U+00A6\n dic.Add(\"*\", \"¤\"); // U+00A4\n dic.Add(\"?\", \"¿\"); // U+00BF\n dic.Add(@\"\"\"\", \"ˮ\"); // U+02EE\n dic.Add(\"<\", \"«\"); // U+00AB\n dic.Add(\">\", \"»\"); // U+00BB\n dic.Add(\"|\", \"│\"); // U+2502\n return dic;\n}\n\npublic static string Escape(string name)\n{\n foreach (KeyValuePair<string, string> replace in EncodeMapping())\n {\n name = name.Replace(replace.Key, replace.Value);\n }\n\n //-- handle dot at the end\n if (name.EndsWith(\".\")) name = name.CropRight(1) + \"°\";\n\n return name;\n}\n\npublic static string UnEscape(string name)\n{\n foreach (KeyValuePair<string, string> replace in EncodeMapping())\n {\n name = name.Replace(replace.Value, replace.Key);\n }\n\n //-- handle dot at the end\n if (name.EndsWith(\"°\")) name = name.CropRight(1) + \".\";\n\n return name;\n}\n %windir%\\system32\\charmap.exe"
},
{
"answer_id": 30383134,
"author": "Bryan Legend",
"author_id": 52771,
"author_profile": "https://Stackoverflow.com/users/52771",
"pm_score": 1,
"selected": false,
"text": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\nusing System.Threading.Tasks;\n\nnamespace LT\n{\n public static class Utility\n {\n static string invalidRegStr;\n\n public static string MakeValidFileName(this string name)\n {\n if (invalidRegStr == null)\n {\n var invalidChars = System.Text.RegularExpressions.Regex.Escape(new string(System.IO.Path.GetInvalidFileNameChars()));\n invalidRegStr = string.Format(@\"([{0}]*\\.+$)|([{0}]+)\", invalidChars);\n }\n\n return System.Text.RegularExpressions.Regex.Replace(name, invalidRegStr, \"_\");\n }\n }\n}\n"
},
{
"answer_id": 53375368,
"author": "kappadoky",
"author_id": 4310710,
"author_profile": "https://Stackoverflow.com/users/4310710",
"pm_score": 3,
"selected": false,
"text": "var invalids = Path.GetInvalidFileNameChars();\nfilename = invalids.Aggregate(filename, (current, c) => current.Replace(c, '_'));\n"
},
{
"answer_id": 65776798,
"author": "greg-e",
"author_id": 2591667,
"author_profile": "https://Stackoverflow.com/users/2591667",
"pm_score": -1,
"selected": false,
"text": "public static class StringPathExtensions\n{\n private static Regex _invalidPathPartsRegex;\n \n static StringPathExtensions()\n {\n var invalidReg = System.Text.RegularExpressions.Regex.Escape(new string(Path.GetInvalidFileNameChars()));\n _invalidPathPartsRegex = new Regex($\"(?<reserved>^(CON|PRN|AUX|CLOCK\\\\$|NUL|COM0|COM1|COM2|COM3|COM4|COM5|COM6|COM7|COM8|COM9|LPT0|LPT1|LPT2|LPT3|LPT4|LPT5|LPT6|LPT7|LPT8|LPT9))|(?<invalid>[{invalidReg}:]+|\\\\.$)\", RegexOptions.Compiled);\n }\n\n public static string SanitizeFileName(this string path)\n {\n return _invalidPathPartsRegex.Replace(path, m =>\n {\n if (!string.IsNullOrWhiteSpace(m.Groups[\"reserved\"].Value))\n return string.Concat(\"_\", m.Groups[\"reserved\"].Value);\n return \"_\";\n });\n }\n}\n"
}
] | 2008/11/21 | [
"https://Stackoverflow.com/questions/309485",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2683/"
] |
309,491 | <p>I'm using the following code to try to read the results of a <code>df</code> command in Linux using <code>popen</code>.</p>
<pre><code>#include <iostream> // file and std I/O functions
int main(int argc, char** argv) {
FILE* fp;
char * buffer;
long bufSize;
size_t ret_code;
fp = popen("df", "r");
if(fp == NULL) { // head off errors reading the results
std::cerr << "Could not execute command: df" << std::endl;
exit(1);
}
// get the size of the results
fseek(fp, 0, SEEK_END);
bufSize = ftell(fp);
rewind(fp);
// allocate the memory to contain the results
buffer = (char*)malloc( sizeof(char) * bufSize );
if(buffer == NULL) {
std::cerr << "Memory error." << std::endl;
exit(2);
}
// read the results into the buffer
ret_code = fread(buffer, 1, sizeof(buffer), fp);
if(ret_code != bufSize) {
std::cerr << "Error reading output." << std::endl;
exit(3);
}
// print the results
std::cout << buffer << std::endl;
// clean up
pclose(fp);
free(buffer);
return (EXIT_SUCCESS);
}
</code></pre>
<p>This code is giving me a "Memory error" with an exit status of '2', so I can see <em>where</em> it's failing, I just don't understand <em>why</em>.</p>
<p>I put this together from example code that I found on <a href="http://ubuntuforums.org/showthread.php?t=285287" rel="nofollow noreferrer">Ubuntu Forums</a> and <a href="http://en.cppreference.com/w/cpp/io/c/fread" rel="nofollow noreferrer">C++ Reference</a>, so I'm not married to it. If anyone can suggest a better way to read the results of a system() call, I'm open to new ideas.</p>
<p><strong>EDIT to the original:</strong> Okay, <code>bufSize</code> is coming up negative, and now I understand why. You can't randomly access a pipe, as I naively tried to do.</p>
<p>I can't be the first person to try to do this. Can someone give (or point me to) an example of how to read the results of a system() call into a variable in C++?</p>
| [
{
"answer_id": 309505,
"author": "flolo",
"author_id": 36472,
"author_profile": "https://Stackoverflow.com/users/36472",
"pm_score": 0,
"selected": false,
"text": "ftell ftell"
},
{
"answer_id": 309523,
"author": "CesarB",
"author_id": 28258,
"author_profile": "https://Stackoverflow.com/users/28258",
"pm_score": 4,
"selected": true,
"text": "std::malloc() std::ftell() std::ftell() df statvfs()"
},
{
"answer_id": 309597,
"author": "zaratustra",
"author_id": 39702,
"author_profile": "https://Stackoverflow.com/users/39702",
"pm_score": 0,
"selected": false,
"text": "// your file opening code\n\nwhile (!feof(fp))\n{\nchar c = getc(fp);\nstd::cout << c;\n}\n"
},
{
"answer_id": 309867,
"author": "Josh Kelley",
"author_id": 25507,
"author_profile": "https://Stackoverflow.com/users/25507",
"pm_score": 2,
"selected": false,
"text": "system() system(3) pipe() fork() exec() read() close() popen() fread() fgets() fgetc() popen() std::istream stdio_filebuf"
},
{
"answer_id": 309919,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "char buffer[1024];\nchar * line = NULL;\nwhile ((line = fgets(buffer, sizeof buffer, fp)) != NULL) {\n // parse one line of df's output here.\n}\n"
},
{
"answer_id": 313249,
"author": "Bill the Lizard",
"author_id": 1288,
"author_profile": "https://Stackoverflow.com/users/1288",
"pm_score": 2,
"selected": false,
"text": "#include <iostream> // cout\n#include <sstream> // ostringstream\n\nint main(int argc, char** argv) {\n FILE* stream = popen( \"df\", \"r\" );\n std::ostringstream output;\n\n while( !feof( stream ) && !ferror( stream ))\n {\n char buf[128];\n int bytesRead = fread( buf, 1, 128, stream );\n output.write( buf, bytesRead );\n }\n std::string result = output.str();\n std::cout << \"<RESULT>\" << std::endl << result << \"</RESULT>\" << std::endl;\n return (0);\n}\n"
},
{
"answer_id": 313382,
"author": "Charlie Martin",
"author_id": 35092,
"author_profile": "https://Stackoverflow.com/users/35092",
"pm_score": 3,
"selected": false,
"text": "FILE * #include <stdio.h>\nchar bfr[BUFSIZ] ;\nFILE * fp;\n// ...\nif((fp=popen(\"/bin/df\", \"r\")) ==NULL) {\n // error processing and return\n}\n// ...\nwhile(fgets(bfr,BUFSIZ,fp) != NULL){\n // process a line\n}\n #include <cstdio>\n#include <iostream>\n#include <string>\n\nFILE * fp ;\n\nif((fp= popen(\"/bin/df\",\"r\")) == NULL) {\n // error processing and exit\n}\n\nifstream ins(fileno(fp)); // ifstream ctor using a file descriptor\n\nstring s;\nwhile (! ins.eof()){\n getline(ins,s);\n // do something\n}\n FILE * FILE *"
}
] | 2008/11/21 | [
"https://Stackoverflow.com/questions/309491",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1288/"
] |
309,494 | <p>I'm trying to make a program in Visual C# that has my one created class, and at application launch it creates an array of my class object, and this array of my object can be used all over the program. So any function, or a control's event can access the array of objects and their member variables.
I created my class as "public" but for some reason i get these errors upon build:
"The name 'MyArrayObjectNameHere' does not exist in the current context"
When I try to access the objects member variables inside a load file dialog event in which I am trying to load data from a file into the member variables of the object array.</p>
<p>Is there a certain place the object array needs to be declared and constructed so it exists in every context? If so, can you tell me where this is?</p>
<p>I currently declare it in the main function before form1 is run.</p>
<p>My class definition looks like this in its own .cs file and the programs namespace:</p>
<pre><code>public class MyClass
{
public int MyInt1;
public int MyInt2;
}
</code></pre>
<p>I declare the array of objects like this inside the main function before the form load:</p>
<pre><code>MyClass[] MyArrayObject;
MyArrayObject = new MyClass[50];
for (int i = 0; i < 50; i++)
{
MyArrayObject[i] = new MyClass();
}
</code></pre>
<p>Thanks in advance for any help.</p>
| [
{
"answer_id": 309519,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "public static class MyClassManager\n{\n private MyClass[] _myclasses;\n public MyClass[] MyClassArray\n {\n get\n {\n if(_myclasses == null)\n {\n _myClasses = new MyClass[50];\n for(int i = 0; i < 50;i++)\n _myClasses[i] = new MyClass();\n }\n return _myclasses;\n\n }\n }\n}\n"
},
{
"answer_id": 309521,
"author": "Rob Walker",
"author_id": 3631,
"author_profile": "https://Stackoverflow.com/users/3631",
"pm_score": 0,
"selected": false,
"text": "class A\n{\n public static B[] MyArray;\n};\n"
}
] | 2008/11/21 | [
"https://Stackoverflow.com/questions/309494",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/117494/"
] |
309,495 | <p>I'm currently using <code>Win32ShellFolderManager2</code> and <code>ShellFolder.getLinkLocation</code> to resolve windows shortcuts in Java. Unfortunately, if the Java program is running as a service under Vista, <code>getLinkLocation</code>, this does not work. Specifically, I get an exception stating "Could not get shell folder ID list".</p>
<p>Searching the web does turn up mentions of this error message, but always in connection with <code>JFileChooser</code>. I'm not using <code>JFileChooser</code>, I just need to resolve a <code>.lnk</code> file to its destination.</p>
<p>Does anyone know of a 3rd-party parser for <code>.lnk</code> files written in Java I could use?</p>
<p>I've since found unofficial documentation for the .lnk format <a href="http://mediasrv.ns.ac.yu/extra/fileformat/windows/lnk/shortcut.pdf" rel="noreferrer">here</a>, but I'd rather not have to do the work if anyone has done it before, since the format is rather scary.</p>
| [
{
"answer_id": 352738,
"author": "Sam Brightman",
"author_id": 2492,
"author_profile": "https://Stackoverflow.com/users/2492",
"pm_score": 2,
"selected": false,
"text": "& 0xff byte int bytes2short import java.io.ByteArrayOutputStream;\nimport java.io.File;\nimport java.io.FileInputStream;\nimport java.text.DecimalFormat;\nimport java.text.NumberFormat;\n\npublic class LnkParser {\n\n public LnkParser(File f) throws Exception {\n parse(f);\n }\n\n private boolean is_dir;\n\n public boolean isDirectory() {\n return is_dir;\n }\n\n private String real_file;\n\n public String getRealFilename() {\n return real_file;\n }\n\n private void parse(File f) throws Exception {\n // read the entire file into a byte buffer\n FileInputStream fin = new FileInputStream(f);\n ByteArrayOutputStream bout = new ByteArrayOutputStream();\n byte[] buff = new byte[256];\n while (true) {\n int n = fin.read(buff);\n if (n == -1) {\n break;\n }\n bout.write(buff, 0, n);\n }\n fin.close();\n byte[] link = bout.toByteArray();\n\n // get the flags byte\n byte flags = link[0x14];\n\n // get the file attributes byte\n final int file_atts_offset = 0x18;\n byte file_atts = link[file_atts_offset];\n byte is_dir_mask = (byte) 0x10;\n if ((file_atts & is_dir_mask) > 0) {\n is_dir = true;\n } else {\n is_dir = false;\n }\n\n // if the shell settings are present, skip them\n final int shell_offset = 0x4c;\n final byte has_shell_mask = (byte) 0x01;\n int shell_len = 0;\n if ((flags & has_shell_mask) > 0) {\n // the plus 2 accounts for the length marker itself\n shell_len = bytes2short(link, shell_offset) + 2;\n }\n\n // get to the file settings\n int file_start = 0x4c + shell_len;\n\n // get the local volume and local system values\n final int basename_offset_offset = 0x10;\n final int finalname_offset_offset = 0x18;\n int basename_offset = link[file_start + basename_offset_offset]\n + file_start;\n int finalname_offset = link[file_start + finalname_offset_offset]\n + file_start;\n String basename = getNullDelimitedString(link, basename_offset);\n String finalname = getNullDelimitedString(link, finalname_offset);\n real_file = basename + finalname;\n }\n\n private static String getNullDelimitedString(byte[] bytes, int off) {\n int len = 0;\n // count bytes until the null character (0)\n while (true) {\n if (bytes[off + len] == 0) {\n break;\n }\n len++;\n }\n return new String(bytes, off, len);\n }\n\n /*\n * convert two bytes into a short note, this is little endian because it's\n * for an Intel only OS.\n */\n private static int bytes2short(byte[] bytes, int off) {\n return ((bytes[off + 1] & 0xff) << 8) | (bytes[off] & 0xff);\n }\n}\n"
},
{
"answer_id": 672775,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 4,
"selected": false,
"text": "public class LnkParser {\n\npublic LnkParser(File f) throws IOException {\n parse(f);\n}\n\nprivate boolean isDirectory;\nprivate boolean isLocal;\n\npublic boolean isDirectory() {\n return isDirectory;\n}\n\nprivate String real_file;\n\npublic String getRealFilename() {\n return real_file;\n}\n\nprivate void parse(File f) throws IOException {\n // read the entire file into a byte buffer\n FileInputStream fin = new FileInputStream(f);\n ByteArrayOutputStream bout = new ByteArrayOutputStream();\n byte[] buff = new byte[256];\n while (true) {\n int n = fin.read(buff);\n if (n == -1) {\n break;\n }\n bout.write(buff, 0, n);\n }\n fin.close();\n byte[] link = bout.toByteArray();\n\n parseLink(link);\n}\n\nprivate void parseLink(byte[] link) {\n // get the flags byte\n byte flags = link[0x14];\n\n // get the file attributes byte\n final int file_atts_offset = 0x18;\n byte file_atts = link[file_atts_offset];\n byte is_dir_mask = (byte)0x10;\n if ((file_atts & is_dir_mask) > 0) {\n isDirectory = true;\n } else {\n isDirectory = false;\n }\n\n // if the shell settings are present, skip them\n final int shell_offset = 0x4c;\n final byte has_shell_mask = (byte)0x01;\n int shell_len = 0;\n if ((flags & has_shell_mask) > 0) {\n // the plus 2 accounts for the length marker itself\n shell_len = bytes2short(link, shell_offset) + 2;\n }\n\n // get to the file settings\n int file_start = 0x4c + shell_len;\n\n final int file_location_info_flag_offset_offset = 0x08;\n int file_location_info_flag = link[file_start + file_location_info_flag_offset_offset];\n isLocal = (file_location_info_flag & 2) == 0;\n // get the local volume and local system values\n //final int localVolumeTable_offset_offset = 0x0C;\n final int basename_offset_offset = 0x10;\n final int networkVolumeTable_offset_offset = 0x14;\n final int finalname_offset_offset = 0x18;\n int finalname_offset = link[file_start + finalname_offset_offset] + file_start;\n String finalname = getNullDelimitedString(link, finalname_offset);\n if (isLocal) {\n int basename_offset = link[file_start + basename_offset_offset] + file_start;\n String basename = getNullDelimitedString(link, basename_offset);\n real_file = basename + finalname;\n } else {\n int networkVolumeTable_offset = link[file_start + networkVolumeTable_offset_offset] + file_start;\n int shareName_offset_offset = 0x08;\n int shareName_offset = link[networkVolumeTable_offset + shareName_offset_offset]\n + networkVolumeTable_offset;\n String shareName = getNullDelimitedString(link, shareName_offset);\n real_file = shareName + \"\\\\\" + finalname;\n }\n}\n\nprivate static String getNullDelimitedString(byte[] bytes, int off) {\n int len = 0;\n // count bytes until the null character (0)\n while (true) {\n if (bytes[off + len] == 0) {\n break;\n }\n len++;\n }\n return new String(bytes, off, len);\n}\n\n/*\n * convert two bytes into a short note, this is little endian because it's\n * for an Intel only OS.\n */\nprivate static int bytes2short(byte[] bytes, int off) {\n return ((bytes[off + 1] & 0xff) << 8) | (bytes[off] & 0xff);\n}\n\n/**\n * Returns the value of the instance variable 'isLocal'.\n *\n * @return Returns the isLocal.\n */\npublic boolean isLocal() {\n return isLocal;\n}\n}\n"
},
{
"answer_id": 779073,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "static int bytes2short(byte[] bytes, int off) {\n int low = (bytes[off]<0 ? bytes[off]+256 : bytes[off]);\n int high = (bytes[off+1]<0 ? bytes[off+1]+256 : bytes[off+1])<<8;\n return 0 | low | high;\n}\n"
},
{
"answer_id": 858403,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "Shortcut scut = Shortcut.loadShortcut(new File(\"C:\\\\t.lnk\"));\nSystem.out.println(scut.toString());\n Shortcut scut = new Shortcut(new File(\"C:\\\\temp\"));\nOutputStream os = new FileOutputStream(\"C:\\\\t.lnk\");\nos.write(scut.getBytes());\nos.flush();\nos.close();\n"
},
{
"answer_id": 9403438,
"author": "Codebling",
"author_id": 675721,
"author_profile": "https://Stackoverflow.com/users/675721",
"pm_score": 6,
"selected": true,
"text": "package org.stackoverflowusers.file;\n\nimport java.io.ByteArrayOutputStream;\nimport java.io.File;\nimport java.io.FileInputStream;\nimport java.io.IOException;\nimport java.io.InputStream;\nimport java.text.ParseException;\n\n/**\n * Represents a Windows shortcut (typically visible to Java only as a '.lnk' file).\n *\n * Retrieved 2011-09-23 from http://stackoverflow.com/questions/309495/windows-shortcut-lnk-parser-in-java/672775#672775\n * Originally called LnkParser\n *\n * Written by: (the stack overflow users, obviously!)\n * Apache Commons VFS dependency removed by crysxd (why were we using that!?) https://github.com/crysxd\n * Headerified, refactored and commented by Code Bling http://stackoverflow.com/users/675721/code-bling\n * Network file support added by Stefan Cordes http://stackoverflow.com/users/81330/stefan-cordes\n * Adapted by Sam Brightman http://stackoverflow.com/users/2492/sam-brightman\n * Based on information in 'The Windows Shortcut File Format' by Jesse Hager <jessehager@iname.com>\n * And somewhat based on code from the book 'Swing Hacks: Tips and Tools for Killer GUIs'\n * by Joshua Marinacci and Chris Adamson\n * ISBN: 0-596-00907-0\n * http://www.oreilly.com/catalog/swinghks/\n */\npublic class WindowsShortcut\n{\n private boolean isDirectory;\n private boolean isLocal;\n private String real_file;\n\n /**\n * Provides a quick test to see if this could be a valid link !\n * If you try to instantiate a new WindowShortcut and the link is not valid,\n * Exceptions may be thrown and Exceptions are extremely slow to generate,\n * therefore any code needing to loop through several files should first check this.\n *\n * @param file the potential link\n * @return true if may be a link, false otherwise\n * @throws IOException if an IOException is thrown while reading from the file\n */\n public static boolean isPotentialValidLink(File file) throws IOException {\n final int minimum_length = 0x64;\n InputStream fis = new FileInputStream(file);\n boolean isPotentiallyValid = false;\n try {\n isPotentiallyValid = file.isFile()\n && file.getName().toLowerCase().endsWith(\".lnk\")\n && fis.available() >= minimum_length\n && isMagicPresent(getBytes(fis, 32));\n } finally {\n fis.close();\n }\n return isPotentiallyValid;\n }\n\n public WindowsShortcut(File file) throws IOException, ParseException {\n InputStream in = new FileInputStream(file);\n try {\n parseLink(getBytes(in));\n } finally {\n in.close();\n }\n }\n\n /**\n * @return the name of the filesystem object pointed to by this shortcut\n */\n public String getRealFilename() {\n return real_file;\n }\n\n /**\n * Tests if the shortcut points to a local resource.\n * @return true if the 'local' bit is set in this shortcut, false otherwise\n */\n public boolean isLocal() {\n return isLocal;\n }\n\n /**\n * Tests if the shortcut points to a directory.\n * @return true if the 'directory' bit is set in this shortcut, false otherwise\n */\n public boolean isDirectory() {\n return isDirectory;\n }\n\n /**\n * Gets all the bytes from an InputStream\n * @param in the InputStream from which to read bytes\n * @return array of all the bytes contained in 'in'\n * @throws IOException if an IOException is encountered while reading the data from the InputStream\n */\n private static byte[] getBytes(InputStream in) throws IOException {\n return getBytes(in, null);\n }\n \n /**\n * Gets up to max bytes from an InputStream\n * @param in the InputStream from which to read bytes\n * @param max maximum number of bytes to read\n * @return array of all the bytes contained in 'in'\n * @throws IOException if an IOException is encountered while reading the data from the InputStream\n */\n private static byte[] getBytes(InputStream in, Integer max) throws IOException {\n // read the entire file into a byte buffer\n ByteArrayOutputStream bout = new ByteArrayOutputStream();\n byte[] buff = new byte[256];\n while (max == null || max > 0) {\n int n = in.read(buff);\n if (n == -1) {\n break;\n }\n bout.write(buff, 0, n);\n if (max != null)\n max -= n;\n }\n in.close();\n return bout.toByteArray();\n }\n\n private static boolean isMagicPresent(byte[] link) {\n final int magic = 0x0000004C;\n final int magic_offset = 0x00;\n return link.length >= 32 && bytesToDword(link, magic_offset) == magic;\n }\n\n /**\n * Gobbles up link data by parsing it and storing info in member fields\n * @param link all the bytes from the .lnk file\n */\n private void parseLink(byte[] link) throws ParseException {\n try {\n if (!isMagicPresent(link))\n throw new ParseException(\"Invalid shortcut; magic is missing\", 0);\n\n // get the flags byte\n byte flags = link[0x14];\n\n // get the file attributes byte\n final int file_atts_offset = 0x18;\n byte file_atts = link[file_atts_offset];\n byte is_dir_mask = (byte)0x10;\n if ((file_atts & is_dir_mask) > 0) {\n isDirectory = true;\n } else {\n isDirectory = false;\n }\n\n // if the shell settings are present, skip them\n final int shell_offset = 0x4c;\n final byte has_shell_mask = (byte)0x01;\n int shell_len = 0;\n if ((flags & has_shell_mask) > 0) {\n // the plus 2 accounts for the length marker itself\n shell_len = bytesToWord(link, shell_offset) + 2;\n }\n\n // get to the file settings\n int file_start = 0x4c + shell_len;\n\n final int file_location_info_flag_offset_offset = 0x08;\n int file_location_info_flag = link[file_start + file_location_info_flag_offset_offset];\n isLocal = (file_location_info_flag & 2) == 0;\n // get the local volume and local system values\n //final int localVolumeTable_offset_offset = 0x0C;\n final int basename_offset_offset = 0x10;\n final int networkVolumeTable_offset_offset = 0x14;\n final int finalname_offset_offset = 0x18;\n int finalname_offset = link[file_start + finalname_offset_offset] + file_start;\n String finalname = getNullDelimitedString(link, finalname_offset);\n if (isLocal) {\n int basename_offset = link[file_start + basename_offset_offset] + file_start;\n String basename = getNullDelimitedString(link, basename_offset);\n real_file = basename + finalname;\n } else {\n int networkVolumeTable_offset = link[file_start + networkVolumeTable_offset_offset] + file_start;\n int shareName_offset_offset = 0x08;\n int shareName_offset = link[networkVolumeTable_offset + shareName_offset_offset]\n + networkVolumeTable_offset;\n String shareName = getNullDelimitedString(link, shareName_offset);\n real_file = shareName + \"\\\\\" + finalname;\n }\n } catch (ArrayIndexOutOfBoundsException e) {\n throw new ParseException(\"Could not be parsed, probably not a valid WindowsShortcut\", 0);\n }\n }\n\n private static String getNullDelimitedString(byte[] bytes, int off) {\n int len = 0;\n // count bytes until the null character (0)\n while (true) {\n if (bytes[off + len] == 0) {\n break;\n }\n len++;\n }\n return new String(bytes, off, len);\n }\n\n /*\n * convert two bytes into a short note, this is little endian because it's\n * for an Intel only OS.\n */\n private static int bytesToWord(byte[] bytes, int off) {\n return ((bytes[off + 1] & 0xff) << 8) | (bytes[off] & 0xff);\n }\n\n private static int bytesToDword(byte[] bytes, int off) {\n return (bytesToWord(bytes, off + 2) << 16) | bytesToWord(bytes, off);\n }\n\n}\n"
},
{
"answer_id": 32308813,
"author": "Naxos84",
"author_id": 3157899,
"author_profile": "https://Stackoverflow.com/users/3157899",
"pm_score": 1,
"selected": false,
"text": "isLocal = (file_location_info_flag & 2) == 0;\n file_location_info_flag false isLocal isLocal = (file_location_info_flag & 1) == 1;\n"
},
{
"answer_id": 38952952,
"author": "Josua Frank",
"author_id": 6717268,
"author_profile": "https://Stackoverflow.com/users/6717268",
"pm_score": 3,
"selected": false,
"text": "ShellLink.createLink(\"path/to/existing/file.txt\", \"path/to/the/future/shortcut.lnk\"); File shortcut = ...;\nString pathToExistingFile = new ShellLink(shortcut).resolveTarget();\n ShellLink sl = ...;\nsl.setIconLocation(\"/path/to/icon/file\");\n"
},
{
"answer_id": 52105443,
"author": "JS Lair",
"author_id": 10297367,
"author_profile": "https://Stackoverflow.com/users/10297367",
"pm_score": 1,
"selected": false,
"text": " public static boolean isPotentialValidLink(final File file) {\n final int minimum_length = 0x64;\n boolean isPotentiallyValid = false;\n if (file.getName().toLowerCase().endsWith(\".lnk\"))\n try (final InputStream fis = new FileInputStream(file)) {\n isPotentiallyValid = file.isFile() && fis.available() >= minimum_length && isMagicPresent(getBytes(fis, 32));\n } catch (Exception e) {\n // forget it\n }\n return isPotentiallyValid;\n }\n final int finalname_offset = bytesToDword(link,file_start + finalname_offset_offset) + file_start;\n final int basename_offset = bytesToDword(link,file_start + basename_offset_offset) + file_start;\n"
},
{
"answer_id": 62923562,
"author": "Abrar Malekji",
"author_id": 12541862,
"author_profile": "https://Stackoverflow.com/users/12541862",
"pm_score": 1,
"selected": false,
"text": "File file=new File(\"C:\\\\ProgramData\\\\Microsoft\\\\Windows\\\\Start Menu\\\\Programs\\\\TeamViewer.lnk\");//shortcut link\n FileInputStream stream=new FileInputStream(file);\n DataInputStream st=new DataInputStream(stream);\n byte[] bytes=new byte[(int)stream.getChannel().size()];\n stream.read(bytes);\n String data=new String(bytes);\n int i1=data.indexOf(\"C:\\\\Program Files\");\n int i2=data.indexOf(\".exe\",i1);\n System.out.println(data.substring(i1, i2+4));\n"
}
] | 2008/11/21 | [
"https://Stackoverflow.com/questions/309495",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15255/"
] |
309,496 | <p>How can I initialize a const / static array of structs as clearly as possible?</p>
<pre><code>class SomeClass
{
struct MyStruct
{
public string label;
public int id;
};
const MyStruct[] MyArray = {
{"a", 1}
{"b", 5}
{"q", 29}
};
};
</code></pre>
| [
{
"answer_id": 309528,
"author": "Jon Skeet",
"author_id": 22656,
"author_profile": "https://Stackoverflow.com/users/22656",
"pm_score": 7,
"selected": true,
"text": "ValueTuple class SomeClass\n{\n\n struct MyStruct\n {\n private readonly string label;\n private readonly int id;\n\n public MyStruct (string label, int id)\n {\n this.label = label;\n this.id = id;\n }\n\n public string Label { get { return label; } }\n public string Id { get { return id; } }\n\n }\n\n static readonly IList<MyStruct> MyArray = new ReadOnlyCollection<MyStruct>\n (new[] {\n new MyStruct (\"a\", 1),\n new MyStruct (\"b\", 5),\n new MyStruct (\"q\", 29)\n });\n}\n ReadOnlyCollection<>"
},
{
"answer_id": 309540,
"author": "Winston Smith",
"author_id": 35086,
"author_profile": "https://Stackoverflow.com/users/35086",
"pm_score": 5,
"selected": false,
"text": "static MyStruct[] myArray = \n new MyStruct[]{\n new MyStruct() { id = 1, label = \"1\" },\n new MyStruct() { id = 2, label = \"2\" },\n new MyStruct() { id = 3, label = \"3\" }\n };\n"
},
{
"answer_id": 309545,
"author": "Ali Ersöz",
"author_id": 4215,
"author_profile": "https://Stackoverflow.com/users/4215",
"pm_score": 3,
"selected": false,
"text": " readonly MyStruct[] MyArray = new MyStruct[]{\n new MyStruct{ label = \"a\", id = 1},\n new MyStruct{ label = \"b\", id = 5},\n new MyStruct{ label = \"c\", id = 1}\n };\n"
},
{
"answer_id": 309595,
"author": "Paul Sonier",
"author_id": 28053,
"author_profile": "https://Stackoverflow.com/users/28053",
"pm_score": -1,
"selected": false,
"text": "public class SomeClass\n{\n public readonly MyStruct[] myArray;\n\n public static SomeClass()\n {\n myArray = { {\"foo\", \"bar\"},\n {\"boo\", \"far\"}};\n }\n}\n"
},
{
"answer_id": 46917343,
"author": "Shreevardhan",
"author_id": 2425366,
"author_profile": "https://Stackoverflow.com/users/2425366",
"pm_score": 2,
"selected": false,
"text": "const static readonly static readonly MyStruct[] MyArray = new[] {\n new MyStruct { label = \"a\", id = 1 },\n new MyStruct { label = \"b\", id = 5 },\n new MyStruct { label = \"q\", id = 29 }\n};\n"
}
] | 2008/11/21 | [
"https://Stackoverflow.com/questions/309496",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4066/"
] |
309,497 | <p>My company has a requirement that all production sites pass an AppScan security scan. Sometimes, when we scan a SharePoint installation, the software detects a blind SQL injection vulnerability. I'm pretty sure this is a false positive--AppScan is probably interpreting some other activity in the HTTP response as success of the blind injection. But it's difficult to prove that this is the case.</p>
<p>I suspect that SharePoint, both MOSS 07 and WSS 3.0, uses stored procedures exclusively behind the scenes. Does anyone know if there is any documentation from Microsoft to this effect, and furthermore, whether any of the stored procedures use dynamically-generated SQL? If everything were sprocs, and none of them dynamic, we would have pretty good evidence that SharePoint has no SQL injection vulnerability.</p>
| [
{
"answer_id": 19728455,
"author": "kravietz",
"author_id": 1274149,
"author_profile": "https://Stackoverflow.com/users/1274149",
"pm_score": -1,
"selected": false,
"text": "WAITFOR DELAY"
}
] | 2008/11/21 | [
"https://Stackoverflow.com/questions/309497",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.