qid
int64
4
19.1M
question
stringlengths
18
48.3k
answers
list
date
stringlengths
10
10
metadata
list
10,915
<p>Warning - I am very new to NHibernate. I know this question seems simple - and I'm sure there's a simple answer, but I've been spinning my wheels for some time on this one. I am dealing with a legacy db which really can't be altered structurally. I have a details table which lists payment plans that have been accepted by a customer. Each payment plan has an ID which links back to a reference table to get the plan's terms, conditions, etc. In my object model, I have an AcceptedPlan class, and a Plan class. Originally, I used a many-to-one relationship from the detail table back to the ref table to model this relationship in NHibernate. I also created a one-to-many relationship going in the opposite direction from the Plan class over to the AcceptedPlan class. This was fine while I was simply reading data. I could go to my Plan object, which was a property of my AcceptedPlan class to read the plan's details. My problem arose when I had to start inserting new rows to the details table. From my reading, it seems the only way to create a new child object is to add it to the parent object and then save the session. But I don't want to have to create a new parent Plan object every time I want to create a new detail record. This seems like unnecessary overhead. Does anyone know if I am going about this in the wrong way?</p>
[ { "answer_id": 11164, "author": "DavidWhitney", "author_id": 1297, "author_profile": "https://Stackoverflow.com/users/1297", "pm_score": 3, "selected": true, "text": "<?xml version=\"1.0\" encoding=\"utf-8\" ?>\n<hibernate-mapping default-cascade=\"save-update\" xmlns=\"urn:nhibernate-mapping-2.2\">\n <class lazy=\"false\" name=\"Namespace.Customer, Namespace\" table=\"Customer\">\n <id name=\"Id\" type=\"Int32\" unsaved-value=\"0\">\n <column name=\"CustomerAccountId\" length=\"4\" sql-type=\"int\" not-null=\"true\" unique=\"true\" index=\"CustomerPK\"/>\n <generator class=\"native\" />\n </id>\n\n <bag name=\"AcceptedOffers\" inverse=\"false\" lazy=\"false\" cascade=\"all-delete-orphan\" table=\"details\">\n <key column=\"CustomerAccountId\" foreign-key=\"AcceptedOfferFK\"/>\n <many-to-many\n class=\"Namespace.AcceptedOffer, Namespace\"\n column=\"AcceptedOfferFK\"\n foreign-key=\"AcceptedOfferID\"\n lazy=\"false\"\n />\n </bag>\n\n </class>\n</hibernate-mapping>\n\n\n<?xml version=\"1.0\" encoding=\"utf-8\" ?>\n<hibernate-mapping default-cascade=\"save-update\" xmlns=\"urn:nhibernate-mapping-2.2\">\n <class lazy=\"false\" name=\"Namespace.AcceptedOffer, Namespace\" table=\"AcceptedOffer\">\n <id name=\"Id\" type=\"Int32\" unsaved-value=\"0\">\n <column name=\"AcceptedOfferId\" length=\"4\" sql-type=\"int\" not-null=\"true\" unique=\"true\" index=\"AcceptedOfferPK\"/>\n <generator class=\"native\" />\n </id>\n\n <many-to-one \n name=\"Plan\"\n class=\"Namespace.Plan, Namespace\"\n lazy=\"false\"\n cascade=\"save-update\"\n >\n <column name=\"PlanFK\" length=\"4\" sql-type=\"int\" not-null=\"false\"/>\n </many-to-one>\n\n <property name=\"StatusId\" type=\"Int32\">\n <column name=\"StatusId\" length=\"4\" sql-type=\"int\" not-null=\"true\"/>\n </property>\n\n </class>\n</hibernate-mapping>\n" }, { "answer_id": 11176, "author": "DavidWhitney", "author_id": 1297, "author_profile": "https://Stackoverflow.com/users/1297", "pm_score": 1, "selected": false, "text": "<?xml version=\"1.0\" encoding=\"utf-8\" ?>\n<hibernate-mapping default-cascade=\"save-update\" xmlns=\"urn:nhibernate-mapping-2.2\">\n <class lazy=\"false\" name=\"Namespace.Customer, Namespace\" table=\"Customer\">\n <id name=\"Id\" type=\"Int32\" unsaved-value=\"0\">\n <column name=\"customer_id\" length=\"4\" sql-type=\"int\" not-null=\"true\" unique=\"true\" index=\"CustomerPK\"/>\n <generator class=\"native\" />\n </id>\n\n <bag name=\"AcceptedOffers\" inverse=\"false\" lazy=\"false\" cascade=\"all-delete-orphan\">\n <key column=\"accepted_offer_id\"/>\n <one-to-many class=\"Namespace.AcceptedOffer, Namespace\"/>\n </bag>\n\n </class>\n</hibernate-mapping>\n\n\n<?xml version=\"1.0\" encoding=\"utf-8\" ?>\n<hibernate-mapping default-cascade=\"save-update\" xmlns=\"urn:nhibernate-mapping-2.2\">\n <class lazy=\"false\" name=\"Namespace.AcceptedOffer, Namespace\" table=\"Accepted_Offer\">\n <id name=\"Id\" type=\"Int32\" unsaved-value=\"0\">\n <column name=\"accepted_offer_id\" length=\"4\" sql-type=\"int\" not-null=\"true\" unique=\"true\" />\n <generator class=\"native\" />\n </id>\n\n <many-to-one name=\"Plan\" class=\"Namespace.Plan, Namespace\" lazy=\"false\" cascade=\"save-update\">\n <column name=\"plan_id\" length=\"4\" sql-type=\"int\" not-null=\"false\"/>\n </many-to-one>\n\n </class>\n</hibernate-mapping>\n" } ]
2008/08/14
[ "https://Stackoverflow.com/questions/10915", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1284/" ]
10,926
<p>I'm building a listing/grid control in a <code>Flex</code> application and using it in a <code>.NET</code> web application. To make a really long story short I am getting XML from a webservice of serialized objects. I have a page limit of how many things can be on a page. I've taken a data grid and made it page, sort across pages, and handle some basic filtering. </p> <p>In regards to paging I'm using a Dictionary keyed on the page and storing the XML for that page. This way whenever a user comes back to a page that I've saved into this dictionary I can grab the XML from local memory instead of hitting the webservice. Basically, I'm caching the data retrieved from each call to the webservice for a page of data.</p> <p>There are several things that can expire my cache. Filtering and sorting are the main reason. However, a user may edit a row of data in the grid by opening an editor. The data they edit could cause the data displayed in the row to be stale. I could easily go to the webservice and get the whole page of data, but since the page size is set at runtime I could be looking at a large amount of records to retrieve.</p> <p>So let me now get to the heart of the issue that I am experiencing. In order to prevent getting the whole page of data back I make a call to the webservice asking for the completely updated record (the editor handles saving its data).</p> <p>Since I'm using custom objects I need to serialize them on the server to XML (this is handled already for other portions of our software). All data is handled through XML in e4x. The cache in the Dictionary is stored as an XMLList.</p> <p><strong>Now let me show you my code...</strong></p> <pre><code>var idOfReplacee:String = this._WebService.GetSingleModelXml.lastResult.*[0].*[0].@Id; var xmlToReplace:XMLList = this._DataPages[this._Options.PageIndex].Data.(@Id == idOfReplacee); if(xmlToReplace.length() &gt; 0) { delete (this._DataPages[this._Options.PageIndex].Data.(@Id == idOfReplacee)[0]); this._DataPages[this._Options.PageIndex].Data += this._WebService.GetSingleModelXml.lastResult.*[0].*[0]; } </code></pre> <p>Basically, I get the id of the node I want to replace. Then I find it in the cache's Data property (<code>XMLList</code>). I make sure it exists since the filter on the second line returns the <code>XMLList</code>.</p> <p>The problem I have is with the delete line. I cannot make that line delete that node from the list. The line following the delete line works. I've added the node to the list.</p> <p>How do I replace or delete that node (meaning the node that I find from the filter statement out of the .Data property of the cache)???</p> <p>Hopefully the underscores for all of my variables do not stay escaped when this is posted! otherwise <code>this.&amp;#95 == this</code>._</p>
[ { "answer_id": 11048, "author": "Matt Dillard", "author_id": 863, "author_profile": "https://Stackoverflow.com/users/863", "pm_score": 0, "selected": false, "text": "delete idOfReplacee delete (this._DataPages[this._Options.PageIndex].Data..(@Id == idOfReplacee)[0]);\n Data" }, { "answer_id": 11059, "author": "Theo", "author_id": 1109, "author_profile": "https://Stackoverflow.com/users/1109", "pm_score": 1, "selected": false, "text": "replace var oldNode : XML = this._DataPages[this._Options.PageIndex].Data.(@Id == idOfReplacee)[0];\nvar newNode : XML = this._WebService.GetSingleModelXml.lastResult.*[0].*[0]; \n\noldNode.parent.replace(oldNode, newNode);\n" }, { "answer_id": 11527, "author": "Mike G", "author_id": 1290, "author_profile": "https://Stackoverflow.com/users/1290", "pm_score": 2, "selected": false, "text": "<Models>\n <Definition Id='1' />\n <Definition Id='2' />\n</Models>\n //gets the index of the node to replace from the same filter\nvar childIndex:int = (this._DataPages[this._Options.PageIndex].Data.(@Id == idOfReplacee)[0]).childIndex();\n//deletes the node from the list\ndelete this._DataPages[this._Options.PageIndex].Data[childIndex];\n//appends the new node from the webservice to the list\nthis._DataPages[this._Options.PageIndex].Data += this._WebService.GetSingleModelXml.lastResult.*[0].*[0];\n" }, { "answer_id": 37029264, "author": "Harbs", "author_id": 5475183, "author_profile": "https://Stackoverflow.com/users/5475183", "pm_score": 1, "selected": false, "text": "oldNode.parent().replace(oldNode.childIndex(), newNode);\n replace()" } ]
2008/08/14
[ "https://Stackoverflow.com/questions/10926", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1290/" ]
10,933
<p>We have an SVN repository running on a Windows server, and I want to link internal documentation, feature changes, bugs and so on to code changes.</p> <p>We've found WebSVN to be amazingly slow - the repository is too large for it (I think).</p> <p>The team using it is primarily coding in C#, and while some have experience with other languages I'd really like a tool anyone on the team can maintain.</p> <p>Most of the tools I've seen are based on PHP, Java, Python, etc. All languages the team could learn, but I'd rather something that uses the skills we already have.</p> <p>Can you recommend a good web-based repository browser for SVN, ideally one that uses ASP.NET, <a href="http://en.wikipedia.org/wiki/Microsoft_SQL_Server" rel="nofollow noreferrer">SQL&nbsp;Server</a> and that runs on <a href="http://en.wikipedia.org/wiki/Internet_Information_Services" rel="nofollow noreferrer">IIS</a>?</p>
[ { "answer_id": 11772, "author": "icco", "author_id": 1063, "author_profile": "https://Stackoverflow.com/users/1063", "pm_score": 2, "selected": false, "text": "svn log --xml\n" } ]
2008/08/14
[ "https://Stackoverflow.com/questions/10933", "https://Stackoverflow.com", "https://Stackoverflow.com/users/905/" ]
10,949
<p>Let's say I have a complex .NET class, with lots of arrays and other class object members. I need to be able to generate a deep clone of this object - so I write a Clone() method, and implement it with a simple BinaryFormatter serialize/deserialize - or perhaps I do the deep clone using some other technique which is more error prone and I'd like to make sure is tested.</p> <p>OK, so now (ok, I should have done it first) I'd like write tests which cover the cloning. All the members of the class are private, and my architecture is so good (!) that I haven't needed to write hundreds of public properties or other accessors. The class isn't IComparable or IEquatable, because that's not needed by the application. My unit tests are in a separate assembly to the production code.</p> <p>What approaches do people take to testing that the cloned object is a good copy? Do you write (or <em>rewrite</em> once you discover the need for the clone) all your unit tests for the class so that they can be invoked with <em>either</em> a 'virgin' object <em>or</em> with a clone of it? How would you test if part of the cloning wasn't deep enough - as this is just the kind of problem which can give hideous-to-find bugs later?</p>
[ { "answer_id": 24166, "author": "Andrew", "author_id": 1948, "author_profile": "https://Stackoverflow.com/users/1948", "pm_score": 1, "selected": false, "text": "[Conditional(\"DEBUG\")]\npublic static void DebugAssertValueEquality<T>(T current, T other, bool expected, \n params string[] ignoredFields) {\n if (null == current) \n { throw new ArgumentNullException(\"current\"); }\n if (null == ignoredFields)\n { ignoredFields = new string[] { }; }\n\n FieldInfo lastField = null;\n bool test;\n if (object.ReferenceEquals(other, null))\n { Debug.Assert(false == expected, \"The other object was null\"); return; }\n test = true;\n foreach (FieldInfo fi in current.GetType().GetFields(BindingFlags.Instance)) {\n if (test = false) { break; }\n if (0 <= Array.IndexOf<string>(ignoredFields, fi.Name))\n { continue; }\n lastField = fi;\n object leftValue = fi.GetValue(current);\n object rightValue = fi.GetValue(other);\n if (object.ReferenceEquals(null, leftValue)) {\n if (!object.ReferenceEquals(null, rightValue))\n { test = false; }\n }\n else if (object.ReferenceEquals(null, rightValue))\n { test = false; }\n else {\n if (!leftValue.Equals(rightValue))\n { test = false; }\n }\n }\n Debug.Assert(test == expected, string.Format(\"field: {0}\", lastField));\n}\n" }, { "answer_id": 12477641, "author": "EricSchaefer", "author_id": 8976, "author_profile": "https://Stackoverflow.com/users/8976", "pm_score": 1, "selected": false, "text": "Equals()" }, { "answer_id": 31139080, "author": "Thulani Chivandikwa", "author_id": 611628, "author_profile": "https://Stackoverflow.com/users/611628", "pm_score": 0, "selected": false, "text": "public static class TestDeepClone\n {\n private static readonly List<long> objectIDs = new List<long>();\n private static readonly ObjectIDGenerator objectIdGenerator = new ObjectIDGenerator();\n\n public static bool DefaultCloneExclusionsCheck(Object obj)\n {\n return\n obj is ValueType ||\n obj is string ||\n obj is Delegate ||\n obj is IEnumerable;\n }\n\n /// <summary>\n /// Executes various assertions to ensure the validity of a deep copy for any object including its compositions\n /// </summary>\n /// <param name=\"original\">The original object</param>\n /// <param name=\"copy\">The cloned object</param>\n /// <param name=\"checkExclude\">A predicate for any exclusions to be done, i.e not to expect IPolicy items to be cloned</param>\n public static void AssertDeepClone(this Object original, Object copy, Predicate<object> checkExclude)\n {\n bool isKnown;\n if (original == null) return;\n if (copy == null) Assert.Fail(\"Copy is null while original is not\", original, copy);\n\n var id = objectIdGenerator.GetId(original, out isKnown); //Avoid checking the same object more than once\n if (!objectIDs.Contains(id))\n {\n objectIDs.Add(id);\n }\n else\n {\n return;\n }\n\n if (!checkExclude(original))\n {\n Assert.That(ReferenceEquals(original, copy) == false);\n }\n\n Type type = original.GetType();\n PropertyInfo[] propertyInfos = type.GetProperties(BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Public);\n FieldInfo[] fieldInfos = type.GetFields(BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Public);\n\n foreach (PropertyInfo memberInfo in propertyInfos)\n {\n var getmethod = memberInfo.GetGetMethod();\n if (getmethod == null) continue;\n var originalValue = getmethod.Invoke(original, new object[] { });\n var copyValue = getmethod.Invoke(copy, new object[] { });\n if (originalValue == null) continue;\n if (!checkExclude(originalValue))\n {\n Assert.That(ReferenceEquals(originalValue, copyValue) == false);\n }\n\n if (originalValue is IEnumerable && !(originalValue is string))\n {\n var originalValueEnumerable = originalValue as IEnumerable;\n var copyValueEnumerable = copyValue as IEnumerable;\n if (copyValueEnumerable == null) Assert.Fail(\"Copy is null while original is not\", new[] { original, copy });\n int count = 0;\n List<object> items = copyValueEnumerable.Cast<object>().ToList();\n foreach (object o in originalValueEnumerable)\n {\n AssertDeepClone(o, items[count], checkExclude);\n count++;\n }\n }\n else\n {\n //Recurse over reference types to check deep clone success\n if (!checkExclude(originalValue))\n {\n AssertDeepClone(originalValue, copyValue, checkExclude);\n }\n\n if (originalValue is ValueType && !(originalValue is Guid))\n {\n //check value of non reference type\n Assert.That(originalValue.Equals(copyValue));\n }\n }\n\n }\n\n foreach (FieldInfo fieldInfo in fieldInfos)\n {\n var originalValue = fieldInfo.GetValue(original);\n var copyValue = fieldInfo.GetValue(copy);\n if (originalValue == null) continue;\n if (!checkExclude(originalValue))\n {\n Assert.That(ReferenceEquals(originalValue, copyValue) == false);\n }\n\n if (originalValue is IEnumerable && !(originalValue is string))\n {\n var originalValueEnumerable = originalValue as IEnumerable;\n var copyValueEnumerable = copyValue as IEnumerable;\n if (copyValueEnumerable == null) Assert.Fail(\"Copy is null while original is not\", new[] { original, copy });\n int count = 0;\n List<object> items = copyValueEnumerable.Cast<object>().ToList();\n foreach (object o in originalValueEnumerable)\n {\n AssertDeepClone(o, items[count], checkExclude);\n count++;\n }\n }\n else\n {\n //Recurse over reference types to check deep clone success\n if (!checkExclude(originalValue))\n {\n AssertDeepClone(originalValue, copyValue, checkExclude);\n }\n if (originalValue is ValueType && !(originalValue is Guid))\n {\n //check value of non reference type\n Assert.That(originalValue.Equals(copyValue));\n }\n }\n }\n }\n }\n" } ]
2008/08/14
[ "https://Stackoverflow.com/questions/10949", "https://Stackoverflow.com", "https://Stackoverflow.com/users/987/" ]
10,985
<p>Does anyone know how I can, in platform-independent C++ code prevent an object from being created on the heap? That is, for a class "Foo", I want to prevent users from doing this:</p> <pre><code>Foo *ptr = new Foo; </code></pre> <p>and only allow them to do this:</p> <pre><code>Foo myfooObject; </code></pre> <p>Does anyone have any ideas?</p> <p>Cheers,</p>
[ { "answer_id": 11003, "author": "Nick", "author_id": 1236, "author_profile": "https://Stackoverflow.com/users/1236", "pm_score": 4, "selected": false, "text": "class Foo {\nprivate:\n void* operator new(size_t size);\n};\n" }, { "answer_id": 11014, "author": "pauldoo", "author_id": 755, "author_profile": "https://Stackoverflow.com/users/755", "pm_score": 3, "selected": false, "text": "FooClass::FooClass() {\n char dummy;\n ptrdiff_t displacement = &dummy - reinterpret_cast<char*>(this);\n if (displacement > 10000 || displacement < -10000) {\n throw \"Not on the stack - maybe..\";\n }\n}\n" }, { "answer_id": 11018, "author": "pauldoo", "author_id": 755, "author_profile": "https://Stackoverflow.com/users/755", "pm_score": 2, "selected": false, "text": "struct MyStruct {\n Foo m_foo;\n};\n\nMyStruct* p = new MyStruct();\n" }, { "answer_id": 11299, "author": "Patrick Johnmeyer", "author_id": 363, "author_profile": "https://Stackoverflow.com/users/363", "pm_score": 6, "selected": true, "text": "private:\n void* operator new(size_t); // standard new\n void* operator new(size_t, void*); // placement new\n void* operator new[](size_t); // array new\n void* operator new[](size_t, void*); // placement array new\n" }, { "answer_id": 37472123, "author": "MerkX", "author_id": 2251119, "author_profile": "https://Stackoverflow.com/users/2251119", "pm_score": 2, "selected": false, "text": "private:\nvoid* operator new(size_t, ...) = delete;\nvoid* operator new[](size_t, ...) = delete;\n" }, { "answer_id": 48359317, "author": "Bala", "author_id": 9245009, "author_profile": "https://Stackoverflow.com/users/9245009", "pm_score": 0, "selected": false, "text": "Class Foo\n{\n private:\n Foo();\n Foo(Foo& );\n public:\n static Foo GenerateInstance() { \n Foo a ; return a; \n }\n}\n" } ]
2008/08/14
[ "https://Stackoverflow.com/questions/10985", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1304/" ]
10,990
<p>Sorry for the basic question - I'm a .NET developer and don't have much experience with LAMP setups.</p> <p>I have a PHP site that will allow uploads to a specific folder. I have been told that this folder needs to be owned by the webserver user for the upload process to work, so I created the folder and then set permissions as such:</p> <pre><code>chown apache:apache -R uploads/ chmod 755 -R uploads/ </code></pre> <p>The only problem now is that the FTP user can not modify the uploaded files at all.</p> <p>Is there a permission setting that will allow me to still upload files and then modify them later as a user other than the webserver user?</p>
[ { "answer_id": 11029, "author": "Max", "author_id": 1309, "author_profile": "https://Stackoverflow.com/users/1309", "pm_score": 4, "selected": false, "text": "move_uploaded_file" }, { "answer_id": 9460755, "author": "M. Ahmad Zafar", "author_id": 462732, "author_profile": "https://Stackoverflow.com/users/462732", "pm_score": 1, "selected": false, "text": "apache read execute 0" }, { "answer_id": 24689360, "author": "CesareoAguirre", "author_id": 960117, "author_profile": "https://Stackoverflow.com/users/960117", "pm_score": 0, "selected": false, "text": "CHOWN chgrp myusername# chown -R myusername:_www uploads" }, { "answer_id": 44402979, "author": "Eric", "author_id": 1568658, "author_profile": "https://Stackoverflow.com/users/1568658", "pm_score": -1, "selected": false, "text": "@Ryan Ahearn Ubuntu front /var/www/html" }, { "answer_id": 73532081, "author": "Julio Vinachi", "author_id": 4929137, "author_profile": "https://Stackoverflow.com/users/4929137", "pm_score": 1, "selected": false, "text": "chmod -R 775 uploads/\nchown -R www-data uploads/\n www-data" } ]
2008/08/14
[ "https://Stackoverflow.com/questions/10990", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1153/" ]
11,028
<p>When I'm joining three or more tables together by a common column, I'd write my query like this:</p> <pre><code>SELECT * FROM a, b, c WHERE a.id = b.id AND b.id = c.id </code></pre> <p>a colleague recently asked my why I didn't do explicit <em>Join Transitive Closure</em> in my queries like this:</p> <pre><code>SELECT * FROM a, b, c WHERE a.id = b.id AND b.id = c.id AND c.id = a.id </code></pre> <p>are the really any advantages to this? Surely the optimiser can imply this for itself?</p> <p><em>edit: I know it's evil syntax, but it's a quick and dirty example of legitimate legacy code +1 @<a href="https://stackoverflow.com/questions/11028/what-are-the-advantages-of-explicit-join-transitive-closure-in-sql#11114">Stu</a> for cleaning it up</em></p>
[ { "answer_id": 11114, "author": "Stu", "author_id": 414, "author_profile": "https://Stackoverflow.com/users/414", "pm_score": 2, "selected": false, "text": "Select\n * -- Oh, and don't ever use *, either\nFrom\n A \n Inner Join B On A.ID = B.ID\n Inner Join C On B.ID = C.ID\n" } ]
2008/08/14
[ "https://Stackoverflow.com/questions/11028", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1030/" ]
11,043
<p>What are the pros and cons of using table aliases in SQL? I personally try to avoid them, as I think they make the code less readable (especially when reading through large where/and statements), but I'd be interested in hearing any counter-points to this. When is it generally a good idea to use table aliases, and do you have any preferred formats?</p>
[ { "answer_id": 11053, "author": "Rob Allen", "author_id": 149, "author_profile": "https://Stackoverflow.com/users/149", "pm_score": 6, "selected": true, "text": "select person.FirstName\n ,person.LastName\n ,addr.StreetAddress\n ,addr.City\n ,addr.State\n ,addr.Zip\n ,phone.PhoneNumber\n ,company.CompanyName\nfrom tblPeople person\nleft outer join tblAffiliations affl on affl.personID = person.personID\nleft outer join tblCompany company on company.companyID = affl.companyID\n" }, { "answer_id": 11064, "author": "Keith", "author_id": 905, "author_profile": "https://Stackoverflow.com/users/905", "pm_score": 3, "selected": false, "text": "--seems pretty readable to me ;-)\nselect a.Text\nfrom Question q\n inner join Answer a\n on a.QuestionId = q.QuestionId\n" }, { "answer_id": 202162, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "SELECT Description -- actually in a\n FROM\n table_a a,\n table_b b\n WHERE\n a.ID = b.ID\n" }, { "answer_id": 6299649, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 5, "selected": false, "text": "select a.id, a.region, a.firstname, a.blah, b.yadda, b.huminahumina, c.crap\nfrom table toys as a\ninner join prices as b on a.blah = b.yadda\ninner join customers as c on c.crap = something else\netc\n" } ]
2008/08/14
[ "https://Stackoverflow.com/questions/11043", "https://Stackoverflow.com", "https://Stackoverflow.com/users/637/" ]
11,045
<p>How can I get a user-defined function to re-evaluate itself based on changed data in the spreadsheet?</p> <p>I tried <strong><kbd>F9</kbd></strong> and <strong><kbd>Shift</kbd>+<kbd>F9</kbd></strong>.</p> <p>The only thing that seems to work is editing the cell with the function call and then pressing Enter.</p>
[ { "answer_id": 12018, "author": "vzczc", "author_id": 224, "author_profile": "https://Stackoverflow.com/users/224", "pm_score": 8, "selected": true, "text": "Application.Volatile Function doubleMe(d)\n Application.Volatile\n doubleMe = d * 2\nEnd Function\n" }, { "answer_id": 120363, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 4, "selected": false, "text": "Public Function doubleMe(d As Variant)\n doubleMe = d * 2\nEnd Function\n Application.Volatile Public Function doubleMe()\n Application.Volatile\n doubleMe = Worksheets(\"Fred\").Range(\"A1\") * 2\nEnd Function\n" }, { "answer_id": 26507013, "author": "Prashanth", "author_id": 4169806, "author_profile": "https://Stackoverflow.com/users/4169806", "pm_score": 0, "selected": false, "text": "Public Sub UpdateMyFunctions()\n Dim myRange As Range\n Dim rng As Range\n\n 'Considering The Functions are in Range A1:B10\n Set myRange = ActiveSheet.Range(\"A1:B10\")\n\n For Each rng In myRange\n rng.Formula = rng.Formula\n Next\nEnd Sub\n" }, { "answer_id": 27279953, "author": "ayman", "author_id": 3180806, "author_profile": "https://Stackoverflow.com/users/3180806", "pm_score": 1, "selected": false, "text": "Application.Calculation = xlCalculationAutomatic \n Application.Calculation = xlCalculationManual \n" }, { "answer_id": 30745135, "author": "MfJ", "author_id": 4992736, "author_profile": "https://Stackoverflow.com/users/4992736", "pm_score": 1, "selected": false, "text": "Range(A:B).Calculate Public Sub UpdateMyFunctions()\n Dim myRange As Range\n Dim rng As Range\n\n ' Assume the functions are in this range A1:B10.\n Set myRange = ActiveSheet.Range(\"A1:B10\")\n\n For Each rng In myRange\n rng.Formula = rng.Formula\n Next\nEnd Sub\n" }, { "answer_id": 47408310, "author": "alex303411", "author_id": 8978155, "author_profile": "https://Stackoverflow.com/users/8978155", "pm_score": 1, "selected": false, "text": "Application.Volatile Application.CalculateFull" }, { "answer_id": 57929883, "author": "Gene Sorg", "author_id": 12065022, "author_profile": "https://Stackoverflow.com/users/12065022", "pm_score": 1, "selected": false, "text": "Private Sub Worksheet_Change(ByVal Target As Range)\n If Not Intersect(Target, Range(\"F3\")) Is Nothing Then\n Application.CalculateFull\n End If\nEnd Sub\n" } ]
2008/08/14
[ "https://Stackoverflow.com/questions/11045", "https://Stackoverflow.com", "https://Stackoverflow.com/users/767/" ]
11,060
<p>This is a difficult and open-ended question I know, but I thought I'd throw it to the floor and see if anyone had any interesting suggestions.</p> <p>I have developed a code-generator that takes our python interface to our C++ code (generated via SWIG) and generates code needed to expose this as WebServices. When I developed this code I did it using TDD, but I've found my tests to be brittle as hell. Because each test essentially wanted to verify that for a given bit of input code (which happens to be a C++ header) I'd get a given bit of outputted code I wrote a small engine that reads test definitions from XML input files and generates test cases from these expectations.</p> <p>The problem is I dread going in to modify the code at all. That and the fact that the unit tests themselves are a: complex, and b: brittle.</p> <p>So I'm trying to think of alternative approaches to this problem, and it strikes me I'm perhaps tackling it the wrong way. Maybe I need to focus more on the outcome, IE: does the code I generate actually run and do what I want it to, rather than, does the code look the way I want it to.</p> <p>Has anyone got any experiences of something similar to this they would care to share?</p>
[ { "answer_id": 70778, "author": "0124816", "author_id": 11521, "author_profile": "https://Stackoverflow.com/users/11521", "pm_score": 0, "selected": false, "text": "int x = 0;\nGENERATED_CODE\nassert(x == 100);\n" }, { "answer_id": 2870088, "author": "Sean B", "author_id": 333532, "author_profile": "https://Stackoverflow.com/users/333532", "pm_score": 0, "selected": false, "text": " public class A : InterfaceA \n { \n InterfaceB b;\n\n InterfaceC c;\n\n public A(InterfaceB b, InterfaceC c) {\n this._b = b;\n this._c = c; }\n\n public string SomeOperation(string input) \n {\n return this._b.SomeOtherOperation(input) \n + this._c.EvenAnotherOperation(input); \n } \n }\n public class When_system_A_has_some_operation_called_with_valid_input : SystemASpecification\n{\n private string _actualString;\n\n private string _expectedString;\n\n private string _input;\n\n private string _returnB;\n\n private string _returnC;\n\n [It]\n public void Should_return_the_expected_string()\n {\n _actualString.Should().Be.EqualTo(this._expectedString);\n }\n\n public override void GivenThat()\n {\n var randomGenerator = new RandomGenerator();\n this._input = randomGenerator.Generate<string>();\n this._returnB = randomGenerator.Generate<string>();\n this._returnC = randomGenerator.Generate<string>();\n\n Dep<InterfaceB>().Stub(b => b.SomeOtherOperation(_input))\n .Return(this._returnB);\n Dep<InterfaceC>().Stub(c => c.EvenAnotherOperation(_input))\n .Return(this._returnC);\n\n this._expectedString = this._returnB + this._returnC;\n }\n\n public override void WhenIRun()\n {\n this._actualString = Sut.SomeOperation(this._input);\n }\n}\n" } ]
2008/08/14
[ "https://Stackoverflow.com/questions/11060", "https://Stackoverflow.com", "https://Stackoverflow.com/users/912/" ]
11,085
<p>In Perl, an object is just a reference to any of the basic Perl data types that has been blessed into a particular class. When you use the ref() function on an unblessed reference, you are told what data type the reference points to. However, when you call ref() on a blessed reference, you are returned the name of the package that reference has been blessed into. </p> <p>I want to know the actual underlying type of the blessed reference. How can I determine this?</p>
[ { "answer_id": 64160, "author": "Michael Carman", "author_id": 8233, "author_profile": "https://Stackoverflow.com/users/8233", "pm_score": 5, "selected": true, "text": "Scalar::Util::reftype() Scalar::Util UNIVERSAL::isa() $x->isa('HASH') # if $x is known to be an object\nUNIVERSAL::isa($x, 'HASH') # if $x might not be an object or reference\n ARRAY SCALAR Class=HASH(0x1234ABCD) my $type = ($object =~ /=(.+)\\(0x[0-9a-f]+\\)$/i);\n" } ]
2008/08/14
[ "https://Stackoverflow.com/questions/11085", "https://Stackoverflow.com", "https://Stackoverflow.com/users/166/" ]
11,088
<p>In Java, there is no such thing as an unsigned byte.</p> <p>Working with some low level code, occasionally you need to work with bytes that have unsigned values greater than 128, which causes Java to interpret them as a negative number due to the MSB being used for sign.</p> <p>What's a good way to work around this? (Saying don't use Java is not an option)</p>
[ { "answer_id": 11101, "author": "pauldoo", "author_id": 755, "author_profile": "https://Stackoverflow.com/users/755", "pm_score": 5, "selected": true, "text": "byte[] foobar = ..;\nint value = foobar[10];\nif (value < 0) value += 256 // Patch up the 'falsely' negative value\n" }, { "answer_id": 15657, "author": "martinatime", "author_id": 1353, "author_profile": "https://Stackoverflow.com/users/1353", "pm_score": 0, "selected": false, "text": "short a = 1s;\nshort b = 2s;\nint c = a + b; // the result is up-converted\nshort small = (short)c; // must cast to get it back to short\n int a = 32;\nint b = 128;\nint foo = (a + b) | 255;\n" }, { "answer_id": 19186, "author": "ejack", "author_id": 1377, "author_profile": "https://Stackoverflow.com/users/1377", "pm_score": 6, "selected": false, "text": "byte[] foobar = ..;\nint value = (foobar[10] & 0xff);\n" }, { "answer_id": 5047679, "author": "octo", "author_id": 282400, "author_profile": "https://Stackoverflow.com/users/282400", "pm_score": 0, "selected": false, "text": "if((val & (byte)0x80) != 0) { ... }\n" } ]
2008/08/14
[ "https://Stackoverflow.com/questions/11088", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1309/" ]
11,099
<p>In the case of languages that support single decision and action without brackets, such as the following example:</p> <pre><code>if (var == true) doSomething(); </code></pre> <p>What is the preferred way of writing this? Should brackets always be used, or should their usage be left as a preference of the individual developer? Additionally, does this practice depend on the size of the code block, such as in the following example:</p> <pre><code>if (var == 1) doSomething(1); else if (var &gt; 1 &amp;&amp; var &lt; 10) doSomething(2); else { validate(var); doSomething(var); } </code></pre>
[ { "answer_id": 11106, "author": "Jon Limjap", "author_id": 372, "author_profile": "https://Stackoverflow.com/users/372", "pm_score": 2, "selected": false, "text": "if (cond1)\n{\n SomeOperation();\n Another();\n}\nelseif (cond2)\n{\n DoSomething();\n}\nelse\n{\n DoNothing();\n DoAnother();\n}\n if (cond1)\n DoFirst();\nelseif (cond2)\n DoSecond();\nelse\n DoElse();\n foreach (var s as Something)\n if (s == someCondition)\n yield return SomeMethod(s);\n" }, { "answer_id": 11107, "author": "stimms", "author_id": 361, "author_profile": "https://Stackoverflow.com/users/361", "pm_score": 4, "selected": true, "text": "if ( a == b) {\n doSomething();\n}\nelse {\n doSomething();\n}\n" }, { "answer_id": 11110, "author": "Ryan Ahearn", "author_id": 75, "author_profile": "https://Stackoverflow.com/users/75", "pm_score": 1, "selected": false, "text": "if (aString) free(aString);\n" }, { "answer_id": 11116, "author": "ZombieSheep", "author_id": 377, "author_profile": "https://Stackoverflow.com/users/377", "pm_score": 3, "selected": false, "text": "if(a==b)\n{\n doSomething();\n}\n if(a==b)\n doSomething();\n doSomethingElse();\n if(a==b)\n{\n doSomething();\n doSomethingElse();\n}\n" }, { "answer_id": 11117, "author": "Kev", "author_id": 419, "author_profile": "https://Stackoverflow.com/users/419", "pm_score": 3, "selected": false, "text": "if(something)\n DoOneThing();\nelse\n DoItDifferently();\n else if(something)\n DoOneThing();\nelse\n DoItDifferently();\n AlwaysGetsCalled(); \n AlwaysGetsCalled()" }, { "answer_id": 11119, "author": "Nick", "author_id": 1236, "author_profile": "https://Stackoverflow.com/users/1236", "pm_score": 2, "selected": false, "text": "if (var == 1)\n doSomething();\ndoSomethingElse();\n if (var == 1)\n doSomething();\n doSomethingExtra();\ndoSomethingElse();\n" }, { "answer_id": 11120, "author": "Pascal Paradis", "author_id": 1291, "author_profile": "https://Stackoverflow.com/users/1291", "pm_score": 0, "selected": false, "text": "if (i != 0)\nbar(i);\nfoo(i);\n" }, { "answer_id": 11134, "author": "Baltimark", "author_id": 1179, "author_profile": "https://Stackoverflow.com/users/1179", "pm_score": 0, "selected": false, "text": "if (cond)\n {\n //statement\n }\n" }, { "answer_id": 11167, "author": "t3rse", "author_id": 64, "author_profile": "https://Stackoverflow.com/users/64", "pm_score": 0, "selected": false, "text": "if(!ok)return;\n if(!ok){\n\n do();\n\n that();\n\n thing();\n}\n" }, { "answer_id": 11283, "author": "James A. Rosen", "author_id": 1190, "author_profile": "https://Stackoverflow.com/users/1190", "pm_score": 1, "selected": false, "text": "do_something if (a == b)\n if (a == b)\n do_something\n do_something_else\nend\n" }, { "answer_id": 11542, "author": "Adam Lassek", "author_id": 1249, "author_profile": "https://Stackoverflow.com/users/1249", "pm_score": 1, "selected": false, "text": "if (a == b)\n DoSomething();\n DoSomethingElse(); <-- outside if statement\n if (a == b) DoSomething();\n var c = (a == b) ? DoSomething() : DoSomethingElse();\n var c = (a == b)\n ? AReallyReallyLongFunctionName()\n : AnotherReallyReallyLongFunctionOrStatement();\n" }, { "answer_id": 39418, "author": "Dewm Solo", "author_id": 4225, "author_profile": "https://Stackoverflow.com/users/4225", "pm_score": 2, "selected": false, "text": "\nIf A == true\n FunctA();\n\nIf B == \"Test\"\n{\n FunctB();\n}\n \nIf A == false {\n //calls and whatnot\n}\n//or\nIf B == \"BlaBla\"\n{\n //calls and whatnot\n}\n//or\nIf C == B\n {\n //calls and whatnot\n }\n" }, { "answer_id": 78060, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "if (condition) {\n statements;\n}\n\nif (condition) {\n statements;\n} else {\n statements;\n}\n\nif (condition) {\n statements;\n} else if (condition) {\n statements;\n} else {\n statements;\n}\n" }, { "answer_id": 85924, "author": "Brad Gilbert", "author_id": 1337, "author_profile": "https://Stackoverflow.com/users/1337", "pm_score": 0, "selected": false, "text": "do_something if condition;\n\ndo_something unless condition;\n sub test{\n my($self,@args) = @_;\n\n return undef unless defined $self;\n\n # rest of code goes here\n\n}\n" }, { "answer_id": 639794, "author": "David Thornley", "author_id": 14148, "author_profile": "https://Stackoverflow.com/users/14148", "pm_score": 0, "selected": false, "text": "if (condition) doThis();\n if (condition) {\n doThis();\n}\n" } ]
2008/08/14
[ "https://Stackoverflow.com/questions/11099", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1185/" ]
11,112
<p>Most wiki software I've presents lots of "features" on their pages. This is fine for desktop users, but is annoying when using an iPhone or other mobile device. <br /><br />I'd prefer pages that just had the content, along with maybe an Edit button and a Search button. The editors are also often too fancy for mobile users; a simple multi-line edit field would be better for mobile users than a bunch of formatting controls.</p> <p>What is a good wiki package for mobile users?</p>
[ { "answer_id": 11106, "author": "Jon Limjap", "author_id": 372, "author_profile": "https://Stackoverflow.com/users/372", "pm_score": 2, "selected": false, "text": "if (cond1)\n{\n SomeOperation();\n Another();\n}\nelseif (cond2)\n{\n DoSomething();\n}\nelse\n{\n DoNothing();\n DoAnother();\n}\n if (cond1)\n DoFirst();\nelseif (cond2)\n DoSecond();\nelse\n DoElse();\n foreach (var s as Something)\n if (s == someCondition)\n yield return SomeMethod(s);\n" }, { "answer_id": 11107, "author": "stimms", "author_id": 361, "author_profile": "https://Stackoverflow.com/users/361", "pm_score": 4, "selected": true, "text": "if ( a == b) {\n doSomething();\n}\nelse {\n doSomething();\n}\n" }, { "answer_id": 11110, "author": "Ryan Ahearn", "author_id": 75, "author_profile": "https://Stackoverflow.com/users/75", "pm_score": 1, "selected": false, "text": "if (aString) free(aString);\n" }, { "answer_id": 11116, "author": "ZombieSheep", "author_id": 377, "author_profile": "https://Stackoverflow.com/users/377", "pm_score": 3, "selected": false, "text": "if(a==b)\n{\n doSomething();\n}\n if(a==b)\n doSomething();\n doSomethingElse();\n if(a==b)\n{\n doSomething();\n doSomethingElse();\n}\n" }, { "answer_id": 11117, "author": "Kev", "author_id": 419, "author_profile": "https://Stackoverflow.com/users/419", "pm_score": 3, "selected": false, "text": "if(something)\n DoOneThing();\nelse\n DoItDifferently();\n else if(something)\n DoOneThing();\nelse\n DoItDifferently();\n AlwaysGetsCalled(); \n AlwaysGetsCalled()" }, { "answer_id": 11119, "author": "Nick", "author_id": 1236, "author_profile": "https://Stackoverflow.com/users/1236", "pm_score": 2, "selected": false, "text": "if (var == 1)\n doSomething();\ndoSomethingElse();\n if (var == 1)\n doSomething();\n doSomethingExtra();\ndoSomethingElse();\n" }, { "answer_id": 11120, "author": "Pascal Paradis", "author_id": 1291, "author_profile": "https://Stackoverflow.com/users/1291", "pm_score": 0, "selected": false, "text": "if (i != 0)\nbar(i);\nfoo(i);\n" }, { "answer_id": 11134, "author": "Baltimark", "author_id": 1179, "author_profile": "https://Stackoverflow.com/users/1179", "pm_score": 0, "selected": false, "text": "if (cond)\n {\n //statement\n }\n" }, { "answer_id": 11167, "author": "t3rse", "author_id": 64, "author_profile": "https://Stackoverflow.com/users/64", "pm_score": 0, "selected": false, "text": "if(!ok)return;\n if(!ok){\n\n do();\n\n that();\n\n thing();\n}\n" }, { "answer_id": 11283, "author": "James A. Rosen", "author_id": 1190, "author_profile": "https://Stackoverflow.com/users/1190", "pm_score": 1, "selected": false, "text": "do_something if (a == b)\n if (a == b)\n do_something\n do_something_else\nend\n" }, { "answer_id": 11542, "author": "Adam Lassek", "author_id": 1249, "author_profile": "https://Stackoverflow.com/users/1249", "pm_score": 1, "selected": false, "text": "if (a == b)\n DoSomething();\n DoSomethingElse(); <-- outside if statement\n if (a == b) DoSomething();\n var c = (a == b) ? DoSomething() : DoSomethingElse();\n var c = (a == b)\n ? AReallyReallyLongFunctionName()\n : AnotherReallyReallyLongFunctionOrStatement();\n" }, { "answer_id": 39418, "author": "Dewm Solo", "author_id": 4225, "author_profile": "https://Stackoverflow.com/users/4225", "pm_score": 2, "selected": false, "text": "\nIf A == true\n FunctA();\n\nIf B == \"Test\"\n{\n FunctB();\n}\n \nIf A == false {\n //calls and whatnot\n}\n//or\nIf B == \"BlaBla\"\n{\n //calls and whatnot\n}\n//or\nIf C == B\n {\n //calls and whatnot\n }\n" }, { "answer_id": 78060, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "if (condition) {\n statements;\n}\n\nif (condition) {\n statements;\n} else {\n statements;\n}\n\nif (condition) {\n statements;\n} else if (condition) {\n statements;\n} else {\n statements;\n}\n" }, { "answer_id": 85924, "author": "Brad Gilbert", "author_id": 1337, "author_profile": "https://Stackoverflow.com/users/1337", "pm_score": 0, "selected": false, "text": "do_something if condition;\n\ndo_something unless condition;\n sub test{\n my($self,@args) = @_;\n\n return undef unless defined $self;\n\n # rest of code goes here\n\n}\n" }, { "answer_id": 639794, "author": "David Thornley", "author_id": 14148, "author_profile": "https://Stackoverflow.com/users/14148", "pm_score": 0, "selected": false, "text": "if (condition) doThis();\n if (condition) {\n doThis();\n}\n" } ]
2008/08/14
[ "https://Stackoverflow.com/questions/11112", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1175/" ]
11,127
<p>In a C++ Windows (XP and NT, if it makes a difference) application I'm working on, I need to get the network name associated with the computer the code is executing on, so that I can convert local filenames from C:\filename.ext to \\network_name\C$\filename.ext. How would I do this?</p> <p>Alternatively, if there's a function that will just do the conversion I described, that would be even better. I looked into WNetGetUniversalName, but that doesn't seem to work with local (C drive) files.</p>
[ { "answer_id": 71343, "author": "jilles de wit", "author_id": 7531, "author_profile": "https://Stackoverflow.com/users/7531", "pm_score": 1, "selected": false, "text": "#include <winsock2.h> //of course this is the way to go on windows only\n\n#pragma comment(lib, \"Ws2_32.lib\")\n\nvoid GetHostName(std::string& host_name)\n{\n WSAData wsa_data;\n int ret_code;\n\n char buf[MAX_PATH];\n\n WSAStartup(MAKEWORD(1, 1), &wsa_data);\n ret_code = gethostname(buf, MAX_PATH);\n\n if (ret_code == SOCKET_ERROR)\n host_name = \"unknown\";\n else\n host_name = buf;\n\n\n WSACleanup();\n\n}\n" }, { "answer_id": 33008849, "author": "Ajay Gupta", "author_id": 2663073, "author_profile": "https://Stackoverflow.com/users/2663073", "pm_score": 1, "selected": false, "text": "GetComputerName BOOL WINAPI GetComputerName(\n _Out_ LPTSTR lpBuffer,\n _Inout_ LPDWORD lpnSize\n);\n GetComputerNameEx BOOL WINAPI GetComputerNameEx(\n _In_ COMPUTER_NAME_FORMAT NameType,\n _Out_ LPTSTR lpBuffer,\n _Inout_ LPDWORD lpnSize\n);\n" } ]
2008/08/14
[ "https://Stackoverflow.com/questions/11127", "https://Stackoverflow.com", "https://Stackoverflow.com/users/179/" ]
11,135
<p>I need to create an ASP page (classic, not ASP.NET) which runs remote shell scripts on a UNIX server, then captures the output into variables in VBScript within the page itself.</p> <p>I have never done ASP or VBScipt before. I have tried to google this stuff, but all I find are references to remote server side scripting, nothing concrete. </p> <p>I could really use:</p> <ol> <li>An elementary example of how this could be done.</li> <li>Any other better alternatives to achieve this in a secure manner.</li> </ol> <hr> <p>Are there any freeware/open source alternatives to these libraries? Any examples?</p>
[ { "answer_id": 71343, "author": "jilles de wit", "author_id": 7531, "author_profile": "https://Stackoverflow.com/users/7531", "pm_score": 1, "selected": false, "text": "#include <winsock2.h> //of course this is the way to go on windows only\n\n#pragma comment(lib, \"Ws2_32.lib\")\n\nvoid GetHostName(std::string& host_name)\n{\n WSAData wsa_data;\n int ret_code;\n\n char buf[MAX_PATH];\n\n WSAStartup(MAKEWORD(1, 1), &wsa_data);\n ret_code = gethostname(buf, MAX_PATH);\n\n if (ret_code == SOCKET_ERROR)\n host_name = \"unknown\";\n else\n host_name = buf;\n\n\n WSACleanup();\n\n}\n" }, { "answer_id": 33008849, "author": "Ajay Gupta", "author_id": 2663073, "author_profile": "https://Stackoverflow.com/users/2663073", "pm_score": 1, "selected": false, "text": "GetComputerName BOOL WINAPI GetComputerName(\n _Out_ LPTSTR lpBuffer,\n _Inout_ LPDWORD lpnSize\n);\n GetComputerNameEx BOOL WINAPI GetComputerNameEx(\n _In_ COMPUTER_NAME_FORMAT NameType,\n _Out_ LPTSTR lpBuffer,\n _Inout_ LPDWORD lpnSize\n);\n" } ]
2008/08/14
[ "https://Stackoverflow.com/questions/11135", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1311/" ]
11,145
<p>I am trying to code a flowchart generator for a language using Ruby. </p> <p>I wanted to know if there were any libraries that I could use to draw various shapes for the various flowchart elements and write out text to those shapes. </p> <p>I would really prefer not having to write code for drawing basic shapes, if I can help it. </p> <p>Can someone could point me to some reference documentation with examples of using that library?</p>
[ { "answer_id": 11191, "author": "Nathan Clark", "author_id": 1331, "author_profile": "https://Stackoverflow.com/users/1331", "pm_score": 2, "selected": false, "text": "draw.rectangle(x1, y1, x2, y2)\ndraw.polygon(x1, y1,...,xN, yN)\n" }, { "answer_id": 12120, "author": "Mike Woodhouse", "author_id": 1060, "author_profile": "https://Stackoverflow.com/users/1060", "pm_score": 3, "selected": true, "text": "gem install ruby-graphviz" }, { "answer_id": 388911, "author": "rampion", "author_id": 9859, "author_profile": "https://Stackoverflow.com/users/9859", "pm_score": 4, "selected": false, "text": "graph {\n A -- B -- C;\n B -- D;\n C -- D [constraint=false];\n}\n digraph {\n A [label=\"start\"];\n B [label=\"eat\"];\n C [label=\"drink\"];\n D [label=\"be merry\"];\n\n A -> B -> C;\n C -> D [constraint=false];\n B -> D [ arrowhead=none, arrowtail=normal]; // reverse this edge\n}\n" } ]
2008/08/14
[ "https://Stackoverflow.com/questions/11145", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1311/" ]
11,194
<p>We're working on a Log Viewer. The use will have the option to filter by user, severity, etc. In the Sql days I'd add to the query string, but I want to do it with Linq. How can I conditionally add where-clauses?</p>
[ { "answer_id": 11201, "author": "TheSmurf", "author_id": 1975282, "author_profile": "https://Stackoverflow.com/users/1975282", "pm_score": 0, "selected": false, "text": "var items = dc.Users.Where(l => l.Date == DateTime.Today && l.Severity == \"Critical\")\n" }, { "answer_id": 11203, "author": "Darren Kopp", "author_id": 77, "author_profile": "https://Stackoverflow.com/users/77", "pm_score": 8, "selected": true, "text": "var logs = from log in context.Logs\n select log;\n\nif (filterBySeverity)\n logs = logs.Where(p => p.Severity == severity);\n\nif (filterByUser)\n logs = logs.Where(p => p.User == user);\n" }, { "answer_id": 11204, "author": "Keith", "author_id": 905, "author_profile": "https://Stackoverflow.com/users/905", "pm_score": 0, "selected": false, "text": "var results =\n from rec in GetSomeRecs()\n where ConditionalCheck(rec)\n select rec;\n\n...\n\nbool ConditionalCheck( typeofRec input ) {\n ...\n}\n var results =\n from rec in GetSomeRecs()\n where \n (!filterBySeverity || rec.Severity == severity) &&\n (!filterByUser|| rec.User == user)\n select rec;\n" }, { "answer_id": 11225, "author": "Jon Limjap", "author_id": 372, "author_profile": "https://Stackoverflow.com/users/372", "pm_score": 0, "selected": false, "text": " var list = new List<string> { \"me\", \"you\", \"meyou\", \"mow\" };\n\n var predicates = new List<Predicate<string>>();\n\n predicates.Add(i => i.Contains(\"me\"));\n predicates.Add(i => i.EndsWith(\"w\"));\n\n var results = new List<string>();\n\n foreach (var p in predicates)\n results.AddRange(from i in list where p.Invoke(i) select i); \n" }, { "answer_id": 11729, "author": "Lars Mæhlum", "author_id": 960, "author_profile": "https://Stackoverflow.com/users/960", "pm_score": 4, "selected": false, "text": "public static IQueryable<Type> HasID(this IQueryable<Type> query, long? id)\n{\n return id.HasValue ? query.Where(o => i.ID.Equals(id.Value)) : query;\n}\n" }, { "answer_id": 11769, "author": "Brad Leach", "author_id": 708, "author_profile": "https://Stackoverflow.com/users/708", "pm_score": 2, "selected": false, "text": "var newKids = Product.ContainsInDescription (\"BlackBerry\", \"iPhone\");\n\nvar classics = Product.ContainsInDescription (\"Nokia\", \"Ericsson\")\n .And (Product.IsSelling());\n\nvar query = from p in Data.Products.Where (newKids.Or (classics))\n select p;\n" }, { "answer_id": 14560, "author": "Andy Rose", "author_id": 1762, "author_profile": "https://Stackoverflow.com/users/1762", "pm_score": 1, "selected": false, "text": "var query =\ndb.Customers.\nWhere(\"City = @0 and Orders.Count >= @1\", \"London\", 10).\nOrderBy(\"CompanyName\").\nSelect(\"new(CompanyName as Name, Phone)\");\n string dynamicQueryString = \"City = \\\"London\\\" and Order.Count >= 10\"; \nvar q = from c in db.Customers.Where(queryString, null)\n orderby c.CompanyName\n select c;\n" }, { "answer_id": 19950, "author": "sgwill", "author_id": 1204, "author_profile": "https://Stackoverflow.com/users/1204", "pm_score": 4, "selected": false, "text": "IQueryable<Log> matches = m_Locator.Logs;\n\n// Users filter\nif (usersFilter)\n matches = matches.Where(l => l.UserName == comboBoxUsers.Text);\n\n // Severity filter\n if (severityFilter)\n matches = matches.Where(l => l.Severity == comboBoxSeverity.Text);\n\n Logs = (from log in matches\n orderby log.EventTime descending\n select log).ToList();\n" }, { "answer_id": 5941594, "author": "Carlos", "author_id": 745725, "author_profile": "https://Stackoverflow.com/users/745725", "pm_score": 5, "selected": false, "text": " public List<Data> GetData(List<string> Numbers, List<string> Letters)\n {\n if (Numbers == null)\n Numbers = new List<string>();\n\n if (Letters == null)\n Letters = new List<string>();\n\n var q = from d in database.table\n where (Numbers.Count == 0 || Numbers.Contains(d.Number))\n where (Letters.Count == 0 || Letters.Contains(d.Letter))\n select new Data\n {\n Number = d.Number,\n Letter = d.Letter,\n };\n return q.ToList();\n\n }\n" }, { "answer_id": 6330322, "author": "James Livingston", "author_id": 145966, "author_profile": "https://Stackoverflow.com/users/145966", "pm_score": 3, "selected": false, "text": "bool lastNameSearch = true/false; // depending if they want to search by last name,\n where where (lastNameSearch && name.LastNameSearch == \"smith\")\n lastNameSearch false" }, { "answer_id": 51278965, "author": "Ryan", "author_id": 2266345, "author_profile": "https://Stackoverflow.com/users/2266345", "pm_score": 4, "selected": false, "text": "if .If() public static IQueryable<TSource> If<TSource>(\n this IQueryable<TSource> source,\n bool condition,\n Func<IQueryable<TSource>, IQueryable<TSource>> branch)\n {\n return condition ? branch(source) : source;\n }\n return context.Logs\n .If(filterBySeverity, q => q.Where(p => p.Severity == severity))\n .If(filterByUser, q => q.Where(p => p.User == user))\n .ToList();\n IEnumerable<T> public static IEnumerable<TSource> If<TSource>(\n this IEnumerable<TSource> source,\n bool condition,\n Func<IEnumerable<TSource>, IEnumerable<TSource>> branch)\n {\n return condition ? branch(source) : source;\n }\n" }, { "answer_id": 55732512, "author": "Gustavo", "author_id": 6672759, "author_profile": "https://Stackoverflow.com/users/6672759", "pm_score": 1, "selected": false, "text": "public static IQueryable<TSource> WhereIf<TSource>(this IQueryable<TSource> source, bool isToExecute, Expression<Func<TSource, bool>> predicate)\n{\n return isToExecute ? source.Where(predicate) : source;\n}\n" } ]
2008/08/14
[ "https://Stackoverflow.com/questions/11194", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1204/" ]
11,200
<p>I'm guessing it needs to be something like:</p> <pre><code>CONVERT(CHAR(24), lastModified, 101) </code></pre> <p>However I'm not sure of the right value for the third parameter.</p> <p>Thanks!</p> <hr> <p>Well I'm trying to write a script to copy my sql server db to a sqlite file, which gets downloaded to an air app, which then syncs the data to another sqlite file. I'm having a ton of trouble with dates. If I select a date in air and try to insert it, it fails because it's not in the right format... even if it was a valid date to begin with. I figured I'd try to experiment with the unix time since that's the only thing thats worked so far. I am considering just leaving them as varchar because I don't sort by them anyway.</p>
[ { "answer_id": 11216, "author": "SQLMenace", "author_id": 740, "author_profile": "https://Stackoverflow.com/users/740", "pm_score": 2, "selected": false, "text": "SELECT DATEDIFF(s,'19700101 05:00:00:000',lastModified)\n" }, { "answer_id": 11234, "author": "SQLMenace", "author_id": 740, "author_profile": "https://Stackoverflow.com/users/740", "pm_score": 0, "selected": false, "text": " select convert(varchar(10),getdate(),112)\n select convert(varchar(30),getdate(),126)\n" }, { "answer_id": 11240, "author": "Shawn", "author_id": 26, "author_profile": "https://Stackoverflow.com/users/26", "pm_score": 2, "selected": true, "text": "convert(char(24), lastModified, 120)\n strftime(\\\"%Y-%m-%d %H:%M:%S\\\", dateModified) as dateModified\n" } ]
2008/08/14
[ "https://Stackoverflow.com/questions/11200", "https://Stackoverflow.com", "https://Stackoverflow.com/users/26/" ]
11,219
<p>I'd like to start moving our application business layers into a collection of REST web services. However, most of our Intranet has been built using Classic ASP and most of the developers where I work keep programming in Classic ASP. Ideally, then, for them to benefit from the advantages of a unique set of web APIs, it would have to be called from Classic ASP pages.</p> <p>I haven't the slightest idea how to do that. </p>
[ { "answer_id": 11238, "author": "KP.", "author_id": 439, "author_profile": "https://Stackoverflow.com/users/439", "pm_score": 6, "selected": true, "text": "Set HttpReq = Server.CreateObject(\"MSXML2.ServerXMLHTTP\")\nHttpReq.open \"GET\", \"Rest_URI\", False\nHttpReq.send\n" }, { "answer_id": 11251, "author": "Kev", "author_id": 419, "author_profile": "https://Stackoverflow.com/users/419", "pm_score": 3, "selected": false, "text": "MSXML2.ServerXMLHTTP XMLHTTP" } ]
2008/08/14
[ "https://Stackoverflow.com/questions/11219", "https://Stackoverflow.com", "https://Stackoverflow.com/users/160/" ]
11,279
<p>I have a small VB.NET application that I'm working on using the full version of Visual Studio 2005. In the <strong>Publish</strong> properties of the project, I have it set to <em>Automatically increment revision with each publish</em>.</p> <p>The issue is that it's only incrementing the revision in the Setup files. It doesn't seem to be updating the version number in the About Box (which is the generic, built-in, About Box template). That version number seems to be coming from <em>My.Application.Info.Version</em>.</p> <p>What should I be using instead so that my automatically incrementing revision number shows up in the about box?</p>
[ { "answer_id": 11297, "author": "Stu", "author_id": 414, "author_profile": "https://Stackoverflow.com/users/414", "pm_score": 2, "selected": true, "text": "Me.LabelVersion.Text = String.Format(\"Version {0}\", My.Application.Deployment.CurrentVersion.ToString)\n" }, { "answer_id": 11304, "author": "rjzii", "author_id": 1185, "author_profile": "https://Stackoverflow.com/users/1185", "pm_score": 1, "selected": false, "text": "using System;\nusing System.Reflection;\npublic class VersionNumber\n{\n public static void Main()\n {\n System.Reflection.Assembly assembly = System.Reflection.Assembly.GetExecutingAssembly();\n Version version = assembly.GetName().Version;\n Console.WriteLine (\"Version: {0}\", version);\n Console.WriteLine (\"Major: {0}\", version.Major);\n Console.WriteLine (\"Minor: {0}\", version.Minor);\n Console.WriteLine (\"Build: {0}\", version.Build);\n Console.WriteLine (\"Revision: {0}\", version.Revision);\n Console.Read();\n }\n}\n" } ]
2008/08/14
[ "https://Stackoverflow.com/questions/11279", "https://Stackoverflow.com", "https://Stackoverflow.com/users/305/" ]
11,288
<p>So WPF doesn't support standard sorting or filtering behavior for views of CompositeCollections, so what would be a best practice for solving this problem. </p> <p>There are two or more object collections of different types. You want to combine them into a single sortable and filterable collection (withing having to manually implement sort or filter).</p> <p>One of the approaches I've considered is to create a new object collection with only a few core properties, including the ones that I would want the collection sorted on, and an object instance of each type. </p> <pre><code>class MyCompositeObject { enum ObjectType; DateTime CreatedDate; string SomeAttribute; myObjectType1 Obj1; myObjectType2 Obj2; { class MyCompositeObjects : List&lt;MyCompositeObject&gt; { } </code></pre> <p>And then loop through my two object collections to build the new composite collection. Obviously this is a bit of a brute force method, but it would work. I'd get all the default view sorting and filtering behavior on my new composite object collection, and I'd be able to put a data template on it to display my list items properly depending on which type is actually stored in that composite item.</p> <p>What suggestions are there for doing this in a more elegant way?</p>
[ { "answer_id": 11297, "author": "Stu", "author_id": 414, "author_profile": "https://Stackoverflow.com/users/414", "pm_score": 2, "selected": true, "text": "Me.LabelVersion.Text = String.Format(\"Version {0}\", My.Application.Deployment.CurrentVersion.ToString)\n" }, { "answer_id": 11304, "author": "rjzii", "author_id": 1185, "author_profile": "https://Stackoverflow.com/users/1185", "pm_score": 1, "selected": false, "text": "using System;\nusing System.Reflection;\npublic class VersionNumber\n{\n public static void Main()\n {\n System.Reflection.Assembly assembly = System.Reflection.Assembly.GetExecutingAssembly();\n Version version = assembly.GetName().Version;\n Console.WriteLine (\"Version: {0}\", version);\n Console.WriteLine (\"Major: {0}\", version.Major);\n Console.WriteLine (\"Minor: {0}\", version.Minor);\n Console.WriteLine (\"Build: {0}\", version.Build);\n Console.WriteLine (\"Revision: {0}\", version.Revision);\n Console.Read();\n }\n}\n" } ]
2008/08/14
[ "https://Stackoverflow.com/questions/11288", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1346/" ]
11,291
<p>I'm slowly learning Objective-C and Cocoa, and the only way I see so far to capture key events in Text Views is to use delegation, but I'm having trouble finding useful documentation and examples on how to implement such a solution. Can anyone point me in the right direction or supply some first-hand help? </p>
[ { "answer_id": 11312, "author": "TheSmurf", "author_id": 1975282, "author_profile": "https://Stackoverflow.com/users/1975282", "pm_score": 5, "selected": true, "text": "- (void)keyUp:(NSEvent *)theEvent\n" }, { "answer_id": 12874, "author": "Brian Warshaw", "author_id": 1344, "author_profile": "https://Stackoverflow.com/users/1344", "pm_score": 1, "selected": false, "text": "- (void)textDidChange:(NSNotification *)aNotification;\n" }, { "answer_id": 13088, "author": "alextgordon", "author_id": 1165750, "author_profile": "https://Stackoverflow.com/users/1165750", "pm_score": 3, "selected": false, "text": "NSRect visibleRect = [[[textView enclosingScrollView] contentView] documentVisibleRect];\nNSRange visibleRange = [[textView layoutManager] glyphRangeForBoundingRect:visibleRect inTextContainer:[textView textContainer]];\n" } ]
2008/08/14
[ "https://Stackoverflow.com/questions/11291", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1344/" ]
11,305
<p>I work in VBA, and want to parse a string eg</p> <pre><code>&lt;PointN xsi:type='typens:PointN' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' xmlns:xs='http://www.w3.org/2001/XMLSchema'&gt; &lt;X&gt;24.365&lt;/X&gt; &lt;Y&gt;78.63&lt;/Y&gt; &lt;/PointN&gt; </code></pre> <p>and get the X &amp; Y values into two separate integer variables.</p> <p>I'm a newbie when it comes to XML, since I'm stuck in VB6 and VBA, because of the field I work in.</p> <p>How do I do this?</p>
[ { "answer_id": 11406, "author": "Devdatta Tengshe", "author_id": 895, "author_profile": "https://Stackoverflow.com/users/895", "pm_score": 6, "selected": false, "text": "Dim objXML As MSXML2.DOMDocument\n\nSet objXML = New MSXML2.DOMDocument\n\nIf Not objXML.loadXML(strXML) Then 'strXML is the string with XML'\n Err.Raise objXML.parseError.ErrorCode, , objXML.parseError.reason\nEnd If\n \nDim point As IXMLDOMNode\nSet point = objXML.firstChild\n\nDebug.Print point.selectSingleNode(\"X\").Text\nDebug.Print point.selectSingleNode(\"Y\").Text\n" }, { "answer_id": 2796385, "author": "DK.", "author_id": 336474, "author_profile": "https://Stackoverflow.com/users/336474", "pm_score": 3, "selected": false, "text": "Sub debugPrintOPML()\n\n' http://msdn.microsoft.com/en-us/library/ms763720(v=VS.85).aspx\n' http://msdn.microsoft.com/en-us/library/system.xml.xmlnode.selectnodes.aspx\n' http://msdn.microsoft.com/en-us/library/ms256086(v=VS.85).aspx ' expressions\n' References: Microsoft XML\n\nDim xmldoc As New DOMDocument60\nDim oNodeList As IXMLDOMSelection\nDim oNodeList2 As IXMLDOMSelection\nDim curNode As IXMLDOMNode\nDim n As Long, n2 As Long, x As Long\n\nDim strXPathQuery As String\nDim attrLength As Byte\nDim FilePath As String\n\nFilePath = \"rss.opml\"\n\nxmldoc.Load CurrentProject.Path & \"\\\" & FilePath\n\nstrXPathQuery = \"opml/body/outline\"\nSet oNodeList = xmldoc.selectNodes(strXPathQuery)\n\nFor n = 0 To (oNodeList.length - 1)\n Set curNode = oNodeList.Item(n)\n attrLength = curNode.Attributes.length\n If attrLength > 1 Then ' or 2 or 3\n Call processNode(curNode)\n Else\n Call processNode(curNode)\n strXPathQuery = \"opml/body/outline[position() = \" & n + 1 & \"]/outline\"\n Set oNodeList2 = xmldoc.selectNodes(strXPathQuery)\n For n2 = 0 To (oNodeList2.length - 1)\n Set curNode = oNodeList2.Item(n2)\n Call processNode(curNode)\n Next\n End If\n Debug.Print \"----------------------\"\nNext\n\nSet xmldoc = Nothing\n\nEnd Sub\n\nSub processNode(curNode As IXMLDOMNode)\n\nDim sAttrName As String\nDim sAttrValue As String\nDim attrLength As Byte\nDim x As Long\n\nattrLength = curNode.Attributes.length\n\nFor x = 0 To (attrLength - 1)\n sAttrName = curNode.Attributes.Item(x).nodeName\n sAttrValue = curNode.Attributes.Item(x).nodeValue\n Debug.Print sAttrName & \" = \" & sAttrValue\nNext\n Debug.Print \"-----------\"\n\nEnd Sub\n ...\nCall xmldocOpen4\nCall debugPrintOPML4(Null)\n...\n\nDim sText4 As String\n\nSub debugPrintOPML4(strXPathQuery As Variant)\n\nDim xmldoc4 As New DOMDocument60\n'Dim xmldoc4 As New MSXML2.DOMDocument60 ' ?\nDim oNodeList As IXMLDOMSelection\nDim curNode As IXMLDOMNode\nDim n4 As Long\n\nIf IsNull(strXPathQuery) Then strXPathQuery = \"opml/body/outline\"\n\n' http://msdn.microsoft.com/en-us/library/ms754585(v=VS.85).aspx\nxmldoc4.async = False\nxmldoc4.loadXML sText4\nIf (xmldoc4.parseError.errorCode <> 0) Then\n Dim myErr\n Set myErr = xmldoc4.parseError\n MsgBox (\"You have error \" & myErr.reason)\nElse\n' MsgBox xmldoc4.xml\nEnd If\n\nSet oNodeList = xmldoc4.selectNodes(strXPathQuery)\n\nFor n4 = 0 To (oNodeList.length - 1)\n Set curNode = oNodeList.Item(n4)\n Call processNode4(strXPathQuery, curNode, n4)\nNext\n\nSet xmldoc4 = Nothing\n\nEnd Sub\n\nSub processNode4(strXPathQuery As Variant, curNode As IXMLDOMNode, n4 As Long)\n\nDim sAttrName As String\nDim sAttrValue As String\nDim x As Long\n\nFor x = 0 To (curNode.Attributes.length - 1)\n sAttrName = curNode.Attributes.Item(x).nodeName\n sAttrValue = curNode.Attributes.Item(x).nodeValue\n 'If sAttrName = \"text\"\n Debug.Print strXPathQuery & \" :: \" & sAttrName & \" = \" & sAttrValue\n 'End If\nNext\n Debug.Print \"\"\n\nIf curNode.childNodes.length > 0 Then\n Call debugPrintOPML4(strXPathQuery & \"[position() = \" & n4 + 1 & \"]/\" & curNode.nodeName)\nEnd If\n\nEnd Sub\n\nSub xmldocOpen4()\n\nDim oFSO As New FileSystemObject ' Microsoft Scripting Runtime Reference\nDim oFS\nDim FilePath As String\n\nFilePath = \"rss_awasu.opml\"\nSet oFS = oFSO.OpenTextFile(CurrentProject.Path & \"\\\" & FilePath)\nsText4 = oFS.ReadAll\noFS.Close\n\nEnd Sub\n Sub xmldocOpen4()\n\nDim FilePath As String\n\nFilePath = \"rss.opml\"\n\n' function ConvertUTF8File(sUTF8File):\n' http://www.vbmonster.com/Uwe/Forum.aspx/vb/24947/How-to-read-UTF-8-chars-using-VBA\n' loading and conversion from Utf-8 to UTF\nsText8 = ConvertUTF8File(CurrentProject.Path & \"\\\" & FilePath)\n\nEnd Sub\n" }, { "answer_id": 5747032, "author": "Tommie C.", "author_id": 608991, "author_profile": "https://Stackoverflow.com/users/608991", "pm_score": 2, "selected": false, "text": "Public Sub LoadDocument()\n Dim xDoc As MSXML.DOMDocument\n Set xDoc = New MSXML.DOMDocument\n xDoc.validateOnParse = False\n If xDoc.Load(\"C:\\My Documents\\sample.xml\") Then\n ' The document loaded successfully.\n ' Now do something intersting.\n DisplayNode xDoc.childNodes, 0\n Else\n ' The document failed to load.\n ' See the previous listing for error information.\n End If\nEnd Sub\n\nPublic Sub DisplayNode(ByRef Nodes As MSXML.IXMLDOMNodeList, _\n ByVal Indent As Integer)\n\n Dim xNode As MSXML.IXMLDOMNode\n Indent = Indent + 2\n\n For Each xNode In Nodes\n If xNode.nodeType = NODE_TEXT Then\n Debug.Print Space$(Indent) & xNode.parentNode.nodeName & _\n \":\" & xNode.nodeValue\n End If\n\n If xNode.hasChildNodes Then\n DisplayNode xNode.childNodes, Indent\n End If\n Next xNode\nEnd Sub\n \nopenTag = \"\"\ncloseTag = \"\" \n' Locate the position of the enclosing tags\nstartPos = InStr(1, temp, openTag)\nendPos = InStr(1, temp, closeTag)\nstartTagPos = InStr(startPos, temp, \">\") + 1\n' Parse xml for returned value\nData = Mid(temp, startTagPos, endPos - startTagPos)\n" }, { "answer_id": 27704551, "author": "mvanle", "author_id": 1213722, "author_profile": "https://Stackoverflow.com/users/1213722", "pm_score": 4, "selected": false, "text": "Dim objDom As Object '// DOMDocument\nDim xmlStr As String, _\n xPath As String\n\nxmlStr = _\n \"<PointN xsi:type='typens:PointN' \" & _\n \"xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' \" & _\n \"xmlns:xs='http://www.w3.org/2001/XMLSchema'> \" & _\n \" <X>24.365</X> \" & _\n \" <Y>78.63</Y> \" & _\n \"</PointN>\"\n\nSet objDom = CreateObject(\"Msxml2.DOMDocument.3.0\") '// Using MSXML 3.0\n\n'/* Load XML */\nobjDom.LoadXML xmlStr\n\n'/*\n' * XPath Query\n' */ \n\n'/* Get X */\nxPath = \"/PointN/X\"\nDebug.Print objDom.SelectSingleNode(xPath).text\n\n'/* Get Y */\nxPath = \"/PointN/Y\"\nDebug.Print objDom.SelectSingleNode(xPath).text\n" }, { "answer_id": 27908457, "author": "Bob Wheatley", "author_id": 4446538, "author_profile": "https://Stackoverflow.com/users/4446538", "pm_score": 2, "selected": false, "text": "'location of triforma structural files\n'c:\\programdata\\bentley\\workspace\\triforma\\tf_imperial\\data\\us.xml\n\nSub ReadTriformaImperialData()\nDim txtFileName As String\nDim txtFileLine As String\nDim txtFileNumber As Long\n\nDim Shape As String\nShape = \"w12x40\"\n\ntxtFileNumber = FreeFile\ntxtFileName = \"c:\\programdata\\bentley\\workspace\\triforma\\tf_imperial\\data\\us.xml\"\n\nOpen txtFileName For Input As #txtFileNumber\n\nDo While Not EOF(txtFileNumber)\nLine Input #txtFileNumber, txtFileLine\n If InStr(1, UCase(txtFileLine), UCase(Shape)) Then\n P1 = InStr(1, UCase(txtFileLine), \"D=\")\n D = Val(Mid(txtFileLine, P1 + 3))\n\n P2 = InStr(1, UCase(txtFileLine), \"TW=\")\n TW = Val(Mid(txtFileLine, P2 + 4))\n\n P3 = InStr(1, UCase(txtFileLine), \"WIDTH=\")\n W = Val(Mid(txtFileLine, P3 + 7))\n\n P4 = InStr(1, UCase(txtFileLine), \"TF=\")\n TF = Val(Mid(txtFileLine, P4 + 4))\n\n Close txtFileNumber\n Exit Do\n End If\nLoop\nEnd Sub\n" }, { "answer_id": 33103998, "author": "No Name", "author_id": 1188613, "author_profile": "https://Stackoverflow.com/users/1188613", "pm_score": 4, "selected": false, "text": " Dim xml As String\n\n xml = \"<root><person><name>Me </name> </person> <person> <name>No Name </name></person></root> \"\n Dim oXml As MSXML2.DOMDocument60\n Set oXml = New MSXML2.DOMDocument60\n oXml.loadXML xml\n Dim oSeqNodes, oSeqNode As IXMLDOMNode\n\n Set oSeqNodes = oXml.selectNodes(\"//root/person\")\n If oSeqNodes.length = 0 Then\n 'show some message\n Else\n For Each oSeqNode In oSeqNodes\n Debug.Print oSeqNode.selectSingleNode(\"name\").Text\n Next\n End If \n" }, { "answer_id": 40899195, "author": "TJ Wilkinson", "author_id": 6813795, "author_profile": "https://Stackoverflow.com/users/6813795", "pm_score": 0, "selected": false, "text": "Cell A1: {your XML here}\nCell B1: <X>\nCell C1: </X>\nCell D1: =REPLACE(A1,1,FIND(A2,A1)+LEN(A2)-1,\"\")\nCell E1: =REPLACE(A4,FIND(A3,A4),LEN(A4)-FIND(A3,A4)+1,\"\")\n Cell A1: {your XML here}\nCell B1: <X>\nCell C1: </X>\nCell D1: 24.365<X><Y>78.68</Y></PointN>\nCell E1: 24.365\n" } ]
2008/08/14
[ "https://Stackoverflow.com/questions/11305", "https://Stackoverflow.com", "https://Stackoverflow.com/users/895/" ]
11,311
<p>Is it possible to format certain text in a WinForm Label instead of breaking the text into multiple labels? Please disregard the HTML tags within the label's text; it's only used to get my point out.</p> <p>For example:</p> <pre><code>Dim myLabel As New Label myLabel.Text = "This is &lt;b&gt;bold&lt;/b&gt; text. This is &lt;i&gt;italicized&lt;/i&gt; text." </code></pre> <p>Which would produce the text in the label as:</p> <blockquote> <p>This is <strong>bold</strong> text. This is <em>italicized</em> text.</p> </blockquote>
[ { "answer_id": 24207716, "author": "Geoff", "author_id": 55487, "author_profile": "https://Stackoverflow.com/users/55487", "pm_score": 4, "selected": false, "text": "Links.Add() linkLabel1.Text = \"You are accessing a government system, and all activity \" +\n \"will be logged. If you do not wish to continue, log out now.\";\nlinkLabel1.AutoSize = false;\nlinkLabel1.Size = new Size(365, 50);\nlinkLabel1.TextAlign = ContentAlignment.MiddleCenter;\nlinkLabel1.Links.Clear();\nlinkLabel1.Links.Add(20, 17).Enabled = false; // \"government system\"\nlinkLabel1.Links.Add(105, 11).Enabled = false; // \"log out now\"\nlinkLabel1.LinkColor = linkLabel1.ForeColor;\nlinkLabel1.DisabledLinkColor = linkLabel1.ForeColor;\n" }, { "answer_id": 28728824, "author": "Nigrimmist", "author_id": 1151741, "author_profile": "https://Stackoverflow.com/users/1151741", "pm_score": 4, "selected": false, "text": "public class RichTextLabel : RichTextBox\n{\n public RichTextLabel()\n {\n base.ReadOnly = true;\n base.BorderStyle = BorderStyle.None;\n base.TabStop = false;\n base.SetStyle(ControlStyles.Selectable, false);\n base.SetStyle(ControlStyles.UserMouse, true);\n base.SetStyle(ControlStyles.SupportsTransparentBackColor, true);\n\n base.MouseEnter += delegate(object sender, EventArgs e)\n {\n this.Cursor = Cursors.Default;\n };\n }\n\n protected override void WndProc(ref Message m)\n {\n if (m.Msg == 0x204) return; // WM_RBUTTONDOWN\n if (m.Msg == 0x205) return; // WM_RBUTTONUP\n base.WndProc(ref m);\n }\n}\n private void AutocompleteItemControl_Load(object sender, EventArgs e)\n {\n RichTextLabel rtl = new RichTextLabel();\n rtl.Font = new Font(\"MS Reference Sans Serif\", 15.57F);\n StringBuilder sb = new StringBuilder();\n sb.Append(@\"{\\rtf1\\ansi \");\n foreach (var wordPart in wordParts)\n {\n if (wordPart.IsSelected)\n {\n sb.Append(@\"\\b \");\n }\n sb.Append(ConvertString2RTF(wordPart.WordPart));\n if (wordPart.IsSelected)\n {\n sb.Append(@\"\\b0 \");\n }\n }\n sb.Append(@\"}\");\n\n rtl.Rtf = sb.ToString();\n rtl.Width = this.Width;\n this.Controls.Add(rtl);\n }\n private string ConvertString2RTF(string input)\n {\n //first take care of special RTF chars\n StringBuilder backslashed = new StringBuilder(input);\n backslashed.Replace(@\"\\\", @\"\\\\\");\n backslashed.Replace(@\"{\", @\"\\{\");\n backslashed.Replace(@\"}\", @\"\\}\");\n\n //then convert the string char by char\n StringBuilder sb = new StringBuilder();\n foreach (char character in backslashed.ToString())\n {\n if (character <= 0x7f)\n sb.Append(character);\n else\n sb.Append(\"\\\\u\" + Convert.ToUInt32(character) + \"?\");\n }\n return sb.ToString();\n }\n" }, { "answer_id": 33211471, "author": "Martin Braun", "author_id": 1540350, "author_profile": "https://Stackoverflow.com/users/1540350", "pm_score": 2, "selected": false, "text": "UserControl TransparentRichTextBox TransparentRichTextBox RichTextBox public class TransparentRichTextBox : RichTextBox\n{\n [DllImport(\"kernel32.dll\", CharSet = CharSet.Auto)]\n static extern IntPtr LoadLibrary(string lpFileName);\n\n protected override CreateParams CreateParams\n {\n get\n {\n CreateParams prams = base.CreateParams;\n if (TransparentRichTextBox.LoadLibrary(\"msftedit.dll\") != IntPtr.Zero)\n {\n prams.ExStyle |= 0x020; // transparent \n prams.ClassName = \"RICHEDIT50W\";\n }\n return prams;\n }\n }\n}\n UserControl TransparentRichTextBox AutoSize AutoSize RichTextBox partial class AutoRichLabel\n{\n /// <summary> \n /// Required designer variable.\n /// </summary>\n private System.ComponentModel.IContainer components = null;\n\n /// <summary> \n /// Clean up any resources being used.\n /// </summary>\n /// <param name=\"disposing\">true if managed resources should be disposed; otherwise, false.</param>\n protected override void Dispose(bool disposing)\n {\n if (disposing && (components != null))\n {\n components.Dispose();\n }\n base.Dispose(disposing);\n }\n\n #region Component Designer generated code\n\n /// <summary> \n /// Required method for Designer support - do not modify \n /// the contents of this method with the code editor.\n /// </summary>\n private void InitializeComponent()\n {\n this.rtb = new TransparentRichTextBox();\n this.SuspendLayout();\n // \n // rtb\n // \n this.rtb.BorderStyle = System.Windows.Forms.BorderStyle.None;\n this.rtb.Dock = System.Windows.Forms.DockStyle.Fill;\n this.rtb.Location = new System.Drawing.Point(0, 0);\n this.rtb.Margin = new System.Windows.Forms.Padding(0);\n this.rtb.Name = \"rtb\";\n this.rtb.ReadOnly = true;\n this.rtb.ScrollBars = System.Windows.Forms.RichTextBoxScrollBars.None;\n this.rtb.Size = new System.Drawing.Size(46, 30);\n this.rtb.TabIndex = 0;\n this.rtb.Text = \"\";\n this.rtb.WordWrap = false;\n this.rtb.ContentsResized += new System.Windows.Forms.ContentsResizedEventHandler(this.rtb_ContentsResized);\n // \n // AutoRichLabel\n // \n this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);\n this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;\n this.AutoSizeMode = System.Windows.Forms.AutoSizeMode.GrowAndShrink;\n this.BackColor = System.Drawing.Color.Transparent;\n this.Controls.Add(this.rtb);\n this.Name = \"AutoRichLabel\";\n this.Size = new System.Drawing.Size(46, 30);\n this.ResumeLayout(false);\n\n }\n\n #endregion\n\n private TransparentRichTextBox rtb;\n}\n /// <summary>\n/// <para>An auto sized label with the ability to display text with formattings by using the Rich Text Format.</para>\n/// <para>­</para>\n/// <para>Short RTF syntax examples: </para>\n/// <para>­</para>\n/// <para>Paragraph: </para>\n/// <para>{\\pard This is a paragraph!\\par}</para>\n/// <para>­</para>\n/// <para>Bold / Italic / Underline: </para>\n/// <para>\\b bold text\\b0</para>\n/// <para>\\i italic text\\i0</para>\n/// <para>\\ul underline text\\ul0</para>\n/// <para>­</para>\n/// <para>Alternate color using color table: </para>\n/// <para>{\\colortbl ;\\red0\\green77\\blue187;}{\\pard The word \\cf1 fish\\cf0 is blue.\\par</para>\n/// <para>­</para>\n/// <para>Additional information: </para>\n/// <para>Always wrap every text in a paragraph. </para>\n/// <para>Different tags can be stacked (i.e. \\pard\\b\\i Bold and Italic\\i0\\b0\\par)</para>\n/// <para>The space behind a tag is ignored. So if you need a space behind it, insert two spaces (i.e. \\pard The word \\bBOLD\\0 is bold.\\par)</para>\n/// <para>Full specification: http://www.biblioscape.com/rtf15_spec.htm </para>\n/// </summary>\npublic partial class AutoRichLabel : UserControl\n{\n /// <summary>\n /// The rich text content. \n /// <para>­</para>\n /// <para>Short RTF syntax examples: </para>\n /// <para>­</para>\n /// <para>Paragraph: </para>\n /// <para>{\\pard This is a paragraph!\\par}</para>\n /// <para>­</para>\n /// <para>Bold / Italic / Underline: </para>\n /// <para>\\b bold text\\b0</para>\n /// <para>\\i italic text\\i0</para>\n /// <para>\\ul underline text\\ul0</para>\n /// <para>­</para>\n /// <para>Alternate color using color table: </para>\n /// <para>{\\colortbl ;\\red0\\green77\\blue187;}{\\pard The word \\cf1 fish\\cf0 is blue.\\par</para>\n /// <para>­</para>\n /// <para>Additional information: </para>\n /// <para>Always wrap every text in a paragraph. </para>\n /// <para>Different tags can be stacked (i.e. \\pard\\b\\i Bold and Italic\\i0\\b0\\par)</para>\n /// <para>The space behind a tag is ignored. So if you need a space behind it, insert two spaces (i.e. \\pard The word \\bBOLD\\0 is bold.\\par)</para>\n /// <para>Full specification: http://www.biblioscape.com/rtf15_spec.htm </para>\n /// </summary>\n [Browsable(true)]\n public string RtfContent\n {\n get\n {\n return this.rtb.Rtf;\n }\n set\n {\n this.rtb.WordWrap = false; // to prevent any display bugs, word wrap must be off while changing the rich text content. \n this.rtb.Rtf = value.StartsWith(@\"{\\rtf1\") ? value : @\"{\\rtf1\" + value + \"}\"; // Setting the rich text content will trigger the ContentsResized event. \n this.Fit(); // Override width and height. \n this.rtb.WordWrap = this.WordWrap; // Set the word wrap back. \n }\n }\n\n /// <summary>\n /// Dynamic width of the control. \n /// </summary>\n [Browsable(false)]\n public new int Width\n {\n get\n {\n return base.Width;\n } \n }\n\n /// <summary>\n /// Dynamic height of the control. \n /// </summary>\n [Browsable(false)]\n public new int Height\n {\n get\n {\n return base.Height;\n }\n }\n\n /// <summary>\n /// The measured width based on the content. \n /// </summary>\n public int DesiredWidth { get; private set; }\n\n /// <summary>\n /// The measured height based on the content. \n /// </summary>\n public int DesiredHeight { get; private set; }\n\n /// <summary>\n /// Determines the text will be word wrapped. This is true, when the maximum size has been set. \n /// </summary>\n public bool WordWrap { get; private set; }\n\n /// <summary>\n /// Constructor. \n /// </summary>\n public AutoRichLabel()\n {\n InitializeComponent();\n }\n\n /// <summary>\n /// Overrides the width and height with the measured width and height\n /// </summary>\n public void Fit()\n {\n base.Width = this.DesiredWidth;\n base.Height = this.DesiredHeight;\n }\n\n /// <summary>\n /// Will be called when the rich text content of the control changes. \n /// </summary>\n private void rtb_ContentsResized(object sender, ContentsResizedEventArgs e)\n {\n this.AutoSize = false; // Disable auto size, else it will break everything\n this.WordWrap = this.MaximumSize.Width > 0; // Enable word wrap when the maximum width has been set. \n this.DesiredWidth = this.rtb.WordWrap ? this.MaximumSize.Width : e.NewRectangle.Width; // Measure width. \n this.DesiredHeight = this.MaximumSize.Height > 0 && this.MaximumSize.Height < e.NewRectangle.Height ? this.MaximumSize.Height : e.NewRectangle.Height; // Measure height. \n this.Fit(); // Override width and height. \n }\n}\n {\\pard This is a paragraph!\\par}\n \\b bold text\\b0\n\\i italic text\\i0\n\\ul underline text\\ul0\n {\\colortbl ;\\red0\\green77\\blue187;}\n{\\pard The word \\cf1 fish\\cf0 is blue.\\par\n \\pard\\b\\i Bold and Italic\\i0\\b0\\par \\pard The word \\bBOLD\\0 is bold.\\par \\ { } \\ RtfContent AutoRichLabel {\\colortbl ;\\red0\\green77\\blue187;}\n{\\pard\\b BOLD\\b0 \\i ITALIC\\i0 \\ul UNDERLINE\\ul0 \\\\\\{\\}\\par}\n{\\pard\\cf1\\b BOLD\\b0 \\i ITALIC\\i0 \\ul UNDERLINE\\ul0\\cf0 \\\\\\{\\}\\par}\n" } ]
2008/08/14
[ "https://Stackoverflow.com/questions/11311", "https://Stackoverflow.com", "https://Stackoverflow.com/users/299/" ]
11,318
<p>Imagine you want to animate some object on a WinForm. You setup a timer to update the state or model, and override the paint event of the Form. But from there, what's the best way to continually repaint the Form for the animation?</p> <ul> <li>Invalidate the Form as soon as you are done drawing?</li> <li>Setup a second timer and invalidate the form on a regular interval?</li> <li>Perhaps there is a common pattern for this thing?</li> <li>Are there any useful .NET classes to help out?</li> </ul> <p>Each time I need to do this I discover a new method with a new drawback. What are the experiences and recommendations from the SO community?</p>
[ { "answer_id": 11404, "author": "Peteter", "author_id": 1192, "author_profile": "https://Stackoverflow.com/users/1192", "pm_score": 4, "selected": true, "text": "private void AnimationTimer_Tick(object sender, EventArgs args)\n{\n // First paint background, like Clear(Control.Background), or by\n // painting an image you have previously buffered that was the background.\n animationControl.CreateGraphics().DrawImage(0, 0, animationImages[animationTick++])); \n}\n" } ]
2008/08/14
[ "https://Stackoverflow.com/questions/11318", "https://Stackoverflow.com", "https://Stackoverflow.com/users/322/" ]
11,330
<p>Let's say I'm creating a chess program. I have a function</p> <pre><code>void foreachMove( void (*action)(chess_move*), chess_game* game); </code></pre> <p>which will call the function pointer action on each valid move. This is all well and good, but what if I need to pass more parameters to the action function? For example:</p> <pre><code>chess_move getNextMove(chess_game* game, int depth){ //for each valid move, determine how good the move is foreachMove(moveHandler, game); } void moveHandler(chess_move* move){ //uh oh, now I need the variables "game" and "depth" from the above function } </code></pre> <p>Redefining the function pointer is not the optimal solution. The foreachMove function is versatile and many different places in the code reference it. It doesn't make sense for each one of those references to have to update their function to include parameters that they don't need.</p> <p>How can I pass extra parameters to a function that I'm calling through a pointer?</p>
[ { "answer_id": 11335, "author": "Antonio Haley", "author_id": 390, "author_profile": "https://Stackoverflow.com/users/390", "pm_score": 3, "selected": false, "text": "void foreachMove( void (*action)(chess_move*, int), chess_game* game )\n" }, { "answer_id": 11379, "author": "Baltimark", "author_id": 1179, "author_profile": "https://Stackoverflow.com/users/1179", "pm_score": 2, "selected": false, "text": "if (depth > -1) //some default\n {\n //do something\n }\n" }, { "answer_id": 11395, "author": "Jesse Beder", "author_id": 112, "author_profile": "https://Stackoverflow.com/users/112", "pm_score": 2, "selected": false, "text": "struct MoveHandler {\n chess_game *game;\n int depth;\n\n MoveHandler(chess_game *g, int d): game(g), depth(d) {}\n\n void operator () (chess_move*) {\n // now you can use the game and the depth\n }\n};\n foreachMove template <typename T>\nvoid foreachMove(T action, chess_game* game);\n chess_move getNextMove(chess_game* game, int depth){\n //for each valid move, determine how good the move is\n foreachMove(MoveHandler(game, depth), game);\n}\n MoveHandler" }, { "answer_id": 11442, "author": "Nathan Fellman", "author_id": 1084, "author_profile": "https://Stackoverflow.com/users/1084", "pm_score": 1, "selected": false, "text": "void MoveHandler (void** DataArray)\n{\n // data1 is always chess_move\n chess_move data1 = DataArray[0]? (*(chess_move*)DataArray[0]) : NULL; \n // data2 is always float\n float data1 = DataArray[1]? (*(float*)DataArray[1]) : NULL; \n // data3 is always char\n char data1 = DataArray[2]? (*(char*)DataArray[2]) : NULL; \n //etc\n}\n\nvoid foreachMove( void (*action)(void**), chess_game* game);\n chess_move getNextMove(chess_game* game, int depth){\n //for each valid move, determine how good the move is\n void* data[4];\n data[0] = &chess_move;\n float f1;\n char c1;\n data[1] = &f1;\n data[2] = &c1;\n data[3] = NULL;\n foreachMove(moveHandler, game);\n}\n" }, { "answer_id": 15871673, "author": "luser droog", "author_id": 733077, "author_profile": "https://Stackoverflow.com/users/733077", "pm_score": 0, "selected": false, "text": "chess_move" } ]
2008/08/14
[ "https://Stackoverflow.com/questions/11330", "https://Stackoverflow.com", "https://Stackoverflow.com/users/432/" ]
11,341
<p>I would like to automatically generate PDF documents from <a href="https://en.wikipedia.org/wiki/WebObjects" rel="nofollow noreferrer">WebObjects</a> based on mulitpage forms. Assuming I have a class which can assemble the related forms (java/wod files) is there a good way to then parse the individual forms into a PDF instead of going to the screen?</p>
[ { "answer_id": 13431, "author": "Chris Hanson", "author_id": 714, "author_profile": "https://Stackoverflow.com/users/714", "pm_score": 3, "selected": true, "text": "WOComponent" } ]
2008/08/14
[ "https://Stackoverflow.com/questions/11341", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1104/" ]
11,345
<p>What is the story behind XPath and support for namespaces? Did XPath as a specification precede namespaces? If I have a document where elements have been given a default namespace: </p> <pre><code>&lt;foo xmlns="uri" /&gt; </code></pre> <p>It appears as though some of the XPath processor libraries won't recognize <code>//foo</code> because of the namespace whereas others will. The option my team has thought about is to add a namespace prefix using regular expressions to the XPath (you can add a namespace prefix via XmlNameTable) but this seems brittle since XPath is such a flexible language when it comes to node tests.</p> <p>Is there a standard that applies to this?</p> <p>My approach is a bit hackish but it seems to work fine; I remove the <code>xmlns</code> declaration with a search/replace and then apply XPath.</p> <pre><code>string readyForXpath = Regex.Replace(xmldocument, "xmlns=\".+\"", String.Empty ); </code></pre> <p>Is that a fair approach or has anyone solved this differently?</p>
[ { "answer_id": 11351, "author": "Stu", "author_id": 414, "author_profile": "https://Stackoverflow.com/users/414", "pm_score": 4, "selected": false, "text": "<foo xmlns='urn:foo'>\n <bar>\n <asdf/>\n </bar> \n</foo>\n //*[local-name()='bar'] \n //bar\n" }, { "answer_id": 11370, "author": "palehorse", "author_id": 312, "author_profile": "https://Stackoverflow.com/users/312", "pm_score": 0, "selected": false, "text": "<xsl:stylesheet\n xmlns:fb=\"uri\"\n xmlns:xsl=\"http://www.w3.org/1999/XSL/Transform\" version=\"1.0\">\n\n <xsl:template match=\"fb:foo/bar\">\n <!-- do stuff here -->\n </xsl:template>\n</xsl:stylsheet>\n" }, { "answer_id": 149088, "author": "Andrew Cowenhoven", "author_id": 12281, "author_profile": "https://Stackoverflow.com/users/12281", "pm_score": 4, "selected": true, "text": "XmlDocument doc = new XmlDocument();\ndoc.LoadXml(xmlWithBogusNamespace); \nXmlNamespaceManager nSpace = new XmlNamespaceManager(doc.NameTable);\nnSpace.AddNamespace(\"myNs\", \"http://theirUri\");\n\nXmlNodeList nodes = doc.SelectNodes(\"//myNs:NodesIWant\",nSpace);\n//etc\n" }, { "answer_id": 49044337, "author": "crazy dev", "author_id": 9427549, "author_profile": "https://Stackoverflow.com/users/9427549", "pm_score": 0, "selected": false, "text": " int \nregister_namespaces(xmlXPathContextPtr xpathCtx, const xmlChar* nsList) {\n xmlChar* nsListDup;\n xmlChar* prefix;\n xmlChar* href;\n xmlChar* next;\n\n assert(xpathCtx);\n assert(nsList);\n\n nsListDup = xmlStrdup(nsList);\n if(nsListDup == NULL) {\n fprintf(stderr, \"Error: unable to strdup namespaces list\\n\");\n return(-1); \n }\n\n next = nsListDup; \n while(next != NULL) {\n /* skip spaces */\n while((*next) == ' ') next++;\n if((*next) == '\\0') break;\n\n /* find prefix */\n prefix = next;\n next = (xmlChar*)xmlStrchr(next, '=');\n if(next == NULL) {\n fprintf(stderr,\"Error: invalid namespaces list format\\n\");\n xmlFree(nsListDup);\n return(-1); \n }\n *(next++) = '\\0'; \n\n /* find href */\n href = next;\n next = (xmlChar*)xmlStrchr(next, ' ');\n if(next != NULL) {\n *(next++) = '\\0'; \n }\n\n /* do register namespace */\n if(xmlXPathRegisterNs(xpathCtx, prefix, href) != 0) {\n fprintf(stderr,\"Error: unable to register NS with prefix=\\\"%s\\\" and href=\\\"%s\\\"\\n\", prefix, href);\n xmlFree(nsListDup);\n return(-1); \n }\n }\n\n xmlFree(nsListDup);\n return(0);\n}\n" } ]
2008/08/14
[ "https://Stackoverflow.com/questions/11345", "https://Stackoverflow.com", "https://Stackoverflow.com/users/64/" ]
11,381
<p>Here's a coding problem for those that like this kind of thing. Let's see your implementations (in your language of choice, of course) of a function which returns a human readable String representation of a specified Integer. For example:</p> <ul> <li>humanReadable(1) returns "one". <li>humanReadable(53) returns "fifty-three". <li>humanReadable(723603) returns "seven hundred and twenty-three thousand, six hundred and three". <li>humanReadable(1456376562) returns "one billion, four hundred and fifty-six million, three hundred and seventy-six thousand, five hundred and sixty-two". </ul> <p>Bonus points for particularly clever/elegant solutions!</p> <p>It might seem like a pointless exercise, but there are number of real world applications for this kind of algorithm (although supporting numbers as high as a billion may be overkill :-)</p>
[ { "answer_id": 11415, "author": "Ryan Ahearn", "author_id": 75, "author_profile": "https://Stackoverflow.com/users/75", "pm_score": 1, "selected": false, "text": "String humanReadable(int inputNumber) {\n if (inputNumber == -1) {\n return \"\";\n }\n int remainder;\n int quotient;\n quotient = inputNumber / 1000000;\n remainder = inputNumber % 1000000;\n if (quotient > 0) {\n return humanReadable(quotient) + \" million, \" + humanReadable(remainder);\n }\n quotient = inputNumber / 1000;\n remainder = inputNumber % 1000;\n if (quotient > 0) {\n return humanReadable(quotient) + \" thousand, \" + humanReadable(remainder);\n }\n quotient = inputNumber / 100;\n remainder = inputNumber % 100;\n if (quotient > 0) {\n return humanReadable(quotient) + \" hundred, \" + humanReadable(remainder);\n }\n quotient = inputNumber / 10;\n remainder = inputNumber % 10;\n if (remainder == 0) {\n //hackish way to flag the algorithm to not output something like \"twenty zero\"\n remainder = -1;\n }\n if (quotient == 1) {\n switch(inputNumber) {\n case 10:\n return \"ten\";\n case 11:\n return \"eleven\";\n case 12:\n return \"twelve\";\n case 13:\n return \"thirteen\";\n case 14:\n return \"fourteen\";\n case 15:\n return \"fifteen\";\n case 16:\n return \"sixteen\";\n case 17:\n return \"seventeen\";\n case 18:\n return \"eighteen\";\n case 19:\n return \"nineteen\";\n }\n }\n switch(quotient) {\n case 2:\n return \"twenty \" + humanReadable(remainder);\n case 3:\n return \"thirty \" + humanReadable(remainder);\n case 4:\n return \"forty \" + humanReadable(remainder);\n case 5:\n return \"fifty \" + humanReadable(remainder);\n case 6:\n return \"sixty \" + humanReadable(remainder);\n case 7:\n return \"seventy \" + humanReadable(remainder);\n case 8:\n return \"eighty \" + humanReadable(remainder);\n case 9:\n return \"ninety \" + humanReadable(remainder);\n }\n switch(inputNumber) {\n case 0:\n return \"zero\";\n case 1:\n return \"one\";\n case 2:\n return \"two\";\n case 3:\n return \"three\";\n case 4:\n return \"four\";\n case 5:\n return \"five\";\n case 6:\n return \"six\";\n case 7:\n return \"seven\";\n case 8:\n return \"eight\";\n case 9:\n return \"nine\";\n }\n}\n" }, { "answer_id": 11417, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "import math\n\ndef encodeOnesDigit(num):\n return ['', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine'][num]\n\ndef encodeTensDigit(num):\n return ['twenty', 'thirty', 'forty', 'fifty', 'sixty', 'seventy', 'eighty', 'ninety'][num-2]\n\ndef encodeTeens(num):\n if num < 10:\n return encodeOnesDigit(num)\n else:\n return ['ten', 'eleven', 'twelve', 'thirteen', 'fourteen', 'fifteen', 'sixteen', 'seventeen', 'eighteen', 'nineteen'][num-10]\n\ndef encodeTriplet(num):\n if num == 0: return ''\n str = ''\n if num >= 100:\n str = encodeOnesDigit(num / 100) + ' hundred'\n tens = num % 100\n if tens >= 20:\n if str != '': str += ' '\n str += encodeTensDigit(tens / 10)\n if tens % 10 > 0:\n str += '-' + encodeOnesDigit(tens % 10)\n elif tens != 0:\n if str != '': str += ' '\n str += encodeTeens(tens)\n return str\n\ndef zipNumbers(numList):\n if len(numList) == 1:\n return numList[0]\n strList = ['', ' thousand', ' million', ' billion'] # Add more as needed\n strList = strList[:len(numList)]\n strList.reverse()\n joinedList = zip(numList, strList)\n joinedList = [item for item in joinedList if item[0] != '']\n return ', '.join(''.join(item) for item in joinedList)\n\ndef humanReadable(num):\n if num == 0: return 'zero'\n negative = False\n if num < 0:\n num *= -1\n negative = True\n numString = str(num)\n tripletCount = int(math.ceil(len(numString) / 3.0))\n numString = numString.zfill(tripletCount * 3)\n tripletList = [int(numString[i*3:i*3+3]) for i in range(tripletCount)]\n readableList = [encodeTriplet(num) for num in tripletList]\n readableStr = zipNumbers(readableList)\n return 'negative ' + readableStr if negative else readableStr\n" }, { "answer_id": 11444, "author": "Stu", "author_id": 414, "author_profile": "https://Stackoverflow.com/users/414", "pm_score": 1, "selected": false, "text": "using System;\n\nnamespace HumanReadable\n{\n public static class HumanReadableExt\n {\n private static readonly string[] _digits = {\n \"\", \"one\", \"two\", \"three\", \"four\", \"five\",\n \"six\", \"seven\", \"eight\", \"nine\", \"eleven\", \"twelve\",\n \"thirteen\", \"fourteen\", \"fifteen\", \"sixteen\", \"seventeen\",\n \"eighteen\", \"nineteen\"\n };\n\n private static readonly string[] _teens = {\n \"\", \"\", \"twenty\", \"thirty\", \"forty\", \"fifty\",\n \"sixty\", \"seventy\", \"eighty\", \"ninety\"\n };\n\n private static readonly string[] _illions = {\n \"\", \"thousand\", \"million\", \"billion\", \"trillion\"\n };\n\n private static string Seg(int number)\n {\n var work = string.Empty;\n\n if (number >= 100) \n work += _digits[number / 100] + \" hundred \";\n\n if ((number % 100) < 20)\n work += _digits[number % 100];\n else\n work += _teens[(number % 100) / 10] + \"-\" + _digits[number % 10];\n\n return work;\n }\n\n public static string HumanReadable(this int number)\n {\n if (number == 0)\n return \"zero\";\n var work = string.Empty;\n\n var parts = new string[_illions.Length];\n\n for (var ind = 0; ind < parts.Length; ind++)\n parts[ind] = Seg((int) (number % Math.Pow(1000, ind + 1) / Math.Pow(1000, ind)));\n\n for (var ind = 0; ind < parts.Length; ind++)\n if (!string.IsNullOrEmpty(parts[ind]))\n work = parts[ind] + \" \" + _illions[ind] + \", \" + work;\n\n work = work.TrimEnd(',', ' ');\n\n var lastSpace = work.LastIndexOf(' ');\n if (lastSpace >= 0)\n work = work.Substring(0, lastSpace) + \" and\" + work.Substring(lastSpace);\n\n return work;\n }\n }\n\n class Program\n {\n\n static void Main(string[] args)\n {\n Console.WriteLine(1.HumanReadable());\n Console.WriteLine(53.HumanReadable());\n Console.WriteLine(723603.HumanReadable());\n Console.WriteLine(1456376562.HumanReadable());\n Console.ReadLine();\n }\n }\n}\n" }, { "answer_id": 214352, "author": "mat kelcey", "author_id": 26094, "author_profile": "https://Stackoverflow.com/users/26094", "pm_score": 0, "selected": false, "text": "> man number\n" } ]
2008/08/14
[ "https://Stackoverflow.com/questions/11381", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1030/" ]
11,405
<p>The following code doesn't compile with gcc, but does with Visual Studio:</p> <pre><code>template &lt;typename T&gt; class A { public: T foo; }; template &lt;typename T&gt; class B: public A &lt;T&gt; { public: void bar() { cout &lt;&lt; foo &lt;&lt; endl; } }; </code></pre> <p>I get the error:</p> <blockquote> <p>test.cpp: In member function ‘void B::bar()’:</p> <p>test.cpp:11: error: ‘foo’ was not declared in this scope</p> </blockquote> <p>But it should be! If I change <code>bar</code> to</p> <pre><code>void bar() { cout &lt;&lt; this-&gt;foo &lt;&lt; endl; } </code></pre> <p>then it <em>does</em> compile, but I don't think I have to do this. Is there something in the official specs of C++ that GCC is following here, or is it just a quirk?</p>
[ { "answer_id": 11425, "author": "Derek Park", "author_id": 872, "author_profile": "https://Stackoverflow.com/users/872", "pm_score": 4, "selected": false, "text": "template <typename T> struct B {\n int m;\n int n;\n int f ();\n int g ();\n};\nint n;\nint g ();\ntemplate <typename T> struct C : B<T> {\n void h ()\n {\n m = 0; // error\n f (); // error\n n = 0; // ::n is modified\n g (); // ::g is called\n }\n};\n template <typename T> void C<T>::h ()\n{\n this->m = 0;\n this->f ();\n this->n = 0\n this->g ();\n}\n template <typename T> struct C : B<T> {\n using B<T>::m;\n using B<T>::f;\n using B<T>::n;\n using B<T>::g;\n void h ()\n {\n m = 0;\n f ();\n n = 0;\n g ();\n }\n};\n typedef double A; \ntemplate<class T> class B { \n typedef int A; \n}; \ntemplate<class T> struct X : B<T> { \n A a; // a has typedouble \n}; \n A X<T> B<T> struct A { \n struct B { /* ... */ }; \n int a; \n int Y; \n}; \nint a; \ntemplate<class T> struct Y : T { \n struct B { /* ... */ }; \n B b; //The B defined in Y \n void f(int i) { a = i; } // ::a \n Y* p; // Y<T> \n}; \nY<A> ya; \n A::B A::a A::Y A Y<A>" }, { "answer_id": 11435, "author": "Vincent Robert", "author_id": 268, "author_profile": "https://Stackoverflow.com/users/268", "pm_score": 5, "selected": false, "text": "B<T> A<T> this template <typename T> class A {\npublic:\n T foo;\n};\n\ntemplate <typename T> class B: public A <T> {\npublic:\n void bar() { cout << A<T>::foo << endl; }\n};\n" }, { "answer_id": 11703, "author": "Matt Price", "author_id": 852, "author_profile": "https://Stackoverflow.com/users/852", "pm_score": 3, "selected": false, "text": "template<>\nclass A<int> {};\n\nB<int> x; \nx.bar();//this will fail because there is no member foo in A<int>\n" } ]
2008/08/14
[ "https://Stackoverflow.com/questions/11405", "https://Stackoverflow.com", "https://Stackoverflow.com/users/112/" ]
11,491
<p>What is the best way people have found to do String to Lower case / Upper case in C++?</p> <p>The issue is complicated by the fact that C++ isn't an English only programming language. Is there a good multilingual method?</p>
[ { "answer_id": 11502, "author": "Darren Kopp", "author_id": 77, "author_profile": "https://Stackoverflow.com/users/77", "pm_score": 6, "selected": true, "text": "#include <algorithm>\nstd::string data = \"Abc\";\nstd::transform(data.begin(), data.end(), data.begin(), ::toupper);\n" }, { "answer_id": 21395, "author": "Nic Strong", "author_id": 2281, "author_profile": "https://Stackoverflow.com/users/2281", "pm_score": 4, "selected": false, "text": "> std::string data = “Abc”; \n> std::transform(data.begin(), data.end(), data.begin(), ::toupper);\n locale loc(\"\");\nconst ctype<char>& ct = use_facet<ctype<char> >(loc);\ntransform(str.begin(), str.end(), std::bind1st(std::mem_fun(&ctype<char>::tolower), &ct));\n" }, { "answer_id": 1724567, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "locale loc(\"\");\nconst ctype<char>& ct = use_factet<ctype<char> >(loc);\ntransform(str.begin(), str.end(), std::bind1st(std::mem_fun(&ctype<char>::tolower), &ct));\n locale loc(\"\");\nconst ctype<char>& ct = use_facet<ctype<char> >(loc);\ntransform(str.begin(), str.end(), str.begin(), std::bind1st(std::mem_fun(&ctype<char>::tolower), &ct));\n" }, { "answer_id": 15151222, "author": "NoOne", "author_id": 964053, "author_profile": "https://Stackoverflow.com/users/964053", "pm_score": 1, "selected": false, "text": "#include <locale.h>\n\n_locale_t locale = _create_locale(LC_CTYPE, \"Greek\");\nAfxMessageBox((CString)\"\"+(TCHAR)_totupper_l(_T('α'), locale));\n_free_locale(locale);\n" }, { "answer_id": 21387775, "author": "James Oravec", "author_id": 1190934, "author_profile": "https://Stackoverflow.com/users/1190934", "pm_score": 1, "selected": false, "text": "VCL SysUtils.hpp LowerCase(unicodeStringVar) UpperCase(unicodeStringVar)" }, { "answer_id": 64410355, "author": "Joma", "author_id": 3158594, "author_profile": "https://Stackoverflow.com/users/3158594", "pm_score": 0, "selected": false, "text": "locale -a sudo apt-get install -y locales locales-all $ g++ main.cpp $ ./a.out Zoë Saldaña played in La maldición del padre Cardona. ëèñ αω óóChloë\nZoë Saldaña played in La maldición del padre Cardona. ëèñ αω óóChloë\nZOË SALDAÑA PLAYED IN LA MALDICIÓN DEL PADRE CARDONA. ËÈÑ ΑΩ ÓÓCHLOË\nZOË SALDAÑA PLAYED IN LA MALDICIÓN DEL PADRE CARDONA. ËÈÑ ΑΩ ÓÓCHLOË\nzoë saldaña played in la maldición del padre cardona. ëèñ αω óóchloë\nzoë saldaña played in la maldición del padre cardona. ëèñ αω óóchloë\n \"C:\\Program Files (x86)\\Microsoft Visual Studio\\2019\\Community\\VC\\Auxiliary\\Build\\vcvars64.bat\" > cl /EHa main.cpp /D \"_DEBUG\" /D \"_CONSOLE\" /D \"_UNICODE\" /D \"UNICODE\" /std:c++17 /DYNAMICBASE \"kernel32.lib\" \"user32.lib\" \"gdi32.lib\" \"winspool.lib\" \"comdlg32.lib\" \"advapi32.lib\" \"shell32.lib\" \"ole32.lib\" \"oleaut32.lib\" \"uuid.lib\" \"odbc32.lib\" \"odbccp32.lib\" /MTd Compilador de optimización de C/C++ de Microsoft (R) versión 19.27.29111 para x64\n(C) Microsoft Corporation. Todos los derechos reservados.\n\nmain.cpp\nMicrosoft (R) Incremental Linker Version 14.27.29111.0\nCopyright (C) Microsoft Corporation. All rights reserved.\n\n/out:main.exe\nmain.obj\nkernel32.lib\nuser32.lib\ngdi32.lib\nwinspool.lib\ncomdlg32.lib\nadvapi32.lib\nshell32.lib\nole32.lib\noleaut32.lib\nuuid.lib\nodbc32.lib\nodbccp32.lib\n >main.exe Zoë Saldaña played in La maldición del padre Cardona. ëèñ αω óóChloë\nZoë Saldaña played in La maldición del padre Cardona. ëèñ αω óóChloë\nZOË SALDAÑA PLAYED IN LA MALDICIÓN DEL PADRE CARDONA. ËÈÑ ΑΩ ÓÓCHLOË\nZOË SALDAÑA PLAYED IN LA MALDICIÓN DEL PADRE CARDONA. ËÈÑ ΑΩ ÓÓCHLOË\nzoë saldaña played in la maldición del padre cardona. ëèñ αω óóchloë\nzoë saldaña played in la maldición del padre cardona. ëèñ αω óóchloë\n /*\n * Filename: c:\\Users\\x\\Cpp\\main.cpp\n * Path: c:\\Users\\x\\Cpp\n * Filename: /home/x/Cpp/main.cpp\n * Path: /home/x/Cpp\n * Created Date: Saturday, October 17th 2020, 10:43:31 pm\n * Author: Joma\n *\n * No Copyright 2020\n */\n\n\n#include <iostream>\n#include <set>\n#include <string>\n#include <locale>\n\n// WINDOWS\n#if (_WIN32)\n#include <Windows.h>\n#include <conio.h>\n#define WINDOWS_PLATFORM 1\n#define DLLCALL STDCALL\n#define DLLIMPORT _declspec(dllimport)\n#define DLLEXPORT _declspec(dllexport)\n#define DLLPRIVATE\n#define NOMINMAX\n\n//EMSCRIPTEN\n#elif defined(__EMSCRIPTEN__)\n#include <emscripten/emscripten.h>\n#include <emscripten/bind.h>\n#include <unistd.h>\n#include <termios.h>\n#define EMSCRIPTEN_PLATFORM 1\n#define DLLCALL\n#define DLLIMPORT\n#define DLLEXPORT __attribute__((visibility(\"default\")))\n#define DLLPRIVATE __attribute__((visibility(\"hidden\")))\n\n// LINUX - Ubuntu, Fedora, , Centos, Debian, RedHat\n#elif (__LINUX__ || __gnu_linux__ || __linux__ || __linux || linux)\n#define LINUX_PLATFORM 1\n#include <unistd.h>\n#include <termios.h>\n#define DLLCALL CDECL\n#define DLLIMPORT\n#define DLLEXPORT __attribute__((visibility(\"default\")))\n#define DLLPRIVATE __attribute__((visibility(\"hidden\")))\n#define CoTaskMemAlloc(p) malloc(p)\n#define CoTaskMemFree(p) free(p)\n\n//ANDROID\n#elif (__ANDROID__ || ANDROID)\n#define ANDROID_PLATFORM 1\n#define DLLCALL\n#define DLLIMPORT\n#define DLLEXPORT __attribute__((visibility(\"default\")))\n#define DLLPRIVATE __attribute__((visibility(\"hidden\")))\n\n//MACOS\n#elif defined(__APPLE__)\n#include <unistd.h>\n#include <termios.h>\n#define DLLCALL\n#define DLLIMPORT\n#define DLLEXPORT __attribute__((visibility(\"default\")))\n#define DLLPRIVATE __attribute__((visibility(\"hidden\")))\n#include \"TargetConditionals.h\"\n#if TARGET_OS_IPHONE && TARGET_IPHONE_SIMULATOR\n#define IOS_SIMULATOR_PLATFORM 1\n#elif TARGET_OS_IPHONE\n#define IOS_PLATFORM 1\n#elif TARGET_OS_MAC\n#define MACOS_PLATFORM 1\n#else\n\n#endif\n\n#endif\n\n\n\ntypedef std::string String;\ntypedef std::wstring WString;\n\n#define EMPTY_STRING u8\"\"s\n#define EMPTY_WSTRING L\"\"s\n\nusing namespace std::literals::string_literals;\n\nclass Strings\n{\npublic:\n static String WideStringToString(const WString& wstr)\n {\n if (wstr.empty())\n {\n return String();\n }\n size_t pos;\n size_t begin = 0;\n String ret;\n\n#if WINDOWS_PLATFORM\n int size;\n pos = wstr.find(static_cast<wchar_t>(0), begin);\n while (pos != WString::npos && begin < wstr.length())\n {\n WString segment = WString(&wstr[begin], pos - begin);\n size = WideCharToMultiByte(CP_UTF8, WC_ERR_INVALID_CHARS, &segment[0], segment.size(), NULL, 0, NULL, NULL);\n String converted = String(size, 0);\n WideCharToMultiByte(CP_UTF8, WC_ERR_INVALID_CHARS, &segment[0], segment.size(), &converted[0], converted.size(), NULL, NULL);\n ret.append(converted);\n ret.append({ 0 });\n begin = pos + 1;\n pos = wstr.find(static_cast<wchar_t>(0), begin);\n }\n if (begin <= wstr.length())\n {\n WString segment = WString(&wstr[begin], wstr.length() - begin);\n size = WideCharToMultiByte(CP_UTF8, WC_ERR_INVALID_CHARS, &segment[0], segment.size(), NULL, 0, NULL, NULL);\n String converted = String(size, 0);\n WideCharToMultiByte(CP_UTF8, WC_ERR_INVALID_CHARS, &segment[0], segment.size(), &converted[0], converted.size(), NULL, NULL);\n ret.append(converted);\n }\n#elif LINUX_PLATFORM || MACOS_PLATFORM || EMSCRIPTEN_PLATFORM\n size_t size;\n pos = wstr.find(static_cast<wchar_t>(0), begin);\n while (pos != WString::npos && begin < wstr.length())\n {\n WString segment = WString(&wstr[begin], pos - begin);\n size = wcstombs(nullptr, segment.c_str(), 0);\n String converted = String(size, 0);\n wcstombs(&converted[0], segment.c_str(), converted.size());\n ret.append(converted);\n ret.append({ 0 });\n begin = pos + 1;\n pos = wstr.find(static_cast<wchar_t>(0), begin);\n }\n if (begin <= wstr.length())\n {\n WString segment = WString(&wstr[begin], wstr.length() - begin);\n size = wcstombs(nullptr, segment.c_str(), 0);\n String converted = String(size, 0);\n wcstombs(&converted[0], segment.c_str(), converted.size());\n ret.append(converted);\n }\n#else\n static_assert(false, \"Unknown Platform\");\n#endif\n return ret;\n }\n\n static WString StringToWideString(const String& str)\n {\n if (str.empty())\n {\n return WString();\n }\n\n size_t pos;\n size_t begin = 0;\n WString ret;\n#ifdef WINDOWS_PLATFORM\n int size = 0;\n pos = str.find(static_cast<char>(0), begin);\n while (pos != std::string::npos) {\n std::string segment = std::string(&str[begin], pos - begin);\n std::wstring converted = std::wstring(segment.size() + 1, 0);\n size = MultiByteToWideChar(CP_UTF8, MB_ERR_INVALID_CHARS, &segment[0], segment.size(), &converted[0], converted.length());\n converted.resize(size);\n ret.append(converted);\n ret.append({ 0 });\n begin = pos + 1;\n pos = str.find(static_cast<char>(0), begin);\n }\n if (begin < str.length()) {\n std::string segment = std::string(&str[begin], str.length() - begin);\n std::wstring converted = std::wstring(segment.size() + 1, 0);\n size = MultiByteToWideChar(CP_UTF8, MB_ERR_INVALID_CHARS, segment.c_str(), segment.size(), &converted[0], converted.length());\n converted.resize(size);\n ret.append(converted);\n }\n\n#elif LINUX_PLATFORM || MACOS_PLATFORM || EMSCRIPTEN_PLATFORM\n size_t size;\n pos = str.find(static_cast<char>(0), begin);\n while (pos != String::npos)\n {\n String segment = String(&str[begin], pos - begin);\n WString converted = WString(segment.size(), 0);\n size = mbstowcs(&converted[0], &segment[0], converted.size());\n converted.resize(size);\n ret.append(converted);\n ret.append({ 0 });\n begin = pos + 1;\n pos = str.find(static_cast<char>(0), begin);\n }\n if (begin < str.length())\n {\n String segment = String(&str[begin], str.length() - begin);\n WString converted = WString(segment.size(), 0);\n size = mbstowcs(&converted[0], &segment[0], converted.size());\n converted.resize(size);\n ret.append(converted);\n }\n#else\n static_assert(false, \"Unknown Platform\");\n#endif\n return ret;\n }\n\n\n static WString ToUpper(const WString& data)\n {\n WString result = data;\n auto& f = std::use_facet<std::ctype<wchar_t>>(std::locale());\n\n f.toupper(&result[0], &result[0] + result.size());\n return result;\n }\n\n static String ToUpper(const String& data)\n {\n return WideStringToString(ToUpper(StringToWideString(data)));\n }\n\n static WString ToLower(const WString& data)\n {\n WString result = data;\n auto& f = std::use_facet<std::ctype<wchar_t>>(std::locale());\n f.tolower(&result[0], &result[0] + result.size());\n return result;\n }\n\n static String ToLower(const String& data)\n {\n return WideStringToString(ToLower(StringToWideString(data)));\n }\n\n};\n\nenum class ConsoleTextStyle\n{\n DEFAULT = 0,\n BOLD = 1,\n FAINT = 2,\n ITALIC = 3,\n UNDERLINE = 4,\n SLOW_BLINK = 5,\n RAPID_BLINK = 6,\n REVERSE = 7,\n};\n\nenum class ConsoleForeground\n{\n DEFAULT = 39,\n BLACK = 30,\n DARK_RED = 31,\n DARK_GREEN = 32,\n DARK_YELLOW = 33,\n DARK_BLUE = 34,\n DARK_MAGENTA = 35,\n DARK_CYAN = 36,\n GRAY = 37,\n DARK_GRAY = 90,\n RED = 91,\n GREEN = 92,\n YELLOW = 93,\n BLUE = 94,\n MAGENTA = 95,\n CYAN = 96,\n WHITE = 97\n};\n\nenum class ConsoleBackground\n{\n DEFAULT = 49,\n BLACK = 40,\n DARK_RED = 41,\n DARK_GREEN = 42,\n DARK_YELLOW = 43,\n DARK_BLUE = 44,\n DARK_MAGENTA = 45,\n DARK_CYAN = 46,\n GRAY = 47,\n DARK_GRAY = 100,\n RED = 101,\n GREEN = 102,\n YELLOW = 103,\n BLUE = 104,\n MAGENTA = 105,\n CYAN = 106,\n WHITE = 107\n};\n\nclass Console\n{\nprivate:\n static void EnableVirtualTermimalProcessing()\n {\n#if defined WINDOWS_PLATFORM\n HANDLE hOut = GetStdHandle(STD_OUTPUT_HANDLE);\n DWORD dwMode = 0;\n GetConsoleMode(hOut, &dwMode);\n if (!(dwMode & ENABLE_VIRTUAL_TERMINAL_PROCESSING))\n {\n dwMode |= ENABLE_VIRTUAL_TERMINAL_PROCESSING;\n SetConsoleMode(hOut, dwMode);\n }\n#endif\n }\n\n static void ResetTerminalFormat()\n {\n std::cout << u8\"\\033[0m\";\n }\n\n static void SetVirtualTerminalFormat(ConsoleForeground foreground, ConsoleBackground background, std::set<ConsoleTextStyle> styles)\n {\n String format = u8\"\\033[\";\n format.append(std::to_string(static_cast<int>(foreground)));\n format.append(u8\";\");\n format.append(std::to_string(static_cast<int>(background)));\n if (styles.size() > 0)\n {\n for (auto it = styles.begin(); it != styles.end(); ++it)\n {\n format.append(u8\";\");\n format.append(std::to_string(static_cast<int>(*it)));\n }\n }\n format.append(u8\"m\");\n std::cout << format;\n }\npublic:\n static void Clear()\n {\n\n#ifdef WINDOWS_PLATFORM\n std::system(u8\"cls\");\n#elif LINUX_PLATFORM || defined MACOS_PLATFORM\n std::system(u8\"clear\");\n#elif EMSCRIPTEN_PLATFORM\n emscripten::val::global()[\"console\"].call<void>(u8\"clear\");\n#else\n static_assert(false, \"Unknown Platform\");\n#endif\n }\n\n static void Write(const String& s, ConsoleForeground foreground = ConsoleForeground::DEFAULT, ConsoleBackground background = ConsoleBackground::DEFAULT, std::set<ConsoleTextStyle> styles = {})\n {\n#ifndef EMSCRIPTEN_PLATFORM\n EnableVirtualTermimalProcessing();\n SetVirtualTerminalFormat(foreground, background, styles);\n#endif\n String str = s;\n#ifdef WINDOWS_PLATFORM\n WString unicode = Strings::StringToWideString(str);\n WriteConsole(GetStdHandle(STD_OUTPUT_HANDLE), unicode.c_str(), static_cast<DWORD>(unicode.length()), nullptr, nullptr);\n#elif defined LINUX_PLATFORM || defined MACOS_PLATFORM || EMSCRIPTEN_PLATFORM\n std::cout << str;\n#else\n static_assert(false, \"Unknown Platform\");\n#endif\n\n#ifndef EMSCRIPTEN_PLATFORM\n ResetTerminalFormat();\n#endif\n }\n\n static void WriteLine(const String& s, ConsoleForeground foreground = ConsoleForeground::DEFAULT, ConsoleBackground background = ConsoleBackground::DEFAULT, std::set<ConsoleTextStyle> styles = {})\n {\n Write(s, foreground, background, styles);\n std::cout << std::endl;\n }\n\n static void Write(const WString& s, ConsoleForeground foreground = ConsoleForeground::DEFAULT, ConsoleBackground background = ConsoleBackground::DEFAULT, std::set<ConsoleTextStyle> styles = {})\n {\n#ifndef EMSCRIPTEN_PLATFORM\n EnableVirtualTermimalProcessing();\n SetVirtualTerminalFormat(foreground, background, styles);\n#endif\n WString str = s;\n\n#ifdef WINDOWS_PLATFORM\n WriteConsole(GetStdHandle(STD_OUTPUT_HANDLE), str.c_str(), static_cast<DWORD>(str.length()), nullptr, nullptr);\n#elif LINUX_PLATFORM || MACOS_PLATFORM || EMSCRIPTEN_PLATFORM\n std::cout << Strings::WideStringToString(str);\n#else\n static_assert(false, \"Unknown Platform\");\n#endif\n\n#ifndef EMSCRIPTEN_PLATFORM\n ResetTerminalFormat();\n#endif\n }\n\n static void WriteLine(const WString& s, ConsoleForeground foreground = ConsoleForeground::DEFAULT, ConsoleBackground background = ConsoleBackground::DEFAULT, std::set<ConsoleTextStyle> styles = {})\n {\n Write(s, foreground, background, styles);\n std::cout << std::endl;\n }\n\n static void WriteLine()\n {\n std::cout << std::endl;\n }\n\n static void Pause()\n {\n char c;\n do\n {\n c = getchar();\n std::cout << \"Press Key \" << std::endl;\n } while (c != 64);\n std::cout << \"KeyPressed\" << std::endl;\n }\n\n static int PauseAny(bool printWhenPressed = false, ConsoleForeground foreground = ConsoleForeground::DEFAULT, ConsoleBackground background = ConsoleBackground::DEFAULT, std::set<ConsoleTextStyle> styles = {})\n {\n int ch;\n#ifdef WINDOWS_PLATFORM\n ch = _getch();\n#elif LINUX_PLATFORM || MACOS_PLATFORM || EMSCRIPTEN_PLATFORM\n struct termios oldt, newt;\n tcgetattr(STDIN_FILENO, &oldt);\n newt = oldt;\n newt.c_lflag &= ~(ICANON | ECHO);\n tcsetattr(STDIN_FILENO, TCSANOW, &newt);\n ch = getchar();\n tcsetattr(STDIN_FILENO, TCSANOW, &oldt);\n#else\n static_assert(false, \"Unknown Platform\");\n#endif\n if (printWhenPressed)\n {\n Console::Write(String(1, ch), foreground, background, styles);\n }\n return ch;\n }\n};\n\n\n\nint main()\n{\n std::locale::global(std::locale(u8\"en_US.UTF-8\"));\n String dataStr = u8\"Zoë Saldaña played in La maldición del padre Cardona. ëèñ αω óóChloë\";\n WString dataWStr = L\"Zoë Saldaña played in La maldición del padre Cardona. ëèñ αω óóChloë\";\n std::string locale = u8\"\";\n //std::string locale = u8\"de_DE.UTF-8\";\n //std::string locale = u8\"en_US.UTF-8\";\n Console::WriteLine(dataStr);\n Console::WriteLine(dataWStr);\n dataStr = Strings::ToUpper(dataStr);\n dataWStr = Strings::ToUpper(dataWStr);\n Console::WriteLine(dataStr);\n Console::WriteLine(dataWStr);\n dataStr = Strings::ToLower(dataStr);\n dataWStr = Strings::ToLower(dataWStr);\n Console::WriteLine(dataStr);\n Console::WriteLine(dataWStr);\n \n \n Console::WriteLine(u8\"Press any key to exit\"s, ConsoleForeground::DARK_GRAY);\n Console::PauseAny();\n\n return 0;\n}\n\n" } ]
2008/08/14
[ "https://Stackoverflow.com/questions/11491", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1366/" ]
11,532
<p>How can I find any unused functions in a PHP project?</p> <p>Are there features or APIs built into PHP that will allow me to analyse my codebase - for example <a href="http://ie.php.net/manual/en/language.oop5.reflection.php" rel="noreferrer">Reflection</a>, <a href="http://php.net/manual/en/function.token-get-all.php" rel="noreferrer"><code>token_get_all()</code></a>?</p> <p>Are these APIs feature rich enough for me not to have to rely on a third party tool to perform this type of analysis?</p>
[ { "answer_id": 14625, "author": "Stacey Richards", "author_id": 1142, "author_profile": "https://Stackoverflow.com/users/1142", "pm_score": 6, "selected": true, "text": "<?php\n $functions = array();\n $path = \"/path/to/my/php/project\";\n define_dir($path, $functions);\n reference_dir($path, $functions);\n echo\n \"<table>\" .\n \"<tr>\" .\n \"<th>Name</th>\" .\n \"<th>Defined</th>\" .\n \"<th>Referenced</th>\" .\n \"</tr>\";\n foreach ($functions as $name => $value) {\n echo\n \"<tr>\" . \n \"<td>\" . htmlentities($name) . \"</td>\" .\n \"<td>\" . (isset($value[0]) ? count($value[0]) : \"-\") . \"</td>\" .\n \"<td>\" . (isset($value[1]) ? count($value[1]) : \"-\") . \"</td>\" .\n \"</tr>\";\n }\n echo \"</table>\";\n function define_dir($path, &$functions) {\n if ($dir = opendir($path)) {\n while (($file = readdir($dir)) !== false) {\n if (substr($file, 0, 1) == \".\") continue;\n if (is_dir($path . \"/\" . $file)) {\n define_dir($path . \"/\" . $file, $functions);\n } else {\n if (substr($file, - 4, 4) != \".php\") continue;\n define_file($path . \"/\" . $file, $functions);\n }\n }\n } \n }\n function define_file($path, &$functions) {\n $tokens = token_get_all(file_get_contents($path));\n for ($i = 0; $i < count($tokens); $i++) {\n $token = $tokens[$i];\n if (is_array($token)) {\n if ($token[0] != T_FUNCTION) continue;\n $i++;\n $token = $tokens[$i];\n if ($token[0] != T_WHITESPACE) die(\"T_WHITESPACE\");\n $i++;\n $token = $tokens[$i];\n if ($token[0] != T_STRING) die(\"T_STRING\");\n $functions[$token[1]][0][] = array($path, $token[2]);\n }\n }\n }\n function reference_dir($path, &$functions) {\n if ($dir = opendir($path)) {\n while (($file = readdir($dir)) !== false) {\n if (substr($file, 0, 1) == \".\") continue;\n if (is_dir($path . \"/\" . $file)) {\n reference_dir($path . \"/\" . $file, $functions);\n } else {\n if (substr($file, - 4, 4) != \".php\") continue;\n reference_file($path . \"/\" . $file, $functions);\n }\n }\n } \n }\n function reference_file($path, &$functions) {\n $tokens = token_get_all(file_get_contents($path));\n for ($i = 0; $i < count($tokens); $i++) {\n $token = $tokens[$i];\n if (is_array($token)) {\n if ($token[0] != T_STRING) continue;\n if ($tokens[$i + 1] != \"(\") continue;\n $functions[$token[1]][1][] = array($path, $token[2]);\n }\n }\n }\n?>\n" }, { "answer_id": 693991, "author": "Till", "author_id": 2859, "author_profile": "https://Stackoverflow.com/users/2859", "pm_score": 2, "selected": false, "text": "getKeywordSetOfCategories()" }, { "answer_id": 4791987, "author": "Gordon", "author_id": 208809, "author_profile": "https://Stackoverflow.com/users/208809", "pm_score": 5, "selected": false, "text": "phpdcd $foo = 'fn'; $foo(); pear install phpunit/phpdcd-beta\n Usage: phpdcd [switches] <directory|file> ...\n\n--recursive Report code as dead if it is only called by dead code.\n\n--exclude <dir> Exclude <dir> from code analysis.\n--suffixes <suffix> A comma-separated list of file suffixes to check.\n\n--help Prints this usage information.\n--version Prints the version and exits.\n\n--verbose Print progress bar.\n" }, { "answer_id": 7133253, "author": "Andrey Butov", "author_id": 137484, "author_profile": "https://Stackoverflow.com/users/137484", "pm_score": 3, "selected": false, "text": "#!/usr/bin/php -f\n \n<?php\n \n// ============================================================================\n//\n// find_unused_functions.php\n//\n// Find unused functions in a set of PHP files.\n// version 1.3\n//\n// ============================================================================\n//\n// Copyright (c) 2011, Andrey Butov. All Rights Reserved.\n// This script is provided as is, without warranty of any kind.\n//\n// http://www.andreybutov.com\n//\n// ============================================================================\n \n// This may take a bit of memory...\nini_set('memory_limit', '2048M');\n \nif ( !isset($argv[1]) ) \n{\n usage();\n}\n \n$root_dir = $argv[1];\n \nif ( !is_dir($root_dir) || !is_readable($root_dir) )\n{\n echo \"ERROR: '$root_dir' is not a readable directory.\\n\";\n usage();\n}\n \n$files = php_files($root_dir);\n$tokenized = array();\n \nif ( count($files) == 0 )\n{\n echo \"No PHP files found.\\n\";\n exit;\n}\n \n$defined_functions = array();\n \nforeach ( $files as $file )\n{\n $tokens = tokenize($file);\n \n if ( $tokens )\n {\n // We retain the tokenized versions of each file,\n // because we'll be using the tokens later to search\n // for function 'uses', and we don't want to \n // re-tokenize the same files again.\n \n $tokenized[$file] = $tokens;\n \n for ( $i = 0 ; $i < count($tokens) ; ++$i )\n {\n $current_token = $tokens[$i];\n $next_token = safe_arr($tokens, $i + 2, false);\n \n if ( is_array($current_token) && $next_token && is_array($next_token) )\n {\n if ( safe_arr($current_token, 0) == T_FUNCTION )\n {\n // Find the 'function' token, then try to grab the \n // token that is the name of the function being defined.\n // \n // For every defined function, retain the file and line\n // location where that function is defined. Since different\n // modules can define a functions with the same name,\n // we retain multiple definition locations for each function name.\n \n $function_name = safe_arr($next_token, 1, false);\n $line = safe_arr($next_token, 2, false);\n \n if ( $function_name && $line )\n {\n $function_name = trim($function_name);\n if ( $function_name != \"\" )\n {\n $defined_functions[$function_name][] = array('file' => $file, 'line' => $line);\n }\n }\n }\n }\n }\n }\n}\n \n// We now have a collection of defined functions and\n// their definition locations. Go through the tokens again, \n// and find 'uses' of the function names. \n \nforeach ( $tokenized as $file => $tokens )\n{\n foreach ( $tokens as $token )\n {\n if ( is_array($token) && safe_arr($token, 0) == T_STRING )\n {\n $function_name = safe_arr($token, 1, false);\n $function_line = safe_arr($token, 2, false);;\n \n if ( $function_name && $function_line )\n {\n $locations_of_defined_function = safe_arr($defined_functions, $function_name, false);\n \n if ( $locations_of_defined_function )\n {\n $found_function_definition = false;\n \n foreach ( $locations_of_defined_function as $location_of_defined_function )\n {\n $function_defined_in_file = $location_of_defined_function['file'];\n $function_defined_on_line = $location_of_defined_function['line'];\n \n if ( $function_defined_in_file == $file && \n $function_defined_on_line == $function_line )\n {\n $found_function_definition = true;\n break;\n }\n }\n \n if ( !$found_function_definition )\n {\n // We found usage of the function name in a context\n // that is not the definition of that function. \n // Consider the function as 'used'.\n \n unset($defined_functions[$function_name]);\n }\n }\n }\n }\n }\n}\n \n \nprint_report($defined_functions); \nexit;\n \n \n// ============================================================================\n \nfunction php_files($path) \n{\n // Get a listing of all the .php files contained within the $path\n // directory and its subdirectories.\n \n $matches = array();\n $folders = array(rtrim($path, DIRECTORY_SEPARATOR));\n \n while( $folder = array_shift($folders) ) \n {\n $matches = array_merge($matches, glob($folder.DIRECTORY_SEPARATOR.\"*.php\", 0));\n $moreFolders = glob($folder.DIRECTORY_SEPARATOR.'*', GLOB_ONLYDIR);\n $folders = array_merge($folders, $moreFolders);\n }\n \n return $matches;\n}\n \n// ============================================================================\n \nfunction safe_arr($arr, $i, $default = \"\")\n{\n return isset($arr[$i]) ? $arr[$i] : $default;\n}\n \n// ============================================================================\n \nfunction tokenize($file)\n{\n $file_contents = file_get_contents($file);\n \n if ( !$file_contents )\n {\n return false;\n }\n \n $tokens = token_get_all($file_contents);\n return ($tokens && count($tokens) > 0) ? $tokens : false;\n}\n \n// ============================================================================\n \nfunction usage()\n{\n global $argv;\n $file = (isset($argv[0])) ? basename($argv[0]) : \"find_unused_functions.php\";\n die(\"USAGE: $file <root_directory>\\n\\n\");\n}\n \n// ============================================================================\n \nfunction print_report($unused_functions)\n{\n if ( count($unused_functions) == 0 )\n {\n echo \"No unused functions found.\\n\";\n }\n \n $count = 0;\n foreach ( $unused_functions as $function => $locations )\n {\n foreach ( $locations as $location )\n {\n echo \"'$function' in {$location['file']} on line {$location['line']}\\n\";\n $count++;\n }\n }\n \n echo \"=======================================\\n\";\n echo \"Found $count unused function\" . (($count == 1) ? '' : 's') . \".\\n\\n\";\n}\n \n// ============================================================================\n \n/* EOF */\n" }, { "answer_id": 9979425, "author": "Tim Cullen", "author_id": 1088372, "author_profile": "https://Stackoverflow.com/users/1088372", "pm_score": 4, "selected": false, "text": "grep -rhio ^function\\ .*\\( .|awk -F'[( ]' '{print \"echo -n \" $2 \" && grep -rin \" $2 \" .|grep -v function|wc -l\"}'|bash|grep 0\n" }, { "answer_id": 55196470, "author": "Tomas Votruba", "author_id": 1348344, "author_profile": "https://Stackoverflow.com/users/1348344", "pm_score": 2, "selected": false, "text": "public function someMethod() ${anything}->someMethod() composer require symplify/easy-coding-standard --dev\n ecs.yaml # ecs.yaml\nservices:\n Symplify\\CodingStandard\\Sniffs\\DeadCode\\UnusedPublicMethodSniff: ~\n vendor/bin/ecs check src\n" }, { "answer_id": 64443364, "author": "Sandy Garrido", "author_id": 7696704, "author_profile": "https://Stackoverflow.com/users/7696704", "pm_score": 3, "selected": false, "text": "composer require phan/phan\n PHP-AST php-ast pecl install ast\n php.ini php -i | grep 'php.ini'\n extension=ast.so\n directory_list exclude_analysis_directory_list exclude_analysis_directory_list ......\n\n'directory_list' => [\n 'public_html'\n],\n\n......\n\n'exclude_analysis_directory_list' => [\n 'vendor/',\n 'public_html/app/plugins',\n 'public_html/app/mu-plugins',\n 'public_html/admin'\n],\n......\n --dead-code-detection ./vendor/bin/phan --dead-code-detection\n the/path/to/php/file.php:324 PhanUnreferencedPublicMethod Possibly zero references to public method\\the\\path\\to\\function::the_funciton()\nthe/path/to/php/file.php:324 PhanUnreferencedPublicMethod Possibly zero references to public method\\the\\path\\to\\function::the_funciton()\nthe/path/to/php/file.php:324 PhanUnreferencedPublicMethod Possibly zero references to public method\\the\\path\\to\\function::the_funciton()\nthe/path/to/php/file.php:324 PhanUnreferencedPublicMethod Possibly zero references to public method\\the\\path\\to\\function::the_funciton()\n" } ]
2008/08/14
[ "https://Stackoverflow.com/questions/11532", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1142/" ]
11,561
<p>I've used Apache CXF to expose about ten java classes as web services.</p> <p>I've generated clients using CXF, Axis, and .NET.</p> <p>In Axis and CXF a "Service" or "Locator" is generated. From this service you can get a "Port". The "Port" is used to make individual calls to the methods exposed by the web service.</p> <p>In .NET the "Service" directly exposes the calls to the web service.</p> <p>Can someone explain the difference between a port, a service, a locator, and an endpoint when it comes to web services?</p> <p>Axis:</p> <pre><code>PatientServiceImplServiceLocator locator = new PatientServiceImplServiceLocator(); PatientService service = locator.getPatientServiceImplPort(); </code></pre> <p>CXF:</p> <pre><code>PatientServiceImplService locator = new PatientServiceImplService(); PatientService service = locator.getPatientServiceImplPort(); </code></pre> <p>.net:</p> <pre><code>PatientServiceImplService service = new PatientServiceImplService(); </code></pre>
[ { "answer_id": 23066361, "author": "pHneutre", "author_id": 1585148, "author_profile": "https://Stackoverflow.com/users/1585148", "pm_score": 2, "selected": false, "text": "<port> <endpoint> port endpoint" } ]
2008/08/14
[ "https://Stackoverflow.com/questions/11561", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1310/" ]
11,562
<p><code>std::swap()</code> is used by many std containers (such as <code>std::list</code> and <code>std::vector</code>) during sorting and even assignment.</p> <p>But the std implementation of <code>swap()</code> is very generalized and rather inefficient for custom types.</p> <p>Thus efficiency can be gained by overloading <code>std::swap()</code> with a custom type specific implementation. But how can you implement it so it will be used by the std containers?</p>
[ { "answer_id": 11599, "author": "Wilka", "author_id": 1367, "author_profile": "https://Stackoverflow.com/users/1367", "pm_score": 6, "selected": false, "text": "namespace std\n{\n template<>\n void swap(my_type& lhs, my_type& rhs)\n {\n // ... blah\n }\n}\n class Base\n{\n // ... stuff ...\n}\nclass Derived : public Base\n{\n // ... stuff ...\n}\n\nnamespace std\n{\n template<>\n void swap(Base& lha, Base& rhs)\n {\n // ...\n }\n}\n" }, { "answer_id": 109613, "author": "puetzk", "author_id": 14312, "author_profile": "https://Stackoverflow.com/users/14312", "pm_score": 5, "selected": false, "text": "namespace std\n{\n template<>\n void swap(myspace::mytype& a, myspace::mytype& b) { ... }\n}\n" }, { "answer_id": 2684544, "author": "Dave Abrahams", "author_id": 125349, "author_profile": "https://Stackoverflow.com/users/125349", "pm_score": 8, "selected": true, "text": "std::swap class X\n{\n // ...\n friend void swap(X& a, X& b)\n {\n using std::swap; // bring in swap for built-in types\n\n swap(a.base1, b.base1);\n swap(a.base2, b.base2);\n // ...\n swap(a.member1, b.member1);\n swap(a.member2, b.member2);\n // ...\n }\n};\n" }, { "answer_id": 8439357, "author": "Howard Hinnant", "author_id": 576911, "author_profile": "https://Stackoverflow.com/users/576911", "pm_score": 6, "selected": false, "text": "std::algorithm std::swap namespace exp namespace std // simulate <algorithm>\n\n#include <cstdio>\n\nnamespace exp\n{\n\n template <class T>\n void\n swap(T& x, T& y)\n {\n printf(\"generic exp::swap\\n\");\n T tmp = x;\n x = y;\n y = tmp;\n }\n\n template <class T>\n void algorithm(T* begin, T* end)\n {\n if (end-begin >= 2)\n exp::swap(begin[0], begin[1]);\n }\n\n}\n\n// simulate user code which includes <algorithm>\n\nstruct A\n{\n};\n\nnamespace exp\n{\n void swap(A&, A&)\n {\n printf(\"exp::swap(A, A)\\n\");\n }\n\n}\n\n// exercise simulation\n\nint main()\n{\n A a[2];\n exp::algorithm(a, a+2);\n}\n generic exp::swap\n swap std exp // simulate <algorithm>\n\n#include <cstdio>\n\nnamespace exp\n{\n\n template <class T>\n void\n swap(T& x, T& y)\n {\n printf(\"generic exp::swap\\n\");\n T tmp = x;\n x = y;\n y = tmp;\n }\n\n template <class T>\n void algorithm(T* begin, T* end)\n {\n if (end-begin >= 2)\n swap(begin[0], begin[1]);\n }\n\n}\n\n// simulate user code which includes <algorithm>\n\nstruct A\n{\n};\n\nvoid swap(A&, A&)\n{\n printf(\"swap(A, A)\\n\");\n}\n\n// exercise simulation\n\nint main()\n{\n A a[2];\n exp::algorithm(a, a+2);\n}\n swap(A, A)\n namespace exp\n{ \n template <>\n void swap(A&, A&)\n {\n printf(\"exp::swap(A, A)\\n\");\n }\n\n}\n A // simulate user code which includes <algorithm>\n\ntemplate <class T>\nstruct A\n{\n};\n\nnamespace exp\n{\n\n template <class T>\n void swap(A<T>&, A<T>&)\n {\n printf(\"exp::swap(A, A)\\n\");\n }\n\n}\n\n// exercise simulation\n\nint main()\n{\n A<int> a[2];\n exp::algorithm(a, a+2);\n}\n swap swap A A<T> swap A" } ]
2008/08/14
[ "https://Stackoverflow.com/questions/11562", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1366/" ]
11,585
<p>For my blog I am wanting to use the Output Cache to save a cached version of a perticular post for around 10 minutes, and thats fine...</p> <pre><code>&lt;%@OutputCache Duration="600" VaryByParam="*" %&gt; </code></pre> <p>However, if someone posts a comment, I want to clear the cache so that the page is refreshed and the comment can be seen.</p> <p>How do I do this in ASP.Net C#?</p>
[ { "answer_id": 11621, "author": "palmsey", "author_id": 521, "author_profile": "https://Stackoverflow.com/users/521", "pm_score": 1, "selected": false, "text": "//add dependency\nstring key = \"post.aspx?id=\" + PostID.ToString();\nCache[key] = new object();\nResponse.AddCacheItemDependency(key);\n Cache.Remove(key);\n" }, { "answer_id": 11641, "author": "GateKiller", "author_id": 383, "author_profile": "https://Stackoverflow.com/users/383", "pm_score": 7, "selected": true, "text": "HttpResponse.RemoveOutputCacheItem(\"/caching/CacheForever.aspx\");\n" }, { "answer_id": 416601, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": " public class Page : System.Web.UI.Page\n {\n protected override void OnLoad(EventArgs e)\n {\n try\n {\n string cacheKey = \"cacheKey\";\n object cache = HttpContext.Current.Cache[cacheKey];\n if (cache == null)\n {\n HttpContext.Current.Cache[cacheKey] = DateTime.UtcNow.ToString();\n }\n\n Response.AddCacheItemDependency(cacheKey);\n }\n catch (Exception ex)\n {\n throw new SystemException(ex.Message);\n }\n\n base.OnLoad(e);\n } \n }\n\n\n\n // Clear All OutPutCache Method \n\n public void ClearAllOutPutCache()\n {\n string cacheKey = \"cacheKey\";\n HttpContext.Cache.Remove(cacheKey);\n }\n" }, { "answer_id": 2876701, "author": "Kevin", "author_id": 153942, "author_profile": "https://Stackoverflow.com/users/153942", "pm_score": 5, "selected": false, "text": "HttpContextBase httpContext = filterContext.HttpContext;\nhttpContext.Response.AddCacheItemDependency(\"Pages\");\n protected void Application_Start()\n{\n HttpRuntime.Cache.Insert(\"Pages\", DateTime.Now);\n}\n HttpRuntime.Cache.Insert(\"Pages\", DateTime.Now);\n" }, { "answer_id": 4727875, "author": "Julien", "author_id": 280617, "author_profile": "https://Stackoverflow.com/users/280617", "pm_score": -1, "selected": false, "text": "HttpRuntime.Close()" }, { "answer_id": 6439754, "author": "Mohd Adil", "author_id": 810324, "author_profile": "https://Stackoverflow.com/users/810324", "pm_score": 2, "selected": false, "text": "Response.Cache.SetExpires(DateTime.UtcNow.AddMinutes(-1));\nResponse.Cache.SetCacheability(HttpCacheability.NoCache);\nResponse.Cache.SetNoStore();\n Session.Abandon();\nSession.Clear();\n" } ]
2008/08/14
[ "https://Stackoverflow.com/questions/11585", "https://Stackoverflow.com", "https://Stackoverflow.com/users/383/" ]
11,586
<p>What's the penetration of design patterns in the real world? Do you use them in your day to day job - discussing how and where to apply them with your coworkers - or do they remain more of an academic concept? </p> <p>Do they actually provide actual value to your job? Or are they just something that people talk about to sound smart?</p> <p>Note: For the purpose of this question ignore 'simple' design patterns like <em>Singleton</em>. I'm talking about designing your code so you can take advantage of <em>Model View Controller</em>, etc.</p>
[ { "answer_id": 11617, "author": "Derek Park", "author_id": 872, "author_profile": "https://Stackoverflow.com/users/872", "pm_score": 7, "selected": true, "text": "Facade Observer Strategy" } ]
2008/08/14
[ "https://Stackoverflow.com/questions/11586", "https://Stackoverflow.com", "https://Stackoverflow.com/users/322/" ]
11,620
<p>I want to rename a database, but keep getting the error that 'couldn't get exclusive lock' on the database, which implies there is some connection(s) still active.</p> <p>How can I kill all the connections to the database so that I can rename it?</p>
[ { "answer_id": 11624, "author": "SQLMenace", "author_id": 740, "author_profile": "https://Stackoverflow.com/users/740", "pm_score": 10, "selected": true, "text": "-- set your current connection to use master otherwise you might get an error\n\nuse master\nALTER DATABASE YourDatabase SET SINGLE_USER WITH ROLLBACK IMMEDIATE \n\n--do you stuff here \n\nALTER DATABASE YourDatabase SET MULTI_USER\n" }, { "answer_id": 11627, "author": "Adam", "author_id": 1341, "author_profile": "https://Stackoverflow.com/users/1341", "pm_score": 7, "selected": false, "text": "USE master\nGO\n\nSET NOCOUNT ON\nDECLARE @DBName varchar(50)\nDECLARE @spidstr varchar(8000)\nDECLARE @ConnKilled smallint\nSET @ConnKilled=0\nSET @spidstr = ''\n\nSet @DBName = 'DB_NAME'\nIF db_id(@DBName) < 4\nBEGIN\nPRINT 'Connections to system databases cannot be killed'\nRETURN\nEND\nSELECT @spidstr=coalesce(@spidstr,',' )+'kill '+convert(varchar, spid)+ '; '\nFROM master..sysprocesses WHERE dbid=db_id(@DBName)\n\nIF LEN(@spidstr) > 0\nBEGIN\nEXEC(@spidstr)\nSELECT @ConnKilled = COUNT(1)\nFROM master..sysprocesses WHERE dbid=db_id(@DBName)\nEND\n" }, { "answer_id": 11630, "author": "Joseph Sturtevant", "author_id": 317, "author_profile": "https://Stackoverflow.com/users/317", "pm_score": 2, "selected": false, "text": "ALTER DATABASE [DATABASE_NAME]\nSET SINGLE_USER\nWITH ROLLBACK IMMEDIATE\n" }, { "answer_id": 11633, "author": "brendan", "author_id": 225, "author_profile": "https://Stackoverflow.com/users/225", "pm_score": 5, "selected": false, "text": "\nALTER DATABASE DB_NAME SET SINGLE_USER WITH ROLLBACK IMMEDIATE \nGO \nSP_RENAMEDB 'DB_NAME','DB_NAME_NEW'\nGo \nALTER DATABASE DB_NAME_NEW SET MULTI_USER -- set back to multi user \nGO \n" }, { "answer_id": 2817992, "author": "btk", "author_id": 289255, "author_profile": "https://Stackoverflow.com/users/289255", "pm_score": 6, "selected": false, "text": "USE master\ngo\n\nDECLARE @dbname sysname\nSET @dbname = 'yourdbname'\n\nDECLARE @spid int\nSELECT @spid = min(spid) from master.dbo.sysprocesses where dbid = db_id(@dbname)\nWHILE @spid IS NOT NULL\nBEGIN\nEXECUTE ('KILL ' + @spid)\nSELECT @spid = min(spid) from master.dbo.sysprocesses where dbid = db_id(@dbname) AND spid > @spid\nEND\n" }, { "answer_id": 9093487, "author": "Talha", "author_id": 1023687, "author_profile": "https://Stackoverflow.com/users/1023687", "pm_score": 3, "selected": false, "text": "Select 'Kill '+ CAST(p.spid AS VARCHAR)KillCommand into #temp\nfrom master.dbo.sysprocesses p (nolock)\njoin master..sysdatabases d (nolock) on p.dbid = d.dbid\nWhere d.[name] = 'your db name'\n\nDeclare @query nvarchar(max)\n--Select * from #temp\nSelect @query =STUFF(( \n select ' ' + KillCommand from #temp\n FOR XML PATH('')),1,1,'') \nExecute sp_executesql @query \nDrop table #temp\n" }, { "answer_id": 11536813, "author": "santhosh kumar", "author_id": 1534044, "author_profile": "https://Stackoverflow.com/users/1534044", "pm_score": 4, "selected": false, "text": "ALTER DATABASE [Test]\nSET OFFLINE WITH ROLLBACK IMMEDIATE\n\nALTER DATABASE [Test]\nSET ONLINE\n" }, { "answer_id": 30097342, "author": "Ray Krungkaew", "author_id": 1554116, "author_profile": "https://Stackoverflow.com/users/1554116", "pm_score": 0, "selected": false, "text": "declare @proc table(\n SPID bigint,\n Status nvarchar(255),\n Login nvarchar(255),\n HostName nvarchar(255),\n BlkBy nvarchar(255),\n DBName nvarchar(255),\n Command nvarchar(MAX),\n CPUTime bigint,\n DiskIO bigint,\n LastBatch nvarchar(255),\n ProgramName nvarchar(255),\n SPID2 bigint,\n REQUESTID bigint\n)\n\ninsert into @proc\nexec sp_who2\n\nselect *, KillCommand = concat('kill ', SPID, ';')\nfrom @proc\n SPID KillCommand\n26 kill 26;\n27 kill 27;\n28 kill 28;\n" } ]
2008/08/14
[ "https://Stackoverflow.com/questions/11620", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1341/" ]
11,632
<p>Certainly there's the difference in general syntax, but what other critical distinctions exist? There are <em>some</em> differences, right?</p>
[ { "answer_id": 11677, "author": "Keith", "author_id": 905, "author_profile": "https://Stackoverflow.com/users/905", "pm_score": 1, "selected": false, "text": "handles '''" } ]
2008/08/14
[ "https://Stackoverflow.com/questions/11632", "https://Stackoverflow.com", "https://Stackoverflow.com/users/337/" ]
11,635
<p>What is the best way of doing case-insensitive string comparison in C++ without transforming a string to all uppercase or all lowercase?</p> <p>Please indicate whether the methods are Unicode-friendly and how portable they are.</p>
[ { "answer_id": 11654, "author": "Darren Kopp", "author_id": 77, "author_profile": "https://Stackoverflow.com/users/77", "pm_score": 4, "selected": false, "text": "_wcsnicmp" }, { "answer_id": 11669, "author": "Wedge", "author_id": 332, "author_profile": "https://Stackoverflow.com/users/332", "pm_score": 4, "selected": false, "text": "strcmp() stricmp() _strncmp() _strnicmp()" }, { "answer_id": 11675, "author": "Coincoin", "author_id": 42, "author_profile": "https://Stackoverflow.com/users/42", "pm_score": 6, "selected": false, "text": "U212B (ANGSTROM SIGN)\nU0041 (LATIN CAPITAL LETTER A) + U030A (COMBINING RING ABOVE)\nU00C5 (LATIN CAPITAL LETTER A WITH RING ABOVE).\n" }, { "answer_id": 11679, "author": "Adam", "author_id": 1366, "author_profile": "https://Stackoverflow.com/users/1366", "pm_score": 4, "selected": false, "text": "bool caseInsensitiveStringCompare( const std::string& str1, const std::string& str2 ) {\n std::string str1Cpy( str1 );\n std::string str2Cpy( str2 );\n std::transform( str1Cpy.begin(), str1Cpy.end(), str1Cpy.begin(), ::tolower );\n std::transform( str2Cpy.begin(), str2Cpy.end(), str2Cpy.begin(), ::tolower );\n return ( str1Cpy == str2Cpy );\n}\n" }, { "answer_id": 27813, "author": "Shadow2531", "author_id": 1697, "author_profile": "https://Stackoverflow.com/users/1697", "pm_score": 5, "selected": false, "text": "bool caseInsensitiveStringCompare(const string& str1, const string& str2) {\n if (str1.size() != str2.size()) {\n return false;\n }\n for (string::const_iterator c1 = str1.begin(), c2 = str2.begin(); c1 != str1.end(); ++c1, ++c2) {\n if (tolower(static_cast<unsigned char>(*c1)) != tolower(static_cast<unsigned char>(*c2))) {\n return false;\n }\n }\n return true;\n}\n" }, { "answer_id": 297355, "author": "John Dibling", "author_id": 241536, "author_profile": "https://Stackoverflow.com/users/241536", "pm_score": 3, "selected": false, "text": "std::string a = \"Hello, World!\";\nstd::string b = \"hello, world!\";\n\nassert( a == b );\n std::istring a = \"Hello, World!\";\nstd::istring b = \"hello, world!\";\n\nassert( a == b );\n /* ---\n\n Case-Insensitive char_traits for std::string's\n\n Use:\n\n To declare a std::string which preserves case but ignores case in comparisons & search,\n use the following syntax:\n\n std::basic_string<char, char_traits_nocase<char> > noCaseString;\n\n A typedef is declared below which simplifies this use for chars:\n\n typedef std::basic_string<char, char_traits_nocase<char> > istring;\n\n --- */\n\n template<class C>\n struct char_traits_nocase : public std::char_traits<C>\n {\n static bool eq( const C& c1, const C& c2 )\n { \n return ::toupper(c1) == ::toupper(c2); \n }\n\n static bool lt( const C& c1, const C& c2 )\n { \n return ::toupper(c1) < ::toupper(c2);\n }\n\n static int compare( const C* s1, const C* s2, size_t N )\n {\n return _strnicmp(s1, s2, N);\n }\n\n static const char* find( const C* s, size_t N, const C& a )\n {\n for( size_t i=0 ; i<N ; ++i )\n {\n if( ::toupper(s[i]) == ::toupper(a) ) \n return s+i ;\n }\n return 0 ;\n }\n\n static bool eq_int_type( const int_type& c1, const int_type& c2 )\n { \n return ::toupper(c1) == ::toupper(c2) ; \n } \n };\n\n template<>\n struct char_traits_nocase<wchar_t> : public std::char_traits<wchar_t>\n {\n static bool eq( const wchar_t& c1, const wchar_t& c2 )\n { \n return ::towupper(c1) == ::towupper(c2); \n }\n\n static bool lt( const wchar_t& c1, const wchar_t& c2 )\n { \n return ::towupper(c1) < ::towupper(c2);\n }\n\n static int compare( const wchar_t* s1, const wchar_t* s2, size_t N )\n {\n return _wcsnicmp(s1, s2, N);\n }\n\n static const wchar_t* find( const wchar_t* s, size_t N, const wchar_t& a )\n {\n for( size_t i=0 ; i<N ; ++i )\n {\n if( ::towupper(s[i]) == ::towupper(a) ) \n return s+i ;\n }\n return 0 ;\n }\n\n static bool eq_int_type( const int_type& c1, const int_type& c2 )\n { \n return ::towupper(c1) == ::towupper(c2) ; \n } \n };\n\n typedef std::basic_string<char, char_traits_nocase<char> > istring;\n typedef std::basic_string<wchar_t, char_traits_nocase<wchar_t> > iwstring;\n" }, { "answer_id": 315463, "author": "Rob", "author_id": 9236, "author_profile": "https://Stackoverflow.com/users/9236", "pm_score": 9, "selected": true, "text": "#include <boost/algorithm/string.hpp>\n// Or, for fewer header dependencies:\n//#include <boost/algorithm/string/predicate.hpp>\n\nstd::string str1 = \"hello, world!\";\nstd::string str2 = \"HELLO, WORLD!\";\n\nif (boost::iequals(str1, str2))\n{\n // Strings are identical\n}\n" }, { "answer_id": 316573, "author": "Johann Gerell", "author_id": 6345, "author_profile": "https://Stackoverflow.com/users/6345", "pm_score": 2, "selected": false, "text": "strcmp strcmp strcmp strcmp" }, { "answer_id": 332713, "author": "bradtgmurray", "author_id": 1546, "author_profile": "https://Stackoverflow.com/users/1546", "pm_score": 5, "selected": false, "text": "strcasecmp stricmp" }, { "answer_id": 2886589, "author": "wilhelmtell", "author_id": 456, "author_profile": "https://Stackoverflow.com/users/456", "pm_score": 7, "selected": false, "text": "char_traits std::string std::basic_string<char> std::basic_string<char, std::char_traits<char> > char_traits basic_string char_traits struct ci_char_traits : public char_traits<char> {\n static bool eq(char c1, char c2) { return toupper(c1) == toupper(c2); }\n static bool ne(char c1, char c2) { return toupper(c1) != toupper(c2); }\n static bool lt(char c1, char c2) { return toupper(c1) < toupper(c2); }\n static int compare(const char* s1, const char* s2, size_t n) {\n while( n-- != 0 ) {\n if( toupper(*s1) < toupper(*s2) ) return -1;\n if( toupper(*s1) > toupper(*s2) ) return 1;\n ++s1; ++s2;\n }\n return 0;\n }\n static const char* find(const char* s, int n, char a) {\n while( n-- > 0 && toupper(*s) != toupper(a) ) {\n ++s;\n }\n return s;\n }\n};\n\ntypedef std::basic_string<char, ci_char_traits> ci_string;\n" }, { "answer_id": 4119881, "author": "Timmmm", "author_id": 265521, "author_profile": "https://Stackoverflow.com/users/265521", "pm_score": 7, "selected": false, "text": "bool iequals(const string& a, const string& b)\n{\n unsigned int sz = a.size();\n if (b.size() != sz)\n return false;\n for (unsigned int i = 0; i < sz; ++i)\n if (tolower(a[i]) != tolower(b[i]))\n return false;\n return true;\n}\n #include <algorithm> bool iequals(const string& a, const string& b)\n{\n return std::equal(a.begin(), a.end(),\n b.begin(), b.end(),\n [](char a, char b) {\n return tolower(a) == tolower(b);\n });\n}\n std::ranges #include <ranges>\n#include <algorithm>\n#include <string>\n\nbool iequals(const std::string_view& lhs, const std::string_view& rhs) {\n auto to_lower{ std::ranges::views::transform(std::tolower) };\n return std::ranges::equal(lhs | to_lower, rhs | to_lower);\n}\n" }, { "answer_id": 10330109, "author": "Igor Milyakov", "author_id": 1358161, "author_profile": "https://Stackoverflow.com/users/1358161", "pm_score": 5, "selected": false, "text": "comparator<char,collator_base::secondary> cmpr;\ncout << (cmpr(str1, str2) ? \"str1 < str2\" : \"str1 >= str2\") << endl;\n" }, { "answer_id": 17330790, "author": "Neutrino", "author_id": 954927, "author_profile": "https://Stackoverflow.com/users/954927", "pm_score": 3, "selected": false, "text": "bool icasecmp(const string& l, const string& r)\n{\n return l.size() == r.size()\n && equal(l.cbegin(), l.cend(), r.cbegin(),\n [](string::value_type l1, string::value_type r1)\n { return toupper(l1) == toupper(r1); });\n}\n\nbool icasecmp(const wstring& l, const wstring& r)\n{\n return l.size() == r.size()\n && equal(l.cbegin(), l.cend(), r.cbegin(),\n [](wstring::value_type l1, wstring::value_type r1)\n { return towupper(l1) == towupper(r1); });\n}\n" }, { "answer_id": 17866339, "author": "reubenjohn", "author_id": 2110869, "author_profile": "https://Stackoverflow.com/users/2110869", "pm_score": 2, "selected": false, "text": "strcmp() strcmpi() stricmp() <string.h> int strcmp(const char*,const char*); //for case sensitive\nint strcmpi(const char*,const char*); //for case insensitive\n string a=\"apple\",b=\"ApPlE\",c=\"ball\";\nif(strcmpi(a.c_str(),b.c_str())==0) //(if it is a match it will return 0)\n cout<<a<<\" and \"<<b<<\" are the same\"<<\"\\n\";\nif(strcmpi(a.c_str(),b.c_str()<0)\n cout<<a[0]<<\" comes before ball \"<<b[0]<<\", so \"<<a<<\" comes before \"<<b;\n" }, { "answer_id": 28869082, "author": "user4578093", "author_id": 4578093, "author_profile": "https://Stackoverflow.com/users/4578093", "pm_score": -1, "selected": false, "text": "bool insensitive_c_compare(char A, char B){\n static char mid_c = ('Z' + 'a') / 2 + 'Z';\n static char up2lo = 'A' - 'a'; /// the offset between upper and lowers\n\n if ('a' >= A and A >= 'z' or 'A' >= A and 'Z' >= A)\n if ('a' >= B and B >= 'z' or 'A' >= B and 'Z' >= B)\n /// check that the character is infact a letter\n /// (trying to turn a 3 into an E would not be pretty!)\n {\n if (A > mid_c and B > mid_c or A < mid_c and B < mid_c)\n {\n return A == B;\n }\n else\n {\n if (A > mid_c)\n A = A - 'a' + 'A'; \n if (B > mid_c)/// convert all uppercase letters to a lowercase ones\n B = B - 'a' + 'A';\n /// this could be changed to B = B + up2lo;\n return A == B;\n }\n }\n}\n" }, { "answer_id": 28900301, "author": "smibe", "author_id": 2239672, "author_profile": "https://Stackoverflow.com/users/2239672", "pm_score": 0, "selected": false, "text": "std::wstring first = L\"Test\";\nstd::wstring second = L\"TEST\";\n\nstd::wregex pattern(first, std::wregex::icase);\nbool isEqual = std::regex_match(second, pattern);\n" }, { "answer_id": 30193591, "author": "Craig Stoddard", "author_id": 4891847, "author_profile": "https://Stackoverflow.com/users/4891847", "pm_score": -1, "selected": false, "text": " for( int i = 0; i < string2.length(); i++)\n {\n if (string1[i] == string2[i] || int(string1[i]) == int(string2[j])+32 ||int(string1[i]) == int(string2[i])-32) \n {\n count++;\n continue;\n }\n else \n {\n break;\n }\n if(count == string2.length())\n {\n //then we have a match\n }\n}\n" }, { "answer_id": 32619426, "author": "Brian Rodriguez", "author_id": 4859885, "author_profile": "https://Stackoverflow.com/users/4859885", "pm_score": 4, "selected": false, "text": "std::lexicographical_compare // lexicographical_compare example\n#include <iostream> // std::cout, std::boolalpha\n#include <algorithm> // std::lexicographical_compare\n#include <cctype> // std::tolower\n\n// a case-insensitive comparison function:\nbool mycomp (char c1, char c2) {\n return std::tolower(c1) < std::tolower(c2);\n}\n\nint main () {\n char foo[] = \"Apple\";\n char bar[] = \"apartment\";\n\n std::cout << std::boolalpha;\n\n std::cout << \"Comparing foo and bar lexicographically (foo < bar):\\n\";\n\n std::cout << \"Using default comparison (operator<): \";\n std::cout << std::lexicographical_compare(foo, foo + 5, bar, bar + 9);\n std::cout << '\\n';\n\n std::cout << \"Using mycomp as comparison object: \";\n std::cout << std::lexicographical_compare(foo, foo + 5, bar, bar + 9, mycomp);\n std::cout << '\\n';\n\n return 0;\n}\n" }, { "answer_id": 32833792, "author": "Simon Richter", "author_id": 613064, "author_profile": "https://Stackoverflow.com/users/613064", "pm_score": 2, "selected": false, "text": "std::locale auto tolower = std::bind1st(\n std::mem_fun(\n &std::ctype<char>::tolower),\n &std::use_facet<std::ctype<char> >(\n std::locale()));\n std::transform std::string left = \"fOo\";\ntransform(left.begin(), left.end(), left.begin(), tolower);\n wchar_t" }, { "answer_id": 34739420, "author": "DavidS", "author_id": 2338792, "author_profile": "https://Stackoverflow.com/users/2338792", "pm_score": 3, "selected": false, "text": "c_str() strcasecmp std::string str1 =\"aBcD\";\nstd::string str2 = \"AbCd\";;\nif (strcasecmp(str1.c_str(), str2.c_str()) == 0)\n{\n //case insensitive equal \n}\n" }, { "answer_id": 39795447, "author": "kyb", "author_id": 3743145, "author_profile": "https://Stackoverflow.com/users/3743145", "pm_score": 4, "selected": false, "text": "strcasecmp(str1.c_str(), str2.c_str()) == 0\n str1 str2 strcasecmp stricmp strcmpi #include <iostream>\n#include <string>\n#include <string.h> //For strcasecmp(). Also could be found in <mem.h>\n\nusing namespace std;\n\n/// Simple wrapper\ninline bool str_ignoreCase_cmp(std::string const& s1, std::string const& s2) {\n if(s1.length() != s2.length())\n return false; // optimization since std::string holds length in variable.\n return strcasecmp(s1.c_str(), s2.c_str()) == 0;\n}\n\n/// Function object - comparator\nstruct StringCaseInsensetiveCompare {\n bool operator()(std::string const& s1, std::string const& s2) {\n if(s1.length() != s2.length())\n return false; // optimization since std::string holds length in variable.\n return strcasecmp(s1.c_str(), s2.c_str()) == 0;\n }\n bool operator()(const char *s1, const char * s2){ \n return strcasecmp(s1,s2)==0;\n }\n};\n\n\n/// Convert bool to string\ninline char const* bool2str(bool b){ return b?\"true\":\"false\"; }\n\nint main()\n{\n cout<< bool2str(strcasecmp(\"asd\",\"AsD\")==0) <<endl;\n cout<< bool2str(strcasecmp(string{\"aasd\"}.c_str(),string{\"AasD\"}.c_str())==0) <<endl;\n StringCaseInsensetiveCompare cmp;\n cout<< bool2str(cmp(\"A\",\"a\")) <<endl;\n cout<< bool2str(cmp(string{\"Aaaa\"},string{\"aaaA\"})) <<endl;\n cout<< bool2str(str_ignoreCase_cmp(string{\"Aaaa\"},string{\"aaaA\"})) <<endl;\n return 0;\n}\n true\ntrue\ntrue\ntrue\ntrue\n" }, { "answer_id": 43226907, "author": "vine'th", "author_id": 478028, "author_profile": "https://Stackoverflow.com/users/478028", "pm_score": 4, "selected": false, "text": "str1.size() == str2.size() && std::equal(str1.begin(), str1.end(), str2.begin(), [](auto a, auto b){return std::tolower(a)==std::tolower(b);})\n std::towlower" }, { "answer_id": 45899185, "author": "Jagadeesh Pulamarasetti", "author_id": 4439625, "author_profile": "https://Stackoverflow.com/users/4439625", "pm_score": 2, "selected": false, "text": "#include<iostream>\n#include<cstring>\n#include<cmath>\nusing namespace std;\nstring tolow(string a)\n{\n for(unsigned int i=0;i<a.length();i++)\n {\n a[i]=tolower(a[i]);\n }\n return a;\n}\nint main()\n{\n string str1,str2;\n cin>>str1>>str2;\n int temp=tolow(str1).compare(tolow(str2));\n if(temp>0)\n cout<<1;\n else if(temp==0)\n cout<<0;\n else\n cout<<-1;\n}\n" }, { "answer_id": 49896180, "author": "DAme", "author_id": 7814722, "author_profile": "https://Stackoverflow.com/users/7814722", "pm_score": 2, "selected": false, "text": "// Case insensitive (could use equivalent _stricmp) \nresult = _stricmp( string1, string2 ); \n std::string s1 = string(\"Hello\");\nif ( _stricmp(s1.c_str(), \"HELLO\") == 0)\n std::cout << \"The string are equals.\";\n" }, { "answer_id": 50052242, "author": "Haseeb Mir", "author_id": 6219626, "author_profile": "https://Stackoverflow.com/users/6219626", "pm_score": 1, "selected": false, "text": "#include <iostream>\n\nstruct iequal\n{\n bool operator()(int c1, int c2) const\n {\n // case insensitive comparison of two characters.\n return std::toupper(c1) == std::toupper(c2);\n }\n};\n\nbool iequals(const std::string& str1, const std::string& str2)\n{\n // use std::equal() to compare range of characters using the functor above.\n return std::equal(str1.begin(), str1.end(), str2.begin(), iequal());\n}\n\nint main(void)\n{\n std::string str_1 = \"HELLO\";\n std::string str_2 = \"hello\";\n\n if(iequals(str_1,str_2))\n {\n std::cout<<\"String are equal\"<<std::endl; \n }\n\n else\n {\n std::cout<<\"String are not equal\"<<std::endl;\n }\n\n\n return 0;\n}\n" } ]
2008/08/14
[ "https://Stackoverflow.com/questions/11635", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1366/" ]
11,665
<p>Here is the sample code for my accordion:</p> <pre><code>&lt;mx:Accordion x="15" y="15" width="230" height="599" styleName="myAccordion"&gt; &lt;mx:Canvas id="pnlSpotlight" label="SPOTLIGHT" height="100%" width="100%" horizontalScrollPolicy="off"&gt; &lt;mx:VBox width="100%" height="80%" paddingTop="2" paddingBottom="1" verticalGap="1"&gt; &lt;mx:Repeater id="rptrSpotlight" dataProvider="{aSpotlight}"&gt; &lt;sm:SmallCourseListItem viewClick="PlayFile(event.currentTarget.getRepeaterItem().fileID);" Description="{rptrSpotlight.currentItem.fileDescription}" FileID = "{rptrSpotlight.currentItem.fileID}" detailsClick="{detailsView.SetFile(event.currentTarget.getRepeaterItem().fileID,this)}" Title="{rptrSpotlight.currentItem.fileTitle}" FileIcon="{iconLibrary.getIcon(rptrSpotlight.currentItem.fileExtension)}" /&gt; &lt;/mx:Repeater&gt; &lt;/mx:VBox&gt; &lt;/mx:Canvas&gt; &lt;/mx:Accordion&gt; </code></pre> <p>I would like to include a button in each header like so:</p> <p><img src="https://i.stack.imgur.com/EN3kP.jpg" alt="wishful&quot; onclick=&quot;alert(&#39;xss&#39;)"></p>
[ { "answer_id": 12266, "author": "Theo", "author_id": 1109, "author_profile": "https://Stackoverflow.com/users/1109", "pm_score": 1, "selected": false, "text": "<mx:Accordion>\n <mx:headerRenderer>\n <mx:Component>\n <AccordionHeader xmlns=\"mx.containers.accordionClasses.*\">\n <mx:Script>\n <![CDATA[\n\n import mx.controls.Button;\n\n\n private var extraButton : Button;\n\n\n override protected function createChildren( ) : void {\n super.createChildren();\n\n if ( extraButton == null ) {\n extraButton = new Button();\n\n addChild(extraButton);\n }\n }\n\n override protected function updateDisplayList( unscaledWidth : Number, unscaledHeight : Number ) : void {\n super.updateDisplayList(unscaledWidth, unscaledHeight);\n\n extraButton.setActualSize(unscaledHeight - 6, unscaledHeight - 6);\n extraButton.move(unscaledWidth - extraButton.width - 3, (unscaledHeight - extraButton.height)/2);\n }\n\n ]]>\n </mx:Script>\n </AccordionHeader>\n </mx:Component>\n </mx:headerRenderer>\n\n <mx:HBox label=\"1\"><Label text=\"Text 1\"/></HBox>\n <mx:HBox label=\"1\"><Label text=\"Text 2\"/></HBox>\n <mx:HBox label=\"1\"><Label text=\"Text 3\"/></HBox>\n</mx:Accordion>\n" } ]
2008/08/14
[ "https://Stackoverflow.com/questions/11665", "https://Stackoverflow.com", "https://Stackoverflow.com/users/26/" ]
11,689
<p>I am intentionally leaving this quite vague at first. I'm looking for discussion and what issues are important more than I'm looking for hard answers.</p> <p>I'm in the middle of designing an app that does something like portfolio management. The design I have so far is</p> <ul> <li>Problem: a problem that needs to be solved</li> <li>Solution: a proposed solution to one or more problems</li> <li>Relationship: a relationship among two problems, two solutions, or a problem and a solution. Further broken down into: <ul> <li>Parent-child - some sort of categorization / tree hierarchy</li> <li>Overlap - the degree to which two solutions or two problems really address the same concept</li> <li>Addresses - the degree to which a problem addresses a solution</li> </ul></li> </ul> <p>My question is about the temporal nature of these things. Problems crop up, then fade. Solutions have an expected resolution date, but that might be modified as they are developed. The degree of a relationship might change over time as problems and solutions evolve.</p> <p>So, the question: what is the best design for versioning of these things so I can get both a current and an historical perspective of my portfolio?</p> <p><em>Later: perhaps I should make this a more specific question, though @Eric Beard's answer is worth an up.</em></p> <p>I've considered three database designs. I'll enough of each to show their drawbacks. My question is: which to pick, or can you think of something better?</p> <h2>1: Problems (and separately, Solutions) are self-referential in versioning.</h2> <pre><code>table problems int id | string name | text description | datetime created_at | int previous_version_id foreign key previous_version_id -&gt; problems.id </code></pre> <p>This is problematic because every time I want a new version, I have to duplicate the entire row, including that long <code>description</code> column.</p> <h2>2: Create a new Relationship type: Version.</h2> <pre><code>table problems int id | string name | text description | datetime created_at </code></pre> <p>This simply moves the relationship from the Problems and Solutions tables into the Relationships table. Same duplication problem, but perhaps a little "cleaner" since I already have an abstract Relationship concept.</p> <h2>3: Use a more Subversion-like structure; move all Problem and Solution attributes into a separate table and version them.</h2> <pre><code>table problems int id table attributes int id | int thing_id | string thing_type | string name | string value | datetime created_at | int previous_version_id foreign key (thing_id, thing_type) -&gt; problems.id or solutions.id foreign key previous_version_id -&gt; attributes.id </code></pre> <p>This means that to load the current version of a Problem or Solution I have to fetch all versions of the attribute, sort them by date and then use the most current. That might not be terrible. What seems really bad to me is that I can't type-check these attributes in the database. That <code>value</code> column has to be free-text. I can make the <code>name</code> column a reference into a separate <code>attribute_names</code> table that has a <code>type</code> column, but that doesn't <em>force</em> the correct type in the <code>attributes</code> table.</p> <p><em>later still: response to @Eric Beard's comments about multi-table foreign keys:</em></p> <p>Alas, what I've described is simplistic: there are only two types of Things (Problems and Solutions). I actually have about 9 or 10 different types of Things, so I'd have 9 or 10 columns of foreign keys under your strategy. I wanted to use single-table inheritance, but the Things have so little in common that it would be <em>extremely</em> wasteful to do combine them into one table.</p>
[ { "answer_id": 12231, "author": "Eric Z Beard", "author_id": 1219, "author_profile": "https://Stackoverflow.com/users/1219", "pm_score": 1, "selected": false, "text": "foreign key (thing_id, thing_type) -> problems.id or solutions.id\n problem_id and solution_id \n" }, { "answer_id": 12278, "author": "James A. Rosen", "author_id": 1190, "author_profile": "https://Stackoverflow.com/users/1190", "pm_score": 0, "selected": false, "text": "custom_attributes description table things\n int id | int type | string name | text description | datetime created_at | other common fields...\n foreign key type -> thing_types.id\n\ntable custom_attributes\n int id | int thing_id | string name | string value\n foreign key thing_id -> things.id\n" }, { "answer_id": 252983, "author": "WW.", "author_id": 14663, "author_profile": "https://Stackoverflow.com/users/14663", "pm_score": 0, "selected": false, "text": "problem_history solution_history VersionNumber EffectiveDate ProblemId VersionNumber problem_history problem_history problem problem_history" } ]
2008/08/14
[ "https://Stackoverflow.com/questions/11689", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1190/" ]
11,690
<p>I've got some Japanese in the ALT attribute, but the tooltip is showing me the ugly block characters in the tooltip. The rest of the content on the page renders correctly. So far, it seems to be limited to the tooltips.</p>
[ { "answer_id": 11747, "author": "eplawless", "author_id": 1370, "author_profile": "https://Stackoverflow.com/users/1370", "pm_score": 1, "selected": false, "text": "<img src=\"test.png\" alt=\"日本語\" />\n" } ]
2008/08/14
[ "https://Stackoverflow.com/questions/11690", "https://Stackoverflow.com", "https://Stackoverflow.com/users/337/" ]
11,699
<p>I'm getting notifications to back up my encryption key for EFS in Vista, however i haven't enabled bit locker or drive encryption.</p> <p>Anyone know how to find out what files may be encrypted or have an explanation for why it would notify me?</p>
[ { "answer_id": 232734, "author": "ParanoidMike", "author_id": 452120, "author_profile": "https://Stackoverflow.com/users/452120", "pm_score": 5, "selected": false, "text": "CIPHER.EXE /U /N\n" } ]
2008/08/14
[ "https://Stackoverflow.com/questions/11699", "https://Stackoverflow.com", "https://Stackoverflow.com/users/580/" ]
11,720
<p>What I would like to do is create a clean virtual machine image as the output of a build of an application.</p> <p>So a new virtual machine would be created (from a template is fine, with the OS installed, and some base software installed) --- a new web site would be created in IIS, and the web app build output copied to a location on the virtual machine hard disk, and IIS configured correctly, the VM would start up and run.</p> <p>I know there are MSBuild tasks to script all the administrative actions in IIS, but how do you script all the actions with Virtual machines? Specifically, creating a new virtual machine from a template, naming it uniquely, starting it, configuring it, etc...</p> <p>Specifically I was wondering if anyone has successfully implemented any VM scripting as part of a build process.</p> <p>Update: I assume with Hyper-V, there is a different set of libraries/APIs to script virtual machines, anyone played around with this? And anyone with real practical experience of doing something like this?</p>
[ { "answer_id": 232734, "author": "ParanoidMike", "author_id": 452120, "author_profile": "https://Stackoverflow.com/users/452120", "pm_score": 5, "selected": false, "text": "CIPHER.EXE /U /N\n" } ]
2008/08/14
[ "https://Stackoverflow.com/questions/11720", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1341/" ]
11,724
<p>On my <strong>Windows XP</strong> machine Visual Studio 2003 2005 and 2008 all complain that I cannot start debugging my <strong>web application</strong> because I must either be a member of the Debug Users group or of the Administrators group. So, I am an Administrator and I added Debug Users just in case, and it still complains.</p> <p>Short of reformatting my machine and starting over, has anyone encountered this and fixed it [with some undocumented command]?</p>
[ { "answer_id": 11842, "author": "Matt Nelson", "author_id": 788, "author_profile": "https://Stackoverflow.com/users/788", "pm_score": 0, "selected": false, "text": "VsJITDebugger.exe -p <PID> VsJITDebugger.exe /?" } ]
2008/08/14
[ "https://Stackoverflow.com/questions/11724", "https://Stackoverflow.com", "https://Stackoverflow.com/users/459/" ]
11,734
<p>I am developing an application to install a large number of data files from multiple DVDs. The application will prompt the user to insert the next disk, however Windows will automatically try to open that disk either in an explorer window or ask the user what to do with the new disk.<br> How can I intercept and cancel auto play messages from my application?</p>
[ { "answer_id": 11735, "author": "Brian Ensink", "author_id": 1254, "author_profile": "https://Stackoverflow.com/users/1254", "pm_score": 3, "selected": true, "text": "IQueryCancelAutoPlay" } ]
2008/08/14
[ "https://Stackoverflow.com/questions/11734", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1254/" ]
11,740
<p>In a web application like wiki or forums or blogging software, it is often useful to store your data in a relational database. Since many hosting companies offer a single database with their hosting plans (with additional databases costing extra) it is very useful for your users when your database objects (tables, views, constraints, and stored procedures) have a common prefix. It is typical for applications aware of database scarcity to have a hard-coded table prefix. I want more, however. Specifically, I'd like to have a table prefix that users can designate—say in the web.config file (with an appropriate default, of course).</p> <p>Since I hate coding <a href="https://en.wikipedia.org/wiki/Create%2C_read%2C_update_and_delete" rel="nofollow noreferrer">CRUD</a> operations by hand, I prefer to work through a competent OR/M and have used (and enjoyed) LINQ to SQL, Subsonic, and ADO.Net. I'm having some thrash in a new project, however, when it comes to putting a table prefix in a user's web.config file. Are there any .Net-based OR/M products that can handle this scenario elegantly?</p> <p>The best I have been able to come up with so far is using LINQ to SQL with an external mapping file that I'd have to update somehow based on an as-yet hypothetical web.config setting.</p> <p>Anyone have a better solution? I tried to make it happen in Entity Framework, but that turned into a mess quickly. (Due to my unfamiliarity with EF? Possibly.) How about SubSonic? Does it have an option to apply a table prefix besides at code generation time?</p>
[ { "answer_id": 12089, "author": "Keith", "author_id": 905, "author_profile": "https://Stackoverflow.com/users/905", "pm_score": 1, "selected": false, "text": "schema select * from dbo.clientAProduct\nselect * from dbo.clientBroduct\n select * from clientA.Product\nselect * from clientB.Product\n" } ]
2008/08/14
[ "https://Stackoverflow.com/questions/11740", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1336/" ]
11,761
<p>I have a web service that queries data from this json file, but I don't want the web service to have to access the file every time. I'm thinking that maybe I can store the data somewhere else (maybe in memory) so the web service can just get the data from there the next time it's trying to query the same data. I kinda understand what needs to be done but I'm just not sure how to actually do it. How do we persist data in a web service? </p> <p><strong>Update:</strong> Both suggestions, caching and using static variables, look good. Maybe I should just use both so I can look at one first, and if it's not in there, use the second one, if it's not in there either, then I'll look at the json file.</p>
[ { "answer_id": 11826, "author": "Mark Glorie", "author_id": 952, "author_profile": "https://Stackoverflow.com/users/952", "pm_score": 4, "selected": true, "text": "Context.Cache.Insert(\"foo\", _\n Foo, _\n Nothing, _\n DateAdd(DateInterval.Minute, 30, Now()), _\n System.Web.Caching.Cache.NoSlidingExpiration)\n <WebMethod(CacheDuration:=60)> _\nPublic Function HelloWorld() As String\n Return \"Hello World\"\nEnd Function\n" }, { "answer_id": 11904, "author": "Seibar", "author_id": 357, "author_profile": "https://Stackoverflow.com/users/357", "pm_score": 2, "selected": false, "text": "public class WebServiceClass\n{\n private static DataTable _myData = null;\n public static DataTable MyData\n {\n get\n {\n if (_myData == null)\n {\n _myData = ParseJsonDataReturnDT();\n }\n return _myData;\n }\n }\n\n [WebMethod]\n public string GetData()\n {\n //... do some stuff with MyData and return a string ...\n return MyData.Rows[0][\"MyColumn\"].ToString();\n }\n}\n" } ]
2008/08/14
[ "https://Stackoverflow.com/questions/11761", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1381/" ]
11,762
<p>I needed some simple string encryption, so I wrote the following code (with a great deal of "inspiration" from <a href="http://www.codeproject.com/KB/security/DotNetCrypto.aspx" rel="noreferrer">here</a>):</p> <pre><code> // create and initialize a crypto algorithm private static SymmetricAlgorithm getAlgorithm(string password) { SymmetricAlgorithm algorithm = Rijndael.Create(); Rfc2898DeriveBytes rdb = new Rfc2898DeriveBytes( password, new byte[] { 0x53,0x6f,0x64,0x69,0x75,0x6d,0x20, // salty goodness 0x43,0x68,0x6c,0x6f,0x72,0x69,0x64,0x65 } ); algorithm.Padding = PaddingMode.ISO10126; algorithm.Key = rdb.GetBytes(32); algorithm.IV = rdb.GetBytes(16); return algorithm; } /* * encryptString * provides simple encryption of a string, with a given password */ public static string encryptString(string clearText, string password) { SymmetricAlgorithm algorithm = getAlgorithm(password); byte[] clearBytes = System.Text.Encoding.Unicode.GetBytes(clearText); MemoryStream ms = new MemoryStream(); CryptoStream cs = new CryptoStream(ms, algorithm.CreateEncryptor(), CryptoStreamMode.Write); cs.Write(clearBytes, 0, clearBytes.Length); cs.Close(); return Convert.ToBase64String(ms.ToArray()); } /* * decryptString * provides simple decryption of a string, with a given password */ public static string decryptString(string cipherText, string password) { SymmetricAlgorithm algorithm = getAlgorithm(password); byte[] cipherBytes = Convert.FromBase64String(cipherText); MemoryStream ms = new MemoryStream(); CryptoStream cs = new CryptoStream(ms, algorithm.CreateDecryptor(), CryptoStreamMode.Write); cs.Write(cipherBytes, 0, cipherBytes.Length); cs.Close(); return System.Text.Encoding.Unicode.GetString(ms.ToArray()); } </code></pre> <p>The code appears to work fine, except that when decrypting data with an incorrect key, I get a CryptographicException - "Padding is invalid and cannot be removed" - on the cs.Close() line in decryptString. </p> <p>example code:</p> <pre><code> string password1 = "password"; string password2 = "letmein"; string startClearText = "The quick brown fox jumps over the lazy dog"; string cipherText = encryptString(startClearText, password1); string endClearText = decryptString(cipherText, password2); // exception thrown </code></pre> <p>My question is, is this to be expected? I would have thought that decrypting with the wrong password would just result in nonsense output, rather than an exception.</p>
[ { "answer_id": 14971080, "author": "jbtule", "author_id": 637783, "author_profile": "https://Stackoverflow.com/users/637783", "pm_score": 3, "selected": false, "text": "AESThenHMAC.AesSimpleDecryptWithPassword(ciphertext, password) null null" }, { "answer_id": 19835066, "author": "Yaniv", "author_id": 2964625, "author_profile": "https://Stackoverflow.com/users/2964625", "pm_score": 4, "selected": false, "text": " MemoryStream msr3 = new MemoryStream();\n CryptoStream encStream = new CryptoStream(msr3, RijndaelAlg.CreateEncryptor(), CryptoStreamMode.Write);\n encStream.Write(bar2, 0, bar2.Length);\n // unless we flush the stream we would get \"Padding is invalid and cannot be removed.\" exception when decoding\n encStream.FlushFinalBlock();\n byte[] bar3 = msr3.ToArray();\n" }, { "answer_id": 28277552, "author": "Mina Wissa", "author_id": 235123, "author_profile": "https://Stackoverflow.com/users/235123", "pm_score": 0, "selected": false, "text": "MemoryStream ms = new MemoryStream(cipherText)\n" }, { "answer_id": 40018716, "author": "Marc L.", "author_id": 85269, "author_profile": "https://Stackoverflow.com/users/85269", "pm_score": 2, "selected": false, "text": "FlushFinalBlock() Close() CryptoStream using CryptoStream using (MemoryStream ms = new MemoryStream())\nusing (var enc = RijndaelAlg.CreateEncryptor())\n{\n using (CryptoStream encStream = new CryptoStream(ms, enc, CryptoStreamMode.Write))\n {\n encStream.Write(bar2, 0, bar2.Length);\n } // implicit close\n byte[] encArray = ms.ToArray();\n}\n using (MemoryStream ms = new MemoryStream())\nusing (var enc = RijndaelAlg.CreateEncryptor())\nusing (CryptoStream encStream = new CryptoStream(ms, enc, CryptoStreamMode.Write))\n{\n encStream.Write(bar2, 0, bar2.Length);\n byte[] encArray = ms.ToArray();\n} // implicit close -- too late!\n" } ]
2008/08/14
[ "https://Stackoverflow.com/questions/11762", "https://Stackoverflow.com", "https://Stackoverflow.com/users/369/" ]
11,767
<p>How can I present a control to the user that allows him/her to select a directory?</p> <p>There doesn't seem to be any native .net controls which do this?</p>
[ { "answer_id": 11781, "author": "David Wengier", "author_id": 489, "author_profile": "https://Stackoverflow.com/users/489", "pm_score": 3, "selected": false, "text": "FolderBrowserDialog System.Windows.Forms" }, { "answer_id": 7634179, "author": "Chandima", "author_id": 976547, "author_profile": "https://Stackoverflow.com/users/976547", "pm_score": 6, "selected": false, "text": "string folderPath = \"\";\nFolderBrowserDialog folderBrowserDialog1 = new FolderBrowserDialog();\nif (folderBrowserDialog1.ShowDialog() == DialogResult.OK) {\n folderPath = folderBrowserDialog1.SelectedPath ;\n}\n" }, { "answer_id": 33817043, "author": "ErikE", "author_id": 57611, "author_profile": "https://Stackoverflow.com/users/57611", "pm_score": 5, "selected": false, "text": "IFileDialog using System;\nusing System.Reflection;\nusing System.Windows.Forms;\n\nnamespace MyCoolCompany.Shuriken {\n /// <summary>\n /// Present the Windows Vista-style open file dialog to select a folder. Fall back for older Windows Versions\n /// </summary>\n public class FolderSelectDialog {\n private string _initialDirectory;\n private string _title;\n private string _fileName = \"\";\n\n public string InitialDirectory {\n get { return string.IsNullOrEmpty(_initialDirectory) ? Environment.CurrentDirectory : _initialDirectory; }\n set { _initialDirectory = value; }\n }\n public string Title {\n get { return _title ?? \"Select a folder\"; }\n set { _title = value; }\n }\n public string FileName { get { return _fileName; } }\n\n public bool Show() { return Show(IntPtr.Zero); }\n\n /// <param name=\"hWndOwner\">Handle of the control or window to be the parent of the file dialog</param>\n /// <returns>true if the user clicks OK</returns>\n public bool Show(IntPtr hWndOwner) {\n var result = Environment.OSVersion.Version.Major >= 6\n ? VistaDialog.Show(hWndOwner, InitialDirectory, Title)\n : ShowXpDialog(hWndOwner, InitialDirectory, Title);\n _fileName = result.FileName;\n return result.Result;\n }\n\n private struct ShowDialogResult {\n public bool Result { get; set; }\n public string FileName { get; set; }\n }\n\n private static ShowDialogResult ShowXpDialog(IntPtr ownerHandle, string initialDirectory, string title) {\n var folderBrowserDialog = new FolderBrowserDialog {\n Description = title,\n SelectedPath = initialDirectory,\n ShowNewFolderButton = false\n };\n var dialogResult = new ShowDialogResult();\n if (folderBrowserDialog.ShowDialog(new WindowWrapper(ownerHandle)) == DialogResult.OK) {\n dialogResult.Result = true;\n dialogResult.FileName = folderBrowserDialog.SelectedPath;\n }\n return dialogResult;\n }\n\n private static class VistaDialog {\n private const string c_foldersFilter = \"Folders|\\n\";\n\n private const BindingFlags c_flags = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic;\n private readonly static Assembly s_windowsFormsAssembly = typeof(FileDialog).Assembly;\n private readonly static Type s_iFileDialogType = s_windowsFormsAssembly.GetType(\"System.Windows.Forms.FileDialogNative+IFileDialog\");\n private readonly static MethodInfo s_createVistaDialogMethodInfo = typeof(OpenFileDialog).GetMethod(\"CreateVistaDialog\", c_flags);\n private readonly static MethodInfo s_onBeforeVistaDialogMethodInfo = typeof(OpenFileDialog).GetMethod(\"OnBeforeVistaDialog\", c_flags);\n private readonly static MethodInfo s_getOptionsMethodInfo = typeof(FileDialog).GetMethod(\"GetOptions\", c_flags);\n private readonly static MethodInfo s_setOptionsMethodInfo = s_iFileDialogType.GetMethod(\"SetOptions\", c_flags);\n private readonly static uint s_fosPickFoldersBitFlag = (uint) s_windowsFormsAssembly\n .GetType(\"System.Windows.Forms.FileDialogNative+FOS\")\n .GetField(\"FOS_PICKFOLDERS\")\n .GetValue(null);\n private readonly static ConstructorInfo s_vistaDialogEventsConstructorInfo = s_windowsFormsAssembly\n .GetType(\"System.Windows.Forms.FileDialog+VistaDialogEvents\")\n .GetConstructor(c_flags, null, new[] { typeof(FileDialog) }, null);\n private readonly static MethodInfo s_adviseMethodInfo = s_iFileDialogType.GetMethod(\"Advise\");\n private readonly static MethodInfo s_unAdviseMethodInfo = s_iFileDialogType.GetMethod(\"Unadvise\");\n private readonly static MethodInfo s_showMethodInfo = s_iFileDialogType.GetMethod(\"Show\");\n\n public static ShowDialogResult Show(IntPtr ownerHandle, string initialDirectory, string title) {\n var openFileDialog = new OpenFileDialog {\n AddExtension = false,\n CheckFileExists = false,\n DereferenceLinks = true,\n Filter = c_foldersFilter,\n InitialDirectory = initialDirectory,\n Multiselect = false,\n Title = title\n };\n\n var iFileDialog = s_createVistaDialogMethodInfo.Invoke(openFileDialog, new object[] { });\n s_onBeforeVistaDialogMethodInfo.Invoke(openFileDialog, new[] { iFileDialog });\n s_setOptionsMethodInfo.Invoke(iFileDialog, new object[] { (uint) s_getOptionsMethodInfo.Invoke(openFileDialog, new object[] { }) | s_fosPickFoldersBitFlag });\n var adviseParametersWithOutputConnectionToken = new[] { s_vistaDialogEventsConstructorInfo.Invoke(new object[] { openFileDialog }), 0U };\n s_adviseMethodInfo.Invoke(iFileDialog, adviseParametersWithOutputConnectionToken);\n\n try {\n int retVal = (int) s_showMethodInfo.Invoke(iFileDialog, new object[] { ownerHandle });\n return new ShowDialogResult {\n Result = retVal == 0,\n FileName = openFileDialog.FileName\n };\n }\n finally {\n s_unAdviseMethodInfo.Invoke(iFileDialog, new[] { adviseParametersWithOutputConnectionToken[1] });\n }\n }\n }\n\n // Wrap an IWin32Window around an IntPtr\n private class WindowWrapper : IWin32Window {\n private readonly IntPtr _handle;\n public WindowWrapper(IntPtr handle) { _handle = handle; }\n public IntPtr Handle { get { return _handle; } }\n }\n }\n}\n VistaDialog Show var dialog = new FolderSelectDialog {\n InitialDirectory = musicFolderTextBox.Text,\n Title = \"Select a folder to import music from\"\n};\nif (dialog.Show(Handle)) {\n musicFolderTextBox.Text = dialog.FileName;\n}\n" }, { "answer_id": 50002970, "author": "Smith", "author_id": 362461, "author_profile": "https://Stackoverflow.com/users/362461", "pm_score": 0, "selected": false, "text": "using System;\nusing System.IO;\nusing System.Runtime.CompilerServices;\nusing System.Runtime.InteropServices;\nusing System.Windows.Forms;\n\ninternal class OpenFolderDialog : IDisposable {\n\n /// <summary>\n /// Gets/sets folder in which dialog will be open.\n /// </summary>\n public string InitialFolder { get; set; }\n\n /// <summary>\n /// Gets/sets directory in which dialog will be open if there is no recent directory available.\n /// </summary>\n public string DefaultFolder { get; set; }\n\n /// <summary>\n /// Gets selected folder.\n /// </summary>\n public string Folder { get; private set; }\n\n\n internal DialogResult ShowDialog(IWin32Window owner) {\n if (Environment.OSVersion.Version.Major >= 6) {\n return ShowVistaDialog(owner);\n } else {\n return ShowLegacyDialog(owner);\n }\n }\n\n private DialogResult ShowVistaDialog(IWin32Window owner) {\n var frm = (NativeMethods.IFileDialog)(new NativeMethods.FileOpenDialogRCW());\n uint options;\n frm.GetOptions(out options);\n options |= NativeMethods.FOS_PICKFOLDERS | NativeMethods.FOS_FORCEFILESYSTEM | NativeMethods.FOS_NOVALIDATE | NativeMethods.FOS_NOTESTFILECREATE | NativeMethods.FOS_DONTADDTORECENT;\n frm.SetOptions(options);\n if (this.InitialFolder != null) {\n NativeMethods.IShellItem directoryShellItem;\n var riid = new Guid(\"43826D1E-E718-42EE-BC55-A1E261C37BFE\"); //IShellItem\n if (NativeMethods.SHCreateItemFromParsingName(this.InitialFolder, IntPtr.Zero, ref riid, out directoryShellItem) == NativeMethods.S_OK) {\n frm.SetFolder(directoryShellItem);\n }\n }\n if (this.DefaultFolder != null) {\n NativeMethods.IShellItem directoryShellItem;\n var riid = new Guid(\"43826D1E-E718-42EE-BC55-A1E261C37BFE\"); //IShellItem\n if (NativeMethods.SHCreateItemFromParsingName(this.DefaultFolder, IntPtr.Zero, ref riid, out directoryShellItem) == NativeMethods.S_OK) {\n frm.SetDefaultFolder(directoryShellItem);\n }\n }\n\n if (frm.Show(owner.Handle) == NativeMethods.S_OK) {\n NativeMethods.IShellItem shellItem;\n if (frm.GetResult(out shellItem) == NativeMethods.S_OK) {\n IntPtr pszString;\n if (shellItem.GetDisplayName(NativeMethods.SIGDN_FILESYSPATH, out pszString) == NativeMethods.S_OK) {\n if (pszString != IntPtr.Zero) {\n try {\n this.Folder = Marshal.PtrToStringAuto(pszString);\n return DialogResult.OK;\n } finally {\n Marshal.FreeCoTaskMem(pszString);\n }\n }\n }\n }\n }\n return DialogResult.Cancel;\n }\n\n private DialogResult ShowLegacyDialog(IWin32Window owner) {\n using (var frm = new SaveFileDialog()) {\n frm.CheckFileExists = false;\n frm.CheckPathExists = true;\n frm.CreatePrompt = false;\n frm.Filter = \"|\" + Guid.Empty.ToString();\n frm.FileName = \"any\";\n if (this.InitialFolder != null) { frm.InitialDirectory = this.InitialFolder; }\n frm.OverwritePrompt = false;\n frm.Title = \"Select Folder\";\n frm.ValidateNames = false;\n if (frm.ShowDialog(owner) == DialogResult.OK) {\n this.Folder = Path.GetDirectoryName(frm.FileName);\n return DialogResult.OK;\n } else {\n return DialogResult.Cancel;\n }\n }\n }\n\n\n public void Dispose() { } //just to have possibility of Using statement.\n\n}\n\ninternal static class NativeMethods {\n\n #region Constants\n\n public const uint FOS_PICKFOLDERS = 0x00000020;\n public const uint FOS_FORCEFILESYSTEM = 0x00000040;\n public const uint FOS_NOVALIDATE = 0x00000100;\n public const uint FOS_NOTESTFILECREATE = 0x00010000;\n public const uint FOS_DONTADDTORECENT = 0x02000000;\n\n public const uint S_OK = 0x0000;\n\n public const uint SIGDN_FILESYSPATH = 0x80058000;\n\n #endregion\n\n\n #region COM\n\n [ComImport, ClassInterface(ClassInterfaceType.None), TypeLibType(TypeLibTypeFlags.FCanCreate), Guid(\"DC1C5A9C-E88A-4DDE-A5A1-60F82A20AEF7\")]\n internal class FileOpenDialogRCW { }\n\n\n [ComImport(), Guid(\"42F85136-DB7E-439C-85F1-E4075D135FC8\"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]\n internal interface IFileDialog {\n [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]\n [PreserveSig()]\n uint Show([In, Optional] IntPtr hwndOwner); //IModalWindow \n\n\n [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]\n uint SetFileTypes([In] uint cFileTypes, [In, MarshalAs(UnmanagedType.LPArray)] IntPtr rgFilterSpec);\n\n [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]\n uint SetFileTypeIndex([In] uint iFileType);\n\n [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]\n uint GetFileTypeIndex(out uint piFileType);\n\n [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]\n uint Advise([In, MarshalAs(UnmanagedType.Interface)] IntPtr pfde, out uint pdwCookie);\n\n [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]\n uint Unadvise([In] uint dwCookie);\n\n [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]\n uint SetOptions([In] uint fos);\n\n [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]\n uint GetOptions(out uint fos);\n\n [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]\n void SetDefaultFolder([In, MarshalAs(UnmanagedType.Interface)] IShellItem psi);\n\n [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]\n uint SetFolder([In, MarshalAs(UnmanagedType.Interface)] IShellItem psi);\n\n [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]\n uint GetFolder([MarshalAs(UnmanagedType.Interface)] out IShellItem ppsi);\n\n [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]\n uint GetCurrentSelection([MarshalAs(UnmanagedType.Interface)] out IShellItem ppsi);\n\n [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]\n uint SetFileName([In, MarshalAs(UnmanagedType.LPWStr)] string pszName);\n\n [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]\n uint GetFileName([MarshalAs(UnmanagedType.LPWStr)] out string pszName);\n\n [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]\n uint SetTitle([In, MarshalAs(UnmanagedType.LPWStr)] string pszTitle);\n\n [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]\n uint SetOkButtonLabel([In, MarshalAs(UnmanagedType.LPWStr)] string pszText);\n\n [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]\n uint SetFileNameLabel([In, MarshalAs(UnmanagedType.LPWStr)] string pszLabel);\n\n [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]\n uint GetResult([MarshalAs(UnmanagedType.Interface)] out IShellItem ppsi);\n\n [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]\n uint AddPlace([In, MarshalAs(UnmanagedType.Interface)] IShellItem psi, uint fdap);\n\n [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]\n uint SetDefaultExtension([In, MarshalAs(UnmanagedType.LPWStr)] string pszDefaultExtension);\n\n [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]\n uint Close([MarshalAs(UnmanagedType.Error)] uint hr);\n\n [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]\n uint SetClientGuid([In] ref Guid guid);\n\n [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]\n uint ClearClientData();\n\n [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]\n uint SetFilter([MarshalAs(UnmanagedType.Interface)] IntPtr pFilter);\n }\n\n\n [ComImport, Guid(\"43826D1E-E718-42EE-BC55-A1E261C37BFE\"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]\n internal interface IShellItem {\n [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]\n uint BindToHandler([In] IntPtr pbc, [In] ref Guid rbhid, [In] ref Guid riid, [Out, MarshalAs(UnmanagedType.Interface)] out IntPtr ppvOut);\n\n [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]\n uint GetParent([MarshalAs(UnmanagedType.Interface)] out IShellItem ppsi);\n\n [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]\n uint GetDisplayName([In] uint sigdnName, out IntPtr ppszName);\n\n [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]\n uint GetAttributes([In] uint sfgaoMask, out uint psfgaoAttribs);\n\n [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]\n uint Compare([In, MarshalAs(UnmanagedType.Interface)] IShellItem psi, [In] uint hint, out int piOrder);\n }\n\n #endregion\n\n\n [DllImport(\"shell32.dll\", CharSet = CharSet.Unicode, SetLastError = true)]\n internal static extern int SHCreateItemFromParsingName([MarshalAs(UnmanagedType.LPWStr)] string pszPath, IntPtr pbc, ref Guid riid, [MarshalAs(UnmanagedType.Interface)] out IShellItem ppv);\n\n}\n using (var frm = new OpenFolderDialog()) {\n if (frm.ShowDialog(this)== DialogResult.OK) {\n MessageBox.Show(this, frm.Folder);\n }\n }\n" } ]
2008/08/14
[ "https://Stackoverflow.com/questions/11767", "https://Stackoverflow.com", "https://Stackoverflow.com/users/234/" ]
11,783
<p>Given an empty method body, will the JIT optimize out the call (I know the C# compiler won't). How would I go about finding out? What tools should I be using and where should I be looking?</p> <p>Since I'm sure it'll be asked, the reason for the empty method is a preprocessor directive.</p> <hr> <p>@Chris: Makes sense, but it could optimize out calls to the method. So the method would still exist, but static calls to it could be removed (or at least inlined...)</p> <p>@Jon: That just tells me the language compiler doesn't do anything. I think what I need to do is run my dll through ngen and look at the assembly.</p>
[ { "answer_id": 12078, "author": "Keith", "author_id": 905, "author_profile": "https://Stackoverflow.com/users/905", "pm_score": 4, "selected": false, "text": "void DoSomethingIfCompFlag() {\n#if COMPILER_FLAG\n //your code\n#endif\n}\n partial void DoSomethingIfCompFlag();\n\n#if COMPILER_FLAG\npartial void DoSomethingIfCompFlag() {\n //your code\n}\n#endif\n" } ]
2008/08/14
[ "https://Stackoverflow.com/questions/11783", "https://Stackoverflow.com", "https://Stackoverflow.com/users/34/" ]
11,804
<p>I'm working on a web service at the moment and there is the potential that the returned results could be quite large ( > 5mb). </p> <p>It's perfectly valid for this set of data to be this large and the web service can be called either sync or async, but I'm wondering what people's thoughts are on the following:</p> <ol> <li><p>If the connection is lost, the entire resultset will have to be regenerated and sent again. Is there any way I can do any sort of "resume" if the connection is lost or reset?</p></li> <li><p>Is sending a result set this large even appropriate? Would it be better to implement some sort of "paging" where the resultset is generated and stored on the server and the client can then download chunks of the resultset in smaller amounts and re-assemble the set at their end?</p></li> </ol>
[ { "answer_id": 920922, "author": "DavidValeri", "author_id": 107057, "author_profile": "https://Stackoverflow.com/users/107057", "pm_score": 3, "selected": true, "text": "WS-ReliableMessaging" } ]
2008/08/15
[ "https://Stackoverflow.com/questions/11804", "https://Stackoverflow.com", "https://Stackoverflow.com/users/493/" ]
11,806
<p>I'm trying to run powershell commands through a web interface (ASP.NET/C#) in order to create mailboxes/etc on Exchange 2007. When I run the page using Visual Studio (Cassini), the page loads up correctly. However, when I run it on IIS (v5.1), I get the error "unknown user name or bad password". The biggest problem that I noticed was that Powershell was logged in as ASPNET instead of my Active Directory Account. How do I force my Powershell session to be authenticated with another Active Directory Account?</p> <p>Basically, the script that I have so far looks something like this:</p> <pre><code>RunspaceConfiguration rc = RunspaceConfiguration.Create(); PSSnapInException snapEx = null; rc.AddPSSnapIn("Microsoft.Exchange.Management.PowerShell.Admin", out snapEx); Runspace runspace = RunspaceFactory.CreateRunspace(rc); runspace.Open(); Pipeline pipeline = runspace.CreatePipeline(); using (pipeline) { pipeline.Commands.AddScript("Get-Mailbox -identity 'user.name'"); pipeline.Commands.Add("Out-String"); Collection&lt;PSObject&gt; results = pipeline.Invoke(); if (pipeline.Error != null &amp;&amp; pipeline.Error.Count &gt; 0) { foreach (object item in pipeline.Error.ReadToEnd()) resultString += "Error: " + item.ToString() + "\n"; } runspace.Close(); foreach (PSObject obj in results) resultString += obj.ToString(); } return resultString; </code></pre>
[ { "answer_id": 12554, "author": "Otto", "author_id": 519, "author_profile": "https://Stackoverflow.com/users/519", "pm_score": 3, "selected": false, "text": "using System;\nusing System.Data;\nusing System.Configuration;\nusing System.Web;\nusing System.Web.Security;\nusing System.Web.UI;\nusing System.Web.UI.WebControls;\nusing System.Web.UI.WebControls.WebParts;\nusing System.Web.UI.HtmlControls;\n\nnamespace orr.Tools\n{\n\n #region Using directives.\n using System.Security.Principal;\n using System.Runtime.InteropServices;\n using System.ComponentModel;\n #endregion\n\n /// <summary>\n /// Impersonation of a user. Allows to execute code under another\n /// user context.\n /// Please note that the account that instantiates the Impersonator class\n /// needs to have the 'Act as part of operating system' privilege set.\n /// </summary>\n /// <remarks> \n /// This class is based on the information in the Microsoft knowledge base\n /// article http://support.microsoft.com/default.aspx?scid=kb;en-us;Q306158\n /// \n /// Encapsulate an instance into a using-directive like e.g.:\n /// \n /// ...\n /// using ( new Impersonator( \"myUsername\", \"myDomainname\", \"myPassword\" ) )\n /// {\n /// ...\n /// [code that executes under the new context]\n /// ...\n /// }\n /// ...\n /// \n /// Please contact the author Uwe Keim (mailto:[email protected])\n /// for questions regarding this class.\n /// </remarks>\n public class Impersonator :\n IDisposable\n {\n #region Public methods.\n /// <summary>\n /// Constructor. Starts the impersonation with the given credentials.\n /// Please note that the account that instantiates the Impersonator class\n /// needs to have the 'Act as part of operating system' privilege set.\n /// </summary>\n /// <param name=\"userName\">The name of the user to act as.</param>\n /// <param name=\"domainName\">The domain name of the user to act as.</param>\n /// <param name=\"password\">The password of the user to act as.</param>\n public Impersonator(\n string userName,\n string domainName,\n string password)\n {\n ImpersonateValidUser(userName, domainName, password);\n }\n\n // ------------------------------------------------------------------\n #endregion\n\n #region IDisposable member.\n\n public void Dispose()\n {\n UndoImpersonation();\n }\n\n // ------------------------------------------------------------------\n #endregion\n\n #region P/Invoke.\n\n [DllImport(\"advapi32.dll\", SetLastError = true)]\n private static extern int LogonUser(\n string lpszUserName,\n string lpszDomain,\n string lpszPassword,\n int dwLogonType,\n int dwLogonProvider,\n ref IntPtr phToken);\n\n [DllImport(\"advapi32.dll\", CharSet = CharSet.Auto, SetLastError = true)]\n private static extern int DuplicateToken(\n IntPtr hToken,\n int impersonationLevel,\n ref IntPtr hNewToken);\n\n [DllImport(\"advapi32.dll\", CharSet = CharSet.Auto, SetLastError = true)]\n private static extern bool RevertToSelf();\n\n [DllImport(\"kernel32.dll\", CharSet = CharSet.Auto)]\n private static extern bool CloseHandle(\n IntPtr handle);\n\n private const int LOGON32_LOGON_INTERACTIVE = 2;\n private const int LOGON32_PROVIDER_DEFAULT = 0;\n\n // ------------------------------------------------------------------\n #endregion\n\n #region Private member.\n // ------------------------------------------------------------------\n\n /// <summary>\n /// Does the actual impersonation.\n /// </summary>\n /// <param name=\"userName\">The name of the user to act as.</param>\n /// <param name=\"domainName\">The domain name of the user to act as.</param>\n /// <param name=\"password\">The password of the user to act as.</param>\n private void ImpersonateValidUser(\n string userName,\n string domain,\n string password)\n {\n WindowsIdentity tempWindowsIdentity = null;\n IntPtr token = IntPtr.Zero;\n IntPtr tokenDuplicate = IntPtr.Zero;\n\n try\n {\n if (RevertToSelf())\n {\n if (LogonUser(\n userName,\n domain,\n password,\n LOGON32_LOGON_INTERACTIVE,\n LOGON32_PROVIDER_DEFAULT,\n ref token) != 0)\n {\n if (DuplicateToken(token, 2, ref tokenDuplicate) != 0)\n {\n tempWindowsIdentity = new WindowsIdentity(tokenDuplicate);\n impersonationContext = tempWindowsIdentity.Impersonate();\n }\n else\n {\n throw new Win32Exception(Marshal.GetLastWin32Error());\n }\n }\n else\n {\n throw new Win32Exception(Marshal.GetLastWin32Error());\n }\n }\n else\n {\n throw new Win32Exception(Marshal.GetLastWin32Error());\n }\n }\n finally\n {\n if (token != IntPtr.Zero)\n {\n CloseHandle(token);\n }\n if (tokenDuplicate != IntPtr.Zero)\n {\n CloseHandle(tokenDuplicate);\n }\n }\n }\n\n /// <summary>\n /// Reverts the impersonation.\n /// </summary>\n private void UndoImpersonation()\n {\n if (impersonationContext != null)\n {\n impersonationContext.Undo();\n }\n }\n\n private WindowsImpersonationContext impersonationContext = null;\n\n // ------------------------------------------------------------------\n #endregion\n }\n}\n" } ]
2008/08/15
[ "https://Stackoverflow.com/questions/11806", "https://Stackoverflow.com", "https://Stackoverflow.com/users/889/" ]
11,809
<p>The only thing I've found has been;</p> <pre class="lang-css prettyprint-override"><code>.hang { text-indent: -3em; margin-left: 3em; } </code></pre> <p>The only way for this to work is putting text in a paragraph, which causes those horribly unsightly extra lines. I'd much rather just have them in a <code>&lt;span class="hang"&gt;&lt;/span&gt;</code> type of thing.</p> <p>I'm also looking for a way to further indent than just a single-level of hanging. Using paragraphs to stack the indentions doesn't work.</p>
[ { "answer_id": 11815, "author": "Shog9", "author_id": 811, "author_profile": "https://Stackoverflow.com/users/811", "pm_score": 5, "selected": true, "text": "<span> <p> <div> display: run-in" }, { "answer_id": 8090502, "author": "David Barnett", "author_id": 1008297, "author_profile": "https://Stackoverflow.com/users/1008297", "pm_score": 4, "selected": false, "text": "p {\n padding-left: 20px; \n} \n\np:first-letter {\n margin-left: -20px;\n}\n p {\n margin-top: 0px;\n margin-bottom: 0px;\n}\n" }, { "answer_id": 29932188, "author": "JCH2", "author_id": 4844225, "author_profile": "https://Stackoverflow.com/users/4844225", "pm_score": 2, "selected": false, "text": "p {\n text-indent: -2en; \n padding-left: 2en;\n}\n" } ]
2008/08/15
[ "https://Stackoverflow.com/questions/11809", "https://Stackoverflow.com", "https://Stackoverflow.com/users/362/" ]
11,820
<p>This <a href="https://stackoverflow.com/questions/11782/file-uploads-via-web-services">question and answer</a> shows how to send a file as a byte array through an XML web service. How much overhead is generated by using this method for file transfer? I assume the data looks something like this:</p> <pre><code>&lt;?xml version="1.0" encoding="UTF-8" ?&gt; &lt;bytes&gt; &lt;byte&gt;16&lt;/byte&gt; &lt;byte&gt;28&lt;/byte&gt; &lt;byte&gt;127&lt;/byte&gt; ... &lt;/bytes&gt; </code></pre> <p>If this format is correct, the bytes must first be converted to UTF-8 characters. Each of these characters allocates 8 bytes. Are the bytes stored in base 10, hex, or binary characters? How much larger does the file appear as it is being sent due to the XML data and character encoding? Is compression built into web services?</p>
[ { "answer_id": 11832, "author": "Kevin Dente", "author_id": 9, "author_profile": "https://Stackoverflow.com/users/9", "pm_score": 5, "selected": true, "text": "base64 base64" } ]
2008/08/15
[ "https://Stackoverflow.com/questions/11820", "https://Stackoverflow.com", "https://Stackoverflow.com/users/26/" ]
11,854
<p>In a project our team is using object lists to perform mass operations on sets of data that should all be processed in a similar way. In particular, different objects would ideally act the same, which would be very easily achieved with polymorphism. The problem I have with it is that inheritance implies the <em>is a</em> relationship, rather than the <em>has a</em> relationship. For example, several objects <em>have a</em> damage counter, but to make this easy to use in an object list, polymorphism could be used - except that would imply an <em>is a</em> relationship which wouldn't be true. (A person <em>is not a</em> damage counter.)</p> <p>The only solution I can think of is to have a member of the class return the proper object type when implicitly casted instead of relying on inheritance. Would it be better to forgo the <em>is a</em> / <em>has a</em> ideal in exchange for ease of programming?</p> <p>Edit: To be more specific, I am using C++, so using polymorphism would allow the different objects to "act the same" in the sense that the derived classes could reside within a single list and be operated upon by a virtual function of the base class. The use of an interface (or imitating them via inheritance) seems like a solution I would be willing to use.</p>
[ { "answer_id": 11859, "author": "Derek Park", "author_id": 872, "author_profile": "https://Stackoverflow.com/users/872", "pm_score": 0, "selected": false, "text": "Damageable DamageCounter Damageable" }, { "answer_id": 11864, "author": "Derek Park", "author_id": 872, "author_profile": "https://Stackoverflow.com/users/872", "pm_score": 0, "selected": false, "text": "vector<Person|Car> vector<with::getDamage()> getDamage() is-a has-a" }, { "answer_id": 11869, "author": "Derek Park", "author_id": 872, "author_profile": "https://Stackoverflow.com/users/872", "pm_score": 0, "selected": false, "text": "addDamage() foreach (obj in mylist)\n obj.addDamage(1)\n class Person : DamageCounter {}\nclass Car : DamageCounter {}\n\nforeach (DamageCounter d in mylist)\n d.addDamage(1)\n Person Car" }, { "answer_id": 11881, "author": "Jon Limjap", "author_id": 372, "author_profile": "https://Stackoverflow.com/users/372", "pm_score": 3, "selected": false, "text": "public interface IDamageable\n{\n void AddDamage(int i);\n int DamageCount {get;}\n}\n public class Person : IDamageable\n\npublic class House : IDamageable\n" }, { "answer_id": 11935, "author": "Brian", "author_id": 725, "author_profile": "https://Stackoverflow.com/users/725", "pm_score": 3, "selected": true, "text": "class Damage {\n virtual void addDamage(int d) = 0;\n virtual int getDamage() = 0;\n};\n\nclass Person : public virtual Damage {\n void addDamage(int d) {\n // ...\n damage += d * 2;\n }\n\n int getDamage() {\n return damage;\n }\n};\n\nclass Car : public virtual Damage {\n void addDamage(int d) {\n // ...\n damage += d;\n }\n\n int getDamage() {\n return damage;\n }\n};\n" }, { "answer_id": 70856, "author": "0124816", "author_id": 11521, "author_profile": "https://Stackoverflow.com/users/11521", "pm_score": 1, "selected": false, "text": "class IDamageable {\n virtual DamageCounter* damage_counter() = 0;\n};\nclass DamageCounter {\n ...\n};\n class Damageable {\n public:\n DamageCounter damage_counter() { return damage_counter_; }\n private:\n DamageCounter damage_counter_;\n};\n" } ]
2008/08/15
[ "https://Stackoverflow.com/questions/11854", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1256/" ]
11,879
<p>Instead of returning a common string, is there a way to return classic objects? If not: what are the best practices? Do you transpose your object to xml and rebuild the object on the other side? What are the other possibilities? </p>
[ { "answer_id": 11899, "author": "lomaxx", "author_id": 493, "author_profile": "https://Stackoverflow.com/users/493", "pm_score": 4, "selected": true, "text": "[Serializable]\npublic class MyClass\n{\n public string MyString {get; set;}\n\n [Serializable]\n public MyOtherClass MyOtherClassProperty {get; set;}\n}\n" } ]
2008/08/15
[ "https://Stackoverflow.com/questions/11879", "https://Stackoverflow.com", "https://Stackoverflow.com/users/391/" ]
11,915
<p>How would you reccommend handling RSS Feeds in ASP.NET MVC? Using a third party library? Using the RSS stuff in the BCL? Just making an RSS view that renders the XML? Or something completely different?</p>
[ { "answer_id": 13662, "author": "Ricky", "author_id": 653, "author_profile": "https://Stackoverflow.com/users/653", "pm_score": 5, "selected": false, "text": "<%@ Page ContentType=\"application/rss+xml\" Language=\"C#\" AutoEventWireup=\"true\" CodeBehind=\"PostRSS.aspx.cs\" Inherits=\"rr.web.Views.Blog.PostRSS\" %><?xml version=\"1.0\" encoding=\"utf-8\"?>\n<rss version=\"2.0\">\n<channel>\n<title>ricky rosario's blog</title>\n<link>http://<%= Request.Url.Host %></link>\n<description>Blog RSS feed for rickyrosario.com</description>\n<lastBuildDate><%= ViewData.Model.First().DatePublished.Value.ToUniversalTime().ToString(\"r\") %></lastBuildDate>\n<language>en-us</language>\n<% foreach (Post p in ViewData.Model) { %>\n <item>\n <title><%= Html.Encode(p.Title) %></title>\n <link>http://<%= Request.Url.Host + Url.Action(\"ViewPostByName\", new RouteValueDictionary(new { name = p.Name })) %></link>\n <guid>http://<%= Request.Url.Host + Url.Action(\"ViewPostByName\", new RouteValueDictionary(new { name = p.Name })) %></guid>\n <pubDate><%= p.DatePublished.Value.ToUniversalTime().ToString(\"r\") %></pubDate>\n <description><%= Html.Encode(p.Content) %></description>\n </item>\n<% } %>\n</channel>\n</rss>\n" }, { "answer_id": 433167, "author": "Eran Kampf", "author_id": 1228206, "author_profile": "https://Stackoverflow.com/users/1228206", "pm_score": 7, "selected": false, "text": "public class RssActionResult : ActionResult\n{\n public SyndicationFeed Feed { get; set; }\n\n public override void ExecuteResult(ControllerContext context)\n {\n context.HttpContext.Response.ContentType = \"application/rss+xml\";\n\n Rss20FeedFormatter rssFormatter = new Rss20FeedFormatter(Feed);\n using (XmlWriter writer = XmlWriter.Create(context.HttpContext.Response.Output))\n {\n rssFormatter.WriteTo(writer);\n }\n }\n}\n return new RssActionResult() { Feed = myFeedInstance };\n" }, { "answer_id": 15932384, "author": "TheDev6", "author_id": 697660, "author_profile": "https://Stackoverflow.com/users/697660", "pm_score": 3, "selected": false, "text": "using System;\nusing System.Collections.Generic;\nusing System.ServiceModel.Syndication;\nusing System.Web;\nusing System.Web.Mvc;\nusing System.Xml;\n\nnamespace MVC3JavaScript_3_2012.Rss\n{\n public class RssFeed : FileResult\n {\n private Uri _currentUrl;\n private readonly string _title;\n private readonly string _description;\n private readonly List<SyndicationItem> _items;\n\n public RssFeed(string contentType, string title, string description, List<SyndicationItem> items)\n : base(contentType)\n {\n _title = title;\n _description = description;\n _items = items;\n }\n\n protected override void WriteFile(HttpResponseBase response)\n {\n var feed = new SyndicationFeed(title: this._title, description: _description, feedAlternateLink: _currentUrl,\n items: this._items);\n var formatter = new Rss20FeedFormatter(feed);\n using (var writer = XmlWriter.Create(response.Output))\n {\n formatter.WriteTo(writer);\n }\n }\n\n public override void ExecuteResult(ControllerContext context)\n {\n _currentUrl = context.RequestContext.HttpContext.Request.Url;\n base.ExecuteResult(context);\n }\n }\n}\n [HttpGet]\npublic ActionResult RssFeed()\n{\n var items = new List<SyndicationItem>();\n for (int i = 0; i < 20; i++)\n {\n var item = new SyndicationItem()\n {\n Id = Guid.NewGuid().ToString(),\n Title = SyndicationContent.CreatePlaintextContent(String.Format(\"My Title {0}\", Guid.NewGuid())),\n Content = SyndicationContent.CreateHtmlContent(\"Content The stuff.\"),\n PublishDate = DateTime.Now\n };\n item.Links.Add(SyndicationLink.CreateAlternateLink(new Uri(\"http://www.google.com\")));//Nothing alternate about it. It is the MAIN link for the item.\n items.Add(item);\n }\n\n return new RssFeed(title: \"Greatness\",\n items: items,\n contentType: \"application/rss+xml\",\n description: String.Format(\"Sooper Dooper {0}\", Guid.NewGuid()));\n\n}\n" } ]
2008/08/15
[ "https://Stackoverflow.com/questions/11915", "https://Stackoverflow.com", "https://Stackoverflow.com/users/571/" ]
11,919
<p>Okay, I've looked all over the internet for a good solution to get PHP and MySQL working on IIS7.0. It's nearly impossible, I've tried it so many times and given up in vain. Please please help by linking some great step-by-step tutorial to adding PHP and MySQL on IIS7.0 from scratch. PHP and MySQL are essential for installing any CMS.</p>
[ { "answer_id": 94341, "author": "Zack Peterson", "author_id": 83, "author_profile": "https://Stackoverflow.com/users/83", "pm_score": 2, "selected": false, "text": ";extension=php_mysql.dll\n Request path: *.php\nExecutable: C:\\php\\php5isapi.dll\nName: PHP\n <html>\n<head>\n<title>PHP Information</title>\n</head>\n<body>\n<?php phpInfo(); ?>\n</body>\n</html>\n" } ]
2008/08/15
[ "https://Stackoverflow.com/questions/11919", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1392/" ]
11,926
<p>I'm new to MVC (and ASP.Net routing). I'm trying to map <code>*.aspx</code> to a controller called <code>PageController</code>. </p> <pre><code>routes.MapRoute( "Page", "{name}.aspx", new { controller = "Page", action = "Index", id = "" } ); </code></pre> <p>Wouldn't the code above map *.aspx to <code>PageController</code>? When I run this and type in any .aspx page I get the following error:</p> <blockquote> <p>The controller for path '/Page.aspx' could not be found or it does not implement the IController interface. Parameter name: controllerType</p> </blockquote> <p>Is there something I'm not doing here?</p>
[ { "answer_id": 11937, "author": "Dale Ragan", "author_id": 1117, "author_profile": "https://Stackoverflow.com/users/1117", "pm_score": 0, "selected": false, "text": "routes.MapRoute(\n \"Page\", \n \"{Page}.aspx\", \n new { controller = \"Page\", action = \"Index\", id = \"\" }\n);\n using System.Web.Mvc;\n\nnamespace MvcApplication1.Controllers\n{\n public class PageController : Controller\n {\n public void Index()\n {\n Response.Write(\"Page.aspx content.\");\n }\n }\n}\n" }, { "answer_id": 11946, "author": "Ryan Eastabrook", "author_id": 105, "author_profile": "https://Stackoverflow.com/users/105", "pm_score": 3, "selected": false, "text": "routes.MapRoute(\n \"Page\",\n \"{Name}.aspx\",\n new { controller = \"Page\", action = \"Display\", id = \"\" }\n );\n\n routes.MapRoute(\n \"Default\", // Route name\n \"{controller}/{action}/{id}\", // URL with parameters\n new { controller = \"Home\", action = \"Index\", id = \"\" } // Parameter defaults\n );\n" }, { "answer_id": 4840639, "author": "Dayi Chen", "author_id": 595443, "author_profile": "https://Stackoverflow.com/users/595443", "pm_score": 0, "selected": false, "text": "public class AspxRouteConstraint : IRouteConstraint\n{\n #region IRouteConstraint Members\n\n public bool Match(HttpContextBase httpContext, Route route, string parameterName, RouteValueDictionary values, RouteDirection routeDirection)\n {\n return values[\"aspx\"].ToString().EndsWith(\".aspx\");\n }\n\n #endregion\n}\n routes.MapRoute(\"all\", \n \"{*aspx}\",//catch all url \n new { Controller = \"Page\", Action = \"index\" }, \n new AspxRouteConstraint() //return true when the url is end with \".aspx\"\n );\n" } ]
2008/08/15
[ "https://Stackoverflow.com/questions/11926", "https://Stackoverflow.com", "https://Stackoverflow.com/users/105/" ]
11,930
<p>How can I determine the IP of my router/gateway in Java? I can get my IP easily enough. I can get my internet IP using a service on a website. But how can I determine my gateway's IP?</p> <p>This is somewhat easy in .NET if you know your way around. But how do you do it in Java?</p>
[ { "answer_id": 11960, "author": "Nick Brosnahan", "author_id": 528, "author_profile": "https://Stackoverflow.com/users/528", "pm_score": 1, "selected": false, "text": "traceroute to www.amazon.com (72.21.203.1), 1 hops max, 40 byte packets\n 1 10.0.1.1 (10.0.1.1) 0.694 ms 0.445 ms 0.398 ms\n" }, { "answer_id": 12030, "author": "Chris Bunch", "author_id": 422, "author_profile": "https://Stackoverflow.com/users/422", "pm_score": 5, "selected": true, "text": "import java.io.*;\nimport java.util.*;\n\npublic class ExecTest {\n public static void main(String[] args) throws IOException {\n Process result = Runtime.getRuntime().exec(\"traceroute -m 1 www.amazon.com\");\n\n BufferedReader output = new BufferedReader(new InputStreamReader(result.getInputStream()));\n String thisLine = output.readLine();\n StringTokenizer st = new StringTokenizer(thisLine);\n st.nextToken();\n String gateway = st.nextToken();\n System.out.printf(\"The gateway is %s\\n\", gateway);\n }\n}\n st.nextToken();" }, { "answer_id": 247216, "author": "Alnitak", "author_id": 6782, "author_profile": "https://Stackoverflow.com/users/6782", "pm_score": 5, "selected": false, "text": "netstat -rn\n traceroute default 0.0.0.0 traceroute traceroute tracert.exe traceroute netstat" }, { "answer_id": 248179, "author": "Hamza Yerlikaya", "author_id": 29742, "author_profile": "https://Stackoverflow.com/users/29742", "pm_score": 2, "selected": false, "text": " try{\n String gateway;\n Process result = Runtime.getRuntime().exec(\"netstat -rn\");\n\n BufferedReader output = new BufferedReader(new InputStreamReader(result.getInputStream()));\n\n String line = output.readLine();\n while(line != null){\n if ( line.trim().startsWith(\"default\") == true || line.trim().startsWith(\"0.0.0.0\") == true )\n break; \n line = output.readLine();\n }\n if(line==null) //gateway not found;\n return;\n\n StringTokenizer st = new StringTokenizer( line );\n st.nextToken();\n st.nextToken();\n gateway = st.nextToken();\n System.out.println(\"gateway is: \"+gateway);\n\n\n } catch( Exception e ) { \n System.out.println( e.toString() );\n gateway = new String();\n adapter = new String();\n }\n" }, { "answer_id": 274999, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": " BufferedReader buffer = null;\n try {\n URL url = new URL(\"http://whatismyip.com/automation/n09230945.asp\");\n InputStreamReader in = new InputStreamReader(url.openStream());\n buffer = new BufferedReader(in);\n\n String line = buffer.readLine();\n System.out.println(line);\n } catch (IOException e) {\n e.printStackTrace();\n } finally {\n try {\n if (buffer != null) {\n buffer.close();\n }\n } catch (IOException e) {\n e.printStackTrace();\n }\n }\n" }, { "answer_id": 9005568, "author": "Loki Nightray", "author_id": 1169530, "author_profile": "https://Stackoverflow.com/users/1169530", "pm_score": 2, "selected": false, "text": "import java.io.BufferedReader; \nimport java.io.IOException; \nimport java.io.InputStreamReader; \nimport java.net.URL; \nimport java.util.regex.Matcher; \nimport java.util.regex.Pattern; \n\npublic class Main {\n\n public static void main(String[] args) {\n BufferedReader buffer = null;\n try {\n URL url = new URL(\n \"http://www.whatismyip.com/tools/ip-address-lookup.asp\");\n InputStreamReader in = new InputStreamReader(url.openStream());\n buffer = new BufferedReader(in);\n String line = buffer.readLine();\n Pattern pattern = Pattern\n .compile(\"(.*)value=\\\"(\\\\d+).(\\\\d+).(\\\\d+).(\\\\d+)\\\"(.*)\");\n Matcher matcher;\n while (line != null) {\n matcher = pattern.matcher(line);\n if (matcher.matches()) {\n line = matcher.group(2) + \".\" + matcher.group(3) + \".\"\n + matcher.group(4) + \".\" + matcher.group(5);\n System.out.println(line);\n }\n line = buffer.readLine();\n }\n } catch (IOException e) {\n e.printStackTrace();\n\n } finally {\n try {\n if (buffer != null) {\n buffer.close();\n }\n } catch (IOException e) {\n e.printStackTrace();\n }\n }\n }\n}\n\nimport java.io.BufferedReader; \nimport java.io.IOException; \nimport java.io.InputStreamReader; \nimport java.net.URL; \nimport java.util.regex.Matcher; \nimport java.util.regex.Pattern; \n\npublic class Main {\n\n public static void main(String[] args) {\n BufferedReader buffer = null;\n try {\n URL url = new URL(\n \"http://www.whatismyip.com/tools/ip-address-lookup.asp\");\n InputStreamReader in = new InputStreamReader(url.openStream());\n buffer = new BufferedReader(in);\n String line = buffer.readLine();\n Pattern pattern = Pattern\n .compile(\"(.*)value=\\\"(\\\\d+).(\\\\d+).(\\\\d+).(\\\\d+)\\\"(.*)\");\n Matcher matcher;\n while (line != null) {\n matcher = pattern.matcher(line);\n if (matcher.matches()) {\n line = matcher.group(2) + \".\" + matcher.group(3) + \".\"\n + matcher.group(4) + \".\" + matcher.group(5);\n System.out.println(line);\n }\n line = buffer.readLine();\n }\n } catch (IOException e) {\n e.printStackTrace();\n\n } finally {\n try {\n if (buffer != null) {\n buffer.close();\n }\n } catch (IOException e) {\n e.printStackTrace();\n }\n }\n }\n}\n" }, { "answer_id": 20806279, "author": "ZZ 5", "author_id": 1646298, "author_profile": "https://Stackoverflow.com/users/1646298", "pm_score": 1, "selected": false, "text": "ipconfig | findstr /i \"Gateway\"\n Default Gateway . . . . . . . . . : 192.168.2.1\nDefault Gateway . . . . . . . . . : ::\n" }, { "answer_id": 36679773, "author": "chandan", "author_id": 6216657, "author_profile": "https://Stackoverflow.com/users/6216657", "pm_score": 1, "selected": false, "text": "netstat -rn private String getDefaultAddress() {\n String defaultAddress = \"\";\n try {\n Process result = Runtime.getRuntime().exec(\"netstat -rn\");\n\n BufferedReader output = new BufferedReader(new InputStreamReader(\n result.getInputStream()));\n\n String line = output.readLine();\n while (line != null) {\n if (line.contains(\"0.0.0.0\")) {\n\n StringTokenizer stringTokenizer = new StringTokenizer(line);\n stringTokenizer.nextElement(); // first element is 0.0.0.0\n stringTokenizer.nextElement(); // second element is 0.0.0.0\n defaultAddress = (String) stringTokenizer.nextElement();\n break;\n }\n\n line = output.readLine();\n\n } // while\n } catch (IOException e) {\n // TODO Auto-generated catch block\n e.printStackTrace();\n }\n\n return defaultAddress;\n\n} // getDefaultAddress\n" }, { "answer_id": 54699876, "author": "PCK4D", "author_id": 5750738, "author_profile": "https://Stackoverflow.com/users/5750738", "pm_score": 0, "selected": false, "text": "import java.net.InetAddress;\nimport java.net.UnknownHostException;\npublic class Main\n{\n public static void main(String[] args)\n {\n try\n {\n //Variables to find out the Default Gateway IP(s)\n String canonicalHostName = InetAddress.getLocalHost().getCanonicalHostName();\n String hostName = InetAddress.getLocalHost().getHostName();\n\n //\"subtract\" the hostName from the canonicalHostName, +1 due to the \".\" in there\n String defaultGatewayLeftover = canonicalHostName.substring(hostName.length() + 1);\n\n //Info printouts\n System.out.println(\"Info:\\nCanonical Host Name: \" + canonicalHostName + \"\\nHost Name: \" + hostName + \"\\nDefault Gateway Leftover: \" + defaultGatewayLeftover + \"\\n\");\n System.out.println(\"Default Gateway Addresses:\\n\" + printAddresses(InetAddress.getAllByName(defaultGatewayLeftover)));\n } catch (UnknownHostException e)\n {\n e.printStackTrace();\n }\n }\n //simple combined string out of the address array\n private static String printAddresses(InetAddress[] allByName)\n {\n if (allByName.length == 0)\n {\n return \"\";\n } else\n {\n String str = \"\";\n int i = 0;\n while (i < allByName.length - 1)\n {\n str += allByName[i] + \"\\n\";\n i++;\n }\n return str + allByName[i];\n }\n }\n}\n Info:\nCanonical Host Name: PCK4D-PC.speedport.ip\nHost Name: PCK4D-PC\nDefault Gateway Leftover: speedport.ip\n\nDefault Gateway Addresses:\nspeedport.ip/192.168.2.1\nspeedport.ip/fe80:0:0:0:0:0:0:1%12\n" } ]
2008/08/15
[ "https://Stackoverflow.com/questions/11930", "https://Stackoverflow.com", "https://Stackoverflow.com/users/338/" ]
11,950
<p>I'm looking for the best way to log errors in an ASP.NET application. I want to be able to receive emails when errors occurs in my application, with detailed information about the Exception and the current Request.</p> <p>In my company we used to have our own ErrorMailer, catching everything in the Global.asax Application_Error. It was "Ok" but not very flexible nor configurable.</p> <p>We switched recently to NLog. It's much more configurable, we can define different targets for the errors, filter them, buffer them (not tried yet). It's a very good improvement.</p> <p>But I discovered lately that there's a whole Namespace in the .Net framework for this purpose : <a href="http://msdn.microsoft.com/en-us/library/system.web.management.aspx" rel="noreferrer">System.Web.Management</a> and it can be configured in the <a href="http://msdn.microsoft.com/en-us/library/2fwh2ss9(VS.80).aspx" rel="noreferrer">healthMonitoring</a> section of web.config.</p> <p>Have you ever worked with .Net health monitoring? What is your solution for error logging?</p>
[ { "answer_id": 11961, "author": "brendan", "author_id": 225, "author_profile": "https://Stackoverflow.com/users/225", "pm_score": 0, "selected": false, "text": "Try\n Dim p as New Person()\n p.Name = \"Joe\"\n p.Age = 30\nCatch ex as Exception\n Log.LogException(ex,\"Err creating person and assigning name/age\")\n Throw ex\nEnd Try\n" } ]
2008/08/15
[ "https://Stackoverflow.com/questions/11950", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1130/" ]
12,009
<p>How can I pipe the new password to smbpasswd so I can automate my installation process.</p>
[ { "answer_id": 12026, "author": "Mark Harrison", "author_id": 116, "author_profile": "https://Stackoverflow.com/users/116", "pm_score": 4, "selected": false, "text": "(echo oldpasswd; echo newpasswd) | smbpasswd -s\n" }, { "answer_id": 12032, "author": "UnkwnTech", "author_id": 115, "author_profile": "https://Stackoverflow.com/users/115", "pm_score": 7, "selected": true, "text": "(echo newpassword; echo confirmNewPassword) | smbpasswd -s\n" }, { "answer_id": 62796, "author": "Bruno De Fraine", "author_id": 6918, "author_profile": "https://Stackoverflow.com/users/6918", "pm_score": 5, "selected": false, "text": " echo -ne \"$PASS\\n$PASS\\n\" | smbpasswd -a -s $LOGIN\n" }, { "answer_id": 15841153, "author": "Charles Prince", "author_id": 2001428, "author_profile": "https://Stackoverflow.com/users/2001428", "pm_score": 1, "selected": false, "text": "#!/usr/bin/python\n#converted from: http://pexpect.sourceforge.net/pexpect.html\n#child = pexpect.spawn('scp foo [email protected]:.')\n#child.expect ('Password:')\n#child.sendline (mypassword)\nimport pexpect\nimport sys\nuser=sys.argv[1]\npasswd=sys.argv[2]\nchild = pexpect.spawn('/usr/bin/smbpasswd -a '+str(user))\nchild.expect('New SMB password:')\nchild.sendline (passwd)\nchild.expect ('Retype new SMB password:')\nchild.sendline (passwd)\n" }, { "answer_id": 19770281, "author": "ReklatsMasters", "author_id": 1556249, "author_profile": "https://Stackoverflow.com/users/1556249", "pm_score": 3, "selected": false, "text": "echo 'somepassword' | tee - | smbpasswd -s" }, { "answer_id": 53428249, "author": "Samuli Seppänen", "author_id": 2543558, "author_profile": "https://Stackoverflow.com/users/2543558", "pm_score": 2, "selected": false, "text": "yes vagrant|head -n 2|smbpasswd -a -s vagrant\n" } ]
2008/08/15
[ "https://Stackoverflow.com/questions/12009", "https://Stackoverflow.com", "https://Stackoverflow.com/users/115/" ]
12,039
<p>I have an application that sometimes causes a BSOD on a Win XP machine. Trying to find out more, I loaded up the resulting *.dmp file (from C:\Windows\Minidump), but get this message when in much of the readout when doing so:</p> <pre><code>********************************************************************* * Symbols can not be loaded because symbol path is not initialized. * * * * The Symbol Path can be set by: * * using the _NT_SYMBOL_PATH environment variable. * * using the -y &lt;symbol_path&gt; argument when starting the debugger. * * using .sympath and .sympath+ * ********************************************************************* </code></pre> <p>What does this mean, and how do I "fix" it?</p>
[ { "answer_id": 12132, "author": "C. K. Young", "author_id": 13, "author_profile": "https://Stackoverflow.com/users/13", "pm_score": 3, "selected": false, "text": "_NT_SYMBOL_PATH srv*C:\\Windows\\Symbols*http //msdl.microsoft.com/download/symbols C:\\Windows\\Symbols _NT_SYMBOL_PATH srv*C:\\Documents and Settings\\cky\\symbols*http //msdl.microsoft.com/download/symbols" }, { "answer_id": 1493488, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "!symfix\n" } ]
2008/08/15
[ "https://Stackoverflow.com/questions/12039", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
12,051
<p>If I inherit from a base class and want to pass something from the constructor of the inherited class to the constructor of the base class, how do I do that?</p> <p>For example, if I inherit from the Exception class I want to do something like this:</p> <pre><code>class MyExceptionClass : Exception { public MyExceptionClass(string message, string extraInfo) { //This is where it's all falling apart base(message); } } </code></pre> <p>Basically what I want is to be able to pass the string message to the base Exception class.</p>
[ { "answer_id": 12052, "author": "Jon Limjap", "author_id": 372, "author_profile": "https://Stackoverflow.com/users/372", "pm_score": 12, "selected": true, "text": "public class MyExceptionClass : Exception\n{\n public MyExceptionClass(string message, string extrainfo) : base(message)\n {\n //other stuff here\n }\n}\n" }, { "answer_id": 1844965, "author": "SnowBEE", "author_id": 224505, "author_profile": "https://Stackoverflow.com/users/224505", "pm_score": 5, "selected": false, "text": "public class MyExceptionClass : Exception\n{\n public MyExceptionClass(string message,\n Exception innerException): base(message, innerException)\n {\n //other stuff here\n }\n}\n" }, { "answer_id": 2731807, "author": "Axl", "author_id": 16605, "author_profile": "https://Stackoverflow.com/users/16605", "pm_score": 9, "selected": false, "text": "class MyExceptionClass : Exception\n{\n public MyExceptionClass(string message, string extraInfo) : \n base(ModifyMessage(message, extraInfo))\n {\n }\n\n private static string ModifyMessage(string message, string extraInfo)\n {\n Trace.WriteLine(\"message was \" + message);\n return message.ToLowerInvariant() + Environment.NewLine + extraInfo;\n }\n}\n" }, { "answer_id": 15103087, "author": "aalimian", "author_id": 1490214, "author_profile": "https://Stackoverflow.com/users/1490214", "pm_score": 7, "selected": false, "text": "public class MyClass : BaseClass\n{\n private MyClass(string someString) : base(someString)\n {\n //your code goes in here\n }\n\n public static MyClass FactoryMethod(string someString)\n {\n //whatever you want to do with your string before passing it in\n return new MyClass(someString);\n }\n}\n" }, { "answer_id": 19905310, "author": "Janus Pedersen", "author_id": 1032159, "author_profile": "https://Stackoverflow.com/users/1032159", "pm_score": 5, "selected": false, "text": "base this public ClassName() : this(par1,par2)\n{\n// do not call the constructor it is called in the this.\n// the base key- word is used to call a inherited constructor \n} \n\n// Hint used overload as often as needed do not write the same code 2 or more times\n" }, { "answer_id": 34973293, "author": "Fab", "author_id": 5328150, "author_profile": "https://Stackoverflow.com/users/5328150", "pm_score": 5, "selected": false, "text": " class MyException : Exception\n public class MyException : Exception\n [Serializable()]\npublic class MyException : Exception\n{\n public MyException()\n {\n // Add any type-specific logic, and supply the default message.\n }\n\n public MyException(string message): base(message) \n {\n // Add any type-specific logic.\n }\n public MyException(string message, Exception innerException): \n base (message, innerException)\n {\n // Add any type-specific logic for inner exceptions.\n }\n protected MyException(SerializationInfo info, \n StreamingContext context) : base(info, context)\n {\n // Implement type-specific serialization constructor logic.\n }\n} \n [Serializable()]\n public sealed class MyException : Exception\n {\n public MyException()\n {\n // Add any type-specific logic, and supply the default message.\n }\n\n public MyException(string message): base(message) \n {\n // Add any type-specific logic.\n }\n public MyException(string message, Exception innerException): \n base (message, innerException)\n {\n // Add any type-specific logic for inner exceptions.\n }\n private MyException(SerializationInfo info, \n StreamingContext context) : base(info, context)\n {\n // Implement type-specific serialization constructor logic.\n }\n } \n" }, { "answer_id": 36475682, "author": "Donat Sasin", "author_id": 5097657, "author_profile": "https://Stackoverflow.com/users/5097657", "pm_score": 4, "selected": false, "text": "public class MyException : Exception\n{\n public MyException() { }\n public MyException(string msg) : base(msg) { }\n public MyException(string msg, Exception inner) : base(msg, inner) { }\n}\n" }, { "answer_id": 37492479, "author": "dynamiclynk", "author_id": 1427166, "author_profile": "https://Stackoverflow.com/users/1427166", "pm_score": 4, "selected": false, "text": "public MyClass(object myObject=null): base(myObject ?? new myOtherObject())\n{\n}\n public MyClass(object myObject=null): base(myObject==null ? new myOtherObject(): myObject)\n{\n}\n" }, { "answer_id": 42786257, "author": "CShark", "author_id": 3033876, "author_profile": "https://Stackoverflow.com/users/3033876", "pm_score": 4, "selected": false, "text": "public class MyException : Exception\n{\n public MyException(string message, string extraInfo) : base(message)\n {\n }\n}\n extraInfo extraInfo Message public class MyException: Exception\n{\n public MyException(string message, string extraInfo) : base($\"{message} Extra info: {extraInfo}\")\n {\n }\n}\n" }, { "answer_id": 60657371, "author": "springy76", "author_id": 442376, "author_profile": "https://Stackoverflow.com/users/442376", "pm_score": 3, "selected": false, "text": "out var public abstract class BaseClass\n{\n protected BaseClass(int a, int b, int c)\n {\n }\n}\n public class DerivedClass : BaseClass\n{\n private readonly object fatData;\n\n public DerivedClass(int m)\n {\n var fd = new { A = 1 * m, B = 2 * m, C = 3 * m };\n base(fd.A, fd.B, fd.C); // base-constructor call\n this.fatData = fd;\n }\n}\n public class DerivedClass : BaseClass\n{\n private readonly object fatData;\n\n public DerivedClass(int m)\n : base(PrepareBaseParameters(m, out var b, out var c, out var fatData), b, c)\n {\n this.fatData = fatData;\n Console.WriteLine(new { b, c, fatData }.ToString());\n }\n\n private static int PrepareBaseParameters(int m, out int b, out int c, out object fatData)\n {\n var fd = new { A = 1 * m, B = 2 * m, C = 3 * m };\n (b, c, fatData) = (fd.B, fd.C, fd); // Tuples not required but nice to use\n return fd.A;\n }\n}\n" } ]
2008/08/15
[ "https://Stackoverflow.com/questions/12051", "https://Stackoverflow.com", "https://Stackoverflow.com/users/493/" ]
12,088
<p>I wonder if anyone uses commercial/free java obfuscators on his own commercial product. I know only about one project that actually had an obfuscating step in the ant build step for releases.</p> <p>Do you obfuscate? And if so, why do you obfuscate?</p> <p>Is it really a way to protect the code or is it just a better feeling for the developers/managers?</p> <p><strong>edit:</strong> Ok, I to be exact about my point: Do you obfuscate to protect your IP (your algorithms, the work you've put into your product)? I won't obfuscate for security reasons, that doesn't feel right. So I'm only talking about protecting your applications code against competitors.</p> <p><a href="https://stackoverflow.com/users/988/staffan">@staffan</a> has a good point:</p> <blockquote> <p>The reason to stay away from chaining code flow is that some of those changes makes it impossible for the JVM to efficiently optimize the code. In effect it will actually degrade the performance of your application.</p> </blockquote>
[ { "answer_id": 12100, "author": "izb", "author_id": 974, "author_profile": "https://Stackoverflow.com/users/974", "pm_score": 4, "selected": false, "text": "public void doSomething()\n{\n /* Generated config class containing static finals: */\n if (Configuration.ISMOTOROLA)\n {\n System.out.println(\"This is a motorola phone\");\n }\n else\n {\n System.out.println(\"This is not a motorola phone\");\n }\n}\n public void doSomething()\n{\n System.out.println(\"This is a motorola phone\");\n}\n" }, { "answer_id": 110472, "author": "adum", "author_id": 9871, "author_profile": "https://Stackoverflow.com/users/9871", "pm_score": 4, "selected": false, "text": " if(i < ll1) goto _L6; else goto _L5\n_L5:\n char ac[] = run(stop(lI1l));\n l7 = (long)ac.length << 32 & 0xffffffff00000000L ^ l7 & 0xffffffffL;\n if((int)((l7 & 0xffffffff00000000L) >> 32) != $5$)\n {\n l = (long)III << 50 & 0x4000000000000L ^ l & 0xfffbffffffffffffL;\n } else\n {\n for(l3 = (long)III & 0xffffffffL ^ l3 & 0xffffffff00000000L; (int)(l3 & 0xffffffffL) < ll1; l3 = (long)(S$$ + (int)(l3 & 0xffffffffL)) ^ l3 & 0xffffffff00000000L)\n {\n for(int j = III; j < ll1; j++)\n {\n l2 = (long)actionevent[j][(int)(l3 & 0xffffffffL)] & 65535L ^ l2 & 0xffffffffffff0000L;\n l6 = (long)(j << -351) & 0xffffffffL ^ l6 & 0xffffffff00000000L;\n l1 = (long)((int)(l6 & 0xffffffffL) + j) & 0xffffffffL ^ l1 & 0xffffffff00000000L;\n l = (long)((int)(l1 & 0xffffffffL) + (int)(l3 & 0xffffffffL)) << 16 & 0xffffffff0000L ^ l & 0xffff00000000ffffL;\n l = (long)ac[(int)((l & 0xffffffff0000L) >> 16)] & 65535L ^ l & 0xffffffffffff0000L;\n if((char)(int)(l2 & 65535L) != (char)(int)(l & 65535L))\n {\n l = (long)III << 50 & 0x4000000000000L ^ l & 0xfffbffffffffffffL;\n }\n }\n\n }\n\n }\n" } ]
2008/08/15
[ "https://Stackoverflow.com/questions/12088", "https://Stackoverflow.com", "https://Stackoverflow.com/users/834/" ]
12,095
<p>Our team is creating a new recruitment workflow system to replace an old one. I have been tasked with migrating the old data into the new schema. I have decided to do this by creating a small Windows Forms project as the schema are radically different and straight TSQL scripts are not an adequate solution.</p> <p>The main sealed class 'ImportController' that does the work declares the following delegate event:</p> <pre><code>public delegate void ImportProgressEventHandler(object sender, ImportProgressEventArgs e); public static event ImportProgressEventHandler importProgressEvent; </code></pre> <p>The main window starts a static method in that class using a new thread:</p> <pre><code>Thread dataProcessingThread = new Thread(new ParameterizedThreadStart(ImportController.ImportData)); dataProcessingThread.Name = "Data Importer: Data Processing Thread"; dataProcessingThread.Start(settings); </code></pre> <p>the ImportProgressEvent args carries a string message, a max int value for the progress bar and an current progress int value. The Windows form subcribes to the event:</p> <pre><code>ImportController.importProgressEvent += new ImportController.ImportProgressEventHandler(ImportController_importProgressEvent); </code></pre> <p>And responds to the event in this manner using it's own delegate:</p> <pre><code> private delegate void TaskCompletedUIDelegate(string completedTask, int currentProgress, int progressMax); private void ImportController_importProgressEvent(object sender, ImportProgressEventArgs e) { this.Invoke(new TaskCompletedUIDelegate(this.DisplayCompletedTask), e.CompletedTask, e.CurrentProgress, e.ProgressMax); } </code></pre> <p>Finally the progress bar and listbox are updated:</p> <pre><code>private void DisplayCompletedTask(string completedTask, int currentProgress, int progressMax) { string[] items = completedTask.Split(new string[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries); foreach (string item in items) { this.lstTasks.Items.Add(item); } if (currentProgress &gt;= 0 &amp;&amp; progressMax &gt; 0 &amp;&amp; currentProgress &lt;= progressMax) { this.ImportProgressBar.Maximum = progressMax; this.ImportProgressBar.Value = currentProgress; } } </code></pre> <p>The thing is the ListBox seems to update very quickly, but the progress bar never moves until the batch is almost complete anyway ??? what gives ?</p>
[ { "answer_id": 12115, "author": "Peteter", "author_id": 1192, "author_profile": "https://Stackoverflow.com/users/1192", "pm_score": 0, "selected": false, "text": "Application.DoEvents();" } ]
2008/08/15
[ "https://Stackoverflow.com/questions/12095", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2083160/" ]
12,103
<p>When I am running the following statement:</p> <pre><code>@filtered = map {s/&amp;nbsp;//g} @outdata; </code></pre> <p>it is returning an empty list instead of the filtered list that I expected. What I am trying to do is remove every occurrence of <code>&amp;nbsp;</code> from an array of string (which is an XML file).</p> <p>Obviously, I am not understanding something. Can anyone tell me the correct way to do this might be, and why this isn't working for me as is?</p>
[ { "answer_id": 12108, "author": "Greg Hewgill", "author_id": 893, "author_profile": "https://Stackoverflow.com/users/893", "pm_score": 4, "selected": true, "text": "@filtered = map {s/&nbsp;//g; $_} @outdata;\n" }, { "answer_id": 13685, "author": "Cebjyre", "author_id": 1612, "author_profile": "https://Stackoverflow.com/users/1612", "pm_score": 2, "selected": false, "text": "@filtered = grep {s/&nbsp;//g; 1} @outdata;\n" }, { "answer_id": 21792, "author": "Tithonium", "author_id": 2425, "author_profile": "https://Stackoverflow.com/users/2425", "pm_score": 4, "selected": false, "text": "map {s/&nbsp;//g} @outdata;\n @filtered = @outdata;\nmap {s/&nbsp;//g} @filtered;\n s/&nbsp;//g foreach @filtered;\n" }, { "answer_id": 63167, "author": "Michael Cramer", "author_id": 1496728, "author_profile": "https://Stackoverflow.com/users/1496728", "pm_score": 3, "selected": false, "text": "@filtered = map {local $_=$_; s/&nbsp;//g; $_} @outdata;\n" }, { "answer_id": 63314, "author": "Shlomi Fish", "author_id": 7709, "author_profile": "https://Stackoverflow.com/users/7709", "pm_score": 3, "selected": false, "text": "@filtered = map { (my $new = $_) =~ s/&nbsp;//g; $new} @outdata;\n" }, { "answer_id": 329969, "author": "ysth", "author_id": 17389, "author_profile": "https://Stackoverflow.com/users/17389", "pm_score": 2, "selected": false, "text": "use Algorithm::Loops \"Filter\";\n@filtered = Filter { s/&nbsp;//g } @outdata;\n" }, { "answer_id": 10657173, "author": "pasja", "author_id": 944375, "author_profile": "https://Stackoverflow.com/users/944375", "pm_score": 3, "selected": false, "text": "@filtered = map {s/&nbsp;//gr} @outdata;\n" } ]
2008/08/15
[ "https://Stackoverflow.com/questions/12103", "https://Stackoverflow.com", "https://Stackoverflow.com/users/274/" ]
12,135
<p>I'm using an XmlSerializer to deserialize a particular type in mscorelib.dll</p> <pre><code>XmlSerializer ser = new XmlSerializer( typeof( [.Net type in System] ) ); return ([.Net type in System]) ser.Deserialize( new StringReader( xmlValue ) ); </code></pre> <p>This throws a caught <code>FileNotFoundException</code> when the assembly is loaded:</p> <blockquote> <p>"Could not load file or assembly 'mscorlib.XmlSerializers, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' or one of its dependencies. The system cannot find the file specified."</p> </blockquote> <p>FusionLog:</p> <pre><code>=== Pre-bind state information === LOG: User = ### LOG: DisplayName = mscorlib.XmlSerializers, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089, processorArchitecture=x86 (Fully-specified) LOG: Appbase = file:///C:/localdir LOG: Initial PrivatePath = NULL Calling assembly : System.Xml, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089. === LOG: This bind starts in default load context. LOG: Using application configuration file: C:\localdir\bin\Debug\appname.vshost.exe.Config LOG: Using machine configuration file from c:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\config\machine.config. LOG: Post-policy reference: mscorlib.XmlSerializers, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089, processorArchitecture=x86 LOG: Attempting download of new URL file:///C:/localdir/bin/Debug/mscorlib.XmlSerializers.DLL. LOG: Attempting download of new URL file:///C:/localdir/bin/Debug/mscorlib.XmlSerializers/mscorlib.XmlSerializers.DLL. LOG: Attempting download of new URL file:///C:/localdir/bin/Debug/mscorlib.XmlSerializers.EXE. LOG: Attempting download of new URL file:///C:/localdir/bin/Debug/mscorlib.XmlSerializers/mscorlib.XmlSerializers.EXE. </code></pre> <p>As far as I know there is no mscorlib.XmlSerializers.DLL, I think the DLL name has bee auto generated by .Net looking for the serializer. </p> <p>You have the option of creating a myApplication.XmlSerializers.DLL when compiling to optimise serializations, so I assume this is part of the framework's checking for it.</p> <p>The problem is that this appears to be causing a delay in loading the application - it seems to hang for a few seconds at this point.</p> <p>Any ideas how to avoid this or speed it up?</p>
[ { "answer_id": 953571, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "XmlRootAttribute rootAttribute = new XmlRootAttribute();\nrootAttribute.ElementName = \"SomeRootName\";\nrootAttribute.IsNullable = true;\n" } ]
2008/08/15
[ "https://Stackoverflow.com/questions/12135", "https://Stackoverflow.com", "https://Stackoverflow.com/users/905/" ]
12,140
<p>A database application that I'm currently working on, stores all sorts of settings in the database. Most of those settings are there to customize certain business rules, but there's also some other stuff in there.</p> <p>The app contains objects that specifically do a certain task, e.g., a certain complicated calculation. Those non-UI objects are unit-tested, but also need access to lots of those global settings. The way we've implemented this right now, is by giving the objects properties that are filled by the Application Controller at runtime. When testing, we create the objects in the test and fill in values for testing (not from the database).</p> <p>This works better, in any case much better than having all those objects need some global <em>Settings</em> object --- that of course effectively makes unit testing impossible :) Disadvantage can be that you sometimes need to set a dozen of properties, or that you need to let those properties 'percolate' into sub-objects.</p> <p><strong>So the general question is</strong>: how do you provide access to global application settings in your projects, without the need for global variables, while still being able to unit test your code? This must be a problem that's been solved 100's of times...</p> <p>(Note: I'm not too much of an experienced programmer, as you'll have noticed; but I love to learn! And of course, I've already done research into this topic, but I'm really looking for some first-hand experiences)</p>
[ { "answer_id": 12183, "author": "Lars Mæhlum", "author_id": 960, "author_profile": "https://Stackoverflow.com/users/960", "pm_score": 0, "selected": false, "text": "public class MySettings\n{\n public static double Setting1\n { get { return SettingsCache.Instance.GetDouble(\"Setting1\"); } }\n\n public static string Setting2\n { get { return SettingsCache.Instance.GetString(\"Setting2\"); } }\n}\n" }, { "answer_id": 12185, "author": "Magnar", "author_id": 1123, "author_profile": "https://Stackoverflow.com/users/1123", "pm_score": 2, "selected": true, "text": "class ServiceLocator {\n private static $soleInstance;\n private $globalSettings;\n\n public static function load($locator) {\n self::$soleInstance = $locator;\n }\n\n public static function globalSettings() {\n if (!isset(self::$soleInstance->globalSettings)) {\n self::$soleInstance->setGlobalSettings(new GlobalSettings());\n }\n return self::$soleInstance->globalSettings;\n }\n}\n ServiceLocator::load(new ServiceLocator());\n ServiceLocator s = new ServiceLocator();\ns->setGlobalSettings(new MockGlobalSettings());\nServiceLocator::load(s);\n" }, { "answer_id": 12210, "author": "Dale Ragan", "author_id": 1117, "author_profile": "https://Stackoverflow.com/users/1117", "pm_score": 1, "selected": false, "text": "public class ConfigurationItem<T>\n{\n private T item;\n\n public ConfigurationItem(T item)\n {\n this.item = item;\n }\n\n public T GetValue()\n {\n return item;\n }\n}\n public class ConfigurationItems\n{\n public static ConfigurationItem<ConnectionStringSettings> ConnectionSettings = new ConfigurationItem<ConnectionStringSettings>(RetrieveConnectionString());\n\n private static ConnectionStringSettings RetrieveConnectionString()\n {\n // In .Net, we store our connection string in the application/web config file.\n // We can access those values through the ConfigurationManager class.\n return ConfigurationManager.ConnectionStrings[ConfigurationManager.AppSettings[\"ConnectionKey\"]];\n }\n}\n ConfigurationItems.ConnectionSettings.GetValue();\n [TestFixture]\npublic class ConfigurationItemsTest\n{\n [Test]\n public void ShouldBeAbleToAccessConnectionStringSettings()\n {\n ConnectionStringSettings item = ConfigurationItems.ConnectionSettings.GetValue();\n Assert.IsNotNull(item);\n }\n}\n" } ]
2008/08/15
[ "https://Stackoverflow.com/questions/12140", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1037/" ]
12,141
<p>For example: Updating all rows of the customer table because you forgot to add the where clause.</p> <ol> <li>What was it like, realizing it and reporting it to your coworkers or customers? </li> <li>What were the lessons learned?</li> </ol>
[ { "answer_id": 12145, "author": "Keith", "author_id": 905, "author_profile": "https://Stackoverflow.com/users/905", "pm_score": 3, "selected": false, "text": "delete from [table] where [condition]\n delete [table] where [condition]\n" }, { "answer_id": 12149, "author": "Surgical Coder", "author_id": 1276, "author_profile": "https://Stackoverflow.com/users/1276", "pm_score": 4, "selected": false, "text": "truncate table Customers\ntruncate table Transactions\n" }, { "answer_id": 12227, "author": "Marshall", "author_id": 1302, "author_profile": "https://Stackoverflow.com/users/1302", "pm_score": 3, "selected": false, "text": "update facilities set address1 = '123 Fake Street'\n where facilityid in (1, 2, 3)\n" }, { "answer_id": 12280, "author": "Seibar", "author_id": 357, "author_profile": "https://Stackoverflow.com/users/357", "pm_score": 2, "selected": false, "text": "update Customers set ModifyUser = 'Terrapin'\n" }, { "answer_id": 12404, "author": "travis", "author_id": 1414, "author_profile": "https://Stackoverflow.com/users/1414", "pm_score": 3, "selected": false, "text": "DROP TABLE" }, { "answer_id": 313038, "author": "Jordan Stewart", "author_id": 33338, "author_profile": "https://Stackoverflow.com/users/33338", "pm_score": 3, "selected": false, "text": "update email set processedTime=null,sentTime=null" } ]
2008/08/15
[ "https://Stackoverflow.com/questions/12141", "https://Stackoverflow.com", "https://Stackoverflow.com/users/990/" ]
12,144
<p>OK, so I don't want to start a holy-war here, but we're in the process of trying to consolidate the way we handle our application configuration files and we're struggling to make a decision on the best approach to take. At the moment, every application we distribute is using it's own ad-hoc configuration files, whether it's property files (ini style), XML or JSON (internal use only at the moment!).</p> <p>Most of our code is Java at the moment, so we've been looking at <a href="http://commons.apache.org/configuration/" rel="noreferrer">Apache Commons Config</a>, but we've found it to be quite verbose. We've also looked at <a href="http://xmlbeans.apache.org/" rel="noreferrer">XMLBeans</a>, but it seems like a lot of faffing around. I also feel as though I'm being pushed towards XML as a format, but my clients and colleagues are apprehensive about trying something else. I can understand it from the client's perspective, everybody's heard of XML, but at the end of the day, shouldn't be using the right tool for the job?</p> <p>What formats and libraries are people using in production systems these days, is anyone else trying to avoid the <a href="http://www.codinghorror.com/blog/archives/001114.html" rel="noreferrer">angle bracket tax</a>?</p> <p><strong><em>Edit:</strong> really needs to be a cross platform solution: Linux, Windows, Solaris etc. and the choice of library used to interface with configuration files is just as important as the choice of format.</em></p>
[ { "answer_id": 12277, "author": "engtech", "author_id": 175, "author_profile": "https://Stackoverflow.com/users/175", "pm_score": 5, "selected": false, "text": "<user id=\"babooey\" on=\"cpu1\">\n <firstname>Bob</firstname>\n <lastname>Abooey</lastname>\n <department>adv</department>\n <cell>555-1212</cell>\n <address password=\"xxxx\">[email protected]</address>\n <address password=\"xxxx\">[email protected]</address>\n</user>\n babooey:\n computer : cpu1\n firstname: Bob\n lastname: Abooey\n cell: 555-1212\n addresses:\n - address: [email protected]\n password: xxxx\n - address: [email protected]\n password: xxxx\n" }, { "answer_id": 12703, "author": "Herms", "author_id": 1409, "author_profile": "https://Stackoverflow.com/users/1409", "pm_score": 3, "selected": false, "text": " <Connector port=\"80\" maxHttpHeaderSize=\"8192\"\n maxThreads=\"150\" minSpareThreads=\"25\" maxSpareThreads=\"75\"\n enableLookups=\"false\" redirectPort=\"8443\" acceptCount=\"100\"\n connectionTimeout=\"20000\" disableUploadTimeout=\"true\" />\n\n\n <Connector port=\"8009\" \n enableLookups=\"false\" redirectPort=\"8443\" protocol=\"AJP/1.3\" />\n" } ]
2008/08/15
[ "https://Stackoverflow.com/questions/12144", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1030/" ]
12,159
<p>I have thus far avoided the nightmare that is testing multi-threaded code since it just seems like too much of a minefield. I'd like to ask how people have gone about testing code that relies on threads for successful execution, or just how people have gone about testing those kinds of issues that only show up when two threads interact in a given manner?</p> <p>This seems like a really key problem for programmers today, it would be useful to pool our knowledge on this one imho.</p>
[ { "answer_id": 12223, "author": "Dale Ragan", "author_id": 1117, "author_profile": "https://Stackoverflow.com/users/1117", "pm_score": 2, "selected": false, "text": "PropertyNotifyChanged WaitCallback ConditionalWaiter" }, { "answer_id": 125487, "author": "Kevin Wong", "author_id": 4792, "author_profile": "https://Stackoverflow.com/users/4792", "pm_score": 4, "selected": false, "text": "throwable tearDown AtomicBoolean @Test(timeout=60*1000) @After\npublic void tearDown() {\n if ( throwable != null )\n throw throwable;\n}\n import static org.junit.Assert.fail;\nimport java.io.File;\nimport java.lang.reflect.InvocationHandler;\nimport java.lang.reflect.Proxy;\nimport java.util.Random;\nimport org.apache.commons.collections.Closure;\nimport org.apache.commons.collections.Predicate;\nimport org.apache.commons.lang.time.StopWatch;\nimport org.easymock.EasyMock;\nimport org.easymock.classextension.internal.ClassExtensionHelper;\nimport static org.easymock.classextension.EasyMock.*;\n\nimport ca.digitalrapids.io.DRFileUtils;\n\n/**\n * Various utilities for testing\n */\npublic abstract class DRTestUtils\n{\n static private Random random = new Random();\n\n/** Calls {@link #waitForCondition(Integer, Integer, Predicate, String)} with\n * default max wait and check period values.\n */\nstatic public void waitForCondition(Predicate predicate, String errorMessage) \n throws Throwable\n{\n waitForCondition(null, null, predicate, errorMessage);\n}\n\n/** Blocks until a condition is true, throwing an {@link AssertionError} if\n * it does not become true during a given max time.\n * @param maxWait_ms max time to wait for true condition. Optional; defaults\n * to 30 * 1000 ms (30 seconds).\n * @param checkPeriod_ms period at which to try the condition. Optional; defaults\n * to 100 ms.\n * @param predicate the condition\n * @param errorMessage message use in the {@link AssertionError}\n * @throws Throwable on {@link AssertionError} or any other exception/error\n */\nstatic public void waitForCondition(Integer maxWait_ms, Integer checkPeriod_ms, \n Predicate predicate, String errorMessage) throws Throwable \n{\n waitForCondition(maxWait_ms, checkPeriod_ms, predicate, new Closure() {\n public void execute(Object errorMessage)\n {\n fail((String)errorMessage);\n }\n }, errorMessage);\n}\n\n/** Blocks until a condition is true, running a closure if\n * it does not become true during a given max time.\n * @param maxWait_ms max time to wait for true condition. Optional; defaults\n * to 30 * 1000 ms (30 seconds).\n * @param checkPeriod_ms period at which to try the condition. Optional; defaults\n * to 100 ms.\n * @param predicate the condition\n * @param closure closure to run\n * @param argument argument for closure\n * @throws Throwable on {@link AssertionError} or any other exception/error\n */\nstatic public void waitForCondition(Integer maxWait_ms, Integer checkPeriod_ms, \n Predicate predicate, Closure closure, Object argument) throws Throwable \n{\n if ( maxWait_ms == null )\n maxWait_ms = 30 * 1000;\n if ( checkPeriod_ms == null )\n checkPeriod_ms = 100;\n StopWatch stopWatch = new StopWatch();\n stopWatch.start();\n while ( !predicate.evaluate(null) ) {\n Thread.sleep(checkPeriod_ms);\n if ( stopWatch.getTime() > maxWait_ms ) {\n closure.execute(argument);\n }\n }\n}\n\n/** Calls {@link #waitForVerify(Integer, Object)} with <code>null</code>\n * for {@code maxWait_ms}\n */\nstatic public void waitForVerify(Object easyMockProxy)\n throws Throwable\n{\n waitForVerify(null, easyMockProxy);\n}\n\n/** Repeatedly calls {@link EasyMock#verify(Object[])} until it succeeds, or a\n * max wait time has elapsed.\n * @param maxWait_ms Max wait time. <code>null</code> defaults to 30s.\n * @param easyMockProxy Proxy to call verify on\n * @throws Throwable\n */\nstatic public void waitForVerify(Integer maxWait_ms, Object easyMockProxy)\n throws Throwable\n{\n if ( maxWait_ms == null )\n maxWait_ms = 30 * 1000;\n StopWatch stopWatch = new StopWatch();\n stopWatch.start();\n for(;;) {\n try\n {\n verify(easyMockProxy);\n break;\n }\n catch (AssertionError e)\n {\n if ( stopWatch.getTime() > maxWait_ms )\n throw e;\n Thread.sleep(100);\n }\n }\n}\n\n/** Returns a path to a directory in the temp dir with the name of the given\n * class. This is useful for temporary test files.\n * @param aClass test class for which to create dir\n * @return the path\n */\nstatic public String getTestDirPathForTestClass(Object object) \n{\n\n String filename = object instanceof Class ? \n ((Class)object).getName() :\n object.getClass().getName();\n return DRFileUtils.getTempDir() + File.separator + \n filename;\n}\n\nstatic public byte[] createRandomByteArray(int bytesLength)\n{\n byte[] sourceBytes = new byte[bytesLength];\n random.nextBytes(sourceBytes);\n return sourceBytes;\n}\n\n/** Returns <code>true</code> if the given object is an EasyMock mock object \n */\nstatic public boolean isEasyMockMock(Object object) {\n try {\n InvocationHandler invocationHandler = Proxy\n .getInvocationHandler(object);\n return invocationHandler.getClass().getName().contains(\"easymock\");\n } catch (IllegalArgumentException e) {\n return false;\n }\n}\n}\n @Test\npublic void testSomething() {\n final AtomicBoolean called = new AtomicBoolean(false);\n subject.setCallback(new SomeCallback() {\n public void callback(Object arg) {\n // check arg here\n called.set(true);\n }\n });\n subject.run();\n assertTrue(called.get());\n}\n" }, { "answer_id": 2345540, "author": "scim", "author_id": 102153, "author_profile": "https://Stackoverflow.com/users/102153", "pm_score": 3, "selected": false, "text": "public interface IThread\n{\n void Start();\n ...\n}\n\npublic class ThreadWrapper : IThread\n{\n private readonly Thread _thread;\n \n public ThreadWrapper(ThreadStart threadStart)\n {\n _thread = new Thread(threadStart);\n }\n\n public Start()\n {\n _thread.Start();\n }\n}\n \npublic interface IThreadingManager\n{\n IThread CreateThread(ThreadStart threadStart);\n}\n\npublic class ThreadingManager : IThreadingManager\n{\n public IThread CreateThread(ThreadStart threadStart)\n {\n return new ThreadWrapper(threadStart)\n }\n}\n" }, { "answer_id": 4227668, "author": "Johan", "author_id": 398441, "author_profile": "https://Stackoverflow.com/users/398441", "pm_score": 4, "selected": false, "text": "await().untilCall( to(myService).myMethod(), greaterThan(3) );\n await().atMost(5,SECONDS).until(fieldIn(myObject).ofType(int.class), equalTo(1));\n await until { something() > 4 } // Scala example\n" }, { "answer_id": 49736681, "author": "Avraham Shalev", "author_id": 4516910, "author_profile": "https://Stackoverflow.com/users/4516910", "pm_score": -1, "selected": false, "text": "Class TestedClass {\n public void doAsychOp() {\n new Thread(new myRunnable()).start();\n }\n}\n @Mock\nprivate Thread threadMock;\n\n@Test\npublic void myTest() throws Exception {\n PowerMockito.mockStatic(Thread.class);\n //when new thread is created execute runnable immediately \n PowerMockito.whenNew(Thread.class).withAnyArguments().then(new Answer<Thread>() {\n @Override\n public Thread answer(InvocationOnMock invocation) throws Throwable {\n // immediately run the runnable\n Runnable runnable = invocation.getArgumentAt(0, Runnable.class);\n if(runnable != null) {\n runnable.run();\n }\n return threadMock;//return a mock so Thread.start() will do nothing \n }\n }); \n TestedClass testcls = new TestedClass()\n testcls.doAsychOp(); //will invoke myRunnable.run in current thread\n //.... check expected \n}\n" }, { "answer_id": 65727155, "author": "Tim", "author_id": 5703407, "author_profile": "https://Stackoverflow.com/users/5703407", "pm_score": 0, "selected": false, "text": "using System;\nusing System.Collections.Generic;\nusing System.Threading;\nusing System.Threading.Tasks;\n\nnamespace Proto.Promises.Tests.Threading\n{\n public class ThreadHelper\n {\n public static readonly int multiThreadCount = Environment.ProcessorCount * 100;\n private static readonly int[] offsets = new int[] { 0, 10, 100, 1000 };\n\n private readonly Stack<Task> _executingTasks = new Stack<Task>(multiThreadCount);\n private readonly Barrier _barrier = new Barrier(1);\n private int _currentParticipants = 0;\n private readonly TimeSpan _timeout;\n\n public ThreadHelper() : this(TimeSpan.FromSeconds(10)) { } // 10 second timeout should be enough for most cases.\n\n public ThreadHelper(TimeSpan timeout)\n {\n _timeout = timeout;\n }\n\n /// <summary>\n /// Execute the action multiple times in parallel threads.\n /// </summary>\n public void ExecuteMultiActionParallel(Action action)\n {\n for (int i = 0; i < multiThreadCount; ++i)\n {\n AddParallelAction(action);\n }\n ExecutePendingParallelActions();\n }\n\n /// <summary>\n /// Execute the action once in a separate thread.\n /// </summary>\n public void ExecuteSingleAction(Action action)\n {\n AddParallelAction(action);\n ExecutePendingParallelActions();\n }\n\n /// <summary>\n /// Add an action to be run in parallel.\n /// </summary>\n public void AddParallelAction(Action action)\n {\n var taskSource = new TaskCompletionSource<bool>();\n lock (_executingTasks)\n {\n ++_currentParticipants;\n _barrier.AddParticipant();\n _executingTasks.Push(taskSource.Task);\n }\n new Thread(() =>\n {\n try\n {\n _barrier.SignalAndWait(); // Try to make actions run in lock-step to increase likelihood of breaking race conditions.\n action.Invoke();\n taskSource.SetResult(true);\n }\n catch (Exception e)\n {\n taskSource.SetException(e);\n }\n }).Start();\n }\n\n /// <summary>\n /// Runs the pending actions in parallel, attempting to run them in lock-step.\n /// </summary>\n public void ExecutePendingParallelActions()\n {\n Task[] tasks;\n lock (_executingTasks)\n {\n _barrier.SignalAndWait();\n _barrier.RemoveParticipants(_currentParticipants);\n _currentParticipants = 0;\n tasks = _executingTasks.ToArray();\n _executingTasks.Clear();\n }\n try\n {\n if (!Task.WaitAll(tasks, _timeout))\n {\n throw new TimeoutException($\"Action(s) timed out after {_timeout}, there may be a deadlock.\");\n }\n }\n catch (AggregateException e)\n {\n // Only throw one exception instead of aggregate to try to avoid overloading the test error output.\n throw e.Flatten().InnerException;\n }\n }\n\n /// <summary>\n /// Run each action in parallel multiple times with differing offsets for each run.\n /// <para/>The number of runs is 4^actions.Length, so be careful if you don't want the test to run too long.\n /// </summary>\n /// <param name=\"expandToProcessorCount\">If true, copies each action on additional threads up to the processor count. This can help test more without increasing the time it takes to complete.\n /// <para/>Example: 2 actions with 6 processors, runs each action 3 times in parallel.</param>\n /// <param name=\"setup\">The action to run before each parallel run.</param>\n /// <param name=\"teardown\">The action to run after each parallel run.</param>\n /// <param name=\"actions\">The actions to run in parallel.</param>\n public void ExecuteParallelActionsWithOffsets(bool expandToProcessorCount, Action setup, Action teardown, params Action[] actions)\n {\n setup += () => { };\n teardown += () => { };\n int actionCount = actions.Length;\n int expandCount = expandToProcessorCount ? Math.Max(Environment.ProcessorCount / actionCount, 1) : 1;\n foreach (var combo in GenerateCombinations(offsets, actionCount))\n {\n setup.Invoke();\n for (int k = 0; k < expandCount; ++k)\n {\n for (int i = 0; i < actionCount; ++i)\n {\n int offset = combo[i];\n Action action = actions[i];\n AddParallelAction(() =>\n {\n for (int j = offset; j > 0; --j) { } // Just spin in a loop for the offset.\n action.Invoke();\n });\n }\n }\n ExecutePendingParallelActions();\n teardown.Invoke();\n }\n }\n\n // Input: [1, 2, 3], 3\n // Ouput: [\n // [1, 1, 1],\n // [2, 1, 1],\n // [3, 1, 1],\n // [1, 2, 1],\n // [2, 2, 1],\n // [3, 2, 1],\n // [1, 3, 1],\n // [2, 3, 1],\n // [3, 3, 1],\n // [1, 1, 2],\n // [2, 1, 2],\n // [3, 1, 2],\n // [1, 2, 2],\n // [2, 2, 2],\n // [3, 2, 2],\n // [1, 3, 2],\n // [2, 3, 2],\n // [3, 3, 2],\n // [1, 1, 3],\n // [2, 1, 3],\n // [3, 1, 3],\n // [1, 2, 3],\n // [2, 2, 3],\n // [3, 2, 3],\n // [1, 3, 3],\n // [2, 3, 3],\n // [3, 3, 3]\n // ]\n private static IEnumerable<int[]> GenerateCombinations(int[] options, int count)\n {\n int[] indexTracker = new int[count];\n int[] combo = new int[count];\n for (int i = 0; i < count; ++i)\n {\n combo[i] = options[0];\n }\n // Same algorithm as picking a combination lock.\n int rollovers = 0;\n while (rollovers < count)\n {\n yield return combo; // No need to duplicate the array since we're just reading it.\n for (int i = 0; i < count; ++i)\n {\n int index = ++indexTracker[i];\n if (index == options.Length)\n {\n indexTracker[i] = 0;\n combo[i] = options[0];\n if (i == rollovers)\n {\n ++rollovers;\n }\n }\n else\n {\n combo[i] = options[index];\n break;\n }\n }\n }\n }\n }\n}\n [Test]\npublic void DeferredMayBeBeResolvedAndPromiseAwaitedConcurrently_void0()\n{\n Promise.Deferred deferred = default(Promise.Deferred);\n Promise promise = default(Promise);\n\n int invokedCount = 0;\n\n var threadHelper = new ThreadHelper();\n threadHelper.ExecuteParallelActionsWithOffsets(false,\n // Setup\n () =>\n {\n invokedCount = 0;\n deferred = Promise.NewDeferred();\n promise = deferred.Promise;\n },\n // Teardown\n () => Assert.AreEqual(1, invokedCount),\n // Parallel Actions\n () => deferred.Resolve(),\n () => promise.Then(() => { Interlocked.Increment(ref invokedCount); }).Forget()\n );\n}\n" }, { "answer_id": 73224125, "author": "mercury0114", "author_id": 4929809, "author_profile": "https://Stackoverflow.com/users/4929809", "pm_score": 0, "selected": false, "text": "def process(input):\n # Spawns several threads to do the job\n # ...\n return output\n process(input1) -> expect to return output1\nprocess(input2) -> expect to return output2\n...\n process" } ]
2008/08/15
[ "https://Stackoverflow.com/questions/12159", "https://Stackoverflow.com", "https://Stackoverflow.com/users/912/" ]
12,176
<p>Is there any way to include the SVN repository revision number in the version string of a .NET assembly? Something like Major.Minor.SVNRev</p> <p>I've seen mention of doing this with something like CC.NET (although on ASP.NET actually), but is there any way to do it without any extra software? I've done similar things in C/C++ before using build batch scripts, but in was accomplished by reading the version number, then having the script write out a file called "ver.h" everytime with something to the effect of:</p> <pre><code>#define MAJORVER 4 #define MINORVER 23 #define SOURCEVER 965 </code></pre> <p>We would then use these defines to generate the version string.</p> <p>Is something like this possible for .NET?</p>
[ { "answer_id": 653382, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "using System;\nusing Microsoft.Build.Framework;\nusing Microsoft.Build.Utilities;\nusing DotSVN.Common;\nusing DotSVN.Common.Entities;\nusing DotSVN.Common.Util;\nusing DotSVN.Server.RepositoryAccess;\n\nnamespace GetSVNVersion\n{\n public class GetRevision : Task\n {\n [Required]\n public string Repository { get; set; }\n [Output]\n public string Revision { get; set; }\n\n public override bool Execute()\n {\n ISVNRepository repo;\n bool connected = true;\n try\n {\n repo = SVNRepositoryFactory.Create(new SVNURL(Repository));\n repo.OpenRepository();\n Revision = repo.GetLatestRevision().ToString();\n Log.LogCommandLine(Repository + \" is revision \" + Revision);\n repo.CloseRepository();\n }\n catch(Exception e)\n {\n Log.LogError(\"Error retrieving revision number for \" + Repository + \": \" + e.Message);\n connected = false;\n }\n return connected;\n }\n }\n}\n" }, { "answer_id": 14195519, "author": "R. Schreurs", "author_id": 456456, "author_profile": "https://Stackoverflow.com/users/456456", "pm_score": 5, "selected": false, "text": "[assembly: AssemblyFileVersion(\"1.0.0.$WCREV$\")] [assembly: AssemblyInformationalVersion(\"Build date: $WCNOW=%Y-%m-%d %H:%M:%S$; Revision date: $WCDATE=%Y-%m-%d %H:%M:%S$; Revision(s) in working copy: $WCRANGE$$WCMODS?; WARNING working copy had uncommitted modifications:$.\")] subwcrev \"$(SolutionDir).\" \"$(ProjectDir)Properties\\AssemblyInfoTemplate.cs\" \"$(ProjectDir)Properties\\AssemblyInfo.cs\" -f #if(!DEBUG) \n $WCMODS?#error Working copy has uncommitted modifications, please commit all modifications before creating a release build.:$ \n#endif \n#if(!DEBUG) \n $WCMIXED?#error Working copy has multiple revisions, please update to the latest revision before creating a release build.:$ \n#endif\n public class VersionInfo\n{ \n public const int RevisionNumber = $WCREV$;\n public const string BuildDate = \"$WCNOW=%Y-%m-%d %H:%M:%S$\";\n public const string RevisionDate = \"$WCDATE=%Y-%m-%d %H:%M:%S$\";\n public const string RevisionsInWorkingCopy = \"$WCRANGE$\";\n public const bool UncommitedModification = $WCMODS?true:false$;\n}\n" } ]
2008/08/15
[ "https://Stackoverflow.com/questions/12176", "https://Stackoverflow.com", "https://Stackoverflow.com/users/194/" ]
12,225
<p>I have a database that contains a date and we are using the MaskedEditExtender (MEE) and MaskedEditValidator to make sure the dates are appropriate. However, we want the Admins to be able to go in and change the data (specifically the date) if necessary. </p> <p>How can I have the MEE field pre-populate with the database value when the data is shown on the page? I've tried to use 'bind' in the 'InitialValue' property but it doesn't populate the textbox.</p> <p>Thanks.</p>
[ { "answer_id": 16718, "author": "Keng", "author_id": 730, "author_profile": "https://Stackoverflow.com/users/730", "pm_score": 2, "selected": true, "text": "Mask=\"99/99/9999 99:99:99\"" } ]
2008/08/15
[ "https://Stackoverflow.com/questions/12225", "https://Stackoverflow.com", "https://Stackoverflow.com/users/730/" ]
12,271
<p>I have created a template for Visual Studio 2008 and it currently shows up under File->New Project->Visual C#. However, it is only really specific to Visual C#/Windows but I can't work out how to get it to show up under the "Windows" category and not the more general "Visual C#".</p>
[ { "answer_id": 12491, "author": "Aidan Ryan", "author_id": 1042, "author_profile": "https://Stackoverflow.com/users/1042", "pm_score": 4, "selected": true, "text": "<VisualStudioInstallDir>\\Common7\\IDE\\ItemTemplates\\CSharp\\\nMy Documents\\Visual Studio 2008\\Templates\\ProjectTemplates\\CSharp\\\n" } ]
2008/08/15
[ "https://Stackoverflow.com/questions/12271", "https://Stackoverflow.com", "https://Stackoverflow.com/users/214/" ]
12,297
<p>I've got a Repeater that lists all the <code>web.sitemap</code> child pages on an ASP.NET page. Its <code>DataSource</code> is a <code>SiteMapNodeCollection</code>. But, I don't want my registration form page to show up there.</p> <pre><code>Dim Children As SiteMapNodeCollection = SiteMap.CurrentNode.ChildNodes 'remove registration page from collection For Each n As SiteMapNode In SiteMap.CurrentNode.ChildNodes If n.Url = "/Registration.aspx" Then Children.Remove(n) End If Next RepeaterSubordinatePages.DataSource = Children </code></pre> <p>The <code>SiteMapNodeCollection.Remove()</code> method throws a </p> <blockquote> <p>NotSupportedException: "Collection is read-only".</p> </blockquote> <p>How can I remove the node from the collection before DataBinding the Repeater?</p>
[ { "answer_id": 12303, "author": "Keith", "author_id": 905, "author_profile": "https://Stackoverflow.com/users/905", "pm_score": 1, "selected": false, "text": "//this will now be an enumeration, rather than a read only collection\nDim children = SiteMap.CurrentNode.ChildNodes.Where( _\n Function (x) x.Url <> \"/Registration.aspx\" )\n\nRepeaterSubordinatePages.DataSource = children \n Function IsShown( n as SiteMapNode ) as Boolean\n Return n.Url <> \"/Registration.aspx\"\nEnd Function\n\n...\n\n//get a generic list\nDim children as List(Of SiteMapNode) = _\n New List(Of SiteMapNode) ( SiteMap.CurrentNode.ChildNodes )\n\n//use the generic list's FindAll method\nRepeaterSubordinatePages.DataSource = children.FindAll( IsShown )\n" }, { "answer_id": 12362, "author": "Zack Peterson", "author_id": 83, "author_profile": "https://Stackoverflow.com/users/83", "pm_score": 0, "selected": false, "text": "Dim children = From n In SiteMap.CurrentNode.ChildNodes _\n Where CType(n, SiteMapNode).Url <> \"/Registration.aspx\" _\n Select n\nRepeaterSubordinatePages.DataSource = children\n CType() System.Collections.Generic.IEnumerable(Of Object) System.Collections.Generic.IEnumerable(Of System.Web.SiteMapNode) System.Web.SiteMapNodeCollection" }, { "answer_id": 12373, "author": "Keith", "author_id": 905, "author_profile": "https://Stackoverflow.com/users/905", "pm_score": 2, "selected": true, "text": "Dim children = _\n From n In SiteMap.CurrentNode.ChildNodes.Cast(Of SiteMapNode)() _\n Where n.Url <> \"/Registration.aspx\" _\n Select n\n" } ]
2008/08/15
[ "https://Stackoverflow.com/questions/12297", "https://Stackoverflow.com", "https://Stackoverflow.com/users/83/" ]
12,304
<p>This is a problem I have seen other people besides myself having, and I haven't found a good explanation.</p> <p>Let's say you have a maintenance plan with a task to check the database, something like this:</p> <pre><code>USE [MyDb] GO DBCC CHECKDB with no_infomsgs, all_errormsgs </code></pre> <p>If you go look in your logs after the task executes, you might see something like this:</p> <pre><code>08/15/2008 06:00:22,spid55,Unknown,DBCC CHECKDB (mssqlsystemresource) executed by NT AUTHORITY\SYSTEM found 0 errors and repaired 0 errors. Elapsed time: 0 hours 0 minutes 0 seconds. 08/15/2008 06:00:21,spid55,Unknown,DBCC CHECKDB (master) executed by NT AUTHORITY\SYSTEM found 0 errors and repaired 0 errors. Elapsed time: 0 hours 0 minutes 0 seconds. </code></pre> <p>Instead of checking MyDb, it checked master and msssqlsystemresource.</p> <p>Why?</p> <p>My workaround is to create a Sql Server Agent Job with this:</p> <pre><code>dbcc checkdb ('MyDb') with no_infomsgs, all_errormsgs; </code></pre> <p>That always works fine.</p> <pre><code>08/15/2008 04:26:04,spid54,Unknown,DBCC CHECKDB (MyDb) WITH all_errormsgs&lt;c/&gt; no_infomsgs executed by NT AUTHORITY\SYSTEM found 0 errors and repaired 0 errors. Elapsed time: 0 hours 26 minutes 3 seconds. </code></pre>
[ { "answer_id": 12320, "author": "Stu", "author_id": 414, "author_profile": "https://Stackoverflow.com/users/414", "pm_score": 1, "selected": false, "text": "GO" } ]
2008/08/15
[ "https://Stackoverflow.com/questions/12304", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1219/" ]
12,306
<p>I'm trying to serialize a Type object in the following way:</p> <pre><code>Type myType = typeof (StringBuilder); var serializer = new XmlSerializer(typeof(Type)); TextWriter writer = new StringWriter(); serializer.Serialize(writer, myType); </code></pre> <p>When I do this, the call to Serialize throws the following exception: </p> <blockquote> <p>"The type System.Text.StringBuilder was not expected. Use the XmlInclude or SoapInclude attribute to specify types that are not known statically."</p> </blockquote> <p>Is there a way for me to serialize the <code>Type</code> object? Note that I am not trying to serialize the <code>StringBuilder</code> itself, but the <code>Type</code> object containing the metadata about the <code>StringBuilder</code> class.</p>
[ { "answer_id": 12314, "author": "AdamSane", "author_id": 805, "author_profile": "https://Stackoverflow.com/users/805", "pm_score": 1, "selected": false, "text": "public abstract class Type : System.Reflection.MemberInfo\n Member of System\n\nSummary:\nRepresents type declarations: class types, interface types, array types, value types, enumeration types, type parameters, generic type definitions, and open or closed constructed generic types.\n\nAttributes:\n[System.Runtime.InteropServices.ClassInterfaceAttribute(0),\nSystem.Runtime.InteropServices.ComDefaultInterfaceAttribute(System.Runtime.InteropServices._Type),\nSystem.Runtime.InteropServices.ComVisibleAttribute(true)]\n" }, { "answer_id": 12342, "author": "Brian Sullivan", "author_id": 767, "author_profile": "https://Stackoverflow.com/users/767", "pm_score": 8, "selected": true, "text": "string typeName = typeof (StringBuilder).FullName;\n Type t = Type.GetType(typeName);\n object o = Activator.CreateInstance(t);\n" }, { "answer_id": 9809872, "author": "hypehuman", "author_id": 1269598, "author_profile": "https://Stackoverflow.com/users/1269598", "pm_score": 4, "selected": false, "text": "// a version of System.Type that can be serialized\n[DataContract]\npublic class SerializableType\n{\n public Type type;\n\n // when serializing, store as a string\n [DataMember]\n string TypeString\n {\n get\n {\n if (type == null)\n return null;\n return type.FullName;\n }\n set\n {\n if (value == null)\n type = null;\n else\n {\n type = Type.GetType(value);\n }\n }\n }\n\n // constructors\n public SerializableType()\n {\n type = null;\n }\n public SerializableType(Type t)\n {\n type = t;\n }\n\n // allow SerializableType to implicitly be converted to and from System.Type\n static public implicit operator Type(SerializableType stype)\n {\n return stype.type;\n }\n static public implicit operator SerializableType(Type t)\n {\n return new SerializableType(t);\n }\n\n // overload the == and != operators\n public static bool operator ==(SerializableType a, SerializableType b)\n {\n // If both are null, or both are same instance, return true.\n if (System.Object.ReferenceEquals(a, b))\n {\n return true;\n }\n\n // If one is null, but not both, return false.\n if (((object)a == null) || ((object)b == null))\n {\n return false;\n }\n\n // Return true if the fields match:\n return a.type == b.type;\n }\n public static bool operator !=(SerializableType a, SerializableType b)\n {\n return !(a == b);\n }\n // we don't need to overload operators between SerializableType and System.Type because we already enabled them to implicitly convert\n\n public override int GetHashCode()\n {\n return type.GetHashCode();\n }\n\n // overload the .Equals method\n public override bool Equals(System.Object obj)\n {\n // If parameter is null return false.\n if (obj == null)\n {\n return false;\n }\n\n // If parameter cannot be cast to SerializableType return false.\n SerializableType p = obj as SerializableType;\n if ((System.Object)p == null)\n {\n return false;\n }\n\n // Return true if the fields match:\n return (type == p.type);\n }\n public bool Equals(SerializableType p)\n {\n // If parameter is null return false:\n if ((object)p == null)\n {\n return false;\n }\n\n // Return true if the fields match:\n return (type == p.type);\n }\n}\n [DataContract]\npublic class A\n{\n\n ...\n\n [DataMember]\n private Dictionary<SerializableType, B> _bees;\n\n ...\n\n public B GetB(Type type)\n {\n return _bees[type];\n }\n\n ...\n\n}\n" }, { "answer_id": 21435254, "author": "Dzyann", "author_id": 752842, "author_profile": "https://Stackoverflow.com/users/752842", "pm_score": 3, "selected": false, "text": "string typeName = typeof (MyClass).FullName;\n\nType type = GetTypeFrom(typeName);\n\nobject myInstance = Activator.CreateInstance(type);\n private Type GetTypeFrom(string valueType)\n {\n var type = Type.GetType(valueType);\n if (type != null)\n return type;\n\n try\n {\n var assemblies = AppDomain.CurrentDomain.GetAssemblies(); \n\n //To speed things up, we check first in the already loaded assemblies.\n foreach (var assembly in assemblies)\n {\n type = assembly.GetType(valueType);\n if (type != null)\n break;\n }\n if (type != null)\n return type;\n\n var loadedAssemblies = assemblies.ToList();\n\n foreach (var loadedAssembly in assemblies)\n {\n foreach (AssemblyName referencedAssemblyName in loadedAssembly.GetReferencedAssemblies())\n {\n var found = loadedAssemblies.All(x => x.GetName() != referencedAssemblyName);\n\n if (!found)\n {\n try\n {\n var referencedAssembly = Assembly.Load(referencedAssemblyName);\n type = referencedAssembly.GetType(valueType);\n if (type != null)\n break;\n loadedAssemblies.Add(referencedAssembly);\n }\n catch\n {\n //We will ignore this, because the Type might still be in one of the other Assemblies.\n }\n }\n }\n } \n }\n catch(Exception exception)\n {\n //throw my custom exception \n }\n\n if (type == null)\n {\n //throw my custom exception.\n }\n\n return type;\n }\n" }, { "answer_id": 54830442, "author": "Peter Riesz", "author_id": 1003150, "author_profile": "https://Stackoverflow.com/users/1003150", "pm_score": 2, "selected": false, "text": "SurrogateSelector SerializationBinder TypeSerializationBinder System.RuntimeType SurrogateSelector // Serializes and deserializes System.Type\npublic class TypeSerializationSurrogate : ISerializationSurrogate {\n public void GetObjectData(object obj, SerializationInfo info, StreamingContext context) {\n info.AddValue(nameof(Type.FullName), (obj as Type).FullName);\n }\n\n public object SetObjectData(object obj, SerializationInfo info, StreamingContext context, ISurrogateSelector selector) {\n return Type.GetType(info.GetString(nameof(Type.FullName)));\n }\n}\n\n// Just a stub, doesn't need an implementation\npublic class TypeStub : Type { ... }\n\n// Binds \"System.RuntimeType\" to our TypeStub\npublic class TypeSerializationBinder : SerializationBinder {\n public override Type BindToType(string assemblyName, string typeName) {\n if(typeName == \"System.RuntimeType\") {\n return typeof(TypeStub);\n }\n return Type.GetType($\"{typeName}, {assemblyName}\");\n }\n}\n\n// Selected out TypeSerializationSurrogate when [de]serializing Type\npublic class TypeSurrogateSelector : ISurrogateSelector {\n public virtual void ChainSelector(ISurrogateSelector selector) => throw new NotSupportedException();\n\n public virtual ISurrogateSelector GetNextSelector() => throw new NotSupportedException();\n\n public virtual ISerializationSurrogate GetSurrogate(Type type, StreamingContext context, out ISurrogateSelector selector) {\n if(typeof(Type).IsAssignableFrom(type)) {\n selector = this;\n return new TypeSerializationSurrogate();\n }\n selector = null;\n return null;\n }\n}\n byte[] bytes\nvar serializeFormatter = new BinaryFormatter() {\n SurrogateSelector = new TypeSurrogateSelector()\n}\nusing (var stream = new MemoryStream()) {\n serializeFormatter.Serialize(stream, typeof(string));\n bytes = stream.ToArray();\n}\n\nvar deserializeFormatter = new BinaryFormatter() {\n SurrogateSelector = new TypeSurrogateSelector(),\n Binder = new TypeDeserializationBinder()\n}\nusing (var stream = new MemoryStream(bytes)) {\n type = (Type)deserializeFormatter .Deserialize(stream);\n Assert.Equal(typeof(string), type);\n}\n" } ]
2008/08/15
[ "https://Stackoverflow.com/questions/12306", "https://Stackoverflow.com", "https://Stackoverflow.com/users/767/" ]
12,319
<p>I'm looking to the equivalent of Windows <a href="http://msdn.microsoft.com/fr-fr/library/yeby3zcb.aspx" rel="noreferrer"><code>_wfopen()</code></a> under Mac OS X. Any idea?</p> <p>I need this in order to port a Windows library that uses <code>wchar*</code> for its File interface. As this is intended to be a cross-platform library, I am unable to rely on how the client application will get the file path and give it to the library.</p>
[ { "answer_id": 13562, "author": "Chris Hanson", "author_id": 714, "author_profile": "https://Stackoverflow.com/users/714", "pm_score": 3, "selected": false, "text": "fopen open fopen wcstombs LATIN SMALL LETTER E WITH ACUTE LATIN SMALL LETTER E COMBINING ACUTE ACCENT" }, { "answer_id": 265407, "author": "Vincent Robert", "author_id": 268, "author_profile": "https://Stackoverflow.com/users/268", "pm_score": 5, "selected": true, "text": "class Utf8\n{\npublic:\n Utf8(const wchar_t* wsz): m_utf8(NULL)\n {\n // OS X uses 32-bit wchar\n const int bytes = wcslen(wsz) * sizeof(wchar_t);\n // comp_bLittleEndian is in the lib I use in order to detect PowerPC/Intel\n CFStringEncoding encoding = comp_bLittleEndian ? kCFStringEncodingUTF32LE\n : kCFStringEncodingUTF32BE;\n CFStringRef str = CFStringCreateWithBytesNoCopy(NULL, \n (const UInt8*)wsz, bytes, \n encoding, false, \n kCFAllocatorNull\n );\n\n const int bytesUtf8 = CFStringGetMaximumSizeOfFileSystemRepresentation(str);\n m_utf8 = new char[bytesUtf8];\n CFStringGetFileSystemRepresentation(str, m_utf8, bytesUtf8);\n CFRelease(str);\n } \n\n ~Utf8() \n { \n if( m_utf8 )\n {\n delete[] m_utf8;\n }\n }\n\npublic:\n operator const char*() const { return m_utf8; }\n\nprivate:\n char* m_utf8;\n};\n const wchar_t wsz = L\"Here is some Unicode content: éà€œæ\";\nconst Utf8 utf8 = wsz;\nFILE* file = fopen(utf8, \"r\");\n" } ]
2008/08/15
[ "https://Stackoverflow.com/questions/12319", "https://Stackoverflow.com", "https://Stackoverflow.com/users/268/" ]
12,330
<p>Is there any known way of listing the WMI classes and their properties available for a particular system? Im interested in a vbscript approach, but please suggest anything really :)</p> <p>P.S. Great site.</p>
[ { "answer_id": 78268, "author": "JustinD", "author_id": 12063, "author_profile": "https://Stackoverflow.com/users/12063", "pm_score": 2, "selected": false, "text": "ManagementPath l_Path = new ManagementPath(l_className);\nManagementClass l_Class = new ManagementClass(myScope, l_ManagementPath, null);\nforeach (PropertyData l_PropertyData in l_Class.Properties)\n{\n string l_type = l_PropertyData.Type.ToString());\n int l_length = Convert.ToInt32(l_PropertyData.Qualifiers[\"maxlen\"].Value); \n}\n" } ]
2008/08/15
[ "https://Stackoverflow.com/questions/12330", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
12,332
<p>I am looking for a more technical explanation than the OS calls the function.</p> <p>Is there a website or book?</p>
[ { "answer_id": 12353, "author": "Vincent Robert", "author_id": 268, "author_profile": "https://Stackoverflow.com/users/268", "pm_score": 3, "selected": false, "text": "main() WinMainCRTStartup() argc, argv, end main() main() atexit() WinMainCRTStartup" }, { "answer_id": 33300, "author": "Anders", "author_id": 3501, "author_profile": "https://Stackoverflow.com/users/3501", "pm_score": 3, "selected": false, "text": "void __cdecl mainCRTStartup( void ) {} void __stdcall WinMainCRTStartup( void ) {} BOOL __stdcall _DllMainCRTStartup(HINSTANCE hinstDLL,DWORD fdwReason,void* lpReserved) {}" } ]
2008/08/15
[ "https://Stackoverflow.com/questions/12332", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
12,348
<p>I'm running PHP 5.2.3 on Windows 2000 Server with IIS 5. I'm trying to get cURL working, so in my <strong>php.ini</strong> file, I have this line:</p> <blockquote> <p>extension_dir ="F:\PHP\ext"</p> </blockquote> <p>And later, I have:</p> <blockquote> <p>extension=php_curl.dll</p> </blockquote> <p>The file <strong>F:\PHP\ext\php_curl.dll</strong> exists, but when I try to run any PHP script, I get this in the error log:</p> <blockquote> <p>PHP Warning: PHP Startup: Unable to load dynamic library 'F:\PHP\ext \php_curl.dll' - The specified module could not be found. in Unknown on line 0 </p> </blockquote>
[ { "answer_id": 12349, "author": "Derek Kurth", "author_id": 1418, "author_profile": "https://Stackoverflow.com/users/1418", "pm_score": 6, "selected": true, "text": "php_curl.dll php_curl.dll libeay32.dll SSLeay32.dll C:\\Windows\\system32 extension_dir php.ini libeay32.dll SSLeay32.dll" }, { "answer_id": 28591600, "author": "elQuique", "author_id": 4580982, "author_profile": "https://Stackoverflow.com/users/4580982", "pm_score": 4, "selected": false, "text": "libeay32.dll ssleay32.dll php_curl.dll c:/php" } ]
2008/08/15
[ "https://Stackoverflow.com/questions/12348", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1418/" ]
12,368
<p>The .NET garbage collector will eventually free up memory, but what if you want that memory back immediately? What code do you need to use in a class <code>MyClass</code> to call</p> <pre><code>MyClass.Dispose() </code></pre> <p>and free up all the used space by variables and objects in <code>MyClass</code>?</p>
[ { "answer_id": 12377, "author": "Darren Kopp", "author_id": 77, "author_profile": "https://Stackoverflow.com/users/77", "pm_score": 2, "selected": false, "text": "public class MyClass : IDisposable\n{\n public void Dispose()\n {\n // cleanup here\n }\n}\n MyClass todispose = new MyClass();\ntodispose.Dispose(); // instance is disposed right here\n using (MyClass instance = new MyClass())\n{\n\n}\n// instance will be disposed right here as it goes out of scope\n" }, { "answer_id": 12380, "author": "Keith", "author_id": 905, "author_profile": "https://Stackoverflow.com/users/905", "pm_score": 0, "selected": false, "text": "MyClass.Dispose();\n using( MyClass x = new MyClass() ) {\n //do stuff\n}\n" }, { "answer_id": 12383, "author": "Seibar", "author_id": 357, "author_profile": "https://Stackoverflow.com/users/357", "pm_score": 0, "selected": false, "text": "GC.Collect();\n" }, { "answer_id": 12394, "author": "Curt Hagenlocher", "author_id": 533, "author_profile": "https://Stackoverflow.com/users/533", "pm_score": 8, "selected": true, "text": "using (DisposableObject tmp = DisposableObject.AcquireResource()) {\n // Do something with tmp\n}\n// At this point, tmp.Dispose() will automatically have been called\n// BUT, tmp may still a perfectly valid object that still takes up memory\n GC.Collect()" }, { "answer_id": 12405, "author": "Patrik Svensson", "author_id": 936, "author_profile": "https://Stackoverflow.com/users/936", "pm_score": 5, "selected": false, "text": "GC.Collect(); \nGC.WaitForPendingFinalizers();\n instance.Dispose();\n using(MyClass instance = new MyClass())\n{\n // Your cool code.\n}\n MyClass instance = null; \n\ntry\n{\n instance = new MyClass(); \n // Your cool code.\n}\nfinally\n{\n if(instance != null)\n instance.Dispose();\n}\n public class MyClass : IDisposable\n{\n private bool disposed;\n\n /// <summary>\n /// Construction\n /// </summary>\n public MyClass()\n {\n }\n\n /// <summary>\n /// Destructor\n /// </summary>\n ~MyClass()\n {\n this.Dispose(false);\n }\n\n /// <summary>\n /// The dispose method that implements IDisposable.\n /// </summary>\n public void Dispose()\n {\n this.Dispose(true);\n GC.SuppressFinalize(this);\n }\n\n /// <summary>\n /// The virtual dispose method that allows\n /// classes inherithed from this one to dispose their resources.\n /// </summary>\n /// <param name=\"disposing\"></param>\n protected virtual void Dispose(bool disposing)\n {\n if (!disposed)\n {\n if (disposing)\n {\n // Dispose managed resources here.\n }\n\n // Dispose unmanaged resources here.\n }\n\n disposed = true;\n }\n}\n" }, { "answer_id": 27597, "author": "Keith", "author_id": 905, "author_profile": "https://Stackoverflow.com/users/905", "pm_score": 0, "selected": false, "text": "IDisposable" }, { "answer_id": 27608, "author": "Konrad Rudolph", "author_id": 1968, "author_profile": "https://Stackoverflow.com/users/1968", "pm_score": 0, "selected": false, "text": "Dispose Dispose Dispose Dispose Using Dispose" }, { "answer_id": 27630, "author": "Keith", "author_id": 905, "author_profile": "https://Stackoverflow.com/users/905", "pm_score": 0, "selected": false, "text": "public Dispose() protected Dispose(true) Dispose() ~Finalize protected Dispose(false) public Dispose() ~Finalize ~Finalize using" }, { "answer_id": 36737, "author": "Keith", "author_id": 905, "author_profile": "https://Stackoverflow.com/users/905", "pm_score": 4, "selected": false, "text": "Dispose GC.Collect() GC.Collect() GC.Collect() GC.Collect() IDisposable //using is best practice\nusing( SqlConnection con = new SqlConnection(\"my con str\" ) )\n{\n //do stuff\n} \n\n//this is what 'using' actually compiles to:\nSqlConnection con = new SqlConnection(\"my con str\" ) ;\ntry\n{\n //do stuff\n}\nfinally\n{\n con.Dispose();\n}\n //rather basic example\npublic sealed MyClass :\n IDisposable\n{ \n //this connection is disposable\n public SqlConnection MyConnection { get; set; }\n\n //make sure this gets rid of it too\n public Dispose() \n {\n //if we still have a connection dispose it\n if( MyConnection != null )\n MyConnection.Dispose();\n\n //note that the connection might have already been disposed\n //always write disposals so that they can be called again\n }\n}\n ~MyClass()\n{\n //calls a protected method \n //the false tells this method\n //not to bother with managed\n //resources\n this.Dispose(false);\n}\n\npublic void Dispose()\n{\n //calls the same method\n //passed true to tell it to\n //clean up managed and unmanaged \n this.Dispose(true);\n\n //as dispose has been correctly\n //called we don't need the \n\n //'backup' finaliser\n GC.SuppressFinalize(this);\n}\n protected virtual void Dispose(bool disposing)\n{\n //check this hasn't been called already\n //remember that Dispose can be called again\n if (!disposed)\n {\n //this is passed true in the regular Dispose\n if (disposing)\n {\n // Dispose managed resources here.\n }\n\n //both regular Dispose and the finaliser\n //will hit this code\n // Dispose unmanaged resources here.\n }\n\n disposed = true;\n}\n" }, { "answer_id": 10422450, "author": "Ashley Frieze", "author_id": 1355930, "author_profile": "https://Stackoverflow.com/users/1355930", "pm_score": 3, "selected": false, "text": "var myBigObject = new MyBigObject(1);\n// something happens\nmyBigObject = new MyBigObject(2);\n// at the above line, there are temporarily two big objects in memory and neither can be collected\n myBigObject = null; // so it could now be collected\nmyBigObject = new MyBigObject(2);\n" } ]
2008/08/15
[ "https://Stackoverflow.com/questions/12368", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1271/" ]
12,374
<p>We’ve found that the unit tests we’ve written for our C#/C++ code have really paid off. But we still have thousands of lines of business logic in stored procedures, which only really get tested in anger when our product is rolled out to a large number of users. </p> <p>What makes this worse is that some of these stored procedures end up being very long, because of the performance hit when passing temporary tables between SPs. This has prevented us from refactoring to make the code simpler.</p> <p>We have made several attempts at building unit tests around some of our key stored procedures (primarily testing the performance), but have found that setting up the test data for these tests is really hard. For example, we end up copying around test databases. In addition to this, the tests end up being really sensitive to change, and even the smallest change to a stored proc. or table requires a large amount of changes to the tests. So after many builds breaking due to these database tests failing intermittently, we’ve just had to pull them out of the build process.</p> <p>So, the main part of my questions is: has anyone ever successfully written unit tests for their stored procedures?</p> <p>The second part of my questions is whether unit testing would be/is easier with linq? </p> <p>I was thinking that rather than having to set up tables of test data, you could simply create a collection of test objects, and test your linq code in a “linq to objects” situation? (I am a totally new to linq so don’t know if this would even work at all)</p>
[ { "answer_id": 25204, "author": "Toran Billups", "author_id": 2701, "author_profile": "https://Stackoverflow.com/users/2701", "pm_score": 5, "selected": true, "text": "Public MustInherit Class Repository(Of T As Class)\n Implements IRepository(Of T)\n\n Private mConnectionString As String = ConfigurationManager.ConnectionStrings(\"Northwind.ConnectionString\").ConnectionString\n Private mConnection As IDbConnection\n Private mTransaction As IDbTransaction\n\n Public Sub New()\n mConnection = Nothing\n mTransaction = Nothing\n End Sub\n\n Public Sub New(ByVal connection As IDbConnection, ByVal transaction As IDbTransaction)\n mConnection = connection\n mTransaction = transaction\n End Sub\n\n Public MustOverride Function BuildEntity(ByVal cmd As SqlCommand) As List(Of T)\n\n Public Function ExecuteReader(ByVal Parameter As Parameter) As List(Of T) Implements IRepository(Of T).ExecuteReader\n Dim entityList As List(Of T)\n If Not mConnection Is Nothing Then\n Using cmd As SqlCommand = mConnection.CreateCommand()\n cmd.Transaction = mTransaction\n cmd.CommandType = Parameter.Type\n cmd.CommandText = Parameter.Text\n If Not Parameter.Items Is Nothing Then\n For Each param As SqlParameter In Parameter.Items\n cmd.Parameters.Add(param)\n Next\n End If\n entityList = BuildEntity(cmd)\n If Not entityList Is Nothing Then\n Return entityList\n End If\n End Using\n Else\n Using conn As SqlConnection = New SqlConnection(mConnectionString)\n Using cmd As SqlCommand = conn.CreateCommand()\n cmd.CommandType = Parameter.Type\n cmd.CommandText = Parameter.Text\n If Not Parameter.Items Is Nothing Then\n For Each param As SqlParameter In Parameter.Items\n cmd.Parameters.Add(param)\n Next\n End If\n conn.Open()\n entityList = BuildEntity(cmd)\n If Not entityList Is Nothing Then\n Return entityList\n End If\n End Using\n End Using\n End If\n\n Return Nothing\n End Function\nEnd Class\n Public Class ProductRepository\n Inherits Repository(Of Product)\n Implements IProductRepository\n\n Private mCache As IHttpCache\n\n 'This const is what you will use in your app\n Public Sub New(ByVal cache As IHttpCache)\n MyBase.New()\n mCache = cache\n End Sub\n\n 'This const is only used for testing so we can inject a connectin/transaction and have them roll'd back after the test\n Public Sub New(ByVal cache As IHttpCache, ByVal connection As IDbConnection, ByVal transaction As IDbTransaction)\n MyBase.New(connection, transaction)\n mCache = cache\n End Sub\n\n Public Function GetProducts() As System.Collections.Generic.List(Of Product) Implements IProductRepository.GetProducts\n Dim Parameter As New Parameter()\n Parameter.Type = CommandType.StoredProcedure\n Parameter.Text = \"spGetProducts\"\n Dim productList As List(Of Product)\n productList = MyBase.ExecuteReader(Parameter)\n Return productList\n End Function\n\n 'This function is used in each class that inherits from the base data access class so we can keep all the boring left-right mapping code in 1 place per object\n Public Overrides Function BuildEntity(ByVal cmd As System.Data.SqlClient.SqlCommand) As System.Collections.Generic.List(Of Product)\n Dim productList As New List(Of Product)\n Using reader As SqlDataReader = cmd.ExecuteReader()\n Dim product As Product\n While reader.Read()\n product = New Product()\n product.ID = reader(\"ProductID\")\n product.SupplierID = reader(\"SupplierID\")\n product.CategoryID = reader(\"CategoryID\")\n product.ProductName = reader(\"ProductName\")\n product.QuantityPerUnit = reader(\"QuantityPerUnit\")\n product.UnitPrice = reader(\"UnitPrice\")\n product.UnitsInStock = reader(\"UnitsInStock\")\n product.UnitsOnOrder = reader(\"UnitsOnOrder\")\n product.ReorderLevel = reader(\"ReorderLevel\")\n productList.Add(product)\n End While\n If productList.Count > 0 Then\n Return productList\n End If\n End Using\n Return Nothing\n End Function\nEnd Class\n Imports System.Configuration\nImports System.Data\nImports System.Data.SqlClient\nImports Microsoft.VisualStudio.TestTools.UnitTesting\n\nPublic MustInherit Class TransactionFixture\n Protected mConnection As IDbConnection\n Protected mTransaction As IDbTransaction\n Private mConnectionString As String = ConfigurationManager.ConnectionStrings(\"Northwind.ConnectionString\").ConnectionString\n\n <TestInitialize()> _\n Public Sub CreateConnectionAndBeginTran()\n mConnection = New SqlConnection(mConnectionString)\n mConnection.Open()\n mTransaction = mConnection.BeginTransaction()\n End Sub\n\n <TestCleanup()> _\n Public Sub RollbackTranAndCloseConnection()\n mTransaction.Rollback()\n mTransaction.Dispose()\n mConnection.Close()\n mConnection.Dispose()\n End Sub\nEnd Class\n Imports SampleApplication.Library\nImports System.Collections.Generic\nImports Microsoft.VisualStudio.TestTools.UnitTesting\n\n<TestClass()> _\nPublic Class ProductRepositoryUnitTest\n Inherits TransactionFixture\n\n Private mRepository As ProductRepository\n\n <TestMethod()> _\n Public Sub Should-Insert-Update-And-Delete-Product()\n mRepository = New ProductRepository(New HttpCache(), mConnection, mTransaction)\n '** Create a test product to manipulate throughout **'\n Dim Product As New Product()\n Product.ProductName = \"TestProduct\"\n Product.SupplierID = 1\n Product.CategoryID = 2\n Product.QuantityPerUnit = \"10 boxes of stuff\"\n Product.UnitPrice = 14.95\n Product.UnitsInStock = 22\n Product.UnitsOnOrder = 19\n Product.ReorderLevel = 12\n '** Insert the new product object into SQL using your insert sproc **'\n mRepository.InsertProduct(Product)\n '** Select the product object that was just inserted and verify it does exist **'\n '** Using your GetProductById sproc **'\n Dim Product2 As Product = mRepository.GetProduct(Product.ID)\n Assert.AreEqual(\"TestProduct\", Product2.ProductName)\n Assert.AreEqual(1, Product2.SupplierID)\n Assert.AreEqual(2, Product2.CategoryID)\n Assert.AreEqual(\"10 boxes of stuff\", Product2.QuantityPerUnit)\n Assert.AreEqual(14.95, Product2.UnitPrice)\n Assert.AreEqual(22, Product2.UnitsInStock)\n Assert.AreEqual(19, Product2.UnitsOnOrder)\n Assert.AreEqual(12, Product2.ReorderLevel)\n '** Update the product object **'\n Product2.ProductName = \"UpdatedTestProduct\"\n Product2.SupplierID = 2\n Product2.CategoryID = 1\n Product2.QuantityPerUnit = \"a box of stuff\"\n Product2.UnitPrice = 16.95\n Product2.UnitsInStock = 10\n Product2.UnitsOnOrder = 20\n Product2.ReorderLevel = 8\n mRepository.UpdateProduct(Product2) '**using your update sproc\n '** Select the product object that was just updated to verify it completed **'\n Dim Product3 As Product = mRepository.GetProduct(Product2.ID)\n Assert.AreEqual(\"UpdatedTestProduct\", Product2.ProductName)\n Assert.AreEqual(2, Product2.SupplierID)\n Assert.AreEqual(1, Product2.CategoryID)\n Assert.AreEqual(\"a box of stuff\", Product2.QuantityPerUnit)\n Assert.AreEqual(16.95, Product2.UnitPrice)\n Assert.AreEqual(10, Product2.UnitsInStock)\n Assert.AreEqual(20, Product2.UnitsOnOrder)\n Assert.AreEqual(8, Product2.ReorderLevel)\n '** Delete the product and verify it does not exist **'\n mRepository.DeleteProduct(Product3.ID)\n '** The above will use your delete product by id sproc **'\n Dim Product4 As Product = mRepository.GetProduct(Product3.ID)\n Assert.AreEqual(Nothing, Product4)\n End Sub\n\nEnd Class\n" }, { "answer_id": 800759, "author": "MatthewMartin", "author_id": 33264, "author_profile": "https://Stackoverflow.com/users/33264", "pm_score": 1, "selected": false, "text": "/*\n\n--setup\nDeclare @foo int Set @foo = (Select top 1 foo from mytable)\n\n--test\nexecute wish_I_had_more_Tests @foo\n\n--look at rowcounts/look for errors\nIf @@rowcount=1 Print 'Ok!' Else Print 'Nokay!'\n\n--Teardown\nDelete from mytable where foo = @foo\n*/\ncreate procedure wish_I_had_more_Tests\nas\nselect....\n" } ]
2008/08/15
[ "https://Stackoverflow.com/questions/12374", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1078/" ]
12,406
<p>From what I've read, <a href="http://blogs.msdn.com/astebner/archive/2008/08/11/8849574.aspx" rel="nofollow noreferrer">VS 2008 SP1 and Team Foundation Server SP1 packages are traditional service packs that require you to first install the original versions before you will be able to install the SP</a>.</p> <p>Is there a way, supported or not, to slipstream the install?</p>
[ { "answer_id": 1707074, "author": "Nagendra", "author_id": 207684, "author_profile": "https://Stackoverflow.com/users/207684", "pm_score": 2, "selected": false, "text": "::Extract the original visual studio 2008 installation to directory VS2k8WithSP1.\nmsiexec.exe /a \"g:\\vs_setup.msi\" TARGETDIR=\"%CD%\\VS2k8WithSP1\"\n\n::Copy some file to make slipstream integration successful.\ncopy \"VS2k8WithSP1\\Program Files\\Microsoft Visual Studio 9.0\\Common7\\1033\\*.chm\" \"VS2k8WithSP1\\Program Files\\Microsoft Visual Studio 9.0\\Common7\\IDE\\\"\n\n::Extract each .msp files to directory VS2k8WithSP1.\nmsiexec.exe /a \"%cd%\\VS2k8WithSP1\\vs_setup.msi\" /p \"%cd%\\SP1\\vs90sp1\\VS90sp1-KB945140-X86-ENU.msp\"\nmsiexec.exe /a \"%cd%\\VS2k8WithSP1\\vs_setup.msi\" /p \"%cd%\\SP1\\vs90sp1\\VC90sp1-KB947888-x86-enu.msp\"\nmsiexec.exe /a \"%cd%\\VS2k8WithSP1\\vs_setup.msi\" /p \"%cd%\\SP1\\vs90sp1\\VC90sp1-KB948484-x86_x64-enu.msp\"\nmsiexec.exe /a \"%cd%\\VS2k8WithSP1\\vs_setup.msi\" /p \"%cd%\\SP1\\vs90sp1\\VC90sp1-KB948560-x86_IA64-enu.msp\"\n\n\n::Copy the product key file\ncopy \"VS2k8WithSP1\\Setup\\Setup.sdb\"\n\n::Copy the setup bootstrapper files\ncopy \"VS2k8WithSP1\\Program Files\\Microsoft Visual Studio 9.0\\CSetupMM\\*.*\" \"VS2k8WithSP1\\Setup\"\n\n::Copy VC runtime files\nmd VS2k8WithSP1\\wcu\\VCRuntimes\ncopy SP1\\vs90sp1\\vc_*runtime.exe VS2k8WithSP1\\wcu\\VCRuntimes\n\n::copy SQL Server Database Publishing Wizard\ncopy SP1\\vs90sp1\\SqlPubWizInstaller.exe VS2k8WithSP1\\wcu\\SqlPub\n\n::copy SQL Server 2008 Management Objects and SQL Server System CLR Types configuration.\nmd VS2k8WithSP1\\wcu\\SMO\ncopy SP1\\vs90sp1\\SharedManagementObjects.msi VS2k8WithSP1\\wcu\\SMO\ncopy SP1\\vs90sp1\\SQLSysClrTypes.msi VS2k8WithSP1\\wcu\\SMO\n\n::copy SQL Server Compact 3.5 SP1 English with the Microsoft SQL Server Compact 3.5 SP1 Design Tools English.\ncopy /Y SP1\\vs90sp1\\SSCERuntime-enu.msi VS2k8WithSP1\\wcu\\SSCE\ncopy /Y SP1\\vs90sp1\\SSCEVSTools-enu.msi VS2k8WithSP1\\wcu\\SSCE\n\n::Extract the dotnetfx35.exe manually to a %tmp% folder. Copy all files and subdirectories from %tmp%\\wcu\\dotnetframework to vs2k8WithSP1\\wcu\\dotnetframework and overwrite files\n::Sorry I could not able to automate this step as /extract option is disabled in the dotnetfx35.exe file.\n" }, { "answer_id": 7402785, "author": "waqqas31", "author_id": 942655, "author_profile": "https://Stackoverflow.com/users/942655", "pm_score": 2, "selected": false, "text": "::Copy some file to make slipstream integration successful. \ncopy \"VS2k8WithSP1\\Program Files\\Microsoft Visual Studio 9.0\\Common7\\1033*.chm\" \"VS2k8WithSP1\\Program Files\\Microsoft Visual Studio 9.0\\Common7\\IDE\\\"\n ::Copy the setup bootstrapper files \ncopy \"VS2k8WithSP1\\Program Files\\Microsoft Visual Studio 9.0\\CSetupMM*.*\" \"VS2k8WithSP1\\Setup\"\n ::copy SQL Server Database Publishing Wizard \ncopy SP1\\vs90sp1\\SqlPubWizInstaller.exe VS2k8WithSP1\\wcu\\SqlPub\n VS70pgui: [2] DepCheck indicates Microsoft SQL Publishing Wizard 1.3 is not installed.\n" } ]
2008/08/15
[ "https://Stackoverflow.com/questions/12406", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5/" ]
12,476
<p>This is a self-explanatory question:</p> <p>Why does this thing bubble into my try catch's even when nothing is wrong? </p> <p>Why is it showing up in my log, hundreds of times?</p> <p><strong>I know its a newb question, but if this site is gonna get search ranking and draw in newbs we have to ask them</strong></p>
[ { "answer_id": 18507130, "author": "Luke Puplett", "author_id": 107783, "author_profile": "https://Stackoverflow.com/users/107783", "pm_score": 0, "selected": false, "text": "Thread.Abort Response.Redirect HttpApplication.Error HttpResponse HttpContext private void CheckIPhoneAccess() { ... }\n Response.Redirect ThreadAbortException Response.SafeRedirect" } ]
2008/08/15
[ "https://Stackoverflow.com/questions/12476", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1220/" ]
12,482
<p>I have CruiseControl.NET Version 1.4 set up on my development server. Whenever a developer checks in code, it makes a compile. </p> <p>Now we're at a place where we can start giving our application to the testers. We'd like to use ClickOnce to distribute the application, with the idea being that when a tester goes to test the application, they have the latest build. </p> <p>I can't find a way to make that happen with CruiseControl.NET. We're using MSBUILD to perform the builds.</p>
[ { "answer_id": 12512, "author": "Judah Gabriel Himango", "author_id": 536, "author_profile": "https://Stackoverflow.com/users/536", "pm_score": 5, "selected": false, "text": "msbuild /target:publish /p:Configuration=Release /p:Platform=AnyCPU; \"c:\\yourProject.csproj\"\n" }, { "answer_id": 103741, "author": "fnCzar", "author_id": 15053, "author_profile": "https://Stackoverflow.com/users/15053", "pm_score": 2, "selected": false, "text": "<target name=\"deployProd\">\n <exec program=\"<framework_dir>\\msbuild.exe\" commandline=\"<project>/<project>.csproj /property:Configuration=PublishProd /property:ApplicationVersion=${build.label}.*;PublishUrl=\\\\<prod_location>\\binups$\\;InstallUrl=\\\\<prod_location>\\binups$\\;UpdateUrl=\\\\<prod_location>\\binups$\\;BootstrapperComponentsUrl=\\\\<prod_location>\\prereqs$\\ /target:publish\"/>\n\n <copy todir=\"<project>\\bin\\PublishProd\\<project>.publish\">\n\n <fileset basedir=\".\">\n <include name=\"publish.htm\"/>\n </fileset>\n\n <filterchain>\n <replacetokens>\n <token key=\"CURRENT_VERSION\" value=\"${build.label}\"/>\n </replacetokens>\n </filterchain>\n </copy>\n\n</target>\n" }, { "answer_id": 462529, "author": "proudgeekdad", "author_id": 702, "author_profile": "https://Stackoverflow.com/users/702", "pm_score": 5, "selected": true, "text": "<!-- override settings -->\n<exec>\n <executable>F:\\Source\\Project\\Environment\\CruiseControl\\CopySettings.bat</executable>\n</exec>\n\n<!-- compile -->\n<msbuild>\n <executable>C:\\WINDOWS\\Microsoft.NET\\Framework\\v3.5\\MSBuild.exe</executable>\n <workingDirectory>F:\\Source\\Project\\Environment\\</workingDirectory>\n <projectFile>Project.sln</projectFile>\n <buildArgs>/noconsolelogger /p:Configuration=Debug /v:diag</buildArgs>\n <targets>Rebuild</targets>\n <timeout>0</timeout>\n <logger>ThoughtWorks.CruiseControl.MsBuild.XmlLogger,ThoughtWorks.CruiseControl.MsBuild.dll</logger>\n</msbuild>\n\n<!-- clickonce publish -->\n<exec>\n <executable>F:\\Source\\Project\\Environment\\CruiseControl\\Publish.bat</executable>\n</exec>\n XCOPY \"F:\\Source\\Project\\Environment\\CruiseControl\\Project\\app.config\" \"F:\\Source\\Project\\Environment\\Project\" /Y /I /R\nXCOPY \"F:\\Source\\Project\\Environment\\CruiseControl\\Project\\My Project\\Settings.Designer.vb\" \"F:\\Source\\Project\\Environment\\Project\\My Project\" /Y /I /R\nXCOPY \"F:\\Source\\Project\\Environment\\CruiseControl\\Project\\My Project\\Settings.settings\" \"F:\\Source\\Project\\Environment\\Project\\My Project\" /Y /I /R\n C:\\WINDOWS\\Microsoft.NET\\Framework\\v3.5\\MSBuild.exe /target:rebuild \"F:\\Source\\Project\\Environment\\Project\\Project.vbproj\" /property:ApplicationRevision=%CCNetLabel% /property:AssemblyName=\"ProjectEnvironment\" /property:PublishUrl=\"\\\\Server\\bin\\Project\\Environment\\\\\"\nC:\\WINDOWS\\Microsoft.NET\\Framework\\v3.5\\MSBuild.exe /target:publish \"F:\\Source\\Project\\Environment\\Project\\Project.vbproj\" /property:ApplicationVersion=\"1.0.0.%CCNetLabel%\" /property:AssemblyVersion=\"1.0.0.%CCNetLabel%\" /property:AssemblyName=\"ProjectEnvironment\" \n\nXCOPY \"F:\\Source\\Project\\Environment\\Project\\bin\\Debug\\app.publish\" \"F:\\Binary\\Project\\Environment\" /Y /I\nXCOPY \"F:\\Source\\Project\\Environment\\Project\\bin\\Debug\\app.publish\\Application Files\" \"F:\\Binary\\Project\\Environment\\Application Files\" /Y /I /S\n" } ]
2008/08/15
[ "https://Stackoverflow.com/questions/12482", "https://Stackoverflow.com", "https://Stackoverflow.com/users/702/" ]
12,489
<p>How do you scan a directory for folders and files in C? It needs to be cross-platform.</p>
[ { "answer_id": 12506, "author": "Clayton", "author_id": 1449, "author_profile": "https://Stackoverflow.com/users/1449", "pm_score": 6, "selected": false, "text": "#define _XOPEN_SOURCE 700\n#include <stdio.h>\n#include <sys/types.h>\n#include <dirent.h>\n\nint main (void)\n{\n DIR *dp;\n struct dirent *ep; \n dp = opendir (\"./\");\n if (dp != NULL)\n {\n while ((ep = readdir (dp)) != NULL)\n puts (ep->d_name);\n \n (void) closedir (dp);\n return 0;\n }\n else\n {\n perror (\"Couldn't open the directory\");\n return -1;\n }\n}\n" }, { "answer_id": 6805559, "author": "user541686", "author_id": 541686, "author_profile": "https://Stackoverflow.com/users/541686", "pm_score": 2, "selected": false, "text": "readdir _find" }, { "answer_id": 14679104, "author": "congusbongus", "author_id": 2038264, "author_profile": "https://Stackoverflow.com/users/2038264", "pm_score": 4, "selected": false, "text": "tinydir_dir dir;\ntinydir_open(&dir, \"/path/to/dir\");\n\nwhile (dir.has_next)\n{\n tinydir_file file;\n tinydir_readfile(&dir, &file);\n\n printf(\"%s\", file.name);\n if (file.is_dir)\n {\n printf(\"/\");\n }\n printf(\"\\n\");\n\n tinydir_next(&dir);\n}\n\ntinydir_close(&dir);\n" }, { "answer_id": 47539331, "author": "Howard Wu", "author_id": 833657, "author_profile": "https://Stackoverflow.com/users/833657", "pm_score": 0, "selected": false, "text": "/**************************************************************\n * A simpler and shorter implementation of ls(1)\n * ls(1) is very similar to the DIR command on DOS and Windows.\n **************************************************************/\n#include <stdio.h>\n#include <dirent.h>\n\nint listdir(const char *path) \n{\n struct dirent *entry;\n DIR *dp;\n\n dp = opendir(path);\n if (dp == NULL) \n {\n perror(\"opendir\");\n return -1;\n }\n\n while((entry = readdir(dp)))\n puts(entry->d_name);\n\n closedir(dp);\n return 0;\n}\n\nint main(int argc, char **argv) {\n int counter = 1;\n\n if (argc == 1)\n listdir(\".\");\n\n while (++counter <= argc) {\n printf(\"\\nListing %s...\\n\", argv[counter-1]);\n listdir(argv[counter-1]);\n }\n\n return 0;\n}\n" } ]
2008/08/15
[ "https://Stackoverflow.com/questions/12489", "https://Stackoverflow.com", "https://Stackoverflow.com/users/432/" ]
12,492
<p>I use emacs to edit my xml files (nxml-mode) and the files were generated by machine don't have any pretty formatting of the tags. </p> <p>I have searched for pretty printing the entire file with indentation and saving it, but wasn't able to find an automatic way.</p> <p>Is there a way? Or atleast some editor on linux which can do it. </p>
[ { "answer_id": 570049, "author": "Christian Berg", "author_id": 5035, "author_profile": "https://Stackoverflow.com/users/5035", "pm_score": 6, "selected": false, "text": "indent-region C-x h\nC-M-\\\n (defun bf-pretty-print-xml-region (begin end)\n \"Pretty format XML markup in region. You need to have nxml-mode\nhttp://www.emacswiki.org/cgi-bin/wiki/NxmlMode installed to do\nthis. The function inserts linebreaks to separate tags that have\nnothing but whitespace between them. It then indents the markup\nby using nxml's indentation rules.\"\n (interactive \"r\")\n (save-excursion\n (nxml-mode)\n (goto-char begin)\n (while (search-forward-regexp \"\\>[ \\\\t]*\\<\" nil t) \n (backward-char) (insert \"\\n\") (setq end (1+ end)))\n (indent-region begin end))\n (message \"Ah, much better!\"))\n" }, { "answer_id": 4280824, "author": "bubak", "author_id": 520637, "author_profile": "https://Stackoverflow.com/users/520637", "pm_score": 4, "selected": false, "text": "(defun nxml-pretty-format ()\n (interactive)\n (save-excursion\n (shell-command-on-region (point-min) (point-max) \"xmllint --format -\" (buffer-name) t)\n (nxml-mode)\n (indent-region begin end)))\n" }, { "answer_id": 5198243, "author": "Jason Viers", "author_id": 480667, "author_profile": "https://Stackoverflow.com/users/480667", "pm_score": 3, "selected": false, "text": "search-forward-regexp end <tag></tag> cl incf ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;\n;; pretty print xml region\n(defun pretty-print-xml-region (begin end)\n \"Pretty format XML markup in region. You need to have nxml-mode\nhttp://www.emacswiki.org/cgi-bin/wiki/NxmlMode installed to do\nthis. The function inserts linebreaks to separate tags that have\nnothing but whitespace between them. It then indents the markup\nby using nxml's indentation rules.\"\n (interactive \"r\")\n (save-excursion\n (nxml-mode)\n (goto-char begin)\n ;; split <foo><foo> or </foo><foo>, but not <foo></foo>\n (while (search-forward-regexp \">[ \\t]*<[^/]\" end t)\n (backward-char 2) (insert \"\\n\") (incf end))\n ;; split <foo/></foo> and </foo></foo>\n (goto-char begin)\n (while (search-forward-regexp \"<.*?/.*?>[ \\t]*<\" end t)\n (backward-char) (insert \"\\n\") (incf end))\n (indent-region begin end nil)\n (normal-mode))\n (message \"All indented!\"))\n" }, { "answer_id": 8004288, "author": "rajashekar", "author_id": 1028948, "author_profile": "https://Stackoverflow.com/users/1028948", "pm_score": 3, "selected": false, "text": "<abc> <abc><abc> <abc></abc> </abc></abc> </abc>\n M-x nxml-mode\nM-x replace-regexp RET > *< RET >C-q C-j< RET \nC-M-\\ to indent\n <abc>\n <abc>\n <abc>\n <abc>\n </abc>\n </abc>\n </abc>\n</abc>\n :set ft=xml\n:%s/>\\s*</>\\r</g\nggVG=\n" }, { "answer_id": 14589619, "author": "Cheeso", "author_id": 48082, "author_profile": "https://Stackoverflow.com/users/48082", "pm_score": 2, "selected": false, "text": "(defun cheeso-pretty-print-xml-region (begin end)\n \"Pretty format XML markup in region. You need to have nxml-mode\nhttp://www.emacswiki.org/cgi-bin/wiki/NxmlMode installed to do\nthis. The function inserts linebreaks to separate tags that have\nnothing but whitespace between them. It then indents the markup\nby using nxml's indentation rules.\"\n (interactive \"r\")\n (save-excursion\n (nxml-mode)\n ;; split <foo><bar> or </foo><bar>, but not <foo></foo>\n (goto-char begin)\n (while (search-forward-regexp \">[ \\t]*<[^/]\" end t)\n (backward-char 2) (insert \"\\n\") (incf end))\n ;; split <foo/></foo> and </foo></foo>\n (goto-char begin)\n (while (search-forward-regexp \"<.*?/.*?>[ \\t]*<\" end t)\n (backward-char) (insert \"\\n\") (incf end))\n ;; put xml namespace decls on newline\n (goto-char begin)\n (while (search-forward-regexp \"\\\\(<\\\\([a-zA-Z][-:A-Za-z0-9]*\\\\)\\\\|['\\\"]\\\\) \\\\(xmlns[=:]\\\\)\" end t)\n (goto-char (match-end 0))\n (backward-char 6) (insert \"\\n\") (incf end))\n (indent-region begin end nil)\n (normal-mode))\n (message \"All indented!\"))\n" }, { "answer_id": 21511772, "author": "Jarekczek", "author_id": 772981, "author_profile": "https://Stackoverflow.com/users/772981", "pm_score": 1, "selected": false, "text": "xml-reformat-tags xml-reformat-tags (if (file-exists-p \"~/.emacs.d/packages/xml-parse.el\")\n (let ((load-path load-path))\n (add-to-list 'load-path \"~/.emacs.d/packages\")\n (require 'xml-parse))\n)\n" }, { "answer_id": 37539920, "author": "Talespin_Kit", "author_id": 579689, "author_profile": "https://Stackoverflow.com/users/579689", "pm_score": 5, "selected": false, "text": "M-x sgml-mode\nM-x sgml-pretty-print\n" }, { "answer_id": 38868126, "author": "JohnnyZ", "author_id": 1273287, "author_profile": "https://Stackoverflow.com/users/1273287", "pm_score": 1, "selected": false, "text": "M-x spacemacs/indent-region-or-buffer\n" }, { "answer_id": 43269076, "author": "ninrod", "author_id": 4921402, "author_profile": "https://Stackoverflow.com/users/4921402", "pm_score": 2, "selected": false, "text": "~/.emacs.d/init.el (require 'sgml-mode)\n\n(defun reformat-xml ()\n (interactive)\n (save-excursion\n (sgml-pretty-print (point-min) (point-max))\n (indent-region (point-min) (point-max))))\n M-x reformat-xml" } ]
2008/08/15
[ "https://Stackoverflow.com/questions/12492", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1448/" ]
12,501
<p>I thought that I had the latest CTP of PowerShell 2 but when I try the command:</p> <p><code>invoke-expression –computername Server01 –command 'get-process PowerShell'</code></p> <p>I get an error message:<br> <strong>A parameter cannot be found that matches parameter name 'computername'.</strong></p> <p>So the question is: How can I tell which version of PowerShell I have installed? And what the latest version is?</p>
[ { "answer_id": 12525, "author": "Kev", "author_id": 419, "author_profile": "https://Stackoverflow.com/users/419", "pm_score": 2, "selected": false, "text": "$host.version.tostring()" }, { "answer_id": 68933, "author": "Jaykul", "author_id": 8718, "author_profile": "https://Stackoverflow.com/users/8718", "pm_score": 2, "selected": false, "text": "Invoke-Command Invoke-Expression $PSVersionTable" }, { "answer_id": 575113, "author": "Jeffrey Snover - MSFT", "author_id": 69339, "author_profile": "https://Stackoverflow.com/users/69339", "pm_score": 2, "selected": false, "text": "[4120:0]PS> $psversiontable\nName Value\n---- -----\nCLRVersion 2.0.50727.3521\nBuildVersion 6.1.7047.0\nPSVersion 2.0\nWSManStackVersion 2.0\nPSCompatibleVersions {1.0, 2.0}\nSerializationVersion 1.1.0.1\nPSRemotingProtocolVersion 2.0\n" }, { "answer_id": 1551482, "author": "aleksandar", "author_id": 8766, "author_profile": "https://Stackoverflow.com/users/8766", "pm_score": 0, "selected": false, "text": "$PSVersionTable $PSVersionTable.PSVersion function Get-PSVersion { \n if (test-path variable:psversiontable) \n {$psversiontable.psversion} \n else \n {[version]\"1.0.0.0\"} \n} \n" } ]
2008/08/15
[ "https://Stackoverflow.com/questions/12501", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1463/" ]
12,516
<p>This morning, I was reading <a href="http://steve.yegge.googlepages.com/when-polymorphism-fails" rel="noreferrer">Steve Yegge's: When Polymorphism Fails</a>, when I came across a question that a co-worker of his used to ask potential employees when they came for their interview at Amazon.</p> <blockquote> <p>As an example of polymorphism in action, let's look at the classic "eval" interview question, which (as far as I know) was brought to Amazon by Ron Braunstein. The question is quite a rich one, as it manages to probe a wide variety of important skills: OOP design, recursion, binary trees, polymorphism and runtime typing, general coding skills, and (if you want to make it extra hard) parsing theory.</p> <p>At some point, the candidate hopefully realizes that you can represent an arithmetic expression as a binary tree, assuming you're only using binary operators such as "+", "-", "*", "/". The leaf nodes are all numbers, and the internal nodes are all operators. Evaluating the expression means walking the tree. If the candidate doesn't realize this, you can gently lead them to it, or if necessary, just tell them.</p> <p>Even if you tell them, it's still an interesting problem.</p> <p>The first half of the question, which some people (whose names I will protect to my dying breath, but their initials are Willie Lewis) feel is a Job Requirement If You Want To Call Yourself A Developer And Work At Amazon, is actually kinda hard. The question is: how do you go from an arithmetic expression (e.g. in a string) such as "2 + (2)" to an expression tree. We may have an ADJ challenge on this question at some point.</p> <p>The second half is: let's say this is a 2-person project, and your partner, who we'll call "Willie", is responsible for transforming the string expression into a tree. You get the easy part: you need to decide what classes Willie is to construct the tree with. You can do it in any language, but make sure you pick one, or Willie will hand you assembly language. If he's feeling ornery, it will be for a processor that is no longer manufactured in production.</p> <p>You'd be amazed at how many candidates boff this one.</p> <p>I won't give away the answer, but a Standard Bad Solution involves the use of a switch or case statment (or just good old-fashioned cascaded-ifs). A Slightly Better Solution involves using a table of function pointers, and the Probably Best Solution involves using polymorphism. I encourage you to work through it sometime. Fun stuff!</p> </blockquote> <p>So, let's try to tackle the problem all three ways. How do you go from an arithmetic expression (e.g. in a string) such as "2 + (2)" to an expression tree using cascaded-if's, a table of function pointers, and/or polymorphism? </p> <p>Feel free to tackle one, two, or all three.</p> <p>[update: title modified to better match what most of the answers have been.]</p>
[ { "answer_id": 12674, "author": "Chris Conway", "author_id": 1412, "author_profile": "https://Stackoverflow.com/users/1412", "pm_score": 2, "selected": false, "text": " +\n / \\\n + 3\n / \\\n1 2\n +\n / \\\n 1 +\n / \\\n 2 3\n" }, { "answer_id": 12688, "author": "Herms", "author_id": 1409, "author_profile": "https://Stackoverflow.com/users/1409", "pm_score": 1, "selected": false, "text": " +\n / \\\n2 ( )\n |\n 2\n +\n / \\\n2 2\n" }, { "answer_id": 12861, "author": "Mark Harrison", "author_id": 116, "author_profile": "https://Stackoverflow.com/users/116", "pm_score": 5, "selected": true, "text": "#!/usr/bin/python\n\nclass Node:\n \"\"\"base class, you should not process one of these\"\"\"\n def process(self):\n raise('you should not be processing a node')\n\nclass BinaryNode(Node):\n \"\"\"base class for binary nodes\"\"\"\n def __init__(self, _left, _right):\n self.left = _left\n self.right = _right\n def process(self):\n raise('you should not be processing a binarynode')\n\nclass Plus(BinaryNode):\n def process(self):\n return self.left.process() + self.right.process()\n\nclass Minus(BinaryNode):\n def process(self):\n return self.left.process() - self.right.process()\n\nclass Mul(BinaryNode):\n def process(self):\n return self.left.process() * self.right.process()\n\nclass Div(BinaryNode):\n def process(self):\n return self.left.process() / self.right.process()\n\nclass Num(Node):\n def __init__(self, _value):\n self.value = _value\n def process(self):\n return self.value\n\ndef demo(n):\n print n.process()\n\ndemo(Num(2)) # 2\ndemo(Plus(Num(2),Num(5))) # 2 + 3\ndemo(Plus(Mul(Num(2),Num(3)),Div(Num(10),Num(5)))) # (2 * 3) + (10 / 2)\n" }, { "answer_id": 12876, "author": "Mark Harrison", "author_id": 116, "author_profile": "https://Stackoverflow.com/users/116", "pm_score": 0, "selected": false, "text": "2 + (2)\n .\n / \\\n 2 ( )\n |\n 2\n" }, { "answer_id": 12893, "author": "Mark Harrison", "author_id": 116, "author_profile": "https://Stackoverflow.com/users/116", "pm_score": 2, "selected": false, "text": " +\n / \\\nnode node\n ( )\n |\n node\n" }, { "answer_id": 474783, "author": "Wilfred Knievel", "author_id": 6124, "author_profile": "https://Stackoverflow.com/users/6124", "pm_score": 0, "selected": false, "text": "using System;\n\nclass Program\n{\n static void Main(string[] args)\n {\n string expression = \"(((3.5 * 4.5) / (1 + 2)) + 5)\";\n Console.WriteLine(string.Format(\"{0} = {1}\", expression, new Expression.ExpressionTree(expression).Value));\n Console.WriteLine(\"\\nShow's over folks, press a key to exit\");\n Console.ReadKey(false);\n }\n}\n\nnamespace Expression\n{\n // -------------------------------------------------------\n\n abstract class NodeBase\n {\n public abstract double Value { get; }\n }\n\n // -------------------------------------------------------\n\n class ValueNode : NodeBase\n {\n public ValueNode(double value)\n {\n _double = value;\n }\n\n private double _double;\n public override double Value\n {\n get\n {\n return _double;\n }\n }\n }\n\n // -------------------------------------------------------\n\n abstract class ExpressionNodeBase : NodeBase\n {\n protected NodeBase GetNode(string expression)\n {\n // Remove parenthesis\n expression = RemoveParenthesis(expression);\n\n // Is expression just a number?\n double value = 0;\n if (double.TryParse(expression, out value))\n {\n return new ValueNode(value);\n }\n else\n {\n int pos = ParseExpression(expression);\n if (pos > 0)\n {\n string leftExpression = expression.Substring(0, pos - 1).Trim();\n string rightExpression = expression.Substring(pos).Trim();\n\n switch (expression.Substring(pos - 1, 1))\n {\n case \"+\":\n return new Add(leftExpression, rightExpression);\n case \"-\":\n return new Subtract(leftExpression, rightExpression);\n case \"*\":\n return new Multiply(leftExpression, rightExpression);\n case \"/\":\n return new Divide(leftExpression, rightExpression);\n default:\n throw new Exception(\"Unknown operator\");\n }\n }\n else\n {\n throw new Exception(\"Unable to parse expression\");\n }\n }\n }\n\n private string RemoveParenthesis(string expression)\n {\n if (expression.Contains(\"(\"))\n {\n expression = expression.Trim();\n\n int level = 0;\n int pos = 0;\n\n foreach (char token in expression.ToCharArray())\n {\n pos++;\n switch (token)\n {\n case '(':\n level++;\n break;\n case ')':\n level--;\n break;\n }\n\n if (level == 0)\n {\n break;\n }\n }\n\n if (level == 0 && pos == expression.Length)\n {\n expression = expression.Substring(1, expression.Length - 2);\n expression = RemoveParenthesis(expression);\n }\n }\n return expression;\n }\n\n private int ParseExpression(string expression)\n {\n int winningLevel = 0;\n byte winningTokenWeight = 0;\n int winningPos = 0;\n\n int level = 0;\n int pos = 0;\n\n foreach (char token in expression.ToCharArray())\n {\n pos++;\n\n switch (token)\n {\n case '(':\n level++;\n break;\n case ')':\n level--;\n break;\n }\n\n if (level <= winningLevel)\n {\n if (OperatorWeight(token) > winningTokenWeight)\n {\n winningLevel = level;\n winningTokenWeight = OperatorWeight(token);\n winningPos = pos;\n }\n }\n }\n return winningPos;\n }\n\n private byte OperatorWeight(char value)\n {\n switch (value)\n {\n case '+':\n case '-':\n return 3;\n case '*':\n return 2;\n case '/':\n return 1;\n default:\n return 0;\n }\n }\n }\n\n // -------------------------------------------------------\n\n class ExpressionTree : ExpressionNodeBase\n {\n protected NodeBase _rootNode;\n\n public ExpressionTree(string expression)\n {\n _rootNode = GetNode(expression);\n }\n\n public override double Value\n {\n get\n {\n return _rootNode.Value;\n }\n }\n }\n\n // -------------------------------------------------------\n\n abstract class OperatorNodeBase : ExpressionNodeBase\n {\n protected NodeBase _leftNode;\n protected NodeBase _rightNode;\n\n public OperatorNodeBase(string leftExpression, string rightExpression)\n {\n _leftNode = GetNode(leftExpression);\n _rightNode = GetNode(rightExpression);\n\n }\n }\n\n // -------------------------------------------------------\n\n class Add : OperatorNodeBase\n {\n public Add(string leftExpression, string rightExpression)\n : base(leftExpression, rightExpression)\n {\n }\n\n public override double Value\n {\n get\n {\n return _leftNode.Value + _rightNode.Value;\n }\n }\n }\n\n // -------------------------------------------------------\n\n class Subtract : OperatorNodeBase\n {\n public Subtract(string leftExpression, string rightExpression)\n : base(leftExpression, rightExpression)\n {\n }\n\n public override double Value\n {\n get\n {\n return _leftNode.Value - _rightNode.Value;\n }\n }\n }\n\n // -------------------------------------------------------\n\n class Divide : OperatorNodeBase\n {\n public Divide(string leftExpression, string rightExpression)\n : base(leftExpression, rightExpression)\n {\n }\n\n public override double Value\n {\n get\n {\n return _leftNode.Value / _rightNode.Value;\n }\n }\n }\n\n // -------------------------------------------------------\n\n class Multiply : OperatorNodeBase\n {\n public Multiply(string leftExpression, string rightExpression)\n : base(leftExpression, rightExpression)\n {\n }\n\n public override double Value\n {\n get\n {\n return _leftNode.Value * _rightNode.Value;\n }\n }\n }\n}\n" }, { "answer_id": 19599052, "author": "mmierzwa", "author_id": 2921510, "author_profile": "https://Stackoverflow.com/users/2921510", "pm_score": 0, "selected": false, "text": "#!/usr/bin/env python\n\n#tree structure [left argument, operator, right argument, priority level]\ntree_root = [None, None, None, None]\n#count of parethesis nesting\nparenthesis_level = 0\n#current node with empty right argument\ncurrent_node = tree_root\n\n#indices in tree_root nodes Left, Operator, Right, PRiority\nL, O, R, PR = 0, 1, 2, 3\n\n#functions that realise operators\ndef sum(a, b):\n return a + b\n\ndef diff(a, b):\n return a - b\n\ndef mul(a, b):\n return a * b\n\ndef div(a, b):\n return a / b\n\n#tree evaluator\ndef process_node(n):\n try:\n len(n)\n except TypeError:\n return n\n left = process_node(n[L])\n right = process_node(n[R])\n return n[O](left, right)\n\n#mapping operators to relevant functions\no2f = {'+': sum, '-': diff, '*': mul, '/': div, '(': None, ')': None}\n\n#converts token to a node in tree\ndef convert_token(t):\n global current_node, tree_root, parenthesis_level\n if t == '(':\n parenthesis_level += 2\n return\n if t == ')':\n parenthesis_level -= 2\n return\n try: #assumption that we have just an integer\n l = int(t)\n except (ValueError, TypeError):\n pass #if not, no problem\n else:\n if tree_root[L] is None: #if it is first number, put it on the left of root node\n tree_root[L] = l\n else: #put on the right of current_node\n current_node[R] = l\n return\n\n priority = (1 if t in '+-' else 2) + parenthesis_level\n\n #if tree_root does not have operator put it there\n if tree_root[O] is None and t in o2f:\n tree_root[O] = o2f[t]\n tree_root[PR] = priority\n return\n\n #if new node has less or equals priority, put it on the top of tree\n if tree_root[PR] >= priority:\n temp = [tree_root, o2f[t], None, priority]\n tree_root = current_node = temp\n return\n\n #starting from root search for a place with higher priority in hierarchy\n current_node = tree_root\n while type(current_node[R]) != type(1) and priority > current_node[R][PR]:\n current_node = current_node[R]\n #insert new node\n temp = [current_node[R], o2f[t], None, priority]\n current_node[R] = temp\n current_node = temp\n\n\n\ndef parse(e):\n token = ''\n for c in e:\n if c <= '9' and c >='0':\n token += c\n continue\n if c == ' ':\n if token != '':\n convert_token(token)\n token = ''\n continue\n if c in o2f:\n if token != '':\n convert_token(token)\n convert_token(c)\n token = ''\n continue\n print \"Unrecognized character:\", c\n if token != '':\n convert_token(token)\n\n\ndef main():\n parse('(((3 * 4) / (1 + 2)) + 5)')\n print tree_root\n print process_node(tree_root)\n\nif __name__ == '__main__':\n main()\n" } ]
2008/08/15
[ "https://Stackoverflow.com/questions/12516", "https://Stackoverflow.com", "https://Stackoverflow.com/users/25/" ]
12,533
<p>Is there a quick one-liner to call datepart in Sql Server and get back the name of the day instead of just the number?</p> <pre><code>select datepart(dw, getdate()); </code></pre> <p>This will return 1-7, with Sunday being 1. I would like 'Sunday' instead of 1.</p>
[ { "answer_id": 12548, "author": "Erick B", "author_id": 1373, "author_profile": "https://Stackoverflow.com/users/1373", "pm_score": 5, "selected": true, "text": "select datename(weekday, getdate());\n" }, { "answer_id": 12549, "author": "Eric Z Beard", "author_id": 1219, "author_profile": "https://Stackoverflow.com/users/1219", "pm_score": 1, "selected": false, "text": "select datename(dw, getdate())\n" } ]
2008/08/15
[ "https://Stackoverflow.com/questions/12533", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1219/" ]
12,556
<p>It looks interesting and I've played around with it some --- but the development IDE in a web browser seems to be nightmare eventually.</p> <p>Does anyone have experience using it and what are your thoughts?</p>
[ { "answer_id": 16222, "author": "Kieron", "author_id": 588, "author_profile": "https://Stackoverflow.com/users/588", "pm_score": 5, "selected": true, "text": "style" } ]
2008/08/15
[ "https://Stackoverflow.com/questions/12556", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1341/" ]
12,565
<p>In Ruby, what's the difference between <code>{}</code> and <code>[]</code>?</p> <p><code>{}</code> seems to be used for both code blocks and hashes.</p> <p>Are <code>[]</code> only for arrays?</p> <p>The documention isn't very clear.</p>
[ { "answer_id": 12575, "author": "John Topley", "author_id": 1450, "author_profile": "https://Stackoverflow.com/users/1450", "pm_score": 3, "selected": false, "text": "{} do end [] Hash[\"key\" => \"value\"]\n { \"key\" => \"value\" }\n" }, { "answer_id": 12608, "author": "James A. Rosen", "author_id": 1190, "author_profile": "https://Stackoverflow.com/users/1190", "pm_score": 2, "selected": false, "text": "[1, 2, 3].class\n# => Array\n\n[1, 2, 3][1]\n# => 2\n\n{ 1 => 2, 3 => 4 }.class\n# => Hash\n\n{ 1 => 2, 3 => 4 }[3]\n# => 4\n\n{ 1 + 2 }.class\n# SyntaxError: compile error, odd number list for Hash\n\nlambda { 1 + 2 }.class\n# => Proc\n\nlambda { 1 + 2 }.call\n# => 3\n" }, { "answer_id": 13935, "author": "Orion Edwards", "author_id": 234, "author_profile": "https://Stackoverflow.com/users/234", "pm_score": 7, "selected": true, "text": "[] {} a = [1,2,3] # an array\nb = {1 => 2} # a hash\n [] [] fetch static Create a = {1 => 2} # create a hash for example\nputs a[1] # same as a.fetch(1), will print 2\n\nHash[1,2,3,4] # this is a custom class method which creates a new hash\n {} 1.upto(2) { puts 'hello' } # it's a block\n1.upto 2 { puts 'hello' } # syntax error, ruby can't figure out where the function args end\n1.upto 2, { puts 'hello' } # the comma means \"argument\", so ruby sees it as a hash - this won't work because puts 'hello' isn't a valid hash\n" }, { "answer_id": 80928, "author": "Evgeny", "author_id": 11414, "author_profile": "https://Stackoverflow.com/users/11414", "pm_score": 2, "selected": false, "text": "ri Array::[]\n ri Hash::[]\n ri []\n s = \"hello world\"\ns[2] # => 108 is ascii for e\ns[2]=109 # 109 is ascii for m\ns # => \"hemlo world\"\n %w{ hello world } # => [\"hello\",\"world\"]\n%w[ hello world ] # => [\"hello\",\"world\"]\n%r{ hello world } # => / hello world /\n%r[ hello world ] # => / hello world /\n%q{ hello world } # => \"hello world\"\n%q[ hello world ] # => \"hello world\"\n%q| hello world | # => \"hello world\"\n" }, { "answer_id": 710327, "author": "sris", "author_id": 83996, "author_profile": "https://Stackoverflow.com/users/83996", "pm_score": 5, "selected": false, "text": "[] proc = Proc.new { |what| puts \"Hello, #{what}!\" }\nmeth = method(:print)\n\nproc[\"World\"]\nmeth[\"Hello\",\",\",\" \", \"World!\", \"\\n\"]\n" }, { "answer_id": 1563105, "author": "rogerdpack", "author_id": 32453, "author_profile": "https://Stackoverflow.com/users/32453", "pm_score": 2, "selected": false, "text": "[] class A\n def [](position)\n # do something\n end\n\n def @rank.[]= key, val\n # define the instance[a] = b method\n end\n\nend\n" } ]
2008/08/15
[ "https://Stackoverflow.com/questions/12565", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1470/" ]
12,576
<p>What can I do to increase the performance/speed of my PHP scripts without installing software on my servers?</p>
[ { "answer_id": 12584, "author": "Frank Krueger", "author_id": 338, "author_profile": "https://Stackoverflow.com/users/338", "pm_score": 5, "selected": true, "text": "function foo($stuff) {\n ...\n return ...;\n}\n function foo($stuff) {\n trace_push_fn('foo');\n ...\n trace_pop_fn('foo');\n return ...;\n}\n function bar($stuff) {\n trace_push_fn('bar');\n\n $query = ...;\n trace_push_sql($query);\n mysql_query($query);\n trace_pop_sql($query);\n\n trace_pop_fn('bar');\n return ...;\n}\n" }, { "answer_id": 24074405, "author": "Dinesh Saini", "author_id": 1547664, "author_profile": "https://Stackoverflow.com/users/1547664", "pm_score": 3, "selected": false, "text": "a) wget http://pear.php.net/go-pear.phar\nb) php go-pear.phar\n \"pear config-set auto_discover 1\"\n \"pear install --alldeps pear/PHP_CodeSniffer\"\n \"pear install --alldeps phpmd/PHP_PMD\"\n \"pear install --alldeps pdepend/PHP_Depend\"\n \"pear install --alldeps phpunit/phpcpd\"\n \"pear config-set auto_discover 0\"\n" }, { "answer_id": 47991499, "author": "Stephan Muggli", "author_id": 7459505, "author_profile": "https://Stackoverflow.com/users/7459505", "pm_score": 0, "selected": false, "text": "OPcache OPcache XHProf Tideways XHProf" } ]
2008/08/15
[ "https://Stackoverflow.com/questions/12576", "https://Stackoverflow.com", "https://Stackoverflow.com/users/115/" ]
12,591
<p>Is there a way, when I parse an XML document using lxml, to validate that document against its DTD using an external catalog file? I need to be able to work the fixed attributes defined in a document’s DTD.</p>
[ { "answer_id": 13040, "author": "Michael Twomey", "author_id": 995, "author_profile": "https://Stackoverflow.com/users/995", "pm_score": 1, "selected": false, "text": "f = StringIO(\"<!ELEMENT b EMPTY>\")\ndtd = etree.DTD(f)\ndtd = etree.DTD(external_id = \"-//OASIS//DTD DocBook XML V4.2//EN\")\n" }, { "answer_id": 36219, "author": "gz.", "author_id": 3665, "author_profile": "https://Stackoverflow.com/users/3665", "pm_score": 0, "selected": false, "text": "C:\\Dev>grep -ir --include=*.px[id] catalog lxml-2.1.1/src | sed -r \"s/\\s+/ /g\"\nlxml-2.1.1/src/lxml/dtd.pxi: catalog.\nlxml-2.1.1/src/lxml/xmlerror.pxd: XML_FROM_CATALOG = 20 # The Catalog module\nlxml-2.1.1/src/lxml/xmlerror.pxd: XML_WAR_CATALOG_PI = 93 # 93\nlxml-2.1.1/src/lxml/xmlerror.pxd: XML_CATALOG_MISSING_ATTR = 1650\nlxml-2.1.1/src/lxml/xmlerror.pxd: XML_CATALOG_ENTRY_BROKEN = 1651 # 1651\nlxml-2.1.1/src/lxml/xmlerror.pxd: XML_CATALOG_PREFER_VALUE = 1652 # 1652\nlxml-2.1.1/src/lxml/xmlerror.pxd: XML_CATALOG_NOT_CATALOG = 1653 # 1653\nlxml-2.1.1/src/lxml/xmlerror.pxd: XML_CATALOG_RECURSION = 1654 # 1654\nlxml-2.1.1/src/lxml/xmlerror.pxi:CATALOG=20\nlxml-2.1.1/src/lxml/xmlerror.pxi:WAR_CATALOG_PI=93\nlxml-2.1.1/src/lxml/xmlerror.pxi:CATALOG_MISSING_ATTR=1650\nlxml-2.1.1/src/lxml/xmlerror.pxi:CATALOG_ENTRY_BROKEN=1651\nlxml-2.1.1/src/lxml/xmlerror.pxi:CATALOG_PREFER_VALUE=1652\nlxml-2.1.1/src/lxml/xmlerror.pxi:CATALOG_NOT_CATALOG=1653\nlxml-2.1.1/src/lxml/xmlerror.pxi:CATALOG_RECURSION=1654\n" }, { "answer_id": 8391738, "author": "Brecht Machiels", "author_id": 438249, "author_profile": "https://Stackoverflow.com/users/438249", "pm_score": 3, "selected": false, "text": "XML_CATALOG_FILES os.environ['XML_CATALOG_FILES'] = 'file:///to/my/catalog.xml'\n XML_CATALOG_FILES pathname2url urljoin file:" } ]
2008/08/15
[ "https://Stackoverflow.com/questions/12591", "https://Stackoverflow.com", "https://Stackoverflow.com/users/207/" ]
12,592
<p>Is it possible to write a <code>doctest</code> unit test that will check that an exception is raised?<br /> For example, if I have a function <code>foo(x)</code> that is supposed to raise an exception if <code>x &lt; 0</code>, how would I write the <code>doctest</code> for that?</p>
[ { "answer_id": 12609, "author": "cnu", "author_id": 1448, "author_profile": "https://Stackoverflow.com/users/1448", "pm_score": 8, "selected": true, "text": " >>> x\n Traceback (most recent call last):\n ...\n NameError: name 'x' is not defined\n" }, { "answer_id": 33787471, "author": "glickind", "author_id": 5577962, "author_profile": "https://Stackoverflow.com/users/5577962", "pm_score": 3, "selected": false, "text": ">>> import math\n>>> math.log(-2)\nTraceback (most recent call last):\n ...\nValueError: math domain error\n" }, { "answer_id": 63539385, "author": "runsun", "author_id": 2565778, "author_profile": "https://Stackoverflow.com/users/2565778", "pm_score": 4, "selected": false, "text": ">>> scope # doctest: +IGNORE_EXCEPTION_DETAIL\nTraceback (most recent call last):\nNameError: name 'scope' is not defined\n" } ]
2008/08/15
[ "https://Stackoverflow.com/questions/12592", "https://Stackoverflow.com", "https://Stackoverflow.com/users/742/" ]
12,594
<p>Let's say I have a drive such as <strong>C:\</strong>, and I want to find out if it's shared and what it's share name (e.g. <strong>C$</strong>) is.</p> <p>To find out if it's shared, I can use <a href="https://learn.microsoft.com/en-us/windows/desktop/api/Lmshare/nf-lmshare-netsharecheck" rel="nofollow noreferrer">NetShareCheck</a>.</p> <p>How do I then map the drive to its share name? I thought that <a href="https://learn.microsoft.com/en-us/windows/desktop/api/Lmshare/nf-lmshare-netsharegetinfo" rel="nofollow noreferrer">NetShareGetInfo</a> would do it, but it looks like that takes the share name, not the local drive name, as an input.</p>
[ { "answer_id": 12634, "author": "Andrew Grant", "author_id": 1043, "author_profile": "https://Stackoverflow.com/users/1043", "pm_score": 0, "selected": false, "text": "SHGetFileInfo with SHGFI_ATTRIBUTES\n" } ]
2008/08/15
[ "https://Stackoverflow.com/questions/12594", "https://Stackoverflow.com", "https://Stackoverflow.com/users/179/" ]