qid
int64 4
19.1M
| question
stringlengths 18
48.3k
| answers
list | date
stringlengths 10
10
| metadata
list |
|---|---|---|---|---|
271,340
|
<p>I'm trying to use a dojo combobox with an Ajax data source. What I have is </p>
<pre><code><div dojoType="dojo.data.ItemFileReadStore"
jsId="tags"
url="<%=ResolveClientUrl("~/Tag/TagMatches")%>" >
</div>
<select dojoType="dijit.form.ComboBox"
store="tags"
value=""
name="tagName">
</select>
</code></pre>
<p>Which does work except that I can't restrict the search set on the server side because I don't know how to change the url from which the data is pulled in order to specify a parameter. Any hints? </p>
|
[
{
"answer_id": 271443,
"author": "Tomalak",
"author_id": 18771,
"author_profile": "https://Stackoverflow.com/users/18771",
"pm_score": 2,
"selected": true,
"text": "<div> ItemFileReadStore var tagMatchUrlBase = '<%=ResolveClientUrl(\"~/Tag/TagMatches\")%>';\n var tagMatchUrl = tagMatchUrlBase + \"?f=\" + escape(somefilterString);\nvar store = new dojo.data.ItemFileReadStore({url: tagMatchUrl});\ntagName.store = store;\n// maybe use store.fetch() to pre-select item #1\n"
}
] |
2008/11/07
|
[
"https://Stackoverflow.com/questions/271340",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/361/"
] |
271,347
|
<p>I have a class that stores a serialized value and a type. I want to have a property/method returning the value already casted:</p>
<pre><code>public String Value { get; set; }
public Type TheType { get; set; }
public typeof(TheType) CastedValue { get { return Convert.ChangeType(Value, typeof(_Type)); }
</code></pre>
<p>Is this possible in C#?</p>
|
[
{
"answer_id": 271356,
"author": "Brannon",
"author_id": 5745,
"author_profile": "https://Stackoverflow.com/users/5745",
"pm_score": 7,
"selected": false,
"text": "class Foo<TValue> {\n public string Value { get; set; }\n public TValue TypedValue {\n get {\n return (TValue)Convert.ChangeType(Value, typeof(TValue));\n }\n }\n}\n class Foo {\n public string Value { get; set; }\n public Type TheType { get; set; }\n\n public T CastValue<T>() {\n return (T)Convert.ChangeType(Value, typeof(T));\n }\n}\n System.ComponentModel.TypeConverter Foo foo = new Foo();\nfoo.Value = \"100\";\nfoo.Type = typeof(int);\n\nint c = foo.CastValue<int>();\n object Foo public object ConvertedValue {\n get {\n return Convert.ChangeType(Value, Type);\n }\n}\n"
}
] |
2008/11/07
|
[
"https://Stackoverflow.com/questions/271347",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
271,364
|
<p><code>:vimgrep</code> looks like a really useful thing.</p>
<p>Here's how to use it:</p>
<pre><code>:vim[grep][!] /{pattern}/[g][j] {file} ...
</code></pre>
<p><code>:help</code> says that you can essentially glob <code>{file}</code> to name, say, <code>*.c</code> for the current directory. I may have started Vim with a list of files that is complicated enough that I don't want to manually type it in for <code>{file}</code>, and besides Vim already knows what those files are.</p>
<p>What I would like to do is vimgrep over any of:</p>
<ul>
<li><code>:args</code></li>
<li><code>:files</code></li>
<li><code>:buffers</code></li>
</ul>
<p>What variable(s) would I use in place of <code>{file}</code> to name, respectively, any of those lists in a <code>vimgrep</code> command?</p>
|
[
{
"answer_id": 271381,
"author": "Jerub",
"author_id": 14648,
"author_profile": "https://Stackoverflow.com/users/14648",
"pm_score": 3,
"selected": false,
"text": ":bufdo vimgrep /pattern/ %\n"
},
{
"answer_id": 271709,
"author": "Luc Hermitte",
"author_id": 15934,
"author_profile": "https://Stackoverflow.com/users/15934",
"pm_score": 5,
"selected": true,
"text": ":h :redir :vimgrep :exe :exe \"vimgrep/pattern/ \" . lh#askvim#Exe(':args')\n :redir :args join(argv(), ' ') :args function BuffersList()\n let all = range(0, bufnr('$'))\n let res = []\n for b in all\n if buflisted(b)\n call add(res, bufname(b))\n endif\n endfor\n return res\nendfunction\n:exe 'vimgrep/pattern/ '.join(BuffersList(),' ')\n"
},
{
"answer_id": 8414211,
"author": "baltazar",
"author_id": 258421,
"author_profile": "https://Stackoverflow.com/users/258421",
"pm_score": 2,
"selected": false,
"text": ":cex [] | tabdo vimgrepa /pattern/ %\n cex [] vimgrepa tabdo argdo bufdo windo :cope\n % ~/.vimrc function TS(text)\n exe \"cex [] | tabdo vimgrepa /\" . a:text . \"/ %\"\nendfunction\ncommand -nargs=1 TS call TS(<q-args>)\ncnoreabbrev ts TS\n :ts from game import\n ts"
},
{
"answer_id": 19365379,
"author": "Steve",
"author_id": 1173869,
"author_profile": "https://Stackoverflow.com/users/1173869",
"pm_score": 3,
"selected": false,
"text": "## :help cmdline-special :vimgrep /re/ ##\n :argdelete ##\n:bufdo argadd %\n ## :n :e"
}
] |
2008/11/07
|
[
"https://Stackoverflow.com/questions/271364",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/35221/"
] |
271,378
|
<p>I have designed my site with a 900 x 600 fixed background image. On the computer it looks fine. How will it look on a PDA device? Will I have to design it separately for PDA?</p>
<p>How should check whether my site can be browsed effectively from mobile phone?</p>
<p>What should I do?</p>
|
[
{
"answer_id": 271452,
"author": "Treb",
"author_id": 22114,
"author_profile": "https://Stackoverflow.com/users/22114",
"pm_score": 2,
"selected": false,
"text": "<link rel=\"stylesheet\" href=\"small.css\" type=\"text/css\" media=\"handheld\">\n media"
}
] |
2008/11/07
|
[
"https://Stackoverflow.com/questions/271378",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
271,380
|
<p>One of the files in my current head revision got corrupted. I want to make an older revision of that file the head revision as usually people sync to head revsion in my project. How to do that?</p>
|
[
{
"answer_id": 271387,
"author": "Martin v. Löwis",
"author_id": 33006,
"author_profile": "https://Stackoverflow.com/users/33006",
"pm_score": 7,
"selected": true,
"text": "svn merge -rHEAD:oldrev filename\nsvn commit -m \"rolled back to oldrev\"\n"
}
] |
2008/11/07
|
[
"https://Stackoverflow.com/questions/271380",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13440/"
] |
271,384
|
<ul>
<li>What are the pros and cons of LINQ (Language-Integrated Query)?</li>
<li>What are the best and worst cases in which to use LINQ?</li>
<li>How have you benefitted or not benefitted from using LINQ?</li>
<li>Which data sources benefit the least and the most from LINQ?</li>
</ul>
|
[
{
"answer_id": 271415,
"author": "Jon Skeet",
"author_id": 22656,
"author_profile": "https://Stackoverflow.com/users/22656",
"pm_score": 6,
"selected": true,
"text": "OrderBy"
},
{
"answer_id": 271462,
"author": "Toby",
"author_id": 291137,
"author_profile": "https://Stackoverflow.com/users/291137",
"pm_score": 2,
"selected": false,
"text": "var l = new List<int>() {1, 2, 3};\ntry\n{\n l.Select(x => x / 0);\n}\ncatch\n{\n // error\n}\n\nl.elementAt(0); // exception occurs here outside of the try catch\n"
}
] |
2008/11/07
|
[
"https://Stackoverflow.com/questions/271384",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/35331/"
] |
271,394
|
<p>A class I am taking currently requires us to do all of our coding in smalltalk (it's a Design class). On one of our projects, I am looking to do some things, and am having a tough time finding how to do them. It seems that what most people do is modify their own version of smalltalk to do what they need it to do. I am not at liberty to do this, as this would cause an error on my prof's computer when he doesn't have the same built-in methods I do.</p>
<p>Here's what I'm looking to do:</p>
<p>Random Numbers. I need to create a random number between 1 and 1000. Right now I'm faking it by doing </p>
<pre><code>rand := Random new.
rand := (rand nextValue) * 1000.
rand := rand asInteger.
</code></pre>
<p>This gives me a number between 0 and 1000. Is there a way to do this in one command? similar to </p>
<pre><code>Random between: 0 and: 1000
</code></pre>
<p>And/Or statements. This one bugs the living daylights out of me. I have tried several different configurations of </p>
<pre><code>(statement) and: (statement) ifTrue...
(statement) and (statement) ifTrue...
</code></pre>
<p>So I'm faking it with nested ifTrue statements:</p>
<pre><code>(statement) ifTrue:[
(statement) ifTrue:[...
</code></pre>
<p>What is the correct way to do and/or and Random in smalltalk?</p>
|
[
{
"answer_id": 271402,
"author": "Martin v. Löwis",
"author_id": 33006,
"author_profile": "https://Stackoverflow.com/users/33006",
"pm_score": 4,
"selected": true,
"text": " (expr) and: (expr) ifTrue: aBlock\n and:ifTrue: ((expr) and: (expr)) ifTrue: aBlock\n"
},
{
"answer_id": 271500,
"author": "Martin v. Löwis",
"author_id": 33006,
"author_profile": "https://Stackoverflow.com/users/33006",
"pm_score": 2,
"selected": false,
"text": "Random>>#nextInt: (self next * anInteger) truncated + 1\n between: low and: high \n ^(self next * (high-low+1)) truncated + low\n"
},
{
"answer_id": 285651,
"author": "Rydier",
"author_id": 22434,
"author_profile": "https://Stackoverflow.com/users/22434",
"pm_score": 3,
"selected": false,
"text": "(aBoolean and: [anotherBoolean]) ifTrue: [doSomething].\n & aBoolean & anotherBoolean ifTrue:[doSomething].\n & and: Random >> between: and:"
},
{
"answer_id": 311121,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 3,
"selected": false,
"text": "(1 to: 1000) atRandom\n"
},
{
"answer_id": 33855293,
"author": "Euan M",
"author_id": 1970590,
"author_profile": "https://Stackoverflow.com/users/1970590",
"pm_score": 0,
"selected": false,
"text": "aRandomSeries := Random new .\n \"Seed a new series of random numbers\" \n\naRandomInt := aRandomSeries newInt: 1000 . \n \"generate a random integer between 0 and 1000\"\n\nanotherRandomInt := aRandomSeries newInt: 1000 .\n \"generate another random integer between 0 and 1000\"\n aBoolean and: or: and: alternativeBlock or: alternativeBlock ( 3 > 2 ) or: [ 3 < 4 ] ifTrue: [ ] aBoolean and: [ anotherBoolean ] ifFalse: [ ] ( ) & | & | and:and: } and:and:and: } and:and:and:and } or:or: } or:or:or: } or:or:or:or: }"
},
{
"answer_id": 33866017,
"author": "John Pfersich",
"author_id": 5561176,
"author_profile": "https://Stackoverflow.com/users/5561176",
"pm_score": 0,
"selected": false,
"text": "(statement) and: (statement) ifTrue...\n(statement) and (statement) ifTrue...\n (statement) and: [statement] ifTrue: [ ... ]\n"
}
] |
2008/11/07
|
[
"https://Stackoverflow.com/questions/271394",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/50/"
] |
271,398
|
<p>Let's make a list of answers where you post your excellent and favorite <a href="http://en.wikipedia.org/wiki/Extension_method" rel="nofollow noreferrer">extension methods</a>. </p>
<p>The requirement is that the full code must be posted and a example and an explanation on how to use it.</p>
<p>Based on the high interest in this topic I have setup an Open Source Project called extensionoverflow on <a href="http://www.codeplex.com/extensionoverflow" rel="nofollow noreferrer"><strong>Codeplex</strong></a>. </p>
<p><strong>Please mark your answers with an acceptance to put the code in the Codeplex project.</strong></p>
<p><strong>Please post the full sourcecode and not a link.</strong></p>
<p><strong>Codeplex News:</strong></p>
<p>24.08.2010 The Codeplex page is now here: <a href="http://extensionoverflow.codeplex.com/" rel="nofollow noreferrer">http://extensionoverflow.codeplex.com/</a></p>
<p>11.11.2008 <strong>XmlSerialize / XmlDeserialize</strong> is now <a href="http://www.codeplex.com/extensionoverflow/SourceControl/FileView.aspx?itemId=284374&changeSetId=17001" rel="nofollow noreferrer">Implemented</a> and <a href="http://www.codeplex.com/extensionoverflow/SourceControl/FileView.aspx?itemId=288847&changeSetId=17001" rel="nofollow noreferrer">Unit Tested</a>.</p>
<p>11.11.2008 There is still room for more developers. ;-) <strong>Join NOW!</strong></p>
<p>11.11.2008 Third contributer joined <a href="http://www.codeplex.com/extensionoverflow" rel="nofollow noreferrer">ExtensionOverflow</a>, welcome to <a href="http://www.codeplex.com/site/users/view/BKristensen" rel="nofollow noreferrer">BKristensen</a></p>
<p>11.11.2008 <strong>FormatWith</strong> is now <a href="http://www.codeplex.com/extensionoverflow/SourceControl/FileView.aspx?itemId=284374&changeSetId=16839" rel="nofollow noreferrer">Implemented</a> and <a href="http://www.codeplex.com/extensionoverflow/SourceControl/FileView.aspx?itemId=288847&changeSetId=16839" rel="nofollow noreferrer">Unit Tested</a>.</p>
<p>09.11.2008 Second contributer joined <a href="http://www.codeplex.com/extensionoverflow" rel="nofollow noreferrer">ExtensionOverflow</a>. welcome to <a href="https://stackoverflow.com/users/3055/chakrit">chakrit</a>.</p>
<p>09.11.2008 We need more developers. ;-)</p>
<p>09.11.2008 <strong>ThrowIfArgumentIsNull</strong> in now <a href="http://www.codeplex.com/extensionoverflow/SourceControl/FileView.aspx?itemId=278942&changeSetId=16468" rel="nofollow noreferrer">Implemented</a> and <a href="http://www.codeplex.com/extensionoverflow/SourceControl/FileView.aspx?itemId=284112&changeSetId=16468" rel="nofollow noreferrer">Unit Tested</a> on Codeplex.</p>
|
[
{
"answer_id": 271409,
"author": "bovium",
"author_id": 11135,
"author_profile": "https://Stackoverflow.com/users/11135",
"pm_score": 5,
"selected": false,
"text": "public static class Extensions\n{\n public static void ThrowIfArgumentIsNull<T>(this T obj, string parameterName) where T : class\n {\n if (obj == null) throw new ArgumentNullException(parameterName + \" not allowed to be null\");\n }\n}\n internal class Test\n{\n public Test(string input1)\n {\n input1.ThrowIfArgumentIsNull(\"input1\");\n }\n}\n"
},
{
"answer_id": 271411,
"author": "chakrit",
"author_id": 3055,
"author_profile": "https://Stackoverflow.com/users/3055",
"pm_score": 7,
"selected": false,
"text": "public static class StringExtensions\n{\n // Enable quick and more natural string.Format calls\n public static string F(this string s, params object[] args)\n {\n return string.Format(s, args);\n }\n}\n var s = \"The co-ordinate is ({0}, {1})\".F(point.X, point.Y);\n \"some string\".F(\"param\") string.Format(\"some string\", \"param\") s = \"Hello {0} world {1}!\".Fmt(\"Stack\", \"Overflow\");\ns = \"Hello {0} world {1}!\".FormatBy(\"Stack\", \"Overflow\");\ns = \"Hello {0} world {1}!\".FormatWith(\"Stack\", \"Overflow\");\ns = \"Hello {0} world {1}!\".Display(\"Stack\", \"Overflow\");\ns = \"Hello {0} world {1}!\".With(\"Stack\", \"Overflow\");\n"
},
{
"answer_id": 271418,
"author": "Christian C. Salvadó",
"author_id": 5445,
"author_profile": "https://Stackoverflow.com/users/5445",
"pm_score": 4,
"selected": false,
"text": "public static class ExtensionMethods \n{\n public static string ToCurrency(this double value, string cultureName)\n {\n CultureInfo currentCulture = new CultureInfo(cultureName);\n return (string.Format(currentCulture, \"{0:C}\", value));\n }\n}\n double test = 154.20;\nstring testString = test.ToCurrency(\"en-US\"); // $154.20\n"
},
{
"answer_id": 271421,
"author": "mlarsen",
"author_id": 17700,
"author_profile": "https://Stackoverflow.com/users/17700",
"pm_score": 5,
"selected": false,
"text": "public static class StringExtensions {\n\n /// <summary>\n /// Parses a string into an Enum\n /// </summary>\n /// <typeparam name=\"T\">The type of the Enum</typeparam>\n /// <param name=\"value\">String value to parse</param>\n /// <returns>The Enum corresponding to the stringExtensions</returns>\n public static T EnumParse<T>(this string value) {\n return StringExtensions.EnumParse<T>(value, false);\n }\n\n public static T EnumParse<T>(this string value, bool ignorecase) {\n\n if (value == null) {\n throw new ArgumentNullException(\"value\");\n }\n\n value = value.Trim();\n\n if (value.Length == 0) {\n throw new ArgumentException(\"Must specify valid information for parsing in the string.\", \"value\");\n }\n\n Type t = typeof(T);\n\n if (!t.IsEnum) {\n throw new ArgumentException(\"Type provided must be an Enum.\", \"T\");\n }\n\n return (T)Enum.Parse(t, value, ignorecase);\n }\n}\n public enum TestEnum\n{\n Bar,\n Test\n}\n\npublic class Test\n{\n public void Test()\n {\n TestEnum foo = \"Test\".EnumParse<TestEnum>();\n }\n }\n"
},
{
"answer_id": 271423,
"author": "TWith2Sugars",
"author_id": 35389,
"author_profile": "https://Stackoverflow.com/users/35389",
"pm_score": 6,
"selected": false,
"text": "/// <summary>Serializes an object of type T in to an xml string</summary>\n/// <typeparam name=\"T\">Any class type</typeparam>\n/// <param name=\"obj\">Object to serialize</param>\n/// <returns>A string that represents Xml, empty otherwise</returns>\npublic static string XmlSerialize<T>(this T obj) where T : class, new()\n{\n if (obj == null) throw new ArgumentNullException(\"obj\");\n\n var serializer = new XmlSerializer(typeof(T));\n using (var writer = new StringWriter())\n {\n serializer.Serialize(writer, obj);\n return writer.ToString();\n }\n}\n\n/// <summary>Deserializes an xml string in to an object of Type T</summary>\n/// <typeparam name=\"T\">Any class type</typeparam>\n/// <param name=\"xml\">Xml as string to deserialize from</param>\n/// <returns>A new object of type T is successful, null if failed</returns>\npublic static T XmlDeserialize<T>(this string xml) where T : class, new()\n{\n if (xml == null) throw new ArgumentNullException(\"xml\");\n\n var serializer = new XmlSerializer(typeof(T));\n using (var reader = new StringReader(xml))\n {\n try { return (T)serializer.Deserialize(reader); }\n catch { return null; } // Could not be deserialized to this type.\n }\n}\n"
},
{
"answer_id": 271426,
"author": "Christian C. Salvadó",
"author_id": 5445,
"author_profile": "https://Stackoverflow.com/users/5445",
"pm_score": 5,
"selected": false,
"text": "DateTime firstDayOfMonth = DateTime.Now.First();\nDateTime lastdayOfMonth = DateTime.Now.Last();\nDateTime lastFridayInMonth = DateTime.Now.Last(DayOfWeek.Friday);\nDateTime nextFriday = DateTime.Now.Next(DayOfWeek.Friday);\nDateTime lunchTime = DateTime.Now.SetTime(11, 30);\nDateTime noonOnFriday = DateTime.Now.Next(DayOfWeek.Friday).Noon();\nDateTime secondMondayOfMonth = DateTime.Now.First(DayOfWeek.Monday).Next(DayOfWeek.Monday).Midnight();\n"
},
{
"answer_id": 271433,
"author": "sontek",
"author_id": 17176,
"author_profile": "https://Stackoverflow.com/users/17176",
"pm_score": -1,
"selected": false,
"text": "public static string ToXml<T>(this T obj) where T : class\n{\n XmlSerializer s = new XmlSerializer(obj.GetType());\n using (StringWriter writer = new StringWriter())\n {\n s.Serialize(writer, obj);\n return writer.ToString();\n }\n}\n\n\"<root><child>foo</child</root>\".ToXml<MyCustomType>();\n"
},
{
"answer_id": 271435,
"author": "TWith2Sugars",
"author_id": 35389,
"author_profile": "https://Stackoverflow.com/users/35389",
"pm_score": 3,
"selected": false,
"text": "/// <summary>\n/// Converts any type in to an Int32\n/// </summary>\n/// <typeparam name=\"T\">Any Object</typeparam>\n/// <param name=\"value\">Value to convert</param>\n/// <returns>The integer, 0 if unsuccessful</returns>\npublic static int ToInt32<T>(this T value)\n{\n int result;\n if (int.TryParse(value.ToString(), out result))\n {\n return result;\n }\n return 0;\n}\n\n/// <summary>\n/// Converts any type in to an Int32 but if null then returns the default\n/// </summary>\n/// <param name=\"value\">Value to convert</param>\n/// <typeparam name=\"T\">Any Object</typeparam>\n/// <param name=\"defaultValue\">Default to use</param>\n/// <returns>The defaultValue if unsuccessful</returns>\npublic static int ToInt32<T>(this T value, int defaultValue)\n{\n int result;\n if (int.TryParse(value.ToString(), out result))\n {\n return result;\n }\n return defaultValue;\n}\n int number = \"123\".ToInt32();\n int badNumber = \"a\".ToInt32(100); // Returns 100 since a is nan\n"
},
{
"answer_id": 271437,
"author": "Jon Skeet",
"author_id": 22656,
"author_profile": "https://Stackoverflow.com/users/22656",
"pm_score": 7,
"selected": false,
"text": "var birthday = 19.June(1976);\nvar workingDay = 7.Hours() + 30.Minutes();\n var evenNaturals = 2.To(int.MaxValue).Step(2);\nvar daysSinceBirth = birthday.To(DateTime.Today).Step(1.Days());\n var myComparer = ProjectionComparer.Create(Person p => p.Name);\nvar next = myComparer.ThenBy(p => p.Age);\nvar reversed = myComparer.Reverse();\n x.ThrowIfNull(\"x\");\n // <Name>Jon</Name><Age>32</Age>\nnew { Name=\"Jon\", Age=32}.ToXElements();\n// Name=\"Jon\" Age=\"32\" (as XAttributes, obviously)\nnew { Name=\"Jon\", Age=32}.ToXAttributes()\n"
},
{
"answer_id": 271444,
"author": "Christian C. Salvadó",
"author_id": 5445,
"author_profile": "https://Stackoverflow.com/users/5445",
"pm_score": 6,
"selected": false,
"text": "public static class ComparableExtensions\n{\n public static bool Between<T>(this T actual, T lower, T upper) where T : IComparable<T>\n {\n return actual.CompareTo(lower) >= 0 && actual.CompareTo(upper) < 0;\n }\n}\n if (myNumber.Between(3,7))\n{\n // ....\n}\n"
},
{
"answer_id": 271451,
"author": "Alan",
"author_id": 31223,
"author_profile": "https://Stackoverflow.com/users/31223",
"pm_score": 2,
"selected": false,
"text": "public static void LoadFrom(this ApplicationSettingsBase settings, NameValueCollection configuration)\n{\n if (configuration != null)\n foreach (string key in configuration.AllKeys)\n if (!String.IsNullOrEmpty(key))\n try\n {\n settings[key] = configuration.Get(key);\n }\n catch (SettingsPropertyNotFoundException)\n {\n // handle bad arguments as you wish\n }\n}\n Settings.Default.LoadFrom(new NameValueCollection() { { \"Setting1\", \"Value1\" }, { \"Setting2\", \"Value2\" } });\n"
},
{
"answer_id": 271478,
"author": "cfeduke",
"author_id": 5645,
"author_profile": "https://Stackoverflow.com/users/5645",
"pm_score": 2,
"selected": false,
"text": "public static IList<T> Clone<T>(this IList<T> list) where T : ICloneable\n{\n var ret = new List<T>(list.Count);\n foreach (var item in list)\n ret.Add((T)item.Clone());\n\n // done\n return ret;\n}\n public static long? ToNullableInt64(this string val)\n{\n long ret;\n return Int64.TryParse(val, out ret) ? ret : new long?();\n}\n public static void Split<T>(this T[] array, \n Func<T,bool> determinator, \n IList<T> onTrue, \n IList<T> onFalse)\n{\n if (onTrue == null)\n onTrue = new List<T>();\n else\n onTrue.Clear();\n\n if (onFalse == null)\n onFalse = new List<T>();\n else\n onFalse.Clear();\n\n if (determinator == null)\n return;\n\n foreach (var item in array)\n {\n if (determinator(item))\n onTrue.Add(item);\n else\n onFalse.Add(item);\n }\n}\n"
},
{
"answer_id": 271611,
"author": "stiduck",
"author_id": 35398,
"author_profile": "https://Stackoverflow.com/users/35398",
"pm_score": 6,
"selected": false,
"text": "public static void AddRange<T, S>(this ICollection<T> list, params S[] values)\n where S : T\n{\n foreach (S value in values)\n list.Add(value);\n}\n var list = new List<Int32>();\nlist.AddRange(5, 4, 8, 4, 2);\n"
},
{
"answer_id": 271656,
"author": "Pure.Krome",
"author_id": 30674,
"author_profile": "https://Stackoverflow.com/users/30674",
"pm_score": 3,
"selected": false,
"text": "using System;\nusing System.Collections.Generic;\nusing System.Globalization;\nusing System.Linq;\nusing System.Text;\n\nnamespace Insert.Your.Namespace.Here.Helpers\n{\n public static class Extensions\n {\n public static bool IsNullOrEmpty<T>(this IEnumerable<T> iEnumerable)\n {\n // Cheers to Joel Mueller for the bugfix. Was .Count(), now it's .Any()\n return iEnumerable == null ||\n !iEnumerable.Any();\n }\n\n public static IList<T> ToListIfNotNullOrEmpty<T>(this IList<T> iList)\n {\n return iList.IsNullOrEmpty() ? null : iList;\n }\n\n public static PagedList<T> ToPagedListIfNotNullOrEmpty<T>(this PagedList<T> pagedList)\n {\n return pagedList.IsNullOrEmpty() ? null : pagedList;\n }\n\n public static string ToPluralString(this int value)\n {\n return value == 1 ? string.Empty : \"s\";\n }\n\n public static string ToReadableTime(this DateTime value)\n {\n TimeSpan span = DateTime.Now.Subtract(value);\n const string plural = \"s\";\n\n\n if (span.Days > 7)\n {\n return value.ToShortDateString();\n }\n\n switch (span.Days)\n {\n case 0:\n switch (span.Hours)\n {\n case 0:\n if (span.Minutes == 0)\n {\n return span.Seconds <= 0\n ? \"now\"\n : string.Format(\"{0} second{1} ago\",\n span.Seconds,\n span.Seconds != 1 ? plural : string.Empty);\n }\n return string.Format(\"{0} minute{1} ago\",\n span.Minutes,\n span.Minutes != 1 ? plural : string.Empty);\n default:\n return string.Format(\"{0} hour{1} ago\",\n span.Hours,\n span.Hours != 1 ? plural : string.Empty);\n }\n default:\n return string.Format(\"{0} day{1} ago\",\n span.Days,\n span.Days != 1 ? plural : string.Empty);\n }\n }\n\n public static string ToShortGuidString(this Guid value)\n {\n return Convert.ToBase64String(value.ToByteArray())\n .Replace(\"/\", \"_\")\n .Replace(\"+\", \"-\")\n .Substring(0, 22);\n }\n\n public static Guid FromShortGuidString(this string value)\n {\n return new Guid(Convert.FromBase64String(value.Replace(\"_\", \"/\")\n .Replace(\"-\", \"+\") + \"==\"));\n }\n\n public static string ToStringMaximumLength(this string value, int maximumLength)\n {\n return ToStringMaximumLength(value, maximumLength, \"...\");\n }\n\n public static string ToStringMaximumLength(this string value, int maximumLength, string postFixText)\n {\n if (string.IsNullOrEmpty(postFixText))\n {\n throw new ArgumentNullException(\"postFixText\");\n }\n\n return value.Length > maximumLength\n ? string.Format(CultureInfo.InvariantCulture,\n \"{0}{1}\",\n value.Substring(0, maximumLength - postFixText.Length),\n postFixText)\n :\n value;\n }\n\n public static string SlugDecode(this string value)\n {\n return value.Replace(\"_\", \" \");\n }\n\n public static string SlugEncode(this string value)\n {\n return value.Replace(\" \", \"_\");\n }\n }\n}\n"
},
{
"answer_id": 271884,
"author": "xyz",
"author_id": 82,
"author_profile": "https://Stackoverflow.com/users/82",
"pm_score": 6,
"selected": false,
"text": "public static bool CoinToss(this Random rng)\n{\n return rng.Next(2) == 0;\n}\n\npublic static T OneOf<T>(this Random rng, params T[] things)\n{\n return things[rng.Next(things.Length)];\n}\n\nRandom rand;\nbool luckyDay = rand.CoinToss();\nstring babyName = rand.OneOf(\"John\", \"George\", \"Radio XBR74 ROCKS!\");\n"
},
{
"answer_id": 271941,
"author": "Venr",
"author_id": 20385,
"author_profile": "https://Stackoverflow.com/users/20385",
"pm_score": 5,
"selected": false,
"text": "public static string ToTitleCase(this string mText)\n{\n if (mText == null) return mText;\n\n System.Globalization.CultureInfo cultureInfo = System.Threading.Thread.CurrentThread.CurrentCulture;\n System.Globalization.TextInfo textInfo = cultureInfo.TextInfo;\n\n // TextInfo.ToTitleCase only operates on the string if is all lower case, otherwise it returns the string unchanged.\n return textInfo.ToTitleCase(mText.ToLower());\n}\n"
},
{
"answer_id": 273648,
"author": "Adam Lassek",
"author_id": 1249,
"author_profile": "https://Stackoverflow.com/users/1249",
"pm_score": 4,
"selected": false,
"text": "public static DateTime? GetNullableDateTime(this MySqlDataReader dr, string fieldName)\n{\n DateTime? nullDate = null;\n return dr.IsDBNull(dr.GetOrdinal(fieldName)) ? nullDate : dr.GetDateTime(fieldName);\n}\n\npublic static string GetNullableString(this MySqlDataReader dr, string fieldName)\n{\n return dr.IsDBNull(dr.GetOrdinal(fieldName)) ? String.Empty : dr.GetString(fieldName);\n}\n\npublic static char? GetNullableChar(this MySqlDataReader dr, string fieldName)\n{\n char? nullChar = null;\n return dr.IsDBNull(dr.GetOrdinal(fieldName)) ? nullChar : dr.GetChar(fieldName);\n}\n public static int? GetNullableInt32(this IDataRecord dr, int ordinal)\n{\n int? nullInt = null;\n return dr.IsDBNull(ordinal) ? nullInt : dr.GetInt32(ordinal);\n}\n\npublic static int? GetNullableInt32(this IDataRecord dr, string fieldname)\n{\n int ordinal = dr.GetOrdinal(fieldname);\n return dr.GetNullableInt32(ordinal);\n}\n\npublic static bool? GetNullableBoolean(this IDataRecord dr, int ordinal)\n{\n bool? nullBool = null;\n return dr.IsDBNull(ordinal) ? nullBool : dr.GetBoolean(ordinal);\n}\n\npublic static bool? GetNullableBoolean(this IDataRecord dr, string fieldname)\n{\n int ordinal = dr.GetOrdinal(fieldname);\n return dr.GetNullableBoolean(ordinal);\n}\n"
},
{
"answer_id": 273665,
"author": "hugoware",
"author_id": 17091,
"author_profile": "https://Stackoverflow.com/users/17091",
"pm_score": 2,
"selected": false,
"text": "/// <summary>\n/// Checks the Request.QueryString for the specified value and returns it, if none \n/// is found then the default value is returned instead\n/// </summary>\npublic static T QueryValue<T>(this HtmlHelper helper, string param, T defaultValue) {\n object value = HttpContext.Current.Request.QueryString[param] as object;\n if (value == null) { return defaultValue; }\n try {\n return (T)Convert.ChangeType(value, typeof(T));\n } catch (Exception) {\n return defaultValue;\n }\n}\n <% if (Html.QueryValue(\"login\", false)) { %>\n <div>Welcome Back!</div>\n\n<% } else { %>\n <%-- Render the control or something --%>\n\n<% } %>\n"
},
{
"answer_id": 274524,
"author": "TheSoftwareJedi",
"author_id": 18941,
"author_profile": "https://Stackoverflow.com/users/18941",
"pm_score": 5,
"selected": false,
"text": "int i = myString.To<int>();\n public static T To<T>(this IConvertible obj)\n{\n return (T)Convert.ChangeType(obj, typeof(T));\n}\n\npublic static T ToOrDefault<T>\n (this IConvertible obj)\n{\n try\n {\n return To<T>(obj);\n }\n catch\n {\n return default(T);\n }\n}\n\npublic static bool ToOrDefault<T>\n (this IConvertible obj,\n out T newObj)\n{\n try\n {\n newObj = To<T>(obj); \n return true;\n }\n catch\n {\n newObj = default(T); \n return false;\n }\n}\n\npublic static T ToOrOther<T>\n (this IConvertible obj,\n T other)\n{\n try\n {\n return To<T>obj);\n }\n catch\n {\n return other;\n }\n}\n\npublic static bool ToOrOther<T>\n (this IConvertible obj,\n out T newObj,\n T other)\n{\n try\n {\n newObj = To<T>(obj);\n return true;\n }\n catch\n {\n newObj = other;\n return false;\n }\n}\n\npublic static T ToOrNull<T>\n (this IConvertible obj)\n where T : class\n{\n try\n {\n return To<T>(obj);\n }\n catch\n {\n return null;\n }\n}\n\npublic static bool ToOrNull<T>\n (this IConvertible obj,\n out T newObj)\n where T : class\n{\n try\n {\n newObj = To<T>(obj);\n return true;\n }\n catch\n {\n newObj = null;\n return false;\n }\n}\n int i = myString.To<int>();\nstring a = myInt.ToOrDefault<string>();\n//note type inference\nDateTime d = myString.ToOrOther(DateTime.MAX_VALUE);\ndouble d;\n//note type inference\nbool didItGiveDefault = myString.ToOrDefault(out d);\nstring s = myDateTime.ToOrNull<string>();\n"
},
{
"answer_id": 274649,
"author": "chakrit",
"author_id": 3055,
"author_profile": "https://Stackoverflow.com/users/3055",
"pm_score": 6,
"selected": false,
"text": "public static class FrameworkExtensions\n{\n // a map function\n public static void ForEach<T>(this IEnumerable<T> @enum, Action<T> mapFunction)\n {\n foreach (var item in @enum) mapFunction(item);\n }\n}\n var buttons = GetListOfButtons() as IEnumerable<Button>;\n\n// click all buttons\nbuttons.ForEach(b => b.Click());\n // no need to type the same assignment 3 times, just\n// new[] up an array and use foreach + lambda\n// everything is properly inferred by csc :-)\nnew { itemA, itemB, itemC }\n .ForEach(item => {\n item.Number = 1;\n item.Str = \"Hello World!\";\n });\n Select Select"
},
{
"answer_id": 274652,
"author": "bruno conde",
"author_id": 31136,
"author_profile": "https://Stackoverflow.com/users/31136",
"pm_score": 3,
"selected": false,
"text": "DirectoryInfo dir = new DirectoryInfo(@\"C:\\test\\myShareDir\");\nConsole.WriteLine(dir.IsSameFileAs(@\"\\\\myMachineName\\myShareDir\"));\n\nFileInfo file = new FileInfo(@\"C:\\test\\myShareDir\\file.txt\");\nConsole.WriteLine(file.IsSameFileAs(@\"\\\\myMachineName\\myShareDir\\file.txt\"));\n public static class FileExtensions\n{\n struct BY_HANDLE_FILE_INFORMATION\n {\n public uint FileAttributes;\n public System.Runtime.InteropServices.ComTypes.FILETIME CreationTime;\n public System.Runtime.InteropServices.ComTypes.FILETIME LastAccessTime;\n public System.Runtime.InteropServices.ComTypes.FILETIME LastWriteTime;\n public uint VolumeSerialNumber;\n public uint FileSizeHigh;\n public uint FileSizeLow;\n public uint NumberOfLinks;\n public uint FileIndexHigh;\n public uint FileIndexLow;\n }\n\n //\n // CreateFile constants\n //\n const uint FILE_SHARE_READ = 0x00000001;\n const uint OPEN_EXISTING = 3;\n const uint GENERIC_READ = (0x80000000);\n const uint FILE_FLAG_BACKUP_SEMANTICS = 0x02000000;\n\n\n [DllImport(\"kernel32.dll\", SetLastError = true)]\n static extern IntPtr CreateFile(\n string lpFileName,\n uint dwDesiredAccess,\n uint dwShareMode,\n IntPtr lpSecurityAttributes,\n uint dwCreationDisposition,\n uint dwFlagsAndAttributes,\n IntPtr hTemplateFile);\n\n [DllImport(\"kernel32.dll\", SetLastError = true)]\n static extern bool GetFileInformationByHandle(IntPtr hFile, out BY_HANDLE_FILE_INFORMATION lpFileInformation);\n\n public static bool IsSameFileAs(this FileSystemInfo file, string path)\n {\n BY_HANDLE_FILE_INFORMATION fileInfo1, fileInfo2;\n IntPtr ptr1 = CreateFile(file.FullName, GENERIC_READ, FILE_SHARE_READ, IntPtr.Zero, OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, IntPtr.Zero);\n if ((int)ptr1 == -1)\n {\n System.ComponentModel.Win32Exception e = new System.ComponentModel.Win32Exception(Marshal.GetLastWin32Error());\n throw e;\n }\n IntPtr ptr2 = CreateFile(path, GENERIC_READ, FILE_SHARE_READ, IntPtr.Zero, OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, IntPtr.Zero);\n if ((int)ptr2 == -1)\n {\n System.ComponentModel.Win32Exception e = new System.ComponentModel.Win32Exception(Marshal.GetLastWin32Error());\n throw e;\n }\n GetFileInformationByHandle(ptr1, out fileInfo1);\n GetFileInformationByHandle(ptr2, out fileInfo2);\n\n return ((fileInfo1.FileIndexHigh == fileInfo2.FileIndexHigh) &&\n (fileInfo1.FileIndexLow == fileInfo2.FileIndexLow));\n }\n}\n"
},
{
"answer_id": 275303,
"author": "Timothy Khouri",
"author_id": 11917,
"author_profile": "https://Stackoverflow.com/users/11917",
"pm_score": 2,
"selected": false,
"text": "public static class MyExtensions\n{\n public static bool IsInteger(this string input)\n {\n int temp;\n\n return int.TryParse(input, out temp);\n }\n\n public static bool IsDecimal(this string input)\n {\n decimal temp;\n\n return decimal.TryParse(input, out temp);\n }\n\n public static int ToInteger(this string input, int defaultValue)\n {\n int temp;\n\n return (int.TryParse(input, out temp)) ? temp : defaultValue;\n }\n\n public static decimal ToDecimal(this string input, decimal defaultValue)\n {\n decimal temp;\n\n return (decimal.TryParse(input, out temp)) ? temp : defaultValue;\n }\n\n public static DateTime ToFirstOfTheMonth(this DateTime input)\n {\n return input.Date.AddDays(-1 * input.Day + 1);\n }\n\n // Intentionally returns 0 if the target date is before the input date.\n public static int MonthsUntil(this DateTime input, DateTime targetDate)\n {\n input = input.ToFirstOfTheMonth();\n\n targetDate = targetDate.ToFirstOfTheMonth();\n\n int result = 0;\n\n while (input < targetDate)\n {\n input = input.AddMonths(1);\n result++;\n }\n\n return result;\n }\n\n // Used for backwards compatibility in a system built before my time.\n public static DataTable ToDataTable(this IEnumerable input)\n {\n // too much code to show here right now...\n }\n}\n"
},
{
"answer_id": 275611,
"author": "µBio",
"author_id": 9796,
"author_profile": "https://Stackoverflow.com/users/9796",
"pm_score": 4,
"selected": false,
"text": "public static string Wordify( this string camelCaseWord )\n{\n // if the word is all upper, just return it\n if( !Regex.IsMatch( camelCaseWord, \"[a-z]\" ) )\n return camelCaseWord;\n\n return string.Join( \" \", Regex.Split( camelCaseWord, @\"(?<!^)(?=[A-Z])\" ) );\n}\n public static string Capitalize( this string word )\n{\n return word[0].ToString( ).ToUpper( ) + word.Substring( 1 );\n}\n SomeEntityObject entity = DataAccessObject.GetSomeEntityObject( id );\nList<PropertyInfo> properties = entity.GetType().GetPublicNonCollectionProperties( );\n\n// wordify the property names to act as column headers for an html table or something\nList<string> columns = properties.Select( p => p.Name.Capitalize( ).Wordify( ) ).ToList( );\n"
},
{
"answer_id": 275620,
"author": "TraumaPony",
"author_id": 18658,
"author_profile": "https://Stackoverflow.com/users/18658",
"pm_score": 3,
"selected": false,
"text": "public static class EnumerableExtensions\n{\n [Pure]\n public static U MapReduce<T, U>(this IEnumerable<T> enumerable, Func<T, U> map, Func<U, U, U> reduce)\n {\n CodeContract.RequiresAlways(enumerable != null);\n CodeContract.RequiresAlways(enumerable.Skip(1).Any());\n CodeContract.RequiresAlways(map != null);\n CodeContract.RequiresAlways(reduce != null);\n return enumerable.AsParallel().Select(map).Aggregate(reduce);\n }\n [Pure]\n public static U MapReduce<T, U>(this IList<T> list, Func<T, U> map, Func<U, U, U> reduce)\n {\n CodeContract.RequiresAlways(list != null);\n CodeContract.RequiresAlways(list.Count >= 2);\n CodeContract.RequiresAlways(map != null);\n CodeContract.RequiresAlways(reduce != null);\n U result = map(list[0]);\n for (int i = 1; i < list.Count; i++)\n {\n result = reduce(result,map(list[i]));\n }\n return result;\n }\n\n //Parallel version; creates garbage\n [Pure]\n public static U MapReduce<T, U>(this IList<T> list, Func<T, U> map, Func<U, U, U> reduce)\n {\n CodeContract.RequiresAlways(list != null);\n CodeContract.RequiresAlways(list.Skip(1).Any());\n CodeContract.RequiresAlways(map != null);\n CodeContract.RequiresAlways(reduce != null);\n\n U[] mapped = new U[list.Count];\n Parallel.For(0, mapped.Length, i =>\n {\n mapped[i] = map(list[i]);\n });\n U result = mapped[0];\n for (int i = 1; i < list.Count; i++)\n {\n result = reduce(result, mapped[i]);\n }\n return result;\n }\n\n}\n"
},
{
"answer_id": 275640,
"author": "Zack Elan",
"author_id": 2461,
"author_profile": "https://Stackoverflow.com/users/2461",
"pm_score": 3,
"selected": false,
"text": "/// <summary>\n/// If a key exists in a dictionary, return its value, \n/// otherwise return the default value for that type.\n/// </summary>\npublic static U GetWithDefault<T, U>(this Dictionary<T, U> dict, T key)\n{\n return dict.GetWithDefault(key, default(U));\n}\n\n/// <summary>\n/// If a key exists in a dictionary, return its value,\n/// otherwise return the provided default value.\n/// </summary>\npublic static U GetWithDefault<T, U>(this Dictionary<T, U> dict, T key, U defaultValue)\n{\n return dict.ContainsKey(key)\n ? dict[key]\n : defaultValue;\n}\n /// <summary>\n/// Format a DateTime as a string that contains no characters\n//// that are banned from filenames, such as ':'.\n/// </summary>\n/// <returns>YYYY-MM-DD_HH.MM.SS</returns>\npublic static string ToFilenameString(this DateTime dt)\n{\n return dt.ToString(\"s\").Replace(\":\", \".\").Replace('T', '_');\n}\n"
},
{
"answer_id": 276307,
"author": "Michael Stum",
"author_id": 91,
"author_profile": "https://Stackoverflow.com/users/91",
"pm_score": 4,
"selected": false,
"text": "/// <summary>\n/// Reverse a String\n/// </summary>\n/// <param name=\"input\">The string to Reverse</param>\n/// <returns>The reversed String</returns>\npublic static string Reverse(this string input)\n{\n char[] array = input.ToCharArray();\n Array.Reverse(array);\n return new string(array);\n}\n"
},
{
"answer_id": 276331,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 5,
"selected": false,
"text": "public static void Log(this Exception obj)\n{\n //your logging logic here\n}\n try\n{\n //Your stuff here\n}\ncatch(Exception ex)\n{\n ex.Log();\n}\n"
},
{
"answer_id": 279789,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "[ThreadStatic]\nprivate static string lastMethodName = null;\n\n[ThreadStatic]\nprivate static int lastParamIndex = 0;\n\n[MethodImpl(MethodImplOptions.NoInlining)]\npublic static void ThrowIfNull<T>(this T parameter)\n{\n var currentStackFrame = new StackFrame(1);\n var props = currentStackFrame.GetMethod().GetParameters();\n\n if (!String.IsNullOrEmpty(lastMethodName)) {\n if (currentStackFrame.GetMethod().Name != lastMethodName) {\n lastParamIndex = 0;\n } else if (lastParamIndex >= props.Length - 1) {\n lastParamIndex = 0;\n } else {\n lastParamIndex++;\n }\n } else {\n lastParamIndex = 0;\n }\n\n if (!typeof(T).IsValueType) {\n for (int i = lastParamIndex; i < props.Length; i++) {\n if (props[i].ParameterType.IsValueType) {\n lastParamIndex++;\n } else {\n break;\n }\n }\n }\n\n if (parameter == null) {\n string paramName = props[lastParamIndex].Name;\n throw new ArgumentNullException(paramName);\n }\n\n lastMethodName = currentStackFrame.GetMethod().Name;\n}\n public void Foo()\n{\n Bar(1, 2, \"Hello\", \"World\"); //no exception\n Bar(1, 2, \"Hello\", null); //exception\n Bar(1, 2, null, \"World\"); //exception\n}\n\npublic void Bar(int x, int y, string someString1, string someString2)\n{\n //will also work with comments removed\n //x.ThrowIfNull();\n //y.ThrowIfNull();\n someString1.ThrowIfNull();\n someString2.ThrowIfNull();\n\n //Do something incredibly useful here!\n}\n"
},
{
"answer_id": 280230,
"author": "lubos hasko",
"author_id": 275,
"author_profile": "https://Stackoverflow.com/users/275",
"pm_score": 2,
"selected": false,
"text": "if (guid != Guid.Empty) return guid;\nelse return Guid.NewGuid();\n return guid.NewGuidIfEmpty();\n public static Guid NewGuidIfEmpty(this Guid uuid)\n{\n return (uuid != Guid.Empty ? uuid : Guid.NewGuid());\n}\n"
},
{
"answer_id": 280252,
"author": "Jay Bazuzi",
"author_id": 5314,
"author_profile": "https://Stackoverflow.com/users/5314",
"pm_score": 3,
"selected": false,
"text": "public static FileInfo SetExtension(this FileInfo fileInfo, string extension)\n{\n return new FileInfo(Path.ChangeExtension(fileInfo.FullName, extension));\n}\n\npublic static FileInfo SetDirectory(this FileInfo fileInfo, string directory)\n{\n return new FileInfo(Path.Combine(directory, fileInfo.Name));\n}\n"
},
{
"answer_id": 280322,
"author": "Eric Schoonover",
"author_id": 3957,
"author_profile": "https://Stackoverflow.com/users/3957",
"pm_score": 4,
"selected": false,
"text": "<label /> Html ViewPage <%= Html.Label(\"LabelId\", \"ForId\", \"Text\")%>\n <label id=\"LabelId\" for=\"ForId\">Text</label>\n public static class HtmlHelperExtensions\n{\n public static string Label(this HtmlHelper Html, string @for, string text)\n {\n return Html.Label(null, @for, text);\n }\n\n public static string Label(this HtmlHelper Html, string @for, string text, object htmlAttributes)\n {\n return Html.Label(null, @for, text, htmlAttributes);\n }\n\n public static string Label(this HtmlHelper Html, string @for, string text, IDictionary<string, object> htmlAttributes)\n {\n return Html.Label(null, @for, text, htmlAttributes);\n }\n\n public static string Label(this HtmlHelper Html, string id, string @for, string text)\n {\n return Html.Label(id, @for, text, null);\n }\n\n public static string Label(this HtmlHelper Html, string id, string @for, string text, object htmlAttributes)\n {\n return Html.Label(id, @for, text, new RouteValueDictionary(htmlAttributes));\n }\n\n public static string Label(this HtmlHelper Html, string id, string @for, string text, IDictionary<string, object> htmlAttributes)\n {\n TagBuilder tag = new TagBuilder(\"label\");\n\n tag.MergeAttributes(htmlAttributes);\n\n if (!string.IsNullOrEmpty(id))\n tag.MergeAttribute(\"id\", Html.AttributeEncode(id));\n\n tag.MergeAttribute(\"for\", Html.AttributeEncode(@for));\n\n tag.SetInnerText(Html.Encode(text));\n\n return tag.ToString(TagRenderMode.Normal);\n }\n}\n"
},
{
"answer_id": 286327,
"author": "BFree",
"author_id": 15861,
"author_profile": "https://Stackoverflow.com/users/15861",
"pm_score": 2,
"selected": false,
"text": "public static class StringExtensions\n{\n /// <summary>\n /// Returns a Subset string starting at the specified start index and ending and the specified end\n /// index.\n /// </summary>\n /// <param name=\"s\">The string to retrieve the subset from.</param>\n /// <param name=\"startIndex\">The specified start index for the subset.</param>\n /// <param name=\"endIndex\">The specified end index for the subset.</param>\n /// <returns>A Subset string starting at the specified start index and ending and the specified end\n /// index.</returns>\n public static string Subsetstring(this string s, int startIndex, int endIndex)\n {\n if (startIndex > endIndex)\n {\n throw new InvalidOperationException(\"End Index must be after Start Index.\");\n }\n\n if (startIndex < 0)\n {\n throw new InvalidOperationException(\"Start Index must be a positive number.\");\n }\n\n if(endIndex <0)\n {\n throw new InvalidOperationException(\"End Index must be a positive number.\");\n }\n\n return s.Substring(startIndex, (endIndex - startIndex));\n }\n\n /// <summary>\n /// Finds the specified Start Text and the End Text in this string instance, and returns a string\n /// containing all the text starting from startText, to the begining of endText. (endText is not\n /// included.)\n /// </summary>\n /// <param name=\"s\">The string to retrieve the subset from.</param>\n /// <param name=\"startText\">The Start Text to begin the Subset from.</param>\n /// <param name=\"endText\">The End Text to where the Subset goes to.</param>\n /// <param name=\"ignoreCase\">Whether or not to ignore case when comparing startText/endText to the string.</param>\n /// <returns>A string containing all the text starting from startText, to the begining of endText.</returns>\n public static string Subsetstring(this string s, string startText, string endText, bool ignoreCase)\n {\n if (string.IsNullOrEmpty(startText) || string.IsNullOrEmpty(endText))\n {\n throw new ArgumentException(\"Start Text and End Text cannot be empty.\");\n }\n string temp = s;\n if (ignoreCase)\n {\n temp = s.ToUpperInvariant();\n startText = startText.ToUpperInvariant();\n endText = endText.ToUpperInvariant();\n }\n int start = temp.IndexOf(startText);\n int end = temp.IndexOf(endText, start);\n return Subsetstring(s, start, end);\n }\n}\n string s = \"This is a tester for my cool extension method!!\";\n s = s.Subsetstring(\"tester\", \"cool\",true);\n"
},
{
"answer_id": 286753,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 3,
"selected": false,
"text": "public static T ToEnum<T>(this string str) where T : struct\n{\n return (T)Enum.Parse(typeof(T), str);\n}\n\n//DayOfWeek sunday = \"Sunday\".ToEnum<DayOfWeek>();\n\npublic static string ToString<T>(this IEnumerable<T> collection, string separator)\n{\n return ToString(collection, t => t.ToString(), separator);\n}\n\npublic static string ToString<T>(this IEnumerable<T> collection, Func<T, string> stringElement, string separator)\n{\n StringBuilder sb = new StringBuilder();\n foreach (var item in collection)\n {\n sb.Append(stringElement(item));\n sb.Append(separator);\n }\n return sb.ToString(0, Math.Max(0, sb.Length - separator.Length)); // quita el ultimo separador\n}\n\n//new []{1,2,3}.ToString(i=>i*2, \", \") --> \"2, 4, 6\"\n public static R Map<T, R>(this T t, Func<T, R> func)\n{\n return func(t);\n}\n\nExpensiveFindWally().Map(wally=>wally.FirstName + \" \" + wally.LastName)\n\npublic static R TryCC<T, R>(this T t, Func<T, R> func)\n where T : class\n where R : class\n{\n if (t == null) return null;\n return func(t);\n}\n\npublic static R? TryCS<T, R>(this T t, Func<T, R> func)\n where T : class\n where R : struct\n{\n if (t == null) return null;\n return func(t);\n}\n\npublic static R? TryCS<T, R>(this T t, Func<T, R?> func)\n where T : class\n where R : struct\n{\n if (t == null) return null;\n return func(t);\n}\n\npublic static R TrySC<T, R>(this T? t, Func<T, R> func)\n where T : struct\n where R : class\n{\n if (t == null) return null;\n return func(t.Value);\n}\n\npublic static R? TrySS<T, R>(this T? t, Func<T, R> func)\n where T : struct\n where R : struct\n{\n if (t == null) return null;\n return func(t.Value);\n}\n\npublic static R? TrySS<T, R>(this T? t, Func<T, R?> func)\n where T : struct\n where R : struct\n{\n if (t == null) return null;\n return func(t.Value);\n}\n\n//int? bossNameLength = Departament.Boss.TryCC(b=>b.Name).TryCS(s=>s.Length);\n\n\npublic static T ThrowIfNullS<T>(this T? t, string mensaje)\n where T : struct\n{\n if (t == null)\n throw new NullReferenceException(mensaje);\n return t.Value;\n}\n\npublic static T ThrowIfNullC<T>(this T t, string mensaje)\n where T : class\n{\n if (t == null)\n throw new NullReferenceException(mensaje);\n return t;\n}\n\npublic static T Do<T>(this T t, Action<T> action)\n{\n action(t);\n return t;\n}\n\n//Button b = new Button{Content = \"Click\"}.Do(b=>Canvas.SetColumn(b,2));\n\npublic static T TryDo<T>(this T t, Action<T> action) where T : class\n{\n if (t != null)\n action(t);\n return t;\n}\n\npublic static T? TryDoS<T>(this T? t, Action<T> action) where T : struct\n{\n if (t != null)\n action(t.Value);\n return t;\n}\n"
},
{
"answer_id": 291402,
"author": "Jesse C. Slicer",
"author_id": 3312,
"author_profile": "https://Stackoverflow.com/users/3312",
"pm_score": 5,
"selected": false,
"text": "if (\"IV\".IsValidRomanNumeral())\n{\n // Do useful stuff with the number 4.\n}\n\nConsole.WriteLine(\"MMMDCCCLXXXVIII\".ParseRomanNumeral());\nConsole.WriteLine(3888.ToRomanNumeralString());\n public static class RomanNumeralExtensions\n {\n private const int NumberOfRomanNumeralMaps = 13;\n\n private static readonly Dictionary<string, int> romanNumerals =\n new Dictionary<string, int>(NumberOfRomanNumeralMaps)\n {\n { \"M\", 1000 }, \n { \"CM\", 900 }, \n { \"D\", 500 }, \n { \"CD\", 400 }, \n { \"C\", 100 }, \n { \"XC\", 90 }, \n { \"L\", 50 }, \n { \"XL\", 40 }, \n { \"X\", 10 }, \n { \"IX\", 9 }, \n { \"V\", 5 }, \n { \"IV\", 4 }, \n { \"I\", 1 }\n };\n\n private static readonly Regex validRomanNumeral = new Regex(\n \"^(?i:(?=[MDCLXVI])((M{0,3})((C[DM])|(D?C{0,3}))\"\n + \"?((X[LC])|(L?XX{0,2})|L)?((I[VX])|(V?(II{0,2}))|V)?))$\", \n RegexOptions.Compiled);\n\n public static bool IsValidRomanNumeral(this string value)\n {\n return validRomanNumeral.IsMatch(value);\n }\n\n public static int ParseRomanNumeral(this string value)\n {\n if (value == null)\n {\n throw new ArgumentNullException(\"value\");\n }\n\n value = value.ToUpperInvariant().Trim();\n\n var length = value.Length;\n\n if ((length == 0) || !value.IsValidRomanNumeral())\n {\n throw new ArgumentException(\"Empty or invalid Roman numeral string.\", \"value\");\n }\n\n var total = 0;\n var i = length;\n\n while (i > 0)\n {\n var digit = romanNumerals[value[--i].ToString()];\n\n if (i > 0)\n {\n var previousDigit = romanNumerals[value[i - 1].ToString()];\n\n if (previousDigit < digit)\n {\n digit -= previousDigit;\n i--;\n }\n }\n\n total += digit;\n }\n\n return total;\n }\n\n public static string ToRomanNumeralString(this int value)\n {\n const int MinValue = 1;\n const int MaxValue = 3999;\n\n if ((value < MinValue) || (value > MaxValue))\n {\n throw new ArgumentOutOfRangeException(\"value\", value, \"Argument out of Roman numeral range.\");\n }\n\n const int MaxRomanNumeralLength = 15;\n var sb = new StringBuilder(MaxRomanNumeralLength);\n\n foreach (var pair in romanNumerals)\n {\n while (value / pair.Value > 0)\n {\n sb.Append(pair.Key);\n value -= pair.Value;\n }\n }\n\n return sb.ToString();\n }\n }\n"
},
{
"answer_id": 326701,
"author": "Anthony",
"author_id": 5599,
"author_profile": "https://Stackoverflow.com/users/5599",
"pm_score": 1,
"selected": false,
"text": "/// <summary>\n/// Wrap an object in a list\n/// </summary>\npublic static IList<T> WrapInList<T>(this T item)\n{\n List<T> result = new List<T>();\n result.Add(item);\n return result;\n}\n myList = someObject.InList();\n public static IEnumerable<T> Append<T>(this IEnumerable<T> enumerable, T newItem)\n{\n foreach (T item in enumerable)\n {\n yield return item;\n }\n\n yield return newItem;\n}\n\npublic static IEnumerable<T> Append<T>(this IEnumerable<T> enumerable, params T[] newItems)\n{\n foreach (T item in enumerable)\n {\n yield return item;\n }\n\n foreach (T newItem in newItems)\n {\n yield return newItem;\n }\n}\n someEnumeration = someEnumeration.Append(newItem);\n someEnumeration = someEnumeration.Append(otherEnumeration);\n public static IList<T> Clone<T>(this IEnumerable<T> source) where T: ICloneable\n{\n List<T> result = new List<T>();\n\n foreach (T item in source)\n {\n result.Add((T)item.Clone());\n }\n\n return result;\n}\n ObservableCollection<T>"
},
{
"answer_id": 329561,
"author": "terjetyl",
"author_id": 29519,
"author_profile": "https://Stackoverflow.com/users/29519",
"pm_score": 2,
"selected": false,
"text": "public static int? ToInt(this string input) \n{\n int val;\n if (int.TryParse(input, out val))\n return val;\n return null;\n}\n\npublic static DateTime? ToDate(this string input)\n{\n DateTime val;\n if (DateTime.TryParse(input, out val))\n return val;\n return null;\n}\n\npublic static decimal? ToDecimal(this string input)\n{\n decimal val;\n if (decimal.TryParse(input, out val))\n return val;\n return null;\n}\n"
},
{
"answer_id": 330044,
"author": "cbp",
"author_id": 21966,
"author_profile": "https://Stackoverflow.com/users/21966",
"pm_score": 2,
"selected": false,
"text": "public static bool AnyOf(this object mask, object flags)\n{\n return ((int)mask & (int)flags) != 0;\n}\npublic static bool AllOf(this object mask, object flags)\n{\n return ((int)mask & (int)flags) == (int)flags;\n}\npublic static object SetOn(this object mask, object flags)\n{\n return (int)mask | (int)flags;\n}\netc.\n var options = SomeOptions.OptionA;\noptions = options.SetOn(OptionB);\noptions = options.SetOn(OptionC);\n\nif (options.AnyOf(SomeOptions.OptionA | SomeOptions.OptionB))\n{\netc.\n public static bool AnyOf(this Enum mask, object flags)\n{\n return (Convert.ToInt642(mask) & (int)flags) != 0;\n}\n"
},
{
"answer_id": 346181,
"author": "Rinat Abdullin",
"author_id": 47366,
"author_profile": "https://Stackoverflow.com/users/47366",
"pm_score": 3,
"selected": false,
"text": "public static TimeSpan Seconds(this int seconds)\n{\n return TimeSpan.FromSeconds(seconds);\n}\n\npublic static TimeSpan Minutes(this int minutes)\n{\n return TimeSpan.FromMinutes(minutes);\n}\n 1.Seconds()\n20.Minutes()\n public static IDisposable GetReadLock(this ReaderWriterLockSlim slimLock)\n{\n slimLock.EnterReadLock();\n return new DisposableAction(slimLock.ExitReadLock);\n}\n\npublic static IDisposable GetWriteLock(this ReaderWriterLockSlim slimLock)\n{\n slimLock.EnterWriteLock();\n return new DisposableAction(slimLock.ExitWriteLock);\n}\n\npublic static IDisposable GetUpgradeableReadLock(this ReaderWriterLockSlim slimLock)\n{\n slimLock.EnterUpgradeableReadLock();\n return new DisposableAction(slimLock.ExitUpgradeableReadLock);\n}\n using (lock.GetUpgradeableReadLock())\n{\n // try read\n using (lock.GetWriteLock())\n {\n //do write\n }\n}\n"
},
{
"answer_id": 357344,
"author": "Robert Dean",
"author_id": 3396,
"author_profile": "https://Stackoverflow.com/users/3396",
"pm_score": 1,
"selected": false,
"text": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Web;\nusing System.Security.Principal;\nusing System.Web.Routing;\nusing System.Web.Mvc;\nusing System.Collections;\nusing System.Reflection;\nnamespace System.Web.Mvc.Html\n{\n public static class HtmlHelperExtensions\n {\n\n /// <summary>\n /// Shows or hides an action link based on the user's membership status\n /// and the controller's authorize attributes\n /// </summary>\n /// <param name=\"linkText\">The link text.</param>\n /// <param name=\"action\">The controller action name.</param>\n /// <param name=\"controller\">The controller name.</param>\n /// <returns></returns>\n public static string SecurityTrimmedActionLink(\n this HtmlHelper htmlHelper,\n string linkText,\n string action,\n string controller)\n {\n return SecurityTrimmedActionLink(htmlHelper, linkText, action, controller, false, null);\n }\n\n /// <summary>\n /// Enables, disables or hides an action link based on the user's membership status\n /// and the controller's authorize attributes\n /// </summary>\n /// <param name=\"linkText\">The link text.</param>\n /// <param name=\"action\">The action name.</param>\n /// <param name=\"controller\">The controller name.</param>\n /// <param name=\"showDisabled\">if set to <c>true</c> [show link as disabled - \n /// using a span tag instead of an anchor tag ].</param>\n /// <param name=\"disabledAttributeText\">Use this to add attributes to the disabled\n /// span tag.</param>\n /// <returns></returns>\n public static string SecurityTrimmedActionLink(\n this HtmlHelper htmlHelper, \n string linkText, \n string action, \n string controller, \n bool showDisabled, \n string disabledAttributeText)\n {\n if (IsAccessibleToUser(action, controller, HttpContext.Current ))\n {\n return htmlHelper.ActionLink(linkText, action, controller);\n }\n else\n {\n return showDisabled ? \n String.Format(\n \"<span{1}>{0}</span>\", \n linkText, \n disabledAttributeText==null?\"\":\" \"+disabledAttributeText\n ) : \"\";\n }\n }\n\n private static IController GetControllerInstance(string controllerName)\n {\n Assembly assembly = Assembly.GetExecutingAssembly();\n Type controllerType = GetControllerType(controllerName);\n return (IController)Activator.CreateInstance(controllerType);\n }\n\n private static ArrayList GetControllerAttributes(string controllerName, HttpContext context)\n {\n if (context.Cache[controllerName + \"_ControllerAttributes\"] == null)\n {\n var controller = GetControllerInstance(controllerName);\n\n context.Cache.Add(\n controllerName + \"_ControllerAttributes\",\n new ArrayList(controller.GetType().GetCustomAttributes(typeof(AuthorizeAttribute), true)),\n null,\n Caching.Cache.NoAbsoluteExpiration,\n Caching.Cache.NoSlidingExpiration,\n Caching.CacheItemPriority.Default,\n null);\n\n }\n return (ArrayList)context.Cache[controllerName + \"_ControllerAttributes\"];\n\n }\n\n private static ArrayList GetMethodAttributes(string controllerName, string actionName, HttpContext context)\n {\n if (context.Cache[controllerName + \"_\" + actionName + \"_ActionAttributes\"] == null)\n {\n ArrayList actionAttrs = new ArrayList();\n var controller = GetControllerInstance(controllerName);\n MethodInfo[] methods = controller.GetType().GetMethods();\n\n foreach (MethodInfo method in methods)\n {\n object[] attributes = method.GetCustomAttributes(typeof(ActionNameAttribute), true);\n\n if ((attributes.Length == 0 && method.Name == actionName)\n ||\n (attributes.Length > 0 && ((ActionNameAttribute)attributes[0]).Name == actionName))\n {\n actionAttrs.AddRange(method.GetCustomAttributes(typeof(AuthorizeAttribute), true));\n }\n }\n\n context.Cache.Add(\n controllerName + \"_\" + actionName + \"_ActionAttributes\",\n actionAttrs,\n null,\n Caching.Cache.NoAbsoluteExpiration,\n Caching.Cache.NoSlidingExpiration,\n Caching.CacheItemPriority.Default,\n null);\n\n }\n\n return (ArrayList)context.Cache[controllerName + \"_\" + actionName+ \"_ActionAttributes\"]; \n }\n\n public static bool IsAccessibleToUser(string actionToAuthorize, string controllerToAuthorize, HttpContext context)\n {\n IPrincipal principal = context.User;\n\n //cache the attribute list for both controller class and it's methods\n\n ArrayList controllerAttributes = GetControllerAttributes(controllerToAuthorize, context);\n\n ArrayList actionAttributes = GetMethodAttributes(controllerToAuthorize, actionToAuthorize, context); \n\n if (controllerAttributes.Count == 0 && actionAttributes.Count == 0)\n return true;\n\n string roles = \"\";\n string users = \"\";\n if (controllerAttributes.Count > 0)\n {\n AuthorizeAttribute attribute = controllerAttributes[0] as AuthorizeAttribute;\n roles += attribute.Roles;\n users += attribute.Users;\n }\n if (actionAttributes.Count > 0)\n {\n AuthorizeAttribute attribute = actionAttributes[0] as AuthorizeAttribute;\n roles += attribute.Roles;\n users += attribute.Users;\n }\n\n if (string.IsNullOrEmpty(roles) && string.IsNullOrEmpty(users) && principal.Identity.IsAuthenticated)\n return true;\n\n string[] roleArray = roles.Split(',');\n string[] usersArray = users.Split(',');\n foreach (string role in roleArray)\n {\n if (role == \"*\" || principal.IsInRole(role))\n return true;\n }\n foreach (string user in usersArray)\n {\n if (user == \"*\" && (principal.Identity.Name == user))\n return true;\n }\n return false;\n }\n\n private static Type GetControllerType(string controllerName)\n {\n Assembly assembly = Assembly.GetExecutingAssembly();\n foreach (Type type in assembly.GetTypes())\n {\n if (\n type.BaseType!=null \n && type.BaseType.Name == \"Controller\" \n && (type.Name.ToUpper() == (controllerName.ToUpper() + \"Controller\".ToUpper())))\n {\n return type;\n }\n }\n return null;\n }\n\n }\n}\n"
},
{
"answer_id": 358259,
"author": "Mark Cidade",
"author_id": 1659,
"author_profile": "https://Stackoverflow.com/users/1659",
"pm_score": 3,
"selected": false,
"text": "static string Format( this string str,\n , params Expression<Func<string,object>>[] args)\n{\n var parameters = args.ToDictionary\n ( e=>string.Format(\"{{{0}}}\",e.Parameters[0].Name)\n , e=>e.Compile()(e.Parameters[0].Name));\n\n var sb = new StringBuilder(str);\n foreach(var kv in parameters)\n {\n sb.Replace( kv.Key\n , kv.Value != null ? kv.Value.ToString() : \"\");\n }\n\n return sb.ToString();\n}\n var str = \"{foo} {bar} {baz}\".Format(foo=>foo, bar=>2, baz=>new object());\n \"foo 2 System.Object"
},
{
"answer_id": 375076,
"author": "Mark Cidade",
"author_id": 1659,
"author_profile": "https://Stackoverflow.com/users/1659",
"pm_score": 0,
"selected": false,
"text": "collection.Add(item1, item2, itemN); static void Add<T>(this ICollection<T> coll, params T[] items)\n { foreach (var item in items) coll.Add(item);\n }\n string.Format() \"{0} {1} {2}\".Format<Custom>(c=>c.Name,\"string\",new object(),new Custom()) \"string {System.Object} Custom1Name\" static string Format<T>( this string format\n , Func<T,object> select\n , params object[] args)\n { for(int i=0; i < args.Length; ++i)\n { var x = args[i] as T;\n if (x != null) args[i] = select(x);\n }\n return string.Format(format, args);\n }\n"
},
{
"answer_id": 398308,
"author": "Mark Maxham",
"author_id": 49737,
"author_profile": "https://Stackoverflow.com/users/49737",
"pm_score": 3,
"selected": false,
"text": "/// <summary>\n/// Replace \"Enumerable.Range(n)\" with \"n.Range()\":\n/// </summary>\n/// <param name=\"n\">iterations</param>\n/// <returns>0..n-1</returns>\npublic static IEnumerable<int> Range(this int n)\n{\n for (int i = 0; i < n; i++)\n yield return i;\n}\n"
},
{
"answer_id": 398423,
"author": "Mark Maxham",
"author_id": 49737,
"author_profile": "https://Stackoverflow.com/users/49737",
"pm_score": 1,
"selected": false,
"text": "/// <summary>\n/// same as python 'join'\n/// </summary>\n/// <typeparam name=\"T\">list type</typeparam>\n/// <param name=\"separator\">string separator </param>\n/// <param name=\"list\">list of objects to be ToString'd</param>\n/// <returns>a concatenated list interleaved with separators</returns>\nstatic public string Join<T>(this string separator, IEnumerable<T> list)\n{\n var sb = new StringBuilder();\n bool first = true;\n\n foreach (T v in list)\n {\n if (!first)\n sb.Append(separator);\n first = false;\n\n if (v != null)\n sb.Append(v.ToString());\n }\n\n return sb.ToString();\n}\n"
},
{
"answer_id": 414561,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 3,
"selected": false,
"text": "public static Dictionary<string, object> ToDictionary(this object o)\n{\n var dictionary = new Dictionary<string, object>();\n\n foreach (var propertyInfo in o.GetType().GetProperties())\n {\n if (propertyInfo.GetIndexParameters().Length == 0)\n {\n dictionary.Add(propertyInfo.Name, propertyInfo.GetValue(o, null));\n }\n }\n\n return dictionary;\n}\n var dummy = new { color = \"#000000\", width = \"100%\", id = \"myid\" };\nDictionary<string, object> dict = dummy.ToDictionary();\n public static void ForEach<T>(this IEnumerable<T> source, Action<T> action)\n{\n foreach (T item in source)\n {\n action(item);\n }\n}\n dummy.ToDictionary().ForEach((p) => Console.Write(\"{0}='{1}' \", p.Key, p.Value));\n"
},
{
"answer_id": 423447,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "// Calls the underlying int.TryParse method to convert a string\n// representation of a number to its 32-bit signed integer equivalent.\n// Returns Zero if conversion fails. \npublic static int ToInt32(this string s)\n{\n int retInt;\n int.TryParse(s, out retInt);\n return retInt;\n}\n string s = \"999\"; int i = s.ToInt32();"
},
{
"answer_id": 423553,
"author": "Chris",
"author_id": 52811,
"author_profile": "https://Stackoverflow.com/users/52811",
"pm_score": 0,
"selected": false,
"text": "// Values ordered true/false\n// True/false values separated by a capital letter\n// Only two values allowed\n// ---------------------------\n// Limited, but could be useful\npublic enum BooleanFormat\n{\n OneZero,\n YN,\n YesNo,\n TF,\n TrueFalse,\n PassFail,\n YepNope\n}\n\npublic static class BooleanExtension\n{\n /// <summary>\n /// Converts the boolean value of this instance to the specified string value. \n /// </summary>\n private static string ToString(this bool value, string passValue, string failValue)\n {\n return value ? passValue : failValue;\n }\n\n /// <summary>\n /// Converts the boolean value of this instance to a string. \n /// </summary>\n /// <param name=\"booleanFormat\">A BooleanFormat value. \n /// Example: BooleanFormat.PassFail would return \"Pass\" if true and \"Fail\" if false.</param>\n /// <returns>Boolean formatted string</returns>\n public static string ToString(this bool value, BooleanFormat booleanFormat)\n {\n string booleanFormatString = Enum.GetName(booleanFormat.GetType(), booleanFormat);\n return ParseBooleanString(value, booleanFormatString); \n }\n\n // Parses boolean format strings, not optimized\n private static string ParseBooleanString(bool value, string booleanFormatString)\n {\n StringBuilder trueString = new StringBuilder();\n StringBuilder falseString = new StringBuilder();\n\n int charCount = booleanFormatString.Length;\n\n bool isTrueString = true;\n\n for (int i = 0; i != charCount; i++)\n {\n if (char.IsUpper(booleanFormatString[i]) && i != 0)\n isTrueString = false;\n\n if (isTrueString)\n trueString.Append(booleanFormatString[i]);\n else\n falseString.Append(booleanFormatString[i]);\n }\n\n return (value == true ? trueString.ToString() : falseString.ToString());\n }\n"
},
{
"answer_id": 423555,
"author": "Jonathan C Dickinson",
"author_id": 24064,
"author_profile": "https://Stackoverflow.com/users/24064",
"pm_score": 1,
"selected": false,
"text": "class Program\n{\n static void Main(string[] args)\n {\n var z = 0;\n var a = 0.AsDefaultFor(() => 1 / z);\n Console.WriteLine(a);\n Console.ReadLine();\n }\n}\n\npublic static class TryExtensions\n{\n public static T AsDefaultFor<T>(this T @this, Func<T> operation)\n {\n try\n {\n return operation();\n }\n catch\n {\n return @this;\n }\n }\n}\n"
},
{
"answer_id": 450208,
"author": "chakrit",
"author_id": 3055,
"author_profile": "https://Stackoverflow.com/users/3055",
"pm_score": 5,
"selected": false,
"text": "public static void With<T>(this T obj, Action<T> act) { act(obj); }\n someVeryVeryLonggggVariableName.With(x => {\n x.Int = 123;\n x.Str = \"Hello\";\n x.Str2 = \" World!\";\n});\n someVeryVeryLonggggVariableName.Int = 123;\nsomeVeryVeryLonggggVariableName.Str = \"Hello\";\nsomeVeryVeryLonggggVariableName.Str2 = \" World!\";\n"
},
{
"answer_id": 572953,
"author": "andleer",
"author_id": 64262,
"author_profile": "https://Stackoverflow.com/users/64262",
"pm_score": 1,
"selected": false,
"text": "var query = dc.Reviewer \n .Where(r => r.FacilityID == facilityID) \n .WhereIf(CheckBoxActive.Checked, r => r.IsActive); \n\npublic static IEnumerable<TSource> WhereIf<TSource>(\n this IEnumerable<TSource> source,\n bool condition, Func<TSource, bool> predicate) \n{ \n if (condition) \n return source.Where(predicate); \n else \n return source; \n}\n\npublic static IQueryable<TSource> WhereIf<TSource>(\n this IQueryable<TSource> source,\n bool condition, Expression<Func<TSource, bool>> predicate) \n{ \n if (condition) \n return source.Where(predicate); \n else \n return source; \n}\n"
},
{
"answer_id": 572978,
"author": "andleer",
"author_id": 64262,
"author_profile": "https://Stackoverflow.com/users/64262",
"pm_score": 1,
"selected": false,
"text": "public static Int32? AsInt32(this string s)\n{\n Int32 value;\n if (Int32.TryParse(s, out value))\n return value;\n\n return null;\n}\n\npublic static bool IsInt32(this string s)\n{\n return s.AsInt32().HasValue;\n}\n\npublic static Int32 ToInt32(this string s)\n{\n return Int32.Parse(s);\n{\n"
},
{
"answer_id": 833363,
"author": "Stefan Steinegger",
"author_id": 2658202,
"author_profile": "https://Stackoverflow.com/users/2658202",
"pm_score": 2,
"selected": false,
"text": "public static string GetMemberName<T, TResult>(\n this T anyObject, \n Expression<Func<T, TResult>> expression)\n{\n return ((MemberExpression)expression.Body).Member.Name;\n}\n \"blah\".GetMemberName(x => x.Length); // returns \"Length\"\n public static string GetMemberName<T, TReturn>(\n Expression<Func<T, TReturn>> expression)\n where T : class\n{\n return ((MemberExpression)expression.Body).Member.Name;\n}\n ReflectionUtility.GetMemberName((string) s => s.Length); // returns \"Length\"\n"
},
{
"answer_id": 833477,
"author": "Winston Smith",
"author_id": 35086,
"author_profile": "https://Stackoverflow.com/users/35086",
"pm_score": 8,
"selected": false,
"text": "public static bool In<T>(this T source, params T[] list)\n{\n if(null==source) throw new ArgumentNullException(\"source\");\n return list.Contains(source);\n}\n if(reallyLongIntegerVariableName == 1 || \n reallyLongIntegerVariableName == 6 || \n reallyLongIntegerVariableName == 9 || \n reallyLongIntegerVariableName == 11)\n{\n // do something....\n}\n\nand\n\nif(reallyLongStringVariableName == \"string1\" || \n reallyLongStringVariableName == \"string2\" || \n reallyLongStringVariableName == \"string3\")\n{\n // do something....\n}\n\nand\n\nif(reallyLongMethodParameterName == SomeEnum.Value1 || \n reallyLongMethodParameterName == SomeEnum.Value2 || \n reallyLongMethodParameterName == SomeEnum.Value3 || \n reallyLongMethodParameterName == SomeEnum.Value4)\n{\n // do something....\n}\n if(reallyLongIntegerVariableName.In(1,6,9,11))\n{\n // do something....\n}\n\nand\n\nif(reallyLongStringVariableName.In(\"string1\",\"string2\",\"string3\"))\n{\n // do something....\n}\n\nand\n\nif(reallyLongMethodParameterName.In(SomeEnum.Value1, SomeEnum.Value2, SomeEnum.Value3, SomeEnum.Value4)\n{\n // do something....\n}\n"
},
{
"answer_id": 858681,
"author": "Joel Mueller",
"author_id": 24380,
"author_profile": "https://Stackoverflow.com/users/24380",
"pm_score": 4,
"selected": false,
"text": "/// <summary>\n/// Creates an <see cref=\"IComparer{T}\"/> instance for the given\n/// delegate function.\n/// </summary>\ninternal class ComparerFactory<T> : IComparer<T>\n{\n public static IComparer<T> Create(Func<T, T, int> comparison)\n {\n return new ComparerFactory<T>(comparison);\n }\n\n private readonly Func<T, T, int> _comparison;\n\n private ComparerFactory(Func<T, T, int> comparison)\n {\n _comparison = comparison;\n }\n\n #region IComparer<T> Members\n\n public int Compare(T x, T y)\n {\n return _comparison(x, y);\n }\n\n #endregion\n}\n public static class EnumerableExtensions\n{\n /// <summary>\n /// Sorts the elements of a sequence in ascending order by using a specified comparison delegate.\n /// </summary>\n public static IOrderedEnumerable<TSource> OrderBy<TSource, TKey>(this IEnumerable<TSource> source, Func<TSource, TKey> keySelector,\n Func<TKey, TKey, int> comparison)\n {\n var comparer = ComparerFactory<TKey>.Create(comparison);\n return source.OrderBy(keySelector, comparer);\n }\n\n /// <summary>\n /// Sorts the elements of a sequence in descending order by using a specified comparison delegate.\n /// </summary>\n public static IOrderedEnumerable<TSource> OrderByDescending<TSource, TKey>(this IEnumerable<TSource> source, Func<TSource, TKey> keySelector,\n Func<TKey, TKey, int> comparison)\n {\n var comparer = ComparerFactory<TKey>.Create(comparison);\n return source.OrderByDescending(keySelector, comparer);\n }\n}\n"
},
{
"answer_id": 953674,
"author": "Manish Basantani",
"author_id": 93613,
"author_profile": "https://Stackoverflow.com/users/93613",
"pm_score": 0,
"selected": false,
"text": "// Checks for an empty collection, and sends the value set in the default constructor for the desired field\npublic static TResult MinGuarded<T, TResult>(this IEnumerable<T> items, Func<T, TResult> expression) where T : new() {\n if(items.IsEmpty()) {\n return (new List<T> { new T() }).Min(expression);\n }\n return items.Min(expression);\n}\n\n// Checks for an empty collection, and sends the value set in the default constructor for the desired field\npublic static TResult MaxGuarded<T, TResult>(this IEnumerable<T> items, Func<T, TResult> expression) where T : new() {\n if(items.IsEmpty()) {\n return (new List<T> { new T() }).Max(expression);\n }\n return items.Max(expression);\n}\n DateTime.MinDate"
},
{
"answer_id": 958020,
"author": "Vasu Balakrishnan",
"author_id": 1879756,
"author_profile": "https://Stackoverflow.com/users/1879756",
"pm_score": 4,
"selected": false,
"text": "public static IEnumerable<T> EmptyIfNull<T>(this IEnumerable<T> pSeq)\n{\n return pSeq ?? Enumerable.Empty<T>();\n}\n MyList.EmptyIfNull().Where(....)\n"
},
{
"answer_id": 1110456,
"author": "Fredy Treboux",
"author_id": 55154,
"author_profile": "https://Stackoverflow.com/users/55154",
"pm_score": 1,
"selected": false,
"text": "obj.SafelyNavigate(x => x.SomeProperty.MaybeAMethod().AnotherProperty);\n"
},
{
"answer_id": 1130145,
"author": "Kenny Eliasson",
"author_id": 107342,
"author_profile": "https://Stackoverflow.com/users/107342",
"pm_score": 3,
"selected": false,
"text": "List<Person> string result = string.Empty;\nforeach (var person in personList) {\n result += person.LastName + \", \";\n}\nresult = result.Substring(0, result.Length - 2);\nreturn result;\n public static string Join<T>(this IEnumerable<T> collection, Func<T, string> func, string separator)\n{\n return String.Join(separator, collection.Select(func).ToArray());\n}\n personList.Join(x => x.LastName, \", \");\n"
},
{
"answer_id": 1251338,
"author": "Chris S",
"author_id": 21574,
"author_profile": "https://Stackoverflow.com/users/21574",
"pm_score": 4,
"selected": false,
"text": "byte[] buffer = File.ReadAllBytes(@\"C:\\file.txt\");\nstring content = buffer.GetString();\n public static class Extensions\n{\n /// <summary>\n /// Converts a byte array to a string, using its byte order mark to convert it to the right encoding.\n /// Original article: http://www.west-wind.com/WebLog/posts/197245.aspx\n /// </summary>\n /// <param name=\"buffer\">An array of bytes to convert</param>\n /// <returns>The byte as a string.</returns>\n public static string GetString(this byte[] buffer)\n {\n if (buffer == null || buffer.Length == 0)\n return \"\";\n\n // Ansi as default\n Encoding encoding = Encoding.Default; \n\n /*\n EF BB BF UTF-8 \n FF FE UTF-16 little endian \n FE FF UTF-16 big endian \n FF FE 00 00 UTF-32, little endian \n 00 00 FE FF UTF-32, big-endian \n */\n\n if (buffer[0] == 0xef && buffer[1] == 0xbb && buffer[2] == 0xbf)\n encoding = Encoding.UTF8;\n else if (buffer[0] == 0xfe && buffer[1] == 0xff)\n encoding = Encoding.Unicode;\n else if (buffer[0] == 0xfe && buffer[1] == 0xff)\n encoding = Encoding.BigEndianUnicode; // utf-16be\n else if (buffer[0] == 0 && buffer[1] == 0 && buffer[2] == 0xfe && buffer[3] == 0xff)\n encoding = Encoding.UTF32;\n else if (buffer[0] == 0x2b && buffer[1] == 0x2f && buffer[2] == 0x76)\n encoding = Encoding.UTF7;\n\n using (MemoryStream stream = new MemoryStream())\n {\n stream.Write(buffer, 0, buffer.Length);\n stream.Seek(0, SeekOrigin.Begin);\n using (StreamReader reader = new StreamReader(stream, encoding))\n {\n return reader.ReadToEnd();\n }\n }\n }\n}\n"
},
{
"answer_id": 1394563,
"author": "Chris S",
"author_id": 21574,
"author_profile": "https://Stackoverflow.com/users/21574",
"pm_score": 1,
"selected": false,
"text": "StringBuilder public static class Extensions\n{\n public static void AppendLine(this StringBuilder builder,string format, params object[] args)\n {\n builder.AppendLine(string.Format(format, args));\n }\n}\n AppendFormat StringBuilder \\n"
},
{
"answer_id": 1434207,
"author": "John Kraft",
"author_id": 7495,
"author_profile": "https://Stackoverflow.com/users/7495",
"pm_score": 2,
"selected": false,
"text": "public static bool IsNull(this object o){\n return o == null;\n}\n public static bool IsNullOrEmpty(this string s){\n return string.IsNullOrEmpty(s);\n}\n if (myClassInstance.IsNull()) //... do something\n\nif (myString.IsNullOrEmpty()) //... do something\n"
},
{
"answer_id": 1460681,
"author": "Konamiman",
"author_id": 4574,
"author_profile": "https://Stackoverflow.com/users/4574",
"pm_score": 3,
"selected": false,
"text": "public static void Show(this UIElement element)\n{\n element.Visibility = Visibility.Visible;\n}\n\npublic static void Hide(this UIElement element)\n{\n element.Visibility = Visibility.Collapsed;\n}\n"
},
{
"answer_id": 1512463,
"author": "Omar",
"author_id": 160823,
"author_profile": "https://Stackoverflow.com/users/160823",
"pm_score": 2,
"selected": false,
"text": "toLength ... public static string Shorten(this string str, int toLength, string cutOffReplacement = \" ...\")\n{\n if (string.IsNullOrEmpty(str) || str.Length <= toLength)\n return str;\n else\n return str.Remove(toLength) + cutOffReplacement;\n}\n"
},
{
"answer_id": 1543566,
"author": "Paolo Tedesco",
"author_id": 15622,
"author_profile": "https://Stackoverflow.com/users/15622",
"pm_score": 5,
"selected": false,
"text": "public static class Extensions {\n public static int K(this int value) {\n return value * 1024;\n }\n public static int M(this int value) {\n return value * 1024 * 1024;\n }\n}\n\npublic class Program {\n public void Main() {\n WSHttpContextBinding serviceMultipleTokenBinding = new WSHttpContextBinding() {\n MaxBufferPoolSize = 2.M(), // instead of 2097152\n MaxReceivedMessageSize = 64.K(), // instead of 65536\n };\n }\n}\n"
},
{
"answer_id": 1662833,
"author": "Greg",
"author_id": 12971,
"author_profile": "https://Stackoverflow.com/users/12971",
"pm_score": 2,
"selected": false,
"text": "public static T FindControl<T>(this Control control, string id) where T : Control\n{\n return (T)control.FindControl(id);\n}\n // With extension method\ncontainer.FindControl<TextBox>(\"myTextBox\").SelectedValue = \"Hello world!\";\n\n// Without extension method\n((TextBox)container.FindControl(\"myTextBox\")).SelectedValue = \"Hello world!\";\n"
},
{
"answer_id": 1662892,
"author": "Greg",
"author_id": 12971,
"author_profile": "https://Stackoverflow.com/users/12971",
"pm_score": 1,
"selected": false,
"text": "out public static bool TryParseInt32(this string input, Action<int> action)\n{\n int result;\n if (Int32.TryParse(input, out result))\n {\n action(result);\n return true;\n }\n return false;\n}\n if (!textBox.Text.TryParseInt32(number => label.Text = SomeMathFunction(number)))\n label.Text = \"Please enter a valid integer\";\n"
},
{
"answer_id": 1742953,
"author": "Dan Diplo",
"author_id": 140392,
"author_profile": "https://Stackoverflow.com/users/140392",
"pm_score": 1,
"selected": false,
"text": "public static bool TryParse<T>(this Control control, string id, out T result) \n where T : Control\n{\n result = control.FindControl(id) as T;\n return result != null;\n}\n Label lbl;\nif (Page.TryParse(\"Label1\", out lbl))\n{\n lbl.Text = \"Safely set text\";\n}\n"
},
{
"answer_id": 1766663,
"author": "Juliet",
"author_id": 40516,
"author_profile": "https://Stackoverflow.com/users/40516",
"pm_score": 5,
"selected": false,
"text": "public static class PaulaBean\n{\n private static String paula = \"Brillant\";\n public static String GetPaula<T>(this T obj) {\n return paula;\n }\n}\n"
},
{
"answer_id": 1766799,
"author": "Thomas Levesque",
"author_id": 98713,
"author_profile": "https://Stackoverflow.com/users/98713",
"pm_score": 3,
"selected": false,
"text": "public static T BinarySearch<T, TKey>(this IList<T> list, Func<T, TKey> keySelector, TKey key)\n where TKey : IComparable<TKey>\n{\n int min = 0;\n int max = list.Count;\n int index = 0;\n while (min < max)\n {\n int mid = (max + min) / 2;\n T midItem = list[mid];\n TKey midKey = keySelector(midItem);\n int comp = midKey.CompareTo(key);\n if (comp < 0)\n {\n min = mid + 1;\n }\n else if (comp > 0)\n {\n max = mid - 1;\n }\n else\n {\n return midItem;\n }\n }\n if (min == max &&\n keySelector(list[min]).CompareTo(key) == 0)\n {\n return list[min];\n }\n throw new InvalidOperationException(\"Item not found\");\n}\n var item = list.BinarySearch(i => i.Id, 42);\n"
},
{
"answer_id": 1767863,
"author": "Thomas Levesque",
"author_id": 98713,
"author_profile": "https://Stackoverflow.com/users/98713",
"pm_score": 2,
"selected": false,
"text": " public static IEnumerable<TResult> Zip<TFirst, TSecond, TResult>(this IEnumerable<TFirst> first, IEnumerable<TSecond> second, Func<TFirst, TSecond, TResult> selector)\n {\n if (first == null)\n throw new ArgumentNullException(\"first\");\n if (second == null)\n throw new ArgumentNullException(\"second\");\n if (selector == null)\n throw new ArgumentNullException(\"selector\");\n\n using (var enum1 = first.GetEnumerator())\n using (var enum2 = second.GetEnumerator())\n {\n while (enum1.MoveNext() && enum2.MoveNext())\n {\n yield return selector(enum1.Current, enum2.Current);\n }\n }\n }\n Enumerable var names = new[] { \"Joe\", \"Jane\", \"Jack\", \"John\" };\nvar ages = new[] { 42, 22, 18, 33 };\n\nvar persons = names.Zip(ages, (n, a) => new { Name = n, Age = a });\n\nforeach (var p in persons)\n{\n Console.WriteLine(\"{0} is {1} years old\", p.Name, p.Age);\n}\n"
},
{
"answer_id": 1767920,
"author": "RCIX",
"author_id": 117069,
"author_profile": "https://Stackoverflow.com/users/117069",
"pm_score": 0,
"selected": false,
"text": "internal static class SortingHelpers\n{\n /// <summary>\n /// Performs an insertion sort on this list.\n /// </summary>\n /// <typeparam name=\"T\">The type of the list supplied.</typeparam>\n /// <param name=\"list\">the list to sort.</param>\n /// <param name=\"comparison\">the method for comparison of two elements.</param>\n /// <returns></returns>\n public static void InsertionSort<T>(this IList<T> list, Comparison<T> comparison)\n {\n for (int i = 2; i < list.Count; i++)\n {\n for (int j = i; j > 1 && comparison(list[j], list[j - 1]) < 0; j--)\n {\n T tempItem = list[j];\n list.RemoveAt(j);\n list.Insert(j - 1, tempItem);\n }\n }\n }\n}\n List<int> list1 = { 3, 5, 1, 2, 9, 4, 6 };\nlist1.InsertionSort((a,b) => a - b);\n//list is now in order of 1,2,3,4,5,6,9\n"
},
{
"answer_id": 1804870,
"author": "tsilb",
"author_id": 11112,
"author_profile": "https://Stackoverflow.com/users/11112",
"pm_score": 0,
"selected": false,
"text": "List<dynamic> List<AnonymousType#1>() /// <summary>Remove extraneous entries for common word permutations</summary>\n/// <param name=\"input\">Incoming series of words to be filtered</param>\n/// <param name=\"MaxIgnoreLength\">Words this long or shorter will not count as duplicates</param>\n/// <param name=\"words2\">Instance list from BuildInstanceList()</param>\n/// <returns>Filtered list of lines from input, based on filter info in words2</returns>\nprivate static List<string> FilterNearDuplicates(List<string> input, int MaxIgnoreLength, List<dynamic> words2)\n{\n List<string> output = new List<string>();\n foreach (string line in input)\n {\n int Dupes = 0;\n foreach (string word in line.Split(new char[] { ' ', ',', ';', '\\\\', '/', ':', '\\\"', '\\r', '\\n', '.' })\n .Where(p => p.Length > MaxIgnoreLength)\n .Distinct())\n {\n int Instances = 0;\n foreach (dynamic dyn in words2)\n if (word == dyn.Word)\n {\n Instances = dyn.Instances;\n if (Instances > 1)\n Dupes++;\n break;\n }\n }\n if (Dupes == 0)\n output.Add(line);\n }\n return output;\n}\n/// <summary>Builds a list of words and how many times they occur in the overall list</summary>\n/// <param name=\"input\">Incoming series of words to be counted</param>\n/// <returns></returns>\nprivate static List<dynamic> BuildInstanceList(List<string> input)\n{\n List<dynamic> words2 = new List<object>();\n foreach (string line in input)\n foreach (string word in line.Split(new char[] { ' ', ',', ';', '\\\\', '/', ':', '\\\"', '\\r', '\\n', '.' }))\n {\n if (string.IsNullOrEmpty(word))\n continue;\n else if (ExistsInList(word, words2))\n for (int i = words2.Count - 1; i >= 0; i--)\n {\n if (words2[i].Word == word)\n words2[i] = new { Word = words2[i].Word, Instances = words2[i].Instances + 1 };\n }\n else\n words2.Add(new { Word = word, Instances = 1 });\n }\n\n return words2;\n}\n/// <summary>Determines whether a dynamic Word object exists in a List of this dynamic type.</summary>\n/// <param name=\"word\">Word to look for</param>\n/// <param name=\"words\">Word dynamics to search through</param>\n/// <returns>Indicator of whether the word exists in the list of words</returns>\nprivate static bool ExistsInList(string word, List<dynamic> words)\n{\n foreach (dynamic dyn in words)\n if (dyn.Word == word)\n return true;\n return false;\n}\n"
},
{
"answer_id": 1804876,
"author": "tsilb",
"author_id": 11112,
"author_profile": "https://Stackoverflow.com/users/11112",
"pm_score": 2,
"selected": false,
"text": "public static string WrapAt(this string str, int WrapPos)\n{\n if (string.IsNullOrEmpty(str))\n throw new ArgumentNullException(\"str\", \"Cannot wrap a null string\");\n str = str.Replace(\"\\r\", \"\").Replace(\"\\n\", \"\");\n\n if (str.Length <= WrapPos)\n return str;\n\n for (int i = str.Length; i >= 0; i--)\n if (i % WrapPos == 0 && i > 0 && i != str.Length)\n str = str.Insert(i, \"\\r\\n\");\n return str;\n}\n"
},
{
"answer_id": 1804880,
"author": "tsilb",
"author_id": 11112,
"author_profile": "https://Stackoverflow.com/users/11112",
"pm_score": -1,
"selected": false,
"text": "/// <summary>Gets the root domain of any URI</summary>\n/// <param name=\"uri\">URI to get root domain of</param>\n/// <returns>Root domain with TLD</returns>\npublic static string GetRootDomain(this System.Uri uri)\n{\n if (uri == null)\n return null;\n\n string Domain = uri.Host;\n while (System.Text.RegularExpressions.Regex.Matches(Domain, @\"[\\.]\").Count > 1)\n Domain = Domain.Substring(Domain.IndexOf('.') + 1);\n Domain = Domain.Substring(0, Domain.IndexOf('.'));\n return Domain;\n}\n"
},
{
"answer_id": 1804940,
"author": "CaffGeek",
"author_id": 54746,
"author_profile": "https://Stackoverflow.com/users/54746",
"pm_score": 0,
"selected": false,
"text": "using (DataSet ds = yourcall()) \n{\n if (ds.HasRows())\n {\n foreach (DataRow dr in ds.Tables[0].Rows)\n {\n int id = dr.Field<int>(\"ID\");\n string name = dr.Field<string>(\"Name\");\n string Action = dr.Field<string>(\"Action\", \"N/A\");\n }\n }\n}\n using System;\nusing System.Data;\n\npublic static class DataSetExtensions\n{\n public static T Field<T>(this DataRow row, string columnName, T defaultValue)\n {\n try\n {\n return row.Field<T>(columnName);\n }\n catch\n {\n return defaultValue;\n }\n }\n\n public static T Field<T>(this DataRow row, string columnName)\n {\n if (row[columnName] == null)\n throw new NullReferenceException(columnName + \" does not exist in DataRow\");\n\n string value = row[columnName].ToString();\n\n if (typeof(T) == \"\".GetType())\n {\n return (T)Convert.ChangeType(value, typeof(T));\n }\n else if (typeof(T) == 0.GetType())\n {\n return (T)Convert.ChangeType(int.Parse(value), typeof(T));\n }\n else if (typeof(T) == false.GetType())\n {\n return (T)Convert.ChangeType(bool.Parse(value), typeof(T));\n }\n else if (typeof(T) == DateTime.Now.GetType())\n {\n return (T)Convert.ChangeType(DateTime.Parse(value), typeof(T));\n }\n else if (typeof(T) == new byte().GetType())\n {\n return (T)Convert.ChangeType(byte.Parse(value), typeof(T));\n }\n else if (typeof(T) == new float().GetType())\n {\n return (T)Convert.ChangeType(float.Parse(value), typeof(T));\n }\n else\n {\n throw new ArgumentException(string.Format(\"Cannot cast '{0}' to '{1}'.\", value, typeof(T).ToString()));\n }\n }\n\n public static bool HasRows(this DataSet dataSet) \n {\n return (dataSet.Tables.Count > 0 && dataSet.Tables[0].Rows.Count > 0);\n }\n}\n"
},
{
"answer_id": 1812003,
"author": "Matt Kocaj",
"author_id": 56145,
"author_profile": "https://Stackoverflow.com/users/56145",
"pm_score": 1,
"selected": false,
"text": "null public bool IsGroup { get { return !this.GroupName.IsNullOrTrimEmpty(); } }\n public static bool IsRequiredWithLengthLessThanOrEqualNoSpecial(this String str, int length)\n{\n return !str.IsNullOrTrimEmpty() &&\n str.RegexMatch(\n @\"^[- \\r\\n\\\\\\.!:*,@$%&\"\"?\\(\\)\\w']{1,{0}}$\".RegexReplace(@\"\\{0\\}\", length.ToString()),\n RegexOptions.Multiline) == str;\n}\n public static class StringHelpers\n{\n /// <summary>\n /// Same as String.IsNullOrEmpty except that\n /// it captures the Empty state for whitespace\n /// strings by Trimming first.\n /// </summary>\n public static bool IsNullOrTrimEmpty(this String helper)\n {\n if (helper == null)\n return true;\n else\n return String.Empty == helper.Trim();\n }\n\n public static int TrimLength(this String helper)\n {\n return helper.Trim().Length;\n }\n\n /// <summary>\n /// Returns the matched string from the regex pattern. The\n /// groupName is for named group match values in the form (?<name>group).\n /// </summary>\n public static string RegexMatch(this String helper, string pattern, RegexOptions options, string groupName)\n {\n if (groupName.IsNullOrTrimEmpty())\n return Regex.Match(helper, pattern, options).Value;\n else\n return Regex.Match(helper, pattern, options).Groups[groupName].Value;\n }\n\n public static string RegexMatch(this String helper, string pattern)\n {\n return RegexMatch(helper, pattern, RegexOptions.None, null);\n }\n\n public static string RegexMatch(this String helper, string pattern, RegexOptions options)\n {\n return RegexMatch(helper, pattern, options, null);\n }\n\n public static string RegexMatch(this String helper, string pattern, string groupName)\n {\n return RegexMatch(helper, pattern, RegexOptions.None, groupName);\n }\n\n /// <summary>\n /// Returns true if there is a match from the regex pattern\n /// </summary>\n public static bool IsRegexMatch(this String helper, string pattern, RegexOptions options)\n {\n return helper.RegexMatch(pattern, options).Length > 0;\n }\n\n public static bool IsRegexMatch(this String helper, string pattern)\n {\n return helper.IsRegexMatch(pattern, RegexOptions.None);\n }\n\n /// <summary>\n /// Returns a string where matching patterns are replaced by the replacement string.\n /// </summary>\n /// <param name=\"pattern\">The regex pattern for matching the items to be replaced</param>\n /// <param name=\"replacement\">The string to replace matching items</param>\n /// <returns></returns>\n public static string RegexReplace(this String helper, string pattern, string replacement, RegexOptions options)\n {\n return Regex.Replace(helper, pattern, replacement, options);\n }\n\n public static string RegexReplace(this String helper, string pattern, string replacement)\n {\n return Regex.Replace(helper, pattern, replacement, RegexOptions.None);\n }\n}\n"
},
{
"answer_id": 1969365,
"author": "Kaveh Shahbazian",
"author_id": 54467,
"author_profile": "https://Stackoverflow.com/users/54467",
"pm_score": 2,
"selected": false,
"text": "// the most beloved extension method for me is Pipe:\n<%= variable.Pipe(x => this.SomeFunction(x)).Pipe(y =>\n{\n ...;\n return this.SomeOtherFunction(y);\n}) %>\n\nvar d = 28.December(2009); // some extension methods for creating DateTime\nDateTime justDatePart = d.JustDate();\nTimeSpan justTimePart = d.JustTime();\nvar nextTime = d.Add(5.Hours());\n\nusing(StreamReader reader = new StreamReader(\"lines-of-data-file-for-example\")) {\n ...\n // for reading streams line by line and usable in LINQ\n var query = from line in reader.Lines(); \n where line.Contains(_today)\n select new { Parts = PartsOf(line), Time = _now };\n}\n\n500.Sleep();\n\nXmlSerialize and XmlDeserialize\n\nIsNull and IsNotNull\n\nIfTrue, IfFalse and Iff:\ntrue.IfTrue(() => Console.WriteLine(\"it is true then!\");\n\nIfNull and IfNotNull\n"
},
{
"answer_id": 1969663,
"author": "moomi",
"author_id": 50949,
"author_profile": "https://Stackoverflow.com/users/50949",
"pm_score": 1,
"selected": false,
"text": "private bool CreateMode;\nprivate MyClass SomeClass;\n\nprotected override void OnInit (EventArgs e)\n{\n CreateMode = Session.GetSessionValue<bool> (\"someKey1\", () => true);\n SomeClass = Session.GetSessionClass<MyClass> (\"someKey2\", () => new MyClass () \n { \n MyProperty = 123 \n });\n}\n \n\npublic static class SessionExtensions \n{\n public delegate object UponCreate ();\n public static T GetSessionClass<T> (this HttpSessionState session, \n string key, UponCreate uponCreate) where T : class\n {\n if (null == session[key])\n {\n var item = uponCreate () as T;\n session[key] = item;\n return item;\n }\n return session[key] as T;\n }\n public static T GetSessionValue<T> (this HttpSessionState session, \n string key, UponCreate uponCreate) where T : struct\n {\n if (null == session[key])\n {\n var item = uponCreate();\n session[key] = item;\n return (T)item;\n }\n return (T)session[key];\n }\n}\n\n\n public static class SessionExtensions \n{\n public delegate object UponCreate ();\n public static T GetSessionClass<T> (this HttpSessionState session, \n string key, UponCreate uponCreate) where T : class\n {\n if (null == session[key])\n {\n var item = uponCreate () as T;\n session[key] = item;\n return item;\n }\n return session[key] as T;\n }\n public static T GetSessionValue<T> (this HttpSessionState session, \n string key, UponCreate uponCreate) where T : struct\n {\n if (null == session[key])\n {\n var item = uponCreate();\n session[key] = item;\n return (T)item;\n }\n return (T)session[key];\n }\n}\n "
},
{
"answer_id": 2016298,
"author": "jpbochi",
"author_id": 123897,
"author_profile": "https://Stackoverflow.com/users/123897",
"pm_score": 3,
"selected": false,
"text": "IEnumerable<> yield return static public IEnumerable<T> Shuffle<T>(this IEnumerable<T> source)\n{\n if (source == null) throw new ArgumentNullException(\"source\");\n\n return ShuffleIterator(source);\n}\n\nstatic private IEnumerable<T> ShuffleIterator<T>(this IEnumerable<T> source)\n{\n T[] array = source.ToArray();\n Random rnd = new Random(); \n for (int n = array.Length; n > 1;)\n {\n int k = rnd.Next(n--); // 0 <= k < n\n\n //Swap items\n if (n != k)\n {\n T tmp = array[k];\n array[k] = array[n];\n array[n] = tmp;\n }\n }\n\n foreach (var item in array) yield return item;\n}\n"
},
{
"answer_id": 2153244,
"author": "Gideon",
"author_id": 82004,
"author_profile": "https://Stackoverflow.com/users/82004",
"pm_score": 2,
"selected": false,
"text": "if true false null string.Empty public static TResult WhenTrue<TResult>(this Boolean value, Func<TResult> expression)\n{\n return value ? expression() : default(TResult);\n}\n\npublic static TResult WhenTrue<TResult>(this Boolean value, TResult content)\n{\n return value ? content : default(TResult);\n}\n\npublic static TResult WhenFalse<TResult>(this Boolean value, Func<TResult> expression)\n{\n return !value ? expression() : default(TResult);\n}\n\npublic static TResult WhenFalse<TResult>(this Boolean value, TResult content)\n{\n return !value ? content : default(TResult);\n}\n <%= (someBool) ? \"print y\" : string.Empty %> <%= someBool.WhenTrue(\"print y\") %>"
},
{
"answer_id": 2212077,
"author": "Jordão",
"author_id": 31158,
"author_profile": "https://Stackoverflow.com/users/31158",
"pm_score": 3,
"selected": false,
"text": "XmlSerializable Thread SqlConnection M XmlSerializable public interface MXmlSerializable { }\npublic static class XmlSerializable {\n public static string ToXml(this MXmlSerializable self) {\n if (self == null) throw new ArgumentNullException();\n var serializer = new XmlSerializer(self.GetType());\n using (var writer = new StringWriter()) {\n serializer.Serialize(writer, self);\n return writer.GetStringBuilder().ToString();\n }\n }\n public static T FromXml<T>(string xml) where T : MXmlSerializable {\n var serializer = new XmlSerializer(typeof(T));\n return (T)serializer.Deserialize(new StringReader(xml));\n }\n}\n public class Customer : MXmlSerializable {\n public string Name { get; set; }\n public bool Preferred { get; set; }\n}\n var customer = new Customer { \n Name = \"Guybrush Threepwood\", \n Preferred = true };\nvar xml = customer.ToXml();\n"
},
{
"answer_id": 2277064,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "public static class StringHelper\n{\n public static String F(this String str, params object[] args)\n {\n return String.Format(str, args);\n }\n}\n \"Say {0}\".F(\"Hello\");\n"
},
{
"answer_id": 2277084,
"author": "moribvndvs",
"author_id": 64750,
"author_profile": "https://Stackoverflow.com/users/64750",
"pm_score": 2,
"selected": false,
"text": "String.As<T> Nullable public static partial class StringExtensions\n{\n /// <summary>\n /// Converts the string to the specified type, using the default value configured for the type.\n /// </summary>\n /// <typeparam name=\"T\">Type the string will be converted to. The type must implement IConvertable.</typeparam>\n /// <param name=\"original\">The original string.</param>\n /// <returns>The converted value.</returns>\n public static T As<T>(this String original)\n {\n return As(original, CultureInfo.CurrentCulture,\n default(T));\n }\n\n /// <summary>\n /// Converts the string to the specified type, using the default value configured for the type.\n /// </summary>\n /// <typeparam name=\"T\">Type the string will be converted to.</typeparam>\n /// <param name=\"original\">The original string.</param>\n /// <param name=\"defaultValue\">The default value to use in case the original string is null or empty, or can't be converted.</param>\n /// <returns>The converted value.</returns>\n public static T As<T>(this String original, T defaultValue)\n {\n return As(original, CultureInfo.CurrentCulture, defaultValue);\n }\n\n /// <summary>\n /// Converts the string to the specified type, using the default value configured for the type.\n /// </summary>\n /// <typeparam name=\"T\">Type the string will be converted to.</typeparam>\n /// <param name=\"original\">The original string.</param>\n /// <param name=\"provider\">Format provider used during the type conversion.</param>\n /// <returns>The converted value.</returns>\n public static T As<T>(this String original, IFormatProvider provider)\n {\n return As(original, provider, default(T));\n }\n\n /// <summary>\n /// Converts the string to the specified type.\n /// </summary>\n /// <typeparam name=\"T\">Type the string will be converted to.</typeparam>\n /// <param name=\"original\">The original string.</param>\n /// <param name=\"provider\">Format provider used during the type conversion.</param>\n /// <param name=\"defaultValue\">The default value to use in case the original string is null or empty, or can't be converted.</param>\n /// <returns>The converted value.</returns>\n /// <remarks>\n /// If an error occurs while converting the specified value to the requested type, the exception is caught and the default is returned. It is strongly recommended you\n /// do NOT use this method if it is important that conversion failures are not swallowed up.\n ///\n /// This method is intended to be used to convert string values to primatives, not for parsing, converting, or deserializing complex types.\n /// </remarks>\n public static T As<T>(this String original, IFormatProvider provider,\n T defaultValue)\n {\n T result;\n Type type = typeof (T);\n\n if (String.IsNullOrEmpty(original)) result = defaultValue;\n else\n {\n // need to get the underlying type if T is Nullable<>.\n\n if (type.IsNullableType())\n {\n type = Nullable.GetUnderlyingType(type);\n }\n\n try\n {\n // ChangeType doesn't work properly on Enums\n result = type.IsEnum\n ? (T) Enum.Parse(type, original, true)\n : (T) Convert.ChangeType(original, type, provider);\n }\n catch // HACK: what can we do to minimize or avoid raising exceptions as part of normal operation? custom string parsing (regex?) for well-known types? it would be best to know if you can convert to the desired type before you attempt to do so.\n {\n result = defaultValue;\n }\n }\n\n return result;\n }\n}\n Type /// <summary>\n/// Extension methods for <see cref=\"Type\"/>.\n/// </summary>\npublic static class TypeExtensions\n{\n /// <summary>\n /// Returns whether or not the specified type is <see cref=\"Nullable{T}\"/>.\n /// </summary>\n /// <param name=\"type\">A <see cref=\"Type\"/>.</param>\n /// <returns>True if the specified type is <see cref=\"Nullable{T}\"/>; otherwise, false.</returns>\n /// <remarks>Use <see cref=\"Nullable.GetUnderlyingType\"/> to access the underlying type.</remarks>\n public static bool IsNullableType(this Type type)\n {\n if (type == null) throw new ArgumentNullException(\"type\");\n\n return type.IsGenericType && type.GetGenericTypeDefinition().Equals(typeof (Nullable<>));\n }\n}\n var someInt = \"1\".As<int>();\nvar someIntDefault = \"bad value\".As(1); // \"bad value\" won't convert, so the default value 1 is returned.\nvar someEnum = \"Sunday\".As<DayOfWeek>();\nsomeEnum = \"0\".As<DayOfWeek>(); // returns Sunday\nvar someNullableEnum = \"\".As<DayOfWeek?>(null); // returns a null value since \"\" can't be converted\n"
},
{
"answer_id": 2437499,
"author": "PhilChuang",
"author_id": 14392,
"author_profile": "https://Stackoverflow.com/users/14392",
"pm_score": 1,
"selected": false,
"text": "CloneableClass cc1 = new CloneableClass ();\nCloneableClass cc2 = null;\nCloneableClass cc3 = null;\n\ncc3 = (CloneableClass) cc1.Clone (); // this is ok\ncc3 = cc2.Clone (); // this throws null ref exception\n// code to handle both cases\ncc3 = cc1 != null ? (CloneableClass) cc1.Clone () : null;\n public static T CloneOrNull<T> (this T self) where T : class, ICloneable\n{\n if (self == null) return null;\n return (T) self.Clone ();\n}\n CloneableClass cc1 = new CloneableClass ();\nCloneableClass cc2 = null;\nCloneableClass cc3 = null;\n\ncc3 = cc1.CloneOrNull (); // clone of cc1\ncc3 = cc2.CloneOrNull (); // null\n// look mom, no casts!\n"
},
{
"answer_id": 2439537,
"author": "Dan Tao",
"author_id": 105570,
"author_profile": "https://Stackoverflow.com/users/105570",
"pm_score": 3,
"selected": false,
"text": "Random Next NextDouble Random NextBool NextChar NextDateTime NextTimeSpan NextDouble minValue maxValue NextString NextByte NextShort NextLong // todo: implement additional CharType values (e.g., AsciiAny)\npublic enum CharType {\n AlphabeticLower,\n AlphabeticUpper,\n AlphabeticAny,\n AlphanumericLower,\n AlphanumericUpper,\n AlphanumericAny,\n Numeric\n}\n\npublic static class RandomExtensions {\n // 10 digits vs. 52 alphabetic characters (upper & lower);\n // probability of being numeric: 10 / 62 = 0.1612903225806452\n private const double AlphanumericProbabilityNumericAny = 10.0 / 62.0;\n\n // 10 digits vs. 26 alphabetic characters (upper OR lower);\n // probability of being numeric: 10 / 36 = 0.2777777777777778\n private const double AlphanumericProbabilityNumericCased = 10.0 / 36.0;\n\n public static bool NextBool(this Random random, double probability) {\n return random.NextDouble() <= probability;\n }\n\n public static bool NextBool(this Random random) {\n return random.NextDouble() <= 0.5;\n }\n\n public static char NextChar(this Random random, CharType mode) {\n switch (mode) {\n case CharType.AlphabeticAny:\n return random.NextAlphabeticChar();\n case CharType.AlphabeticLower:\n return random.NextAlphabeticChar(false);\n case CharType.AlphabeticUpper:\n return random.NextAlphabeticChar(true);\n case CharType.AlphanumericAny:\n return random.NextAlphanumericChar();\n case CharType.AlphanumericLower:\n return random.NextAlphanumericChar(false);\n case CharType.AlphanumericUpper:\n return random.NextAlphanumericChar(true);\n case CharType.Numeric:\n return random.NextNumericChar();\n default:\n return random.NextAlphanumericChar();\n }\n }\n\n public static char NextChar(this Random random) {\n return random.NextChar(CharType.AlphanumericAny);\n }\n\n private static char NextAlphanumericChar(this Random random, bool uppercase) {\n bool numeric = random.NextBool(AlphanumericProbabilityNumericCased);\n\n if (numeric)\n return random.NextNumericChar();\n else\n return random.NextAlphabeticChar(uppercase);\n }\n\n private static char NextAlphanumericChar(this Random random) {\n bool numeric = random.NextBool(AlphanumericProbabilityNumericAny);\n\n if (numeric)\n return random.NextNumericChar();\n else\n return random.NextAlphabeticChar(random.NextBool());\n }\n\n private static char NextAlphabeticChar(this Random random, bool uppercase) {\n if (uppercase)\n return (char)random.Next(65, 91);\n else\n return (char)random.Next(97, 123);\n }\n\n private static char NextAlphabeticChar(this Random random) {\n return random.NextAlphabeticChar(random.NextBool());\n }\n\n private static char NextNumericChar(this Random random) {\n return (char)random.Next(48, 58);\n }\n\n public static DateTime NextDateTime(this Random random, DateTime minValue, DateTime maxValue) {\n return DateTime.FromOADate(\n random.NextDouble(minValue.ToOADate(), maxValue.ToOADate())\n );\n }\n\n public static DateTime NextDateTime(this Random random) {\n return random.NextDateTime(DateTime.MinValue, DateTime.MaxValue);\n }\n\n public static double NextDouble(this Random random, double minValue, double maxValue) {\n if (maxValue < minValue)\n throw new ArgumentException(\"Minimum value must be less than maximum value.\");\n\n double difference = maxValue - minValue;\n if (!double.IsInfinity(difference))\n return minValue + (random.NextDouble() * difference);\n\n else {\n // to avoid evaluating to Double.Infinity, we split the range into two halves:\n double halfDifference = (maxValue * 0.5) - (minValue * 0.5);\n\n // 50/50 chance of returning a value from the first or second half of the range\n if (random.NextBool())\n return minValue + (random.NextDouble() * halfDifference);\n else\n return (minValue + halfDifference) + (random.NextDouble() * halfDifference);\n }\n }\n\n public static string NextString(this Random random, int numChars, CharType mode) {\n char[] chars = new char[numChars];\n\n for (int i = 0; i < numChars; ++i)\n chars[i] = random.NextChar(mode);\n\n return new string(chars);\n }\n\n public static string NextString(this Random random, int numChars) {\n return random.NextString(numChars, CharType.AlphanumericAny);\n }\n\n public static TimeSpan NextTimeSpan(this Random random, TimeSpan minValue, TimeSpan maxValue) {\n return TimeSpan.FromMilliseconds(\n random.NextDouble(minValue.TotalMilliseconds, maxValue.TotalMilliseconds)\n );\n }\n\n public static TimeSpan NextTimeSpan(this Random random) {\n return random.NextTimeSpan(TimeSpan.MinValue, TimeSpan.MaxValue);\n }\n}\n"
},
{
"answer_id": 2439988,
"author": "Janko R",
"author_id": 292466,
"author_profile": "https://Stackoverflow.com/users/292466",
"pm_score": 0,
"selected": false,
"text": "public static class DictionaryExtensions\n{\n public static Nullable<TValue> GetValueOrNull<TKey, TValue>(this Dictionary<TKey, TValue> dictionary, TKey key)\n where TValue : struct\n {\n TValue result;\n if (dictionary.TryGetValue(key, out result))\n return result;\n else\n return null;\n }\n}\n"
},
{
"answer_id": 2549153,
"author": "John Leidegren",
"author_id": 58961,
"author_profile": "https://Stackoverflow.com/users/58961",
"pm_score": 3,
"selected": false,
"text": "public static bool EqualsIgnoreCase(this string a, string b)\n{\n return string.Equals(a, b, StringComparison.OrdinalIgnoreCase);\n}\n StartsWithIgnoreCase EndsWithIgnoreCase ContainsIgnoreCase"
},
{
"answer_id": 2550726,
"author": "Max Toro",
"author_id": 39923,
"author_profile": "https://Stackoverflow.com/users/39923",
"pm_score": 4,
"selected": false,
"text": "DbCommand command = connection.CreateCommand();\ncommand.CommandText = \"SELECT @param\";\n\nDbParameter param = command.CreateParameter();\nparam.ParameterName = \"@param\";\nparam.Value = \"Hello World\";\n\ncommand.Parameters.Add(param);\n DbCommand command = connection.CreateCommand(\"SELECT {0}\", \"Hello World\");\n using System;\nusing System.Data.Common;\nusing System.Globalization;\nusing System.Reflection;\n\nnamespace DbExtensions {\n\n public static class Db {\n\n static readonly Func<DbConnection, DbProviderFactory> getDbProviderFactory;\n static readonly Func<DbCommandBuilder, int, string> getParameterName;\n static readonly Func<DbCommandBuilder, int, string> getParameterPlaceholder;\n\n static Db() {\n\n getDbProviderFactory = (Func<DbConnection, DbProviderFactory>)Delegate.CreateDelegate(typeof(Func<DbConnection, DbProviderFactory>), typeof(DbConnection).GetProperty(\"DbProviderFactory\", BindingFlags.Instance | BindingFlags.NonPublic).GetGetMethod(true));\n getParameterName = (Func<DbCommandBuilder, int, string>)Delegate.CreateDelegate(typeof(Func<DbCommandBuilder, int, string>), typeof(DbCommandBuilder).GetMethod(\"GetParameterName\", BindingFlags.Instance | BindingFlags.NonPublic, Type.DefaultBinder, new Type[] { typeof(Int32) }, null));\n getParameterPlaceholder = (Func<DbCommandBuilder, int, string>)Delegate.CreateDelegate(typeof(Func<DbCommandBuilder, int, string>), typeof(DbCommandBuilder).GetMethod(\"GetParameterPlaceholder\", BindingFlags.Instance | BindingFlags.NonPublic, Type.DefaultBinder, new Type[] { typeof(Int32) }, null));\n }\n\n public static DbProviderFactory GetProviderFactory(this DbConnection connection) {\n return getDbProviderFactory(connection);\n }\n\n public static DbCommand CreateCommand(this DbConnection connection, string commandText, params object[] parameters) {\n\n if (connection == null) throw new ArgumentNullException(\"connection\");\n\n return CreateCommandImpl(GetProviderFactory(connection).CreateCommandBuilder(), connection.CreateCommand(), commandText, parameters);\n }\n\n private static DbCommand CreateCommandImpl(DbCommandBuilder commandBuilder, DbCommand command, string commandText, params object[] parameters) {\n\n if (commandBuilder == null) throw new ArgumentNullException(\"commandBuilder\");\n if (command == null) throw new ArgumentNullException(\"command\");\n if (commandText == null) throw new ArgumentNullException(\"commandText\");\n\n if (parameters == null || parameters.Length == 0) {\n command.CommandText = commandText;\n return command;\n }\n\n object[] paramPlaceholders = new object[parameters.Length];\n\n for (int i = 0; i < paramPlaceholders.Length; i++) {\n\n DbParameter dbParam = command.CreateParameter();\n dbParam.ParameterName = getParameterName(commandBuilder, i);\n dbParam.Value = parameters[i] ?? DBNull.Value;\n command.Parameters.Add(dbParam);\n\n paramPlaceholders[i] = getParameterPlaceholder(commandBuilder, i);\n }\n\n command.CommandText = String.Format(CultureInfo.InvariantCulture, commandText, paramPlaceholders);\n\n return command;\n }\n }\n}\n"
},
{
"answer_id": 2687774,
"author": "Mark Rushakoff",
"author_id": 126042,
"author_profile": "https://Stackoverflow.com/users/126042",
"pm_score": 3,
"selected": false,
"text": "InvokeRequired using System;\nusing System.Windows.Forms;\n\n/// <summary>\n/// Extension methods acting on Control objects.\n/// </summary>\ninternal static class ControlExtensionMethods\n{\n /// <summary>\n /// Invokes the given action on the given control's UI thread, if invocation is needed.\n /// </summary>\n /// <param name=\"control\">Control on whose UI thread to possibly invoke.</param>\n /// <param name=\"action\">Action to be invoked on the given control.</param>\n public static void MaybeInvoke(this Control control, Action action)\n {\n if (control != null && control.InvokeRequired)\n {\n control.Invoke(action);\n }\n else\n {\n action();\n }\n }\n\n /// <summary>\n /// Maybe Invoke a Func that returns a value.\n /// </summary>\n /// <typeparam name=\"T\">Return type of func.</typeparam>\n /// <param name=\"control\">Control on which to maybe invoke.</param>\n /// <param name=\"func\">Function returning a value, to invoke.</param>\n /// <returns>The result of the call to func.</returns>\n public static T MaybeInvoke<T>(this Control control, Func<T> func)\n {\n if (control != null && control.InvokeRequired)\n {\n return (T)(control.Invoke(func));\n }\n else\n {\n return func();\n }\n }\n}\n myForm.MaybeInvoke(() => this.Text = \"Hello world\");\n\n// Sometimes the control might be null, but that's okay.\nvar dialogResult = this.Parent.MaybeInvoke(() => MessageBox.Show(this, \"Yes or no?\", \"Choice\", MessageBoxButtons.YesNo));\n"
},
{
"answer_id": 2832683,
"author": "ytoledano",
"author_id": 245452,
"author_profile": "https://Stackoverflow.com/users/245452",
"pm_score": 2,
"selected": false,
"text": "public static bool IsNullOrDefault<T>(this T? o) \n where T : struct\n{\n return o == null || o.Value.Equals(default(T));\n}\n"
},
{
"answer_id": 2844557,
"author": "Thomas Levesque",
"author_id": 98713,
"author_profile": "https://Stackoverflow.com/users/98713",
"pm_score": 2,
"selected": false,
"text": "public static T GetService<T>(this IServiceProvider provider)\n{\n return (T)provider.GetService(typeof(T));\n}\n IServiceProvider IProvideValueTarget target = (IProvideValueTarget)serviceProvider(typeof(IProvideValueTarget));\n var target = serviceProvider.GetService<IProvideValueTarget>();\n"
},
{
"answer_id": 2959072,
"author": "Chao",
"author_id": 300996,
"author_profile": "https://Stackoverflow.com/users/300996",
"pm_score": 2,
"selected": false,
"text": "public static class nullpartials\n {\n public static MvcHtmlString NullPartial(this HtmlHelper helper, string Partial, string NullPartial, object Model)\n {\n if (Model == null)\n return helper.Partial(NullPartial);\n else\n return helper.Partial(Partial, Model);\n }\n\n public static MvcHtmlString NullPartial(this HtmlHelper helper, string Partial, string NullPartial, object Model, ViewDataDictionary viewdata)\n {\n if (Model == null)\n return helper.Partial(NullPartial, viewdata);\n else\n return helper.Partial(Partial, Model, viewdata);\n }\n\n public static void RenderNullPartial(this HtmlHelper helper, string Partial, string NullPartial, object Model)\n {\n if (Model == null)\n {\n helper.RenderPartial(NullPartial);\n return;\n }\n else\n {\n helper.RenderPartial(Partial, Model);\n return;\n }\n }\n\n public static void RenderNullPartial(this HtmlHelper helper, string Partial, string NullPartial, object Model, ViewDataDictionary viewdata)\n {\n if (Model == null)\n {\n helper.RenderPartial(NullPartial, viewdata);\n return;\n }\n else\n {\n helper.RenderPartial(Partial, Model, viewdata);\n return;\n }\n }\n }\n"
},
{
"answer_id": 2966853,
"author": "si618",
"author_id": 44540,
"author_profile": "https://Stackoverflow.com/users/44540",
"pm_score": 3,
"selected": false,
"text": "/// <summary>\n/// Gets the key using <paramref name=\"caseInsensitiveKey\"/> from <paramref name=\"dictionary\"/>.\n/// </summary>\n/// <typeparam name=\"T\">The dictionary value.</typeparam>\n/// <param name=\"dictionary\">The dictionary.</param>\n/// <param name=\"caseInsensitiveKey\">The case insensitive key.</param>\n/// <returns>\n/// An existing key; or <see cref=\"string.Empty\"/> if not found.\n/// </returns>\npublic static string GetKeyIgnoringCase<T>(this IDictionary<string, T> dictionary, string caseInsensitiveKey)\n{\n if (string.IsNullOrEmpty(caseInsensitiveKey)) return string.Empty;\n foreach (string key in dictionary.Keys)\n {\n if (key.Equals(caseInsensitiveKey, StringComparison.InvariantCultureIgnoreCase))\n {\n return key;\n }\n }\n return string.Empty;\n}\n"
},
{
"answer_id": 3098630,
"author": "cbp",
"author_id": 21966,
"author_profile": "https://Stackoverflow.com/users/21966",
"pm_score": 1,
"selected": false,
"text": "public static void DelimitedAppend(this StringBuilder sb, string value, string delimiter)\n{\n if (sb.Length > 0)\n sb.Append(delimiter);\n sb.Append(value);\n}\n var farmAnimals = new[] { new { Species = \"Dog\", IsTasty = false }, new { Species = \"Cat\", IsTasty = false }, new { Species = \"Chicken\", IsTasty = true }, };\nvar soupIngredients = new StringBuilder();\nforeach (var edible in farmAnimals.Where(farmAnimal => farmAnimal.IsTasty))\n soupIngredients.DelimitedAppend(edible.Species, \", \");\n"
},
{
"answer_id": 3098674,
"author": "johnc",
"author_id": 5302,
"author_profile": "https://Stackoverflow.com/users/5302",
"pm_score": 3,
"selected": false,
"text": "public static class ExtensionMethods_Object\n{\n [DebuggerStepThrough()]\n public static bool Is<T>(this object item) where T : class\n {\n return item is T;\n }\n\n [DebuggerStepThrough()]\n public static bool IsNot<T>(this object item) where T : class\n {\n return !(item.Is<T>());\n }\n\n [DebuggerStepThrough()]\n public static T As<T>(this object item) where T : class\n {\n return item as T;\n }\n}\n"
},
{
"answer_id": 3132635,
"author": "John",
"author_id": 83091,
"author_profile": "https://Stackoverflow.com/users/83091",
"pm_score": 1,
"selected": false,
"text": "/// <summary>\n/// Returns the fiscal year for the passed in date\n/// </summary>\n/// <param name=\"value\">the date</param>\n/// <returns>the fiscal year</returns>\npublic static int FiscalYear(this DateTime value)\n{\n int ret = value.Year;\n if (value.Month >= 7) ret++;\n return ret;\n}\n\n/// <summary>\n/// Returns the fiscal year for the passed in date\n/// </summary>\n/// <param name=\"value\">the date</param>\n/// <returns>the fiscal year</returns>\npublic static string FiscalYearString(this DateTime value)\n{\n int fy = FiscalYear(value);\n return \"{0}/{1}\".Format(fy - 1, fy);\n}\n"
},
{
"answer_id": 3232611,
"author": "fre0n",
"author_id": 252004,
"author_profile": "https://Stackoverflow.com/users/252004",
"pm_score": 5,
"selected": false,
"text": "/// <summary>\n/// Returns whether the function is being executed during design time in Visual Studio.\n/// </summary>\npublic static bool IsDesignTime(this Control control)\n{\n if (LicenseManager.UsageMode == LicenseUsageMode.Designtime)\n {\n return true;\n }\n\n if (control.Site != null && control.Site.DesignMode)\n {\n return true;\n }\n\n var parent = control.Parent;\n while (parent != null)\n {\n if (parent.Site != null && parent.Site.DesignMode)\n {\n return true;\n }\n parent = parent.Parent;\n }\n return false;\n}\n\n/// <summary>\n/// Sets the DropDownWidth to ensure that no item's text is cut off.\n/// </summary>\npublic static void SetDropDownWidth(this ComboBox comboBox)\n{\n var g = comboBox.CreateGraphics();\n var font = comboBox.Font;\n float maxWidth = 0;\n\n foreach (var item in comboBox.Items)\n {\n maxWidth = Math.Max(maxWidth, g.MeasureString(item.ToString(), font).Width);\n }\n\n if (comboBox.Items.Count > comboBox.MaxDropDownItems)\n {\n maxWidth += SystemInformation.VerticalScrollBarWidth;\n }\n\n comboBox.DropDownWidth = Math.Max(comboBox.Width, Convert.ToInt32(maxWidth));\n}\n public class SomeForm : Form\n{\n public SomeForm()\n {\n InitializeComponent();\n\n if (this.IsDesignTime())\n {\n return;\n }\n\n // Do something that makes the visual studio crash or hang if we're in design time,\n // but any other time executes just fine\n }\n}\n ComboBox cbo = new ComboBox { Width = 50 };\ncbo.Items.Add(\"Short\");\ncbo.Items.Add(\"A little longer\");\ncbo.Items.Add(\"Holy cow, this is a really, really long item. How in the world will it fit?\");\ncbo.SetDropDownWidth();\n"
},
{
"answer_id": 3237976,
"author": "Soonts",
"author_id": 126995,
"author_profile": "https://Stackoverflow.com/users/126995",
"pm_score": 0,
"selected": false,
"text": "// This file contains extension methods for generic List<> class to operate on sorted lists.\n// Duplicate values are OK.\n// O(ln(n)) is still much faster then the O(n) of LINQ's searches/filters.\nstatic partial class SortedList\n{\n // Return the index of the first element with the key greater then provided.\n // If there's no such element within the provided range, it returns iAfterLast.\n public static int sortedFirstGreaterIndex<tElt, tKey>( this IList<tElt> list, Func<tElt, tKey, int> comparer, tKey key, int iFirst, int iAfterLast )\n {\n if( iFirst < 0 || iAfterLast < 0 || iFirst > list.Count || iAfterLast > list.Count )\n throw new IndexOutOfRangeException();\n if( iFirst > iAfterLast )\n throw new ArgumentException();\n if( iFirst == iAfterLast )\n return iAfterLast;\n\n int low = iFirst, high = iAfterLast;\n // The code below is inspired by the following article:\n // http://en.wikipedia.org/wiki/Binary_search#Single_comparison_per_iteration\n while( low < high )\n {\n int mid = ( high + low ) / 2;\n // 'mid' might be 'iFirst' in case 'iFirst+1 == iAfterLast'.\n // 'mid' will never be 'iAfterLast'.\n if( comparer( list[ mid ], key ) <= 0 ) // \"<=\" since we gonna find the first \"greater\" element\n low = mid + 1;\n else\n high = mid;\n }\n return low;\n }\n\n // Return the index of the first element with the key greater then the provided key.\n // If there's no such element, returns list.Count.\n public static int sortedFirstGreaterIndex<tElt, tKey>( this IList<tElt> list, Func<tElt, tKey, int> comparer, tKey key )\n {\n return list.sortedFirstGreaterIndex( comparer, key, 0, list.Count );\n }\n\n // Add an element to the sorted array.\n // This could be an expensive operation if frequently adding elements that sort firstly.\n // This is cheap operation when adding elements that sort near the tail of the list.\n public static int sortedAdd<tElt>( this List<tElt> list, Func<tElt, tElt, int> comparer, tElt elt )\n {\n if( list.Count == 0 || comparer( list[ list.Count - 1 ], elt ) <= 0 )\n {\n // either the list is empty, or the item is greater then all elements already in the collection.\n list.Add( elt );\n return list.Count - 1;\n }\n int ind = list.sortedFirstGreaterIndex( comparer, elt );\n list.Insert( ind, elt );\n return ind;\n }\n\n // Find first exactly equal element, return -1 if not found.\n public static int sortedFindFirstIndex<tElt, tKey>( this List<tElt> list, Func<tElt, tKey, int> comparer, tKey elt )\n {\n int low = 0, high = list.Count - 1;\n\n while( low < high )\n {\n int mid = ( high + low ) / 2;\n if( comparer( list[ mid ], elt ) < 0 )\n low = mid + 1;\n else\n high = mid; // this includes the case when we've found an element exactly matching the key\n }\n if( high >= 0 && 0 == comparer( list[ high ], elt ) )\n return high;\n return -1;\n }\n\n // Return the IEnumerable that returns array elements in the reverse order.\n public static IEnumerable<tElt> sortedReverse<tElt>( this List<tElt> list )\n {\n for( int i=list.Count - 1; i >= 0; i-- )\n yield return list[ i ];\n }\n}\n"
},
{
"answer_id": 3282815,
"author": "Tadas Šukys",
"author_id": 135877,
"author_profile": "https://Stackoverflow.com/users/135877",
"pm_score": 2,
"selected": false,
"text": "public static bool IsNullOrEmpty(this ICollection obj)\n{\n return (obj == null || obj.Count == 0);\n}\n bool isNullOrEmpty = array.IsNullOrEmpty()\n bool isNullOrEmpty = array == null || array.Length == 0;\n"
},
{
"answer_id": 3317559,
"author": "stoic",
"author_id": 261257,
"author_profile": "https://Stackoverflow.com/users/261257",
"pm_score": 2,
"selected": false,
"text": "public static class DataTableConverter\n{\n /// <summary>\n /// Convert a List{T} to a DataTable.\n /// </summary>\n public static DataTable ToDataTable<T>(this IList<T> items)\n {\n var tb = new DataTable(typeof(T).Name);\n\n PropertyInfo[] props = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance);\n\n foreach (PropertyInfo prop in props)\n {\n Type t = GetCoreType(prop.PropertyType);\n tb.Columns.Add(prop.Name, t);\n }\n\n foreach (T item in items)\n {\n var values = new object[props.Length];\n\n for (int i = 0; i < props.Length; i++)\n {\n values[i] = props[i].GetValue(item, null);\n }\n\n tb.Rows.Add(values);\n }\n\n return tb;\n }\n\n /// <summary>\n /// Determine of specified type is nullable\n /// </summary>\n public static bool IsNullable(Type t)\n {\n return !t.IsValueType || (t.IsGenericType && t.GetGenericTypeDefinition() == typeof(Nullable<>));\n }\n\n /// <summary>\n /// Return underlying type if type is Nullable otherwise return the type\n /// </summary>\n public static Type GetCoreType(Type t)\n {\n if (t != null && IsNullable(t))\n {\n if (!t.IsValueType)\n {\n return t;\n }\n else\n {\n return Nullable.GetUnderlyingType(t);\n }\n }\n else\n {\n return t;\n }\n }\n}\n IList<MyClass> myClassList = new List<MyClass>();\n DataTable myClassDataTable = myClassList.ToDataTable();\n"
},
{
"answer_id": 3321163,
"author": "Krisc",
"author_id": 299946,
"author_profile": "https://Stackoverflow.com/users/299946",
"pm_score": 2,
"selected": false,
"text": "public static bool CompareEx(this string strA, string strB, CultureInfo culture, bool ignoreCase)\n{\n return string.Compare(strA, strB, ignoreCase, culture) == 0;\n}\n"
},
{
"answer_id": 3321394,
"author": "Kenneth J",
"author_id": 195456,
"author_profile": "https://Stackoverflow.com/users/195456",
"pm_score": 2,
"selected": false,
"text": "public static class MailExtension\n{\n // GetEmailCreditial(out strServer) gets credentials from an XML file\n public static void Send(this MailMessage email)\n {\n string strServer = String.Empty;\n NetworkCredential credentials = GetEmailCreditial(out strServer);\n SmtpClient client = new SmtpClient(strServer) { Credentials = credentials };\n client.Send(email);\n }\n\n public static void Send(this IEnumerable<MailMessage> emails)\n {\n string strServer = String.Empty;\n NetworkCredential credentials = GetEmailCreditial(out strServer);\n SmtpClient client = new SmtpClient(strServer) { Credentials = credentials };\n foreach (MailMessage email in emails)\n client.Send(email);\n }\n}\n\n// Example of use: \nnew MailMessage(\"info@myDomain.com\",\"you@gmail.com\",\"This is an important Subject\", \"Body goes here\").Send();\n//Assume email1,email2,email3 are MailMessage objects\nnew List<MailMessage>(){email1, email2, email}.Send();\n"
},
{
"answer_id": 3423109,
"author": "Daniel A.A. Pelsmaeker",
"author_id": 146622,
"author_profile": "https://Stackoverflow.com/users/146622",
"pm_score": 2,
"selected": false,
"text": "/// <summary>\n/// Returns a string representation of a byte array.\n/// </summary>\n/// <param name=\"bytearray\">The byte array to represent.</param>\n/// <param name=\"subdivision\">The number of elements per group,\n/// or 0 to not restrict it. The default is 0.</param>\n/// <param name=\"subsubdivision\">The number of elements per line,\n/// or 0 to not restrict it. The default is 0.</param>\n/// <param name=\"divider\">The string dividing the individual bytes. The default is \" \".</param>\n/// <param name=\"subdivider\">The string dividing the groups. The default is \" \".</param>\n/// <param name=\"subsubdivider\">The string dividing the lines. The default is \"\\r\\n\".</param>\n/// <param name=\"uppercase\">Whether the representation is in uppercase hexadecimal.\n/// The default is <see langword=\"true\"/>.</param>\n/// <param name=\"prebyte\">The string to put before each byte. The default is an empty string.</param>\n/// <param name=\"postbyte\">The string to put after each byte. The default is an empty string.</param>\n/// <returns>The string representation.</returns>\n/// <exception cref=\"ArgumentNullException\">\n/// <paramref name=\"bytearray\"/> is <see langword=\"null\"/>.\n/// </exception>\npublic static string ToArrayString(this byte[] bytearray,\n int subdivision = 0,\n int subsubdivision = 0,\n string divider = \" \",\n string subdivider = \" \",\n string subsubdivider = \"\\r\\n\",\n bool uppercase = true,\n string prebyte = \"\",\n string postbyte = \"\")\n{\n #region Contract\n if (bytearray == null)\n throw new ArgumentNullException(\"bytearray\");\n #endregion\n\n StringBuilder sb = new StringBuilder(\n bytearray.Length * (2 + divider.Length + prebyte.Length + postbyte.Length) +\n (subdivision > 0 ? (bytearray.Length / subdivision) * subdivider.Length : 0) +\n (subsubdivision > 0 ? (bytearray.Length / subsubdivision) * subsubdivider.Length : 0));\n int groupElements = (subdivision > 0 ? subdivision - 1 : -1);\n int lineElements = (subsubdivision > 0 ? subsubdivision - 1 : -1);\n for (long i = 0; i < bytearray.LongLength - 1; i++)\n {\n sb.Append(prebyte);\n sb.Append(String.Format(CultureInfo.InvariantCulture, (uppercase ? \"{0:X2}\" : \"{0:x2}\"), bytearray[i]));\n sb.Append(postbyte);\n\n if (lineElements == 0)\n {\n sb.Append(subsubdivider);\n groupElements = subdivision;\n lineElements = subsubdivision;\n }\n else if (groupElements == 0)\n {\n sb.Append(subdivider);\n groupElements = subdivision;\n }\n else\n sb.Append(divider);\n\n lineElements--;\n groupElements--;\n }\n sb.Append(prebyte);\n sb.Append(String.Format(CultureInfo.InvariantCulture, (uppercase ? \"{0:X2}\" : \"{0:x2}\"), bytearray[bytearray.LongLength - 1]));\n sb.Append(postbyte);\n\n return sb.ToString();\n}\n ToArrayString() ToArrayString(4, 16) byte[] bytearray = new byte[]{ ... };\nConsole.Write(bytearray.ToArrayString(4, 16, \", \", \", \", \",\\r\\n\", true, \"0x\"));\n"
},
{
"answer_id": 3524142,
"author": "Luke Puplett",
"author_id": 107783,
"author_profile": "https://Stackoverflow.com/users/107783",
"pm_score": 1,
"selected": false,
"text": "public static string ToHtmlEncodedString(this string s)\n{\n if (String.IsNullOrEmpty(s))\n return s;\n return HttpUtility.HtmlEncode(s);\n}\n"
},
{
"answer_id": 3527407,
"author": "Thomas Levesque",
"author_id": 98713,
"author_profile": "https://Stackoverflow.com/users/98713",
"pm_score": 2,
"selected": false,
"text": "public static bool MatchesWildcard(this string text, string pattern)\n{\n int it = 0;\n while (text.CharAt(it) != 0 &&\n pattern.CharAt(it) != '*')\n {\n if (pattern.CharAt(it) != text.CharAt(it) && pattern.CharAt(it) != '?')\n return false;\n it++;\n }\n\n int cp = 0;\n int mp = 0;\n int ip = it;\n\n while (text.CharAt(it) != 0)\n {\n if (pattern.CharAt(ip) == '*')\n {\n if (pattern.CharAt(++ip) == 0)\n return true;\n mp = ip;\n cp = it + 1;\n }\n else if (pattern.CharAt(ip) == text.CharAt(it) || pattern.CharAt(ip) == '?')\n {\n ip++;\n it++;\n }\n else\n {\n ip = mp;\n it = cp++;\n }\n }\n\n while (pattern.CharAt(ip) == '*')\n {\n ip++;\n }\n return pattern.CharAt(ip) == 0;\n}\n\npublic static char CharAt(this string s, int index)\n{\n if (index < s.Length)\n return s[index];\n return '\\0';\n}\n CharAt if (fileName.MatchesWildcard(\"*.cs\"))\n{\n Console.WriteLine(\"{0} is a C# source file\", fileName);\n}\n"
},
{
"answer_id": 3576617,
"author": "fre0n",
"author_id": 252004,
"author_profile": "https://Stackoverflow.com/users/252004",
"pm_score": 2,
"selected": false,
"text": "/// <summary>\n/// Invoke an event asynchronously. Each subscriber to the event will be invoked on a separate thread.\n/// </summary>\n/// <param name=\"someEvent\">The event to be invoked asynchronously.</param>\n/// <param name=\"sender\">The sender of the event.</param>\n/// <param name=\"args\">The args of the event.</param>\n/// <typeparam name=\"TEventArgs\">The type of <see cref=\"EventArgs\"/> to be used with the event.</typeparam>\npublic static void InvokeAsync<TEventArgs>(this EventHandler<TEventArgs> someEvent, object sender, TEventArgs args)\n where TEventArgs : EventArgs\n{\n if (someEvent == null)\n {\n return;\n }\n\n var eventListeners = someEvent.GetInvocationList();\n\n AsyncCallback endAsyncCallback = delegate(IAsyncResult iar)\n {\n var ar = iar as AsyncResult;\n if (ar == null)\n {\n return;\n }\n\n var invokedMethod = ar.AsyncDelegate as EventHandler<TEventArgs>;\n if (invokedMethod != null)\n {\n invokedMethod.EndInvoke(iar);\n }\n };\n\n foreach (EventHandler<TEventArgs> methodToInvoke in eventListeners)\n {\n methodToInvoke.BeginInvoke(sender, args, endAsyncCallback, null);\n }\n}\n\n/// <summary>\n/// Invoke an event asynchronously. Each subscriber to the event will be invoked on a separate thread.\n/// </summary>\n/// <param name=\"someEvent\">The event to be invoked asynchronously.</param>\n/// <param name=\"sender\">The sender of the event.</param>\n/// <param name=\"args\">The args of the event.</param>\npublic static void InvokeAsync(this EventHandler someEvent, object sender, EventArgs args)\n{\n if (someEvent == null)\n {\n return;\n }\n\n var eventListeners = someEvent.GetInvocationList();\n\n AsyncCallback endAsyncCallback = delegate(IAsyncResult iar)\n {\n var ar = iar as AsyncResult;\n if (ar == null)\n {\n return;\n }\n\n var invokedMethod = ar.AsyncDelegate as EventHandler;\n if (invokedMethod != null)\n {\n invokedMethod.EndInvoke(iar);\n }\n };\n\n foreach (EventHandler methodToInvoke in eventListeners)\n {\n methodToInvoke.BeginInvoke(sender, args, endAsyncCallback, null);\n }\n}\n public class Foo\n{\n public event EventHandler<EventArgs> Bar;\n\n public void OnBar()\n {\n Bar.InvokeAsync(this, EventArgs.Empty);\n }\n}\n EventHandler<EventArgs> handler = Bar;\nif (handler != null)\n{\n // Invoke the event\n}\n void Main()\n{\n EventHandler<EventArgs> handler1 =\n delegate(object sender, EventArgs args)\n {\n // Simulate performing work in handler1\n Thread.Sleep(100);\n Console.WriteLine(\"Handled 1\");\n };\n\n EventHandler<EventArgs> handler2 =\n delegate(object sender, EventArgs args)\n {\n // Simulate performing work in handler2\n Thread.Sleep(50);\n Console.WriteLine(\"Handled 2\");\n };\n\n EventHandler<EventArgs> handler3 =\n delegate(object sender, EventArgs args)\n {\n // Simulate performing work in handler3\n Thread.Sleep(25);\n Console.WriteLine(\"Handled 3\");\n };\n\n var foo = new Foo();\n foo.Bar += handler1;\n foo.Bar += handler2;\n foo.Bar += handler3;\n foo.OnBar();\n\n Console.WriteLine(\"Start executing important stuff\");\n\n // Simulate performing some important stuff here, where we don't want to\n // wait around for the event handlers to finish executing\n Thread.Sleep(1000);\n\n Console.WriteLine(\"Finished executing important stuff\");\n}\n"
},
{
"answer_id": 3690091,
"author": "prabir",
"author_id": 157260,
"author_profile": "https://Stackoverflow.com/users/157260",
"pm_score": 2,
"selected": false,
"text": "private static readonly DateTime EPOCH = DateTime.SpecifyKind(new DateTime(1970, 1, 1, 0, 0, 0, 0),DateTimeKind.Utc);\n\npublic static DateTime FromUnixTimestamp(long timestamp)\n{\n return EPOCH.AddSeconds(timestamp);\n}\n\npublic static long ToUnixTimestamp(DateTime date)\n{\n TimeSpan diff = date.ToUniversalTime() - EPOCH;\n return (long)diff.TotalSeconds;\n}\n\npublic static DateTime FromIso8601FormattedDateTime(string iso8601DateTime){\n return DateTime.ParseExact(iso8601DateTime, \"o\", System.Globalization.CultureInfo.InvariantCulture);\n}\n\npublic static string ToIso8601FormattedDateTime(DateTime dateTime)\n{\n return dateTime.ToString(\"o\");\n}\n"
},
{
"answer_id": 3757152,
"author": "benPearce",
"author_id": 4490,
"author_profile": "https://Stackoverflow.com/users/4490",
"pm_score": 1,
"selected": false,
"text": "public static string Overwrite(this string s, int startIndex, string newStringValue)\n{\n return s.Remove(startIndex, newStringValue.Length).Insert(startIndex, newStringValue);\n}\n string s = new String(' ',60);\ns = s.Overwrite(7,\"NewValue\");\n"
},
{
"answer_id": 3757160,
"author": "benPearce",
"author_id": 4490,
"author_profile": "https://Stackoverflow.com/users/4490",
"pm_score": 3,
"selected": false,
"text": "public static bool IsFuture(this DateTime date, DateTime from)\n{\n return date.Date > from.Date;\n}\n\npublic static bool IsFuture(this DateTime date)\n{\n return date.IsFuture(DateTime.Now);\n}\n\npublic static bool IsPast(this DateTime date, DateTime from)\n{\n return date.Date < from.Date;\n}\n\npublic static bool IsPast(this DateTime date)\n{\n return date.IsPast(DateTime.Now);\n}\n"
},
{
"answer_id": 3834758,
"author": "mattmc3",
"author_id": 83144,
"author_profile": "https://Stackoverflow.com/users/83144",
"pm_score": 4,
"selected": false,
"text": "\"abc\".IsLike(\"a*\"); // true\n\"Abc\".IsLike(\"[A-Z][a-z][a-z]\"); // true\n\"abc123\".IsLike(\"*###\"); // true\n\"hat\".IsLike(\"?at\"); // true\n\"joe\".IsLike(\"[!aeiou]*\"); // true\n\n\"joe\".IsLike(\"?at\"); // false\n\"joe\".IsLike(\"[A-Z][a-z][a-z]\"); // false\n public static class StringEntentions {\n /// <summary>\n /// Indicates whether the current string matches the supplied wildcard pattern. Behaves the same\n /// as VB's \"Like\" Operator.\n /// </summary>\n /// <param name=\"s\">The string instance where the extension method is called</param>\n /// <param name=\"wildcardPattern\">The wildcard pattern to match. Syntax matches VB's Like operator.</param>\n /// <returns>true if the string matches the supplied pattern, false otherwise.</returns>\n /// <remarks>See http://msdn.microsoft.com/en-us/library/swf8kaxw(v=VS.100).aspx</remarks>\n public static bool IsLike(this string s, string wildcardPattern) {\n if (s == null || String.IsNullOrEmpty(wildcardPattern)) return false;\n // turn into regex pattern, and match the whole string with ^$\n var regexPattern = \"^\" + Regex.Escape(wildcardPattern) + \"$\";\n\n // add support for ?, #, *, [], and [!]\n regexPattern = regexPattern.Replace(@\"\\[!\", \"[^\")\n .Replace(@\"\\[\", \"[\")\n .Replace(@\"\\]\", \"]\")\n .Replace(@\"\\?\", \".\")\n .Replace(@\"\\*\", \".*\")\n .Replace(@\"\\#\", @\"\\d\");\n\n var result = false;\n try {\n result = Regex.IsMatch(s, regexPattern);\n }\n catch (ArgumentException ex) {\n throw new ArgumentException(String.Format(\"Invalid pattern: {0}\", wildcardPattern), ex);\n }\n return result;\n }\n}\n"
},
{
"answer_id": 3842545,
"author": "scobi",
"author_id": 14582,
"author_profile": "https://Stackoverflow.com/users/14582",
"pm_score": 4,
"selected": false,
"text": "// requires .NET 4\n\npublic static TReturn NullOr<TIn, TReturn>(this TIn obj, Func<TIn, TReturn> func,\n TReturn elseValue = default(TReturn)) where TIn : class\n { return obj != null ? func(obj) : elseValue; }\n\n// versions for CLR 2, which doesn't support optional params\n\npublic static TReturn NullOr<TIn, TReturn>(this TIn obj, Func<TIn, TReturn> func,\n TReturn elseValue) where TIn : class\n { return obj != null ? func(obj) : elseValue; }\npublic static TReturn NullOr<TIn, TReturn>(this TIn obj, Func<TIn, TReturn> func)\n where TIn : class\n { return obj != null ? func(obj) : default(TReturn); }\n var lname = thingy.NullOr(t => t.Name).NullOr(n => n.ToLower());\n var lname = (thingy != null ? thingy.Name : null) != null\n ? thingy.Name.ToLower() : null;\n"
},
{
"answer_id": 3932311,
"author": "RameshVel",
"author_id": 97572,
"author_profile": "https://Stackoverflow.com/users/97572",
"pm_score": 2,
"selected": false,
"text": "public static bool IsNullOrEmpty<TSource>(this List<TSource> src)\n{ \n return (src == null || src.Count == 0);\n}\n public static bool Compare(this FileInfo f1, FileInfo f2, string propertyName)\n{\n try\n {\n PropertyInfo p1 = f1.GetType().GetProperty(propertyName);\n PropertyInfo p2 = f2.GetType().GetProperty(propertyName);\n\n if (p1.GetValue(f1, null) == p2.GetValue(f1, null))\n return true;\n }\n catch (Exception ex)\n {\n return false;\n }\n return false;\n}\n FileInfo fo = new FileInfo(\"c:\\\\netlog.txt\");\nFileInfo f1 = new FileInfo(\"c:\\\\regkey.txt\");\n\nfo.compare(f1, \"CreationTime\");\n"
},
{
"answer_id": 3935547,
"author": "scobi",
"author_id": 14582,
"author_profile": "https://Stackoverflow.com/users/14582",
"pm_score": 3,
"selected": false,
"text": "public static IObservable<T> ToAsyncObservable<T>(this IEnumerable<T> @this)\n{\n return Observable.Create<T>(observer =>\n {\n var task = new Task(() =>\n {\n try\n {\n @this.Run(observer.OnNext);\n observer.OnCompleted();\n }\n catch (Exception e)\n {\n observer.OnError(e);\n }\n });\n\n task.Start();\n\n return () => { };\n });\n}\n new DirectoryInfo(@\"c:\\program files\")\n .EnumerateFiles(\"*\", SearchOption.AllDirectories)\n .ToAsyncObservable()\n .BufferWithTime(TimeSpan.FromSeconds(0.5))\n .ObserveOnDispatcher()\n .Subscribe(\n l => Console.WriteLine(\"{0} received\", l.Count),\n () => Console.WriteLine(\"Done!\"));\n\nfor (;;)\n{\n Thread.Sleep(10);\n Dispatcher.PushFrame(new DispatcherFrame());\n}\n"
},
{
"answer_id": 3936445,
"author": "Richard Szalay",
"author_id": 3603,
"author_profile": "https://Stackoverflow.com/users/3603",
"pm_score": 2,
"selected": false,
"text": "INotifyPropertyChanged GetPropertyValues IObservable<T> Skip(1) IObservable<int> values = viewModel.GetPropertyValues(x => x.IntProperty);\n public static class NotifyPropertyChangeReactiveExtensions\n{\n // Returns the values of property (an Expression) as they change, \n // starting with the current value\n public static IObservable<TValue> GetPropertyValues<TSource, TValue>(\n this TSource source, Expression<Func<TSource, TValue>> property)\n where TSource : INotifyPropertyChanged\n {\n MemberExpression memberExpression = property.Body as MemberExpression;\n\n if (memberExpression == null)\n {\n throw new ArgumentException(\n \"property must directly access a property of the source\");\n }\n\n string propertyName = memberExpression.Member.Name;\n\n Func<TSource, TValue> accessor = property.Compile();\n\n return source.GetPropertyChangedEvents()\n .Where(x => x.EventArgs.PropertyName == propertyName)\n .Select(x => accessor(source))\n .StartWith(accessor(source));\n }\n\n // This is a wrapper around FromEvent(PropertyChanged)\n public static IObservable<IEvent<PropertyChangedEventArgs>>\n GetPropertyChangedEvents(this INotifyPropertyChanged source)\n {\n return Observable.FromEvent<PropertyChangedEventHandler, \n PropertyChangedEventArgs>(\n h => new PropertyChangedEventHandler(h),\n h => source.PropertyChanged += h,\n h => source.PropertyChanged -= h);\n }\n}\n"
},
{
"answer_id": 3940680,
"author": "Will Vousden",
"author_id": 58635,
"author_profile": "https://Stackoverflow.com/users/58635",
"pm_score": 2,
"selected": false,
"text": "public static void Raise(this EventHandler handler, object sender, EventArgs e)\n{\n if (handler != null)\n {\n handler(sender, e);\n }\n}\n\npublic static void Raise<T>(this EventHandler<T> handler, object sender, T e) where T : EventArgs\n{\n if (handler != null)\n {\n handler(sender, e);\n }\n}\n public event EventHandler Bar;\n\npublic void Foo()\n{\n Bar.Raise(this, EventArgs.Empty);\n}\n"
},
{
"answer_id": 3944491,
"author": "dejanb",
"author_id": 376044,
"author_profile": "https://Stackoverflow.com/users/376044",
"pm_score": 2,
"selected": false,
"text": "public static class ControlExtenders\n{\n /// <summary>\n /// Advanced version of find control.\n /// </summary>\n /// <typeparam name=\"T\">Type of control to find.</typeparam>\n /// <param name=\"id\">Control id to find.</param>\n /// <returns>Control of given type.</returns>\n /// <remarks>\n /// If the control with the given id is not found\n /// a new control instance of the given type is returned.\n /// </remarks>\n public static T FindControl<T>(this Control control, string id) where T : Control\n {\n // User normal FindControl method to get the control\n Control _control = control.FindControl(id);\n\n // If control was found and is of the correct type we return it\n if (_control != null && _control is T)\n {\n // Return new control\n return (T)_control;\n }\n\n // Create new control instance\n _control = (T)Activator.CreateInstance(typeof(T));\n\n // Add control to source control so the\n // next it is found and the value can be\n // passed on itd, remember to hide it and\n // set an ID so it can be found next time\n if (!(_control is ExtenderControlBase))\n {\n _control.Visible = false;\n }\n _control.ID = id;\n control.Controls.Add(_control);\n\n // Use reflection to create a new instance of the control\n return (T)_control;\n }\n}\n\npublic static class GenericListExtenders\n{\n /// <summary>\n /// Sorts a generic list by items properties.\n /// </summary>\n /// <typeparam name=\"T\">Type of collection.</typeparam>\n /// <param name=\"list\">Generic list.</param>\n /// <param name=\"fieldName\">Field to sort data on.</param>\n /// <param name=\"sortDirection\">Sort direction.</param>\n /// <remarks>\n /// Use this method when a dinamyc sort field is requiered. If the \n /// sorting field is known manual sorting might improve performance.\n /// </remarks>\n public static void SortObjects<T>(this List<T> list, string fieldName, SortDirection sortDirection)\n {\n PropertyInfo propInfo = typeof(T).GetProperty(fieldName);\n if (propInfo != null)\n {\n Comparison<T> compare = delegate(T a, T b)\n {\n bool asc = sortDirection == SortDirection.Ascending;\n object valueA = asc ? propInfo.GetValue(a, null) : propInfo.GetValue(b, null);\n object valueB = asc ? propInfo.GetValue(b, null) : propInfo.GetValue(a, null);\n return valueA is IComparable ? ((IComparable)valueA).CompareTo(valueB) : 0;\n };\n list.Sort(compare);\n }\n }\n\n /// <summary>\n /// Creates a pagged collection from generic list.\n /// </summary>\n /// <typeparam name=\"T\">Type of collection.</typeparam>\n /// <param name=\"list\">Generic list.</param>\n /// <param name=\"sortField\">Field to sort data on.</param>\n /// <param name=\"sortDirection\">Sort direction.</param>\n /// <param name=\"from\">Page from item index.</param>\n /// <param name=\"to\">Page to item index.</param>\n /// <param name=\"copy\">Creates a copy and returns a new list instead of changing the current one.</param>\n /// <returns>Pagged list collection.</returns>\n public static List<T> Page<T>(this List<T> list, string sortField, bool sortDirection, int from, int to, bool copy)\n {\n List<T> _pageList = new List<T>();\n\n // Copy list\n if (copy)\n {\n T[] _arrList = new T[list.Count];\n list.CopyTo(_arrList);\n _pageList = new List<T>(_arrList);\n }\n else\n {\n _pageList = list;\n }\n\n // Make sure there are enough items in the list\n if (from > _pageList.Count)\n {\n int diff = Math.Abs(from - to);\n from = _pageList.Count - diff;\n }\n if (to > _pageList.Count)\n {\n to = _pageList.Count;\n }\n\n // Sort items\n if (!string.IsNullOrEmpty(sortField))\n {\n SortDirection sortDir = SortDirection.Descending;\n if (!sortDirection) sortDir = SortDirection.Ascending;\n _pageList.SortObjects(sortField, sortDir);\n }\n\n // Calculate max number of items per page\n int count = to - from;\n if (from + count > _pageList.Count) count -= (from + count) - _pageList.Count;\n\n // Get max number of items per page\n T[] pagged = new T[count];\n _pageList.CopyTo(from, pagged, 0, count);\n\n // Return pagged items\n return new List<T>(pagged);\n }\n\n /// <summary>\n /// Shuffle's list items.\n /// </summary>\n /// <typeparam name=\"T\">List type.</typeparam>\n /// <param name=\"list\">Generic list.</param>\n public static void Shuffle<T>(this List<T> list)\n {\n Random rng = new Random();\n for (int i = list.Count - 1; i > 0; i--)\n {\n int swapIndex = rng.Next(i + 1);\n if (swapIndex != i)\n {\n T tmp = list[swapIndex];\n list[swapIndex] = list[i];\n list[i] = tmp;\n }\n }\n }\n\n /// <summary>\n /// Converts generic List to DataTable.\n /// </summary>\n /// <typeparam name=\"T\">Type.</typeparam>\n /// <param name=\"list\">Generic list.</param>\n /// <param name=\"columns\">Name of the columns to copy to the DataTable.</param>\n /// <returns>DataTable.</returns>\n public static DataTable ToDataTable<T>(this List<T> list, string[] columns)\n {\n List<string> _columns = new List<string>(columns);\n DataTable dt = new DataTable();\n\n foreach (PropertyInfo info in typeof(T).GetProperties())\n {\n if (_columns.Contains(info.Name) || columns == null)\n {\n dt.Columns.Add(new DataColumn(info.Name, info.PropertyType));\n }\n }\n foreach (T t in list)\n {\n DataRow row = dt.NewRow();\n foreach (PropertyInfo info in typeof(T).GetProperties())\n {\n if (_columns.Contains(info.Name) || columns == null)\n {\n row[info.Name] = info.GetValue(t, null);\n }\n }\n dt.Rows.Add(row);\n }\n return dt;\n }\n}\n\npublic static class DateTimeExtenders\n{\n /// <summary>\n /// Returns number of month from a string representation.\n /// </summary>\n /// <returns>Number of month.</returns>\n public static int MonthToNumber(this DateTime datetime, string month)\n {\n month = month.ToLower();\n for (int i = 1; i <= 12; i++)\n {\n DateTime _dt = DateTime.Parse(\"1.\" + i + \".2000\");\n string _month = CultureInfo.InvariantCulture.DateTimeFormat.GetMonthName(i).ToLower();\n if (_month == month)\n {\n return i;\n }\n }\n return 0;\n }\n\n /// <summary>\n /// Returns month name from month number.\n /// </summary>\n /// <returns>Name of month.</returns>\n public static string MonthToName(this DateTime datetime, int month)\n {\n for (int i = 1; i <= 12; i++)\n {\n if (i == month)\n {\n return CultureInfo.InvariantCulture.DateTimeFormat.GetMonthName(i);\n }\n }\n return \"\";\n }\n}\n\npublic static class ObjectExtender\n{\n public static object CloneBinary<T>(this T originalObject)\n {\n using (var stream = new System.IO.MemoryStream())\n {\n BinaryFormatter binaryFormatter = new BinaryFormatter();\n binaryFormatter.Serialize(stream, originalObject);\n stream.Position = 0;\n return (T)binaryFormatter.Deserialize(stream);\n }\n }\n\n public static object CloneObject(this object obj)\n {\n using (MemoryStream memStream = new MemoryStream())\n {\n BinaryFormatter binaryFormatter = new BinaryFormatter(null, new StreamingContext(StreamingContextStates.Clone));\n binaryFormatter.Serialize(memStream, obj);\n memStream.Position = 0;\n return binaryFormatter.Deserialize(memStream);\n }\n }\n}\n\npublic static class StringExtenders\n{\n /// <summary>\n /// Returns string as unit.\n /// </summary>\n /// <param name=\"value\">Value.</param>\n /// <returns>Unit</returns>\n public static Unit ToUnit(this string value)\n {\n // Return empty unit\n if (string.IsNullOrEmpty(value))\n return Unit.Empty;\n\n // Trim value\n value = value.Trim();\n\n // Return pixel unit\n if (value.EndsWith(\"px\"))\n {\n // Set unit type\n string _int = value.Replace(\"px\", \"\");\n\n // Try parsing to int\n double _val = 0;\n if (!double.TryParse(_int, out _val))\n {\n // Invalid value\n return Unit.Empty;\n }\n\n // Return unit\n return new Unit(_val, UnitType.Pixel);\n }\n\n // Return percent unit\n if (value.EndsWith(\"%\"))\n {\n // Set unit type\n string _int = value.Replace(\"%\", \"\");\n\n // Try parsing to int\n double _val = 0;\n if (!double.TryParse(_int, out _val))\n {\n // Invalid value\n return Unit.Empty;\n }\n\n // Return unit\n return new Unit(_val, UnitType.Percentage);\n }\n\n // No match found\n return new Unit();\n }\n\n /// <summary>\n /// Returns alternative string if current string is null or empty.\n /// </summary>\n /// <param name=\"str\"></param>\n /// <param name=\"alternative\"></param>\n /// <returns></returns>\n public static string Alternative(this string str, string alternative)\n {\n if (string.IsNullOrEmpty(str)) return alternative;\n return str;\n }\n\n /// <summary>\n /// Removes all HTML tags from string.\n /// </summary>\n /// <param name=\"html\">String containing HTML tags.</param>\n /// <returns>String with no HTML tags.</returns>\n public static string StripHTML(this string html)\n {\n string nohtml = Regex.Replace(html, \"<(.|\\n)*?>\", \"\");\n nohtml = nohtml.Replace(\"\\r\\n\", \"\").Replace(\"\\n\", \"\").Replace(\" \", \"\").Trim();\n return nohtml;\n }\n}\n Control c = this.FindControl(\"tbName\");\nif (c != null)\n{\n // Do something with c\n customer.Name = ((TextBox)c).Text;\n}\n TextBox c = this.FindControl<TextBox>(\"tbName\");\ncustomer.Name = c.Text;\n string str = \"\";\nif (string.IsNullOrEmpty(str))\n{\n str = \"I'm empty!\";\n}\n str = str.Alternative(\"I'm empty!\");\n"
},
{
"answer_id": 3973579,
"author": "KeithS",
"author_id": 436376,
"author_profile": "https://Stackoverflow.com/users/436376",
"pm_score": 2,
"selected": false,
"text": "public static class FluentOrderingExtensions\n public class FluentOrderer<T> : IEnumerable<T>\n {\n internal List<Comparison<T>> Comparers = new List<Comparison<T>>();\n\n internal IEnumerable<T> Source;\n\n public FluentOrderer(IEnumerable<T> source)\n {\n Source = source;\n }\n\n #region Implementation of IEnumerable\n\n public IEnumerator<T> GetEnumerator()\n {\n var workingArray = Source.ToArray();\n Array.Sort(workingArray, IterativeComparison);\n\n foreach(var element in workingArray) yield return element;\n }\n\n private int IterativeComparison(T a, T b)\n {\n foreach (var comparer in Comparers)\n {\n var result = comparer(a,b);\n if(result != 0) return result;\n }\n return 0;\n }\n\n IEnumerator IEnumerable.GetEnumerator()\n {\n return GetEnumerator();\n }\n\n #endregion\n }\n\n public static FluentOrderer<T> OrderFluentlyBy<T,TResult>(this IEnumerable<T> source, Func<T,TResult> predicate) \n where TResult : IComparable<TResult>\n {\n var result = new FluentOrderer<T>(source);\n result.Comparers.Add((a,b)=>predicate(a).CompareTo(predicate(b)));\n return result;\n }\n\n public static FluentOrderer<T> OrderFluentlyByDescending<T,TResult>(this IEnumerable<T> source, Func<T,TResult> predicate) \n where TResult : IComparable<TResult>\n {\n var result = new FluentOrderer<T>(source);\n result.Comparers.Add((a,b)=>predicate(a).CompareTo(predicate(b)) * -1);\n return result;\n }\n\n public static FluentOrderer<T> ThenBy<T, TResult>(this FluentOrderer<T> source, Func<T, TResult> predicate)\n where TResult : IComparable<TResult>\n {\n source.Comparers.Add((a, b) => predicate(a).CompareTo(predicate(b)));\n return source;\n }\n\n public static FluentOrderer<T> ThenByDescending<T, TResult>(this FluentOrderer<T> source, Func<T, TResult> predicate)\n where TResult : IComparable<TResult>\n {\n source.Comparers.Add((a, b) => predicate(a).CompareTo(predicate(b)) * -1);\n return source;\n }\n}\n var myFluentlyOrderedList = GetABunchOfComplexObjects()\n .OrderFluentlyBy(x=>x.PropertyA)\n .ThenByDescending(x=>x.PropertyB)\n .ThenBy(x=>x.SomeMethod())\n .ThenBy(x=>SomeOtherMethodAppliedTo(x))\n .ToList();\n"
},
{
"answer_id": 3997753,
"author": "John",
"author_id": 83091,
"author_profile": "https://Stackoverflow.com/users/83091",
"pm_score": 0,
"selected": false,
"text": "public static class TypeExtensions\n{\n public static string GenerateClassDefinition(this Type type)\n {\n var properties = type.GetFields();\n var sb = new StringBuilder();\n var classtext = @\"private class $name\n {\n $props}\";\n\n foreach (var p in GetTypeInfo(type))\n {\n sb.AppendFormat(\" public {0} {1} \", p.Item2, p.Item1).AppendLine(\" { get; set; }\");\n }\n\n return classtext.Replace(\"$name\", type.Name).Replace(\"$props\", sb.ToString());\n }\n\n #region Private Methods\n private static List<Tuple<string, string>> GetTypeInfo(Type type)\n {\n var ret = new List<Tuple<string, string>>();\n var fields = type.GetFields();\n var props = type.GetProperties();\n\n foreach(var p in props) ret.Add(new Tuple<string, string>(p.Name, TranslateType(p.PropertyType))); \n foreach(var f in fields) ret.Add(new Tuple<string, string>(f.Name, TranslateType(f.FieldType)));\n\n return ret;\n }\n\n\n private static string TranslateType(Type input)\n {\n string ret;\n\n if (Nullable.GetUnderlyingType(input) != null)\n {\n ret = string.Format(\"{0}?\", TranslateType(Nullable.GetUnderlyingType(input)));\n }\n else\n {\n switch (input.Name)\n {\n case \"Int32\": ret = \"int\"; break;\n case \"Int64\": ret = \"long\"; break;\n case \"IntPtr\": ret = \"long\"; break;\n case \"Boolean\": ret = \"bool\"; break;\n case \"String\":\n case \"Char\":\n case \"Decimal\":\n ret = input.Name.ToLower(); break;\n default: ret = input.Name; break;\n }\n }\n\n return ret;\n }\n #endregion\n}\n Process.GetProcesses().First().GetType().GenerateClassDefinition();\n Process.GetProcesses().First().GetType().GenerateClassDefinition().Dump();\n"
},
{
"answer_id": 4001342,
"author": "KeithS",
"author_id": 436376,
"author_profile": "https://Stackoverflow.com/users/436376",
"pm_score": 3,
"selected": false,
"text": "public static T ObjectWithMin<T, TResult>(this IEnumerable<T> sequence, Func<T, TResult> predicate)\n where T : class\n where TResult : IComparable\n{\n if (!sequence.Any()) return null;\n\n //get the first object with its predicate value\n var seed = sequence.Select(x => new {Object = x, Value = predicate(x)}).FirstOrDefault();\n //compare against all others, replacing the accumulator with the lesser value\n //tie goes to first object found\n return\n sequence.Select(x => new {Object = x, Value = predicate(x)})\n .Aggregate(seed,(acc, x) => acc.Value.CompareTo(x.Value) <= 0 ? acc : x).Object;\n}\n\npublic static T ObjectWithMax<T, TResult>(this IEnumerable<T> sequence, Func<T, TResult> predicate)\n where T : class\n where TResult : IComparable\n{\n if (!sequence.Any()) return null;\n\n //get the first object with its predicate value\n var seed = sequence.Select(x => new {Object = x, Value = predicate(x)}).FirstOrDefault();\n //compare against all others, replacing the accumulator with the greater value\n //tie goes to last object found\n return\n sequence.Select(x => new {Object = x, Value = predicate(x)})\n .Aggregate(seed, (acc, x) => acc.Value.CompareTo(x.Value) > 0 ? acc : x).Object;\n}\n var myObject = myList.ObjectWithMin(x=>x.PropA);\n var myObject = myList.OrderBy(x=>x.PropA).FirstOrDefault(); //O(nlog(n)) and unstable\n var myObject = myList.Where(x=>x.PropA == myList.Min(x=>x.PropA)).FirstOrDefault(); //O(N^2) but stable\n var minValue = myList.Min(x=>x.PropA);\nvar myObject = myList.Where(x=>x.PropA == minValue).FirstOrDefault(); //not a one-liner, and though linear and stable it's slower (evaluates the enumerable twice)\n"
},
{
"answer_id": 4001549,
"author": "KeithS",
"author_id": 436376,
"author_profile": "https://Stackoverflow.com/users/436376",
"pm_score": 1,
"selected": false,
"text": "public enum ParseFailBehavior\n{\n ReturnNull,\n ReturnDefault,\n ThrowException\n}\n\npublic static T? ParseNullableEnum<T>(this string theValue, ParseFailBehavior desiredBehavior = ParseFailBehavior.ReturnNull) where T:struct\n{\n T output;\n T? result = Enum.TryParse<T>(theValue, out output) \n ? (T?)output\n : desiredBehavior == ParseFailBehavior.ReturnDefault\n ? (T?)default(T)\n : null;\n\n if(result == null && desiredBehavior == ParseFailBehavior.ThrowException)\n throw new ArgumentException(\"Parse Failed for value {0} of enum type {1}\".\n FormatWith(theValue, typeof(T).Name)); \n}\n public static T? ParseNummableEnum<T>(this string theValue)\n{\n return theValue.ParseNullableEnum<T>(ParseFailBehavior.ReturnNull);\n}\n\npublic static T? ParseNullableEnum<T>(this string theValue, \n ParseFailBehavior desiredBehavior) where T:struct\n{\n try\n {\n return (T?) Enum.Parse(typeof (T), theValue);\n }\n catch (Exception)\n {\n if(desiredBehavior == ParseFailBehavior.ThrowException) throw;\n }\n\n return desiredBehavior == ParseFailBehavior.ReturnDefault ? (T?)default(T) : null;\n}\n //returns null if OptionOne isn't an enum constant\nvar myEnum = \"OptionOne\".ParseNullableEnum<OptionEnum>(); \n\n//guarantees a return value IF the enum has a \"zero\" constant value (generally a good practice)\nvar myEnum = \"OptionTwo\".ParseNullableEnum<OptionEnum>(ParseFailBehavior.ReturnDefault).Value \n"
},
{
"answer_id": 4152788,
"author": "Will Vousden",
"author_id": 58635,
"author_profile": "https://Stackoverflow.com/users/58635",
"pm_score": 2,
"selected": false,
"text": "public static T GetAttribute<T>(this ICustomAttributeProvider provider, bool inherit = false, int index = 0) where T : Attribute\n{\n return provider.GetAttribute(typeof(T), inherit, index) as T;\n}\n\npublic static Attribute GetAttribute(this ICustomAttributeProvider provider, Type type, bool inherit = false, int index = 0)\n{\n bool exists = provider.IsDefined(type, inherit);\n if (!exists)\n {\n return null;\n }\n\n object[] attributes = provider.GetCustomAttributes(type, inherit);\n if (attributes != null && attributes.Length != 0)\n {\n return attributes[index] as Attribute;\n }\n else\n {\n return null;\n }\n}\n public static string GetDescription(this Enum value)\n{\n var fieldInfo = value.GetType().GetField(value.ToString());\n var attribute = fieldInfo.GetAttribute<DescriptionAttribute>();\n return attribute != null ? attribute.Description : null;\n}\n"
},
{
"answer_id": 4178109,
"author": "Roman A. Taycher",
"author_id": 259130,
"author_profile": "https://Stackoverflow.com/users/259130",
"pm_score": 0,
"selected": false,
"text": "using System;\nnamespace SmalltalkBooleanExtensionMethods\n{\n\n public static class BooleanExtension\n {\n public static T ifTrue<T> (this bool aBoolean, Func<T> method)\n {\n if (aBoolean)\n return (T)method();\n else\n return default(T);\n }\n\n public static void ifTrue (this bool aBoolean, Action method)\n {\n if (aBoolean)\n method();\n }\n\n\n public static T ifFalse<T> (this bool aBoolean, Func<T> method)\n {\n if (!aBoolean)\n return (T)method();\n else\n return default(T);\n }\n\n public static void ifFalse (this bool aBoolean, Action method)\n {\n if (!aBoolean)\n method();\n }\n\n\n public static T ifTrueifFalse<T> (this Boolean aBoolean, Func<T> methodA, Func<T> methodB)\n {\n if (aBoolean)\n return (T)methodA();\n else\n return (T)methodB();\n }\n\n public static void ifTrueifFalse (this Boolean aBoolean, Action methodA, Action methodB)\n {\n if (aBoolean)\n methodA();\n else\n methodB();\n }\n\n }\n\n\n}\n using System;\n\nnamespace SmalltalkBooleanExtensionMethods\n{\n public static class IntExtension\n {\n public static int timesRepeat<T>(this int x, Func<T> method)\n {\n for (int i = x; i > 0; i--)\n {\n method();\n }\n\n return x;\n }\n\n public static int timesRepeat(this int x, Action method)\n {\n for (int i = x; i > 0; i--)\n {\n method();\n }\n\n return x;\n }\n }\n}\n using System;\nusing SmalltalkBooleanExtensionMethods;\nusing NUnit.Framework;\n\nnamespace SmalltalkBooleanExtensionMethodsTest\n{\n [TestFixture]\n public class SBEMTest\n {\n int i;\n bool itWorks;\n\n [SetUp]\n public void Init()\n {\n\n i = 0;\n itWorks = false;\n }\n\n [Test()]\n public void TestifTrue()\n {\n\n itWorks = (true.ifTrue(() => true));\n Assert.IsTrue(itWorks);\n }\n [Test()]\n public void TestifFalse()\n {\n itWorks = (false.ifFalse(() => true));\n Assert.IsTrue(itWorks);\n }\n\n [Test()]\n public void TestifTrueifFalse()\n {\n itWorks = false.ifTrueifFalse(() => false, () => true);\n Assert.IsTrue(itWorks);\n itWorks = false;\n itWorks = true.ifTrueifFalse(() => true, () => false);\n Assert.IsTrue(itWorks);\n }\n\n [Test()]\n public void TestTimesRepeat()\n {\n (5).timesRepeat(() => i = i + 1);\n Assert.AreEqual(i, 5);\n }\n\n [Test()]\n public void TestVoidMethodIfTrue()\n {\n\n true.ifTrue(() => SetItWorksBooleanToTrue());\n Assert.IsTrue(itWorks);\n }\n\n [Test()]\n public void TestVoidMethodIfFalse()\n {\n\n false.ifFalse(() => SetItWorksBooleanToTrue());\n Assert.IsTrue(itWorks);\n }\n\n public void TestVoidMethodIfTrueIfFalse()\n {\n true.ifTrueifFalse(() => SetItWorksBooleanToTrue(), () => SetItWorksBooleanToFalse());\n false.ifTrueifFalse(() => SetItWorksBooleanToFalse(), () => SetItWorksBooleanToTrue());\n Assert.IsTrue(itWorks);\n\n }\n\n public void TestVoidMethodTimesRepeat()\n {\n (5).timesRepeat(() => AddOneToi());\n Assert.AreEqual(i, 5);\n }\n\n public void SetItWorksBooleanToTrue()\n {\n itWorks = true;\n }\n\n public void SetItWorksBooleanToFalse()\n {\n itWorks = false;\n }\n\n public void AddOneToi()\n {\n i = i + 1;\n }\n }\n}\n"
},
{
"answer_id": 4339648,
"author": "Nicholas Carey",
"author_id": 467473,
"author_profile": "https://Stackoverflow.com/users/467473",
"pm_score": 1,
"selected": false,
"text": "namespace Extensions.String\n{\n using System.Text.RegularExpressions;\n\n public static class Extensions\n {\n /// <summary>\n /// Normalizes whitespace in a string.\n /// Leading/Trailing whitespace is eliminated and\n /// all sequences of internal whitespace are reduced to\n /// a single SP (ASCII 0x20) character.\n /// </summary>\n /// <param name=\"s\">The string whose whitespace is to be normalized</param>\n /// <returns>a normalized string</returns>\n public static string NormalizeWS( this string @this )\n {\n string src = @this ?? \"\" ;\n string normalized = rxWS.Replace( src , m =>{\n bool isLeadingTrailingWS = ( m.Index == 0 || m.Index+m.Length == src.Length ? true : false ) ;\n string p = ( isLeadingTrailingWS ? \"\" : \" \" ) ;\n return p ;\n }) ;\n\n return normalized ;\n\n }\n private static Regex rxWS = new Regex( @\"\\s+\" ) ;\n }\n}\n"
},
{
"answer_id": 4525903,
"author": "Chris",
"author_id": 553218,
"author_profile": "https://Stackoverflow.com/users/553218",
"pm_score": 0,
"selected": false,
"text": " public static class Utilities\n{\n public enum DropDownListSelectionType\n {\n ByValue,\n ByText\n }\n\n public static void SelectItem(this System.Web.UI.WebControls.DropDownList drp, string selectedValue, DropDownListSelectionType type)\n {\n drp.ClearSelection();\n System.Web.UI.WebControls.ListItem li;\n if (type == DropDownListSelectionType.ByValue)\n li = drp.Items.FindByValue(selectedValue.Trim());\n else\n li = drp.Items.FindByText(selectedValue.Trim());\n if (li != null)\n li.Selected = true;\n }}\n DropDownList1.SelectItem(\"ABCD\", Utilities.DropDownListSelectionType.ByText);\n DropDownList1.SelectItem(\"11\", Utilities.DropDownListSelectionType.ByValue);\n"
},
{
"answer_id": 4689138,
"author": "HuseyinUslu",
"author_id": 170181,
"author_profile": "https://Stackoverflow.com/users/170181",
"pm_score": 3,
"selected": false,
"text": "public static Bitmap GrayScale(this Bitmap bitmap)\n{\n Bitmap newBitmap = new Bitmap(bitmap.Width, bitmap.Height);\n Graphics g = Graphics.FromImage(newBitmap);\n\n //the grayscale ColorMatrix\n ColorMatrix colorMatrix = new ColorMatrix(new float[][] {\n new float[] {.3f, .3f, .3f, 0, 0},\n new float[] {.59f, .59f, .59f, 0, 0},\n new float[] {.11f, .11f, .11f, 0, 0},\n new float[] {0, 0, 0, 1, 0},\n new float[] {0, 0, 0, 0, 1}\n });\n\n ImageAttributes attributes = new ImageAttributes();\n attributes.SetColorMatrix(colorMatrix);\n g.DrawImage(bitmap, new Rectangle(0, 0, bitmap.Width, bitmap.Height), 0, 0, bitmap.Width, bitmap.Height, GraphicsUnit.Pixel, attributes);\n g.Dispose();\n return newBitmap;\n}\n Bitmap grayscaled = bitmap.GrayScale()\n"
},
{
"answer_id": 4689170,
"author": "HuseyinUslu",
"author_id": 170181,
"author_profile": "https://Stackoverflow.com/users/170181",
"pm_score": 0,
"selected": false,
"text": "public static class InvokeExtensions\n{\n public static void InvokeHandler(this Control control, MethodInvoker del) // Sync. control-invoke extension.\n {\n if (control.InvokeRequired)\n {\n control.Invoke(del);\n return; \n }\n del(); // run the actual code.\n }\n\n public static void AsyncInvokeHandler(this Control control, MethodInvoker del) // Async. control-invoke extension.\n {\n if (control.InvokeRequired)\n {\n control.BeginInvoke(del);\n return; \n }\n del(); // run the actual code.\n }\n}\n this.TreeView.AsyncInvokeHandler(() =>\n {\n this.Text = 'xyz'\n });\n"
},
{
"answer_id": 4690969,
"author": "19WAS85",
"author_id": 79191,
"author_profile": "https://Stackoverflow.com/users/79191",
"pm_score": 1,
"selected": false,
"text": "var names = new[] { \"Wagner\", \"Francine\", \"Arthur\", \"Bernardo\" };\n\nnames.ToString(\"Name: {0}\\n\");\n// Name: Wagner\n// Name: Francine\n// Name: Arthur\n// Name: Bernardo\n\nnames.ToString(name => name.Length > 6 ? String.Format(\"{0} \", name) : String.Empty);\n// Francine Bernardo\n\nnames.Join(\" - \");\n// Wagner - Francine - Arthur - Bernardo\n public static string ToString<T>(this IEnumerable<T> self, string format)\n{\n return self.ToString(i => String.Format(format, i));\n}\n\npublic static string ToString<T>(this IEnumerable<T> self, Func<T, object> function)\n{\n var result = new StringBuilder();\n\n foreach (var item in self) result.Append(function(item));\n\n return result.ToString();\n}\n\npublic static string Join<T>(this IEnumerable<T> self, string separator)\n{\n return String.Join(separator, values: self.ToArray());\n}\n"
},
{
"answer_id": 4714651,
"author": "Shaul Behr",
"author_id": 7850,
"author_profile": "https://Stackoverflow.com/users/7850",
"pm_score": 2,
"selected": false,
"text": "out public static TVal GetValueOrDefault<TKey, TVal>(this IDictionary<TKey, TVal> d, TKey key) {\n if (d.ContainsKey(key))\n return d[key];\n return default(TVal);\n}\n"
},
{
"answer_id": 4723915,
"author": "HuseyinUslu",
"author_id": 170181,
"author_profile": "https://Stackoverflow.com/users/170181",
"pm_score": 2,
"selected": false,
"text": "public static class ControlExtensions\n{\n public static void DoubleBuffer(this Control control) \n {\n // http://stackoverflow.com/questions/76993/how-to-double-buffer-net-controls-on-a-form/77233#77233\n // Taxes: Remote Desktop Connection and painting: http://blogs.msdn.com/oldnewthing/archive/2006/01/03/508694.aspx\n\n if (System.Windows.Forms.SystemInformation.TerminalServerSession) return;\n System.Reflection.PropertyInfo dbProp = typeof(System.Windows.Forms.Control).GetProperty(\"DoubleBuffered\", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance);\n dbProp.SetValue(control, true, null);\n }\n}\n this.someControl.DoubleBuffer();\n"
},
{
"answer_id": 4838802,
"author": "Steve Potter",
"author_id": 574723,
"author_profile": "https://Stackoverflow.com/users/574723",
"pm_score": 2,
"selected": false,
"text": "new[] { \"first\", \"second\", \"third\" }.Each((value, index) =>\n{\n if (value.Contains(\"d\"))\n return false;\n Console.Write(value);\n return true;\n});\n /// <summary>\n/// Generic iterator function that is useful to replace a foreach loop with at your discretion. A provided action is performed on each element.\n/// </summary>\n/// <typeparam name=\"T\"></typeparam>\n/// <param name=\"source\"></param>\n/// <param name=\"action\">Function that takes in the current value in the sequence. \n/// <returns></returns>\npublic static IEnumerable<T> Each<T>(this IEnumerable<T> source, Action<T> action)\n{\n return source.Each((value, index) =>\n {\n action(value);\n return true;\n });\n}\n\n\n/// <summary>\n/// Generic iterator function that is useful to replace a foreach loop with at your discretion. A provided action is performed on each element.\n/// </summary>\n/// <typeparam name=\"T\"></typeparam>\n/// <param name=\"source\"></param>\n/// <param name=\"action\">Function that takes in the current value and its index in the sequence. \n/// <returns></returns>\npublic static IEnumerable<T> Each<T>(this IEnumerable<T> source, Action<T, int> action)\n{\n return source.Each((value, index) =>\n {\n action(value, index);\n return true;\n });\n}\n\n/// <summary>\n/// Generic iterator function that is useful to replace a foreach loop with at your discretion. A provided action is performed on each element.\n/// </summary>\n/// <typeparam name=\"T\"></typeparam>\n/// <param name=\"source\"></param>\n/// <param name=\"action\">Function that takes in the current value in the sequence. Returns a value indicating whether the iteration should continue. So return false if you don't want to iterate anymore.</param>\n/// <returns></returns>\npublic static IEnumerable<T> Each<T>(this IEnumerable<T> source, Func<T, bool> action)\n{\n return source.Each((value, index) =>\n {\n return action(value);\n });\n}\n\n/// <summary>\n/// Generic iterator function that is useful to replace a foreach loop with at your discretion. A provided action is performed on each element.\n/// </summary>\n/// <typeparam name=\"T\"></typeparam>\n/// <param name=\"source\"></param>\n/// <param name=\"action\">Function that takes in the current value and its index in the sequence. Returns a value indicating whether the iteration should continue. So return false if you don't want to iterate anymore.</param>\n/// <returns></returns>\npublic static IEnumerable<T> Each<T>(this IEnumerable<T> source, Func<T, int, bool> action)\n{\n if (source == null)\n return source;\n\n int index = 0;\n foreach (var sourceItem in source)\n {\n if (!action(sourceItem, index))\n break;\n index++;\n }\n return source;\n}\n"
},
{
"answer_id": 5569514,
"author": "fre0n",
"author_id": 252004,
"author_profile": "https://Stackoverflow.com/users/252004",
"pm_score": 0,
"selected": false,
"text": "Equals(object) IEquatable<T> IsEqualTo Equals(object) if (myTerriblyComplexObject.IsEqualTo(myOtherTerriblyComplexObject))\n{\n // Do something terribly interesting.\n}\n Equals(object, object) thisObject Equals(object) thisObject thisObject Equals(object) thisObject IEquatable<T> otherObject T Equals(T) IEnumerable thisObject Equals(object) thisObject /// <summary>\n/// Provides extension methods to determine if objects are equal.\n/// </summary>\npublic static class EqualsEx\n{\n /// <summary>\n /// The <see cref=\"Type\"/> of <see cref=\"string\"/>.\n /// </summary>\n private static readonly Type StringType = typeof(string);\n\n /// <summary>\n /// The <see cref=\"Type\"/> of <see cref=\"object\"/>.\n /// </summary>\n private static readonly Type ObjectType = typeof(object);\n\n /// <summary>\n /// The <see cref=\"Type\"/> of <see cref=\"IEquatable{T}\"/>.\n /// </summary>\n private static readonly Type EquatableType = typeof(IEquatable<>);\n\n /// <summary>\n /// Determines whether <paramref name=\"thisObject\"/> is equal to <paramref name=\"otherObject\"/>.\n /// </summary>\n /// <param name=\"thisObject\">\n /// This object.\n /// </param>\n /// <param name=\"otherObject\">\n /// The other object.\n /// </param>\n /// <returns>\n /// True, if they are equal, otherwise false.\n /// </returns>\n public static bool IsEqualTo(this object thisObject, object otherObject)\n {\n if (Equals(thisObject, otherObject))\n {\n // Always check Equals first. If the object has overridden Equals, use it. This will also capture the case where both are the same reference.\n return true;\n }\n\n if (thisObject == null)\n {\n // Because Equals(object, object) returns true if both are null, if either is null, return false.\n return false;\n }\n\n var thisObjectType = thisObject.GetType();\n var equalsMethod = thisObjectType.GetMethod(\"Equals\", BindingFlags.Public | BindingFlags.Instance, null, new[] { ObjectType }, null);\n if (equalsMethod.DeclaringType == thisObjectType)\n {\n // thisObject overrides Equals, and we have already failed the Equals test, so return false.\n return false;\n }\n\n var otherObjectType = otherObject == null ? null : otherObject.GetType();\n\n // If thisObject inherits from IEquatable<>, and otherObject can be passed into its Equals method, use it.\n var equatableTypes = thisObjectType.GetInterfaces().Where( // Get interfaces of thisObjectType that...\n i => i.IsGenericType // ...are generic...\n && i.GetGenericTypeDefinition() == EquatableType // ...and are IEquatable of some type...\n && (otherObjectType == null || i.GetGenericArguments()[0].IsAssignableFrom(otherObjectType))); // ...and otherObjectType can be assigned to the IEquatable's type.\n\n if (equatableTypes.Any())\n {\n // If we found any interfaces that meed our criteria, invoke the Equals method for each interface.\n // If any return true, return true. If all return false, return false.\n return equatableTypes\n .Select(equatableType => equatableType.GetMethod(\"Equals\", BindingFlags.Public | BindingFlags.Instance))\n .Any(equatableEqualsMethod => (bool)equatableEqualsMethod.Invoke(thisObject, new[] { otherObject }));\n }\n\n if (thisObjectType != StringType && thisObject is IEnumerable && otherObject is IEnumerable)\n {\n // If both are IEnumerable, check their items.\n var thisEnumerable = ((IEnumerable)thisObject).Cast<object>();\n var otherEnumerable = ((IEnumerable)otherObject).Cast<object>();\n\n return thisEnumerable.SequenceEqual(otherEnumerable, IsEqualToComparer.Instance);\n }\n\n if (thisObjectType != otherObjectType)\n {\n // If they have different types, they cannot be equal.\n return false;\n }\n\n if (thisObjectType.IsValueType || thisObjectType == StringType)\n {\n // If it is a value type, we have already determined that they are not equal, so return false.\n return false;\n }\n\n // Recurse into each public property: if any are not equal, return false. If all are true, return true.\n return !(from propertyInfo in thisObjectType.GetProperties()\n let thisPropertyValue = propertyInfo.GetValue(thisObject, null)\n let otherPropertyValue = propertyInfo.GetValue(otherObject, null)\n where !thisPropertyValue.IsEqualTo(otherPropertyValue)\n select thisPropertyValue).Any();\n }\n\n /// <summary>\n /// A <see cref=\"IEqualityComparer{T}\"/> to be used when comparing sequences of collections.\n /// </summary>\n private class IsEqualToComparer : IEqualityComparer<object>\n {\n /// <summary>\n /// The singleton instance of <see cref=\"IsEqualToComparer\"/>.\n /// </summary>\n public static readonly IsEqualToComparer Instance;\n\n /// <summary>\n /// Initializes static members of the <see cref=\"EqualsEx.IsEqualToComparer\"/> class.\n /// </summary>\n static IsEqualToComparer()\n {\n Instance = new IsEqualToComparer();\n }\n\n /// <summary>\n /// Prevents a default instance of the <see cref=\"EqualsEx.IsEqualToComparer\"/> class from being created.\n /// </summary>\n private IsEqualToComparer()\n {\n }\n\n /// <summary>\n /// Determines whether the specified objects are equal.\n /// </summary>\n /// <param name=\"x\">\n /// The first object to compare.\n /// </param>\n /// <param name=\"y\">\n /// The second object to compare.\n /// </param>\n /// <returns>\n /// true if the specified objects are equal; otherwise, false.\n /// </returns>\n bool IEqualityComparer<object>.Equals(object x, object y)\n {\n return x.IsEqualTo(y);\n }\n\n /// <summary>\n /// Not implemented - throws an <see cref=\"NotImplementedException\"/>.\n /// </summary>\n /// <param name=\"obj\">\n /// The <see cref=\"object\"/> for which a hash code is to be returned.\n /// </param>\n /// <returns>\n /// A hash code for the specified object.\n /// </returns>\n int IEqualityComparer<object>.GetHashCode(object obj)\n {\n throw new NotImplementedException();\n }\n }\n}\n"
},
{
"answer_id": 5709002,
"author": "Amy B",
"author_id": 8155,
"author_profile": "https://Stackoverflow.com/users/8155",
"pm_score": 0,
"selected": false,
"text": "List<Order> orders = dataContext.Orders.FetchByIds(\n orderIdChunks,\n list => row => list.Contains(row.OrderId)\n);\n\nList<Customer> customers = dataContext.Orders.FetchByIds(\n orderIdChunks,\n list => row => list.Contains(row.OrderId),\n row => row.Customer\n);\n\npublic static List<ResultType> FetchByIds<RecordType, ResultType>(\n this IQueryable<RecordType> querySource,\n List<List<int>> IdChunks,\n Func<List<int>, Expression<Func<RecordType, bool>>> filterExpressionGenerator,\n Expression<Func<RecordType, ResultType>> projectionExpression\n ) where RecordType : class\n{\n List<ResultType> result = new List<ResultType>();\n foreach (List<int> chunk in IdChunks)\n {\n Expression<Func<RecordType, bool>> filterExpression =\n filterExpressionGenerator(chunk);\n\n IQueryable<ResultType> query = querySource\n .Where(filterExpression)\n .Select(projectionExpression);\n\n List<ResultType> rows = query.ToList();\n result.AddRange(rows);\n }\n\n return result;\n}\n\npublic static List<RecordType> FetchByIds<RecordType>(\n this IQueryable<RecordType> querySource,\n List<List<int>> IdChunks,\n Func<List<int>, Expression<Func<RecordType, bool>>> filterExpressionGenerator\n ) where RecordType : class\n{\n Expression<Func<RecordType, RecordType>> identity = r => r;\n\n return FetchByIds(\n querySource,\n IdChunks,\n filterExpressionGenerator,\n identity\n );\n}\n"
},
{
"answer_id": 5751106,
"author": "Chuck Savage",
"author_id": 353147,
"author_profile": "https://Stackoverflow.com/users/353147",
"pm_score": 2,
"selected": false,
"text": "/// <summary>\n/// Open with default 'open' program\n/// </summary>\n/// <param name=\"value\"></param>\npublic static Process Open(this FileInfo value)\n{\n if (!value.Exists)\n throw new FileNotFoundException(\"File doesn't exist\");\n Process p = new Process();\n p.StartInfo.FileName = value.FullName;\n p.StartInfo.Verb = \"Open\";\n p.Start();\n return p;\n}\n\n/// <summary>\n/// Print the file\n/// </summary>\n/// <param name=\"value\"></param>\npublic static void Print(this FileInfo value)\n{\n if (!value.Exists)\n throw new FileNotFoundException(\"File doesn't exist\");\n Process p = new Process();\n p.StartInfo.FileName = value.FullName;\n p.StartInfo.Verb = \"Print\";\n p.Start();\n}\n\n/// <summary>\n/// Send this file to the Recycle Bin\n/// </summary>\n/// <exception cref=\"File doesn't exist\" />\n/// <param name=\"value\"></param>\npublic static void Recycle(this FileInfo value)\n{ \n value.Recycle(false);\n}\n\n/// <summary>\n/// Send this file to the Recycle Bin\n/// On show, if person refuses to send file to the recycle bin, \n/// exception is thrown or otherwise delete fails\n/// </summary>\n/// <exception cref=\"File doesn't exist\" />\n/// <exception cref=\"On show, if user refuses, throws exception 'The operation was canceled.'\" />\n/// <param name=\"value\">File being recycled</param>\n/// <param name=\"showDialog\">true to show pop-up</param>\npublic static void Recycle(this FileInfo value, bool showDialog)\n{\n if (!value.Exists)\n throw new FileNotFoundException(\"File doesn't exist\");\n if( showDialog )\n FileSystem.DeleteFile\n (value.FullName, UIOption.AllDialogs, \n RecycleOption.SendToRecycleBin);\n else\n FileSystem.DeleteFile\n (value.FullName, UIOption.OnlyErrorDialogs, \n RecycleOption.SendToRecycleBin);\n}\n new FileInfo(\"C:\\image.jpg\").Open();\n new FileInfo(\"C:\\image.jpg\").Print();\n Microsoft.VisualBasic using Microsoft.VisualBasic.FileIO; new FileInfo(\"C:\\image.jpg\").Recycle();\n // let user have a chance to cancel send to recycle bin.\nnew FileInfo(\"C:\\image.jpg\").Recycle(true);\n"
},
{
"answer_id": 5913908,
"author": "John",
"author_id": 83091,
"author_profile": "https://Stackoverflow.com/users/83091",
"pm_score": 0,
"selected": false,
"text": "/// <summary>\n/// Compares the files to see if they are different. \n/// First checks file size\n/// Then modified if the file is larger than the specified size\n/// Then compares the bytes\n/// </summary>\n/// <param name=\"file1\">The source file</param>\n/// <param name=\"file2\">The destination file</param>\n/// <param name=\"mb\">Skip the smart check if the file is larger than this many megabytes. Default is 10.</param>\n/// <returns></returns>\npublic static bool IsDifferentThan(this FileInfo file1, FileInfo file2, int mb = 10)\n{\n var ret = false;\n\n // different size is a different file\n if(file1.Length != file2.Length) return true;\n\n // if the file times are different and the file is bigger than 10mb flag it for updating\n if(file1.LastWriteTimeUtc > file2.LastWriteTimeUtc && file1.Length > ((mb*1024)*1024)) return true;\n\n var f1 = File.ReadAllBytes(file1.FullName);\n var f2 = File.ReadAllBytes(file2.FullName);\n\n // loop through backwards because if they are different\n // it is more likely that the last few bytes will be different\n // than the first few\n for(var i = file1.Length - 1; i > 0; i--)\n {\n if(f1[i] != f2[i])\n {\n ret = true;\n break;\n }\n }\n\n return ret;\n}\n"
},
{
"answer_id": 6031710,
"author": "takrl",
"author_id": 520044,
"author_profile": "https://Stackoverflow.com/users/520044",
"pm_score": 2,
"selected": false,
"text": "public static class ColorExtensions\n{\n // Gets a color that will be readable on top of a given background color\n public static Color GetForegroundColor(this Color input)\n {\n // Math taken from one of the replies to\n // http://stackoverflow.com/questions/2241447/make-foregroundcolor-black-or-white-depending-on-background\n if (Math.Sqrt(input.R * input.R * .241 + input.G * input.G * .691 + input.B * input.B * .068) > 128)\n return Color.Black;\n else\n return Color.White;\n }\n\n // Converts a given Color to gray\n public static Color ToGray(this Color input)\n {\n int g = (int)(input.R * .299) + (int)(input.G * .587) + (int)(input.B * .114);\n return Color.FromArgb(input.A, g, g, g);\n }\n}\n Color foreColor = someBackColor.GetForegroundColor();\nColor grayColor = someBackColor.ToGray();\n"
},
{
"answer_id": 6038212,
"author": "Gleno",
"author_id": 427673,
"author_profile": "https://Stackoverflow.com/users/427673",
"pm_score": 1,
"selected": false,
"text": "Convert.ChangeType private static readonly Dictionary<Type, MethodInfo> Parsers = new Dictionary<Type, MethodInfo>();\n\npublic static T Parse<T>(this string value, T defaultValue = default(T))\n{\n if (string.IsNullOrEmpty(value)) return defaultValue;\n\n if (!Parsers.ContainsKey(typeof(T)))\n Parsers[typeof (T)] = typeof (T).GetMethods(BindingFlags.Public | BindingFlags.Static)\n .Where(mi => mi.Name == \"TryParse\")\n .Single(mi =>\n {\n var parameters = mi.GetParameters();\n if (parameters.Length != 2) return false;\n return parameters[0].ParameterType == typeof (string) &&\n parameters[1].ParameterType == typeof (T).MakeByRefType();\n });\n\n var @params = new object[] {value, default(T)};\n return (bool) Parsers[typeof (T)].Invoke(null, @params) ?\n (T) @params[1] : defaultValue;\n}\n var hundredTwentyThree = \"123\".Parse(0);\nvar badnumber = \"test\".Parse(-1);\nvar date = \"01/01/01\".Parse<DateTime>();\n"
},
{
"answer_id": 7089538,
"author": "NeverFade",
"author_id": 604351,
"author_profile": "https://Stackoverflow.com/users/604351",
"pm_score": 0,
"selected": false,
"text": "static public string ToFaString (this string value)\n {\n // 1728 , 1584\n string result = \"\";\n if (value != null)\n {\n char[] resChar = value.ToCharArray();\n for (int i = 0; i < resChar.Length; i++)\n {\n if (resChar[i] >= '0' && resChar[i] <= '9')\n result += (char)(resChar[i] + 1728);\n else\n result += resChar[i];\n }\n }\n return result;\n }\n"
},
{
"answer_id": 7089576,
"author": "NeverFade",
"author_id": 604351,
"author_profile": "https://Stackoverflow.com/users/604351",
"pm_score": 0,
"selected": false,
"text": " static public bool IsAllZero (this string input)\n {\n if(string.IsNullOrEmpty(input))\n return true;\n foreach (char ch in input)\n {\n if(ch != '0')\n return false;\n }\n return true;\n }\n"
},
{
"answer_id": 7201703,
"author": "sasjaq",
"author_id": 913610,
"author_profile": "https://Stackoverflow.com/users/913610",
"pm_score": 1,
"selected": false,
"text": "public static T Safe<T>(this T obj) where T : new()\n{\n if (obj == null)\n {\n obj = new T();\n }\n\n return obj;\n}\n MyClass myClass = Provider.GetSomeResult();\nstring temp = myClass.Safe().SomeValue;\n MyClass myClass = Provider.GetSomeResult();\nstring temp = \"some default value\";\nif (myClass != null)\n{\n temp = myClass.SomeValue;\n}\n"
},
{
"answer_id": 7201807,
"author": "sasjaq",
"author_id": 913610,
"author_profile": "https://Stackoverflow.com/users/913610",
"pm_score": 0,
"selected": false,
"text": " public static readonly DateTime Epoch = new DateTime(1970, 1, 1, 0, 0, 0);\n\n public static long ToUnixTimestamp(this DateTime dateTime)\n {\n return (long) (dateTime - Epoch).TotalSeconds;\n }\n\n public static long ToUnixUltraTimestamp(this DateTime dateTime)\n {\n return (long) (dateTime - Epoch).TotalMilliseconds;\n }\n public static DateTime ToDateTime(this long unixDateTime)\n {\n return Epoch.AddSeconds(unixDateTime);\n }\n\n public static DateTime ToDateTimeUltra(this long unixUltraDateTime)\n {\n return Epoch.AddMilliseconds(unixUltraDateTime);\n }\n"
},
{
"answer_id": 7926954,
"author": "Otiel",
"author_id": 825024,
"author_profile": "https://Stackoverflow.com/users/825024",
"pm_score": 2,
"selected": false,
"text": "IndexOf LastIndexOf String public static partial class StringExtensions {\n\n public static int NthIndexOf(this String str, String match, int occurrence) {\n int i = 1;\n int index = 0;\n\n while (i <= occurrence && \n ( index = str.IndexOf(match, index + 1) ) != -1) {\n\n if (i == occurrence) {\n // Occurrence match found!\n return index;\n }\n i++;\n }\n\n // Match not found\n return -1;\n }\n}\n"
},
{
"answer_id": 8068261,
"author": "jaekie",
"author_id": 1398964,
"author_profile": "https://Stackoverflow.com/users/1398964",
"pm_score": 1,
"selected": false,
"text": "public static string[] Split(this string value, string regexPattern)\n{\n return value.Split(regexPattern, RegexOptions.None);\n}\n\npublic static string[] Split(this string value, string regexPattern, \n RegexOptions options)\n{\n return Regex.Split(value, regexPattern, options);\n}\n var obj = \"test1,test2,test3\";\nstring[] arrays = obj.Split(\",\");\n"
},
{
"answer_id": 8472175,
"author": "Otiel",
"author_id": 825024,
"author_profile": "https://Stackoverflow.com/users/825024",
"pm_score": 2,
"selected": false,
"text": "List<MyObject> myObjects = new List<MyObject>() { \n new MyObject() {Name = \"a\", Id = 0}, \n new MyObject() {Name = \"b\", Id = 1}, \n new MyObject() {Name = \"c\", Id = 2} }\ncomboBox.FillDataSource<MyObject>(myObjects, x => x.Name);\n /** <summary>Fills the System.Windows.Forms.ComboBox object DataSource with a \n * list of T objects.</summary>\n * <param name=\"values\">The list of T objects.</param>\n * <param name=\"displayedValue\">A function to apply to each element to get the \n * display value.</param>\n */\npublic static void FillDataSource<T>(this ComboBox comboBox, List<T> values,\n Func<T, String> displayedValue) {\n\n // Create dataTable\n DataTable data = new DataTable();\n data.Columns.Add(\"ValueMember\", typeof(T));\n data.Columns.Add(\"DisplayMember\");\n\n for (int i = 0; i < values.Count; i++) {\n // For each value/displayed value\n\n // Create new row with value & displayed value\n DataRow dr = data.NewRow();\n dr[\"ValueMember\"] = values[i];\n dr[\"DisplayMember\"] = displayedValue(values[i]) ?? \"\";\n // Add row to the dataTable\n data.Rows.Add(dr);\n }\n\n // Bind datasource to the comboBox\n comboBox.DataSource = data;\n comboBox.ValueMember = \"ValueMember\";\n comboBox.DisplayMember = \"DisplayMember\";\n}\n"
},
{
"answer_id": 9593534,
"author": "jerone",
"author_id": 108448,
"author_profile": "https://Stackoverflow.com/users/108448",
"pm_score": 0,
"selected": false,
"text": "/// <summary>\n/// Collection Helper\n/// </summary>\n/// <remarks>\n/// Use IEnumerable by default, but when altering or getting item at index use IList.\n/// </remarks>\npublic static class CollectionHelper\n{\n\n #region Alter;\n\n /// <summary>\n /// Swap item to another place\n /// </summary>\n /// <typeparam name=\"T\">Collection type</typeparam>\n /// <param name=\"this\">Collection</param>\n /// <param name=\"IndexA\">Index a</param>\n /// <param name=\"IndexB\">Index b</param>\n /// <returns>New collection</returns>\n public static IList<T> Swap<T>(this IList<T> @this, Int32 IndexA, Int32 IndexB)\n {\n T Temp = @this[IndexA];\n @this[IndexA] = @this[IndexB];\n @this[IndexB] = Temp;\n return @this;\n }\n\n /// <summary>\n /// Swap item to the left\n /// </summary>\n /// <typeparam name=\"T\">Collection type</typeparam>\n /// <param name=\"this\">Collection</param>\n /// <param name=\"Index\">Index</param>\n /// <returns>New collection</returns>\n public static IList<T> SwapLeft<T>(this IList<T> @this, Int32 Index)\n {\n return @this.Swap(Index, Index - 1);\n }\n\n /// <summary>\n /// Swap item to the right\n /// </summary>\n /// <typeparam name=\"T\">Collection type</typeparam>\n /// <param name=\"this\">Collection</param>\n /// <param name=\"Index\">Index</param>\n /// <returns>New collection</returns>\n public static IList<T> SwapRight<T>(this IList<T> @this, Int32 Index)\n {\n return @this.Swap(Index, Index + 1);\n }\n\n #endregion Alter;\n\n #region Action;\n\n /// <summary>\n /// Execute action at specified index\n /// </summary>\n /// <typeparam name=\"T\">Collection type</typeparam>\n /// <param name=\"this\">Collection</param>\n /// <param name=\"Index\">Index</param>\n /// <param name=\"ActionAt\">Action to execute</param>\n /// <returns>New collection</returns>\n public static IList<T> ActionAt<T>(this IList<T> @this, Int32 Index, Action<T> ActionAt)\n {\n ActionAt(@this[Index]);\n return @this;\n }\n\n #endregion Action;\n\n #region Randomize;\n\n /// <summary>\n /// Take random items\n /// </summary>\n /// <typeparam name=\"T\">Collection type</typeparam>\n /// <param name=\"this\">Collection</param>\n /// <param name=\"Count\">Number of items to take</param>\n /// <returns>New collection</returns>\n public static IEnumerable<T> TakeRandom<T>(this IEnumerable<T> @this, Int32 Count)\n {\n return @this.Shuffle().Take(Count);\n }\n\n /// <summary>\n /// Take random item\n /// </summary>\n /// <typeparam name=\"T\">Collection type</typeparam>\n /// <param name=\"this\">Collection</param>\n /// <returns>Item</returns>\n public static T TakeRandom<T>(this IEnumerable<T> @this)\n {\n return @this.TakeRandom(1).Single();\n }\n\n /// <summary>\n /// Shuffle list\n /// </summary>\n /// <typeparam name=\"T\">Collection type</typeparam>\n /// <param name=\"this\">Collection</param>\n /// <returns>New collection</returns>\n public static IEnumerable<T> Shuffle<T>(this IEnumerable<T> @this)\n {\n return @this.OrderBy(Item => Guid.NewGuid());\n }\n\n #endregion Randomize;\n\n #region Navigate;\n\n /// <summary>\n /// Get next item in collection and give first item, when last item is selected;\n /// </summary>\n /// <typeparam name=\"T\">Collection type</typeparam>\n /// <param name=\"this\">Collection</param>\n /// <param name=\"Index\">Index in collection</param>\n /// <returns>Next item</returns>\n public static T Next<T>(this IList<T> @this, ref Int32 Index)\n {\n Index = ++Index >= 0 && Index < @this.Count ? Index : 0;\n return @this[Index];\n }\n\n /// <summary>\n /// Get previous item in collection and give last item, when first item is selected;\n /// </summary>\n /// <typeparam name=\"T\">Collection type</typeparam>\n /// <param name=\"this\">Collection</param>\n /// <param name=\"Index\">Index in collection</param>\n /// <returns>Previous item</returns>\n public static T Previous<T>(this IList<T> @this, ref Int32 Index)\n {\n Index = --Index >= 0 && Index < @this.Count ? Index : @this.Count - 1;\n return @this[Index];\n }\n\n #endregion Navigate;\n\n #region Clone;\n\n /// <summary>\n /// \n /// </summary>\n /// <typeparam name=\"T\">Collection type</typeparam>\n /// <param name=\"this\">Collection</param>\n /// <returns>Cloned collection</returns>\n public static IEnumerable<T> Clone<T>(this IEnumerable<T> @this) where T : ICloneable\n {\n return @this.Select(Item => (T)Item.Clone());\n }\n\n #endregion Clone;\n\n #region String;\n\n /// <summary>\n /// Joins multiple string with Separator\n /// </summary>\n /// <param name=\"this\">Collection</param>\n /// <param name=\"Separator\">Separator</param>\n /// <returns>Joined string</returns>\n public static String Join(this IEnumerable<String> @this, String Separator = \"\")\n {\n return String.Join(Separator, @this);\n }\n\n #endregion String;\n\n}\n"
},
{
"answer_id": 9839800,
"author": "takrl",
"author_id": 520044,
"author_profile": "https://Stackoverflow.com/users/520044",
"pm_score": 0,
"selected": false,
"text": "public static bool IsWinXPOrHigher(this OperatingSystem OS)\n{\n return (OS.Platform == PlatformID.Win32NT)\n && ((OS.Version.Major > 5) || ((OS.Version.Major == 5) && (OS.Version.Minor >= 1)));\n}\n\npublic static bool IsWinVistaOrHigher(this OperatingSystem OS)\n{\n return (OS.Platform == PlatformID.Win32NT)\n && (OS.Version.Major >= 6);\n}\n\npublic static bool IsWin7OrHigher(this OperatingSystem OS)\n{\n return (OS.Platform == PlatformID.Win32NT)\n && ((OS.Version.Major > 6) || ((OS.Version.Major == 6) && (OS.Version.Minor >= 1)));\n}\n\npublic static bool IsWin8OrHigher(this OperatingSystem OS)\n{\n return (OS.Platform == PlatformID.Win32NT)\n && ((OS.Version.Major > 6) || ((OS.Version.Major == 6) && (OS.Version.Minor >= 2)));\n}\n if (Environment.OSVersion.IsWinXPOrHigher())\n{\n // do stuff\n}\n\nif (Environment.OSVersion.IsWinVistaOrHigher())\n{\n // do stuff\n}\n\nif (Environment.OSVersion.IsWin7OrHigher())\n{\n // do stuff\n}\n\nif (Environment.OSVersion.IsWin8OrHigher())\n{\n // do stuff\n}\n"
},
{
"answer_id": 10042182,
"author": "Luke Puplett",
"author_id": 107783,
"author_profile": "https://Stackoverflow.com/users/107783",
"pm_score": 0,
"selected": false,
"text": " /// <summary>\n /// Adds the specified query parameter to the URI builder.\n /// </summary>\n /// <param name=\"builder\">The builder.</param>\n /// <param name=\"parameterName\">Name of the parameter.</param>\n /// <param name=\"value\">The URI escaped value.</param>\n /// <returns>The final full query string.</returns>\n public static string AddQueryParam(this UriBuilder builder, string parameterName, string value)\n {\n if (parameterName == null)\n throw new ArgumentNullException(\"parameterName\");\n\n if (parameterName.Length == 0)\n throw new ArgumentException(\"The parameter name is empty.\");\n\n if (value == null)\n throw new ArgumentNullException(\"value\");\n\n if (value.Length == 0)\n throw new ArgumentException(\"The value is empty.\");\n\n if (builder.Query.Length == 0)\n {\n builder.Query = String.Concat(parameterName, \"=\", value);\n }\n else if\n (builder.Query.Contains(String.Concat(\"&\", parameterName, \"=\"))\n || builder.Query.Contains(String.Concat(\"?\", parameterName, \"=\")))\n {\n throw new InvalidOperationException(String.Format(\"The parameter {0} already exists.\", parameterName));\n }\n else\n {\n builder.Query = String.Concat(builder.Query.Substring(1), \"&\", parameterName, \"=\", value);\n }\n\n return builder.Query;\n }\n"
}
] |
2008/11/07
|
[
"https://Stackoverflow.com/questions/271398",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11135/"
] |
271,406
|
<p>I have a table in lua with some data.</p>
<pre><code>sometable = {
{name = "bob", something = "foo"},
{name = "greg", something = "bar"}
}
</code></pre>
<p>I then want to loop through the table and assign a number to each name as a variable. New to lua and tried it like this.</p>
<pre><code>for i,t in ipairs(sometable) do
t.name = i
end
</code></pre>
<p>I was then assuming print("name1", bob) would give me name1 = 1. Right now I'm getting nil. So I'm back to my ugly static list of variables till some kind soul tells me how I'm an idiot.</p>
|
[
{
"answer_id": 274107,
"author": "Doug Currie",
"author_id": 33252,
"author_profile": "https://Stackoverflow.com/users/33252",
"pm_score": 3,
"selected": true,
"text": "> sometable = {{name = \"bob\", something = \"foo\"},{name = \"greg\", something = \"bar\"}}\n> for i,t in ipairs(sometable) do t[t.name] = i end\n> for i,t in ipairs(sometable) do for j,u in pairs (t) do print (j,u) end end \nname bob\nsomething foo\nbob 1\ngreg 2\nsomething bar\nname greg\n> return sometable[1].bob\n1>\n"
}
] |
2008/11/07
|
[
"https://Stackoverflow.com/questions/271406",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18933/"
] |
271,428
|
<hr>
<p>Thanks for answers,Actually I am not puzzled about draw 1024*768 pixels is slower than 100* 100 pixels... It is so simple a logic..
Which made me puzzled is that DrawImage's interpolation algorithm may be very slow, while there exists lots of better algorithm, and its decoder seems can decode from a jpg with a certain resolution, it is really cool, I search for sometime but do not find any free lib to do this...</p>
<p>It is really strange!
I add the following code into on Paint method. c:\1.jpg is 5M jpg file, about 4000*3000</p>
<p>//--------------------------------------------------------------</p>
<pre><code>HDC hdc = pDC->GetSafeHdc();
bitmap = Bitmap::FromFile(L"c:\\1.jpg",true);
Graphics graphics(hdc);
graphics.SetInterpolationMode( InterpolationModeNearestNeighbor );
graphics.DrawImage(bitmap,0,0,200,200);
</code></pre>
<p>The above is really fast! even real time! I don't think decode a 5m JPG can be that fast!</p>
<p>//--------------------------------------------------------------</p>
<pre><code>HDC hdc = pDC->GetSafeHdc();
bitmap = Bitmap::FromFile(L"c:\\1.jpg",true);
Graphics graphics(hdc);
graphics.SetInterpolationMode( InterpolationModeNearestNeighbor );
graphics.DrawImage(bitmap,0,0,2000,2000);
</code></pre>
<p>The above code become really slow</p>
<p>//--------------------------------------------------------------</p>
<p>If I add Bitmap = Bitmap::FromFile(L"c:\1.jpg", true); // into construct</p>
<p>leave </p>
<pre><code> Graphics graphics(hdc);
graphics.SetInterpolationMode( InterpolationModeNearestNeighbor );
graphics.DrawImage(bitmap,0,0,2000,2000);
</code></pre>
<p>in OnPaint method,
The code is still a bit slow~~~</p>
<p>//------------------------------------------------------------------</p>
<p>Comparing with decoding, the drawImage Process is really slow...</p>
<p>Why and How did they do that? Did Microsoft pay the men taking charge of decoder double salary than the men taking charge of writing drawingImage?</p>
|
[
{
"answer_id": 271463,
"author": "Johann Gerell",
"author_id": 6345,
"author_profile": "https://Stackoverflow.com/users/6345",
"pm_score": 3,
"selected": false,
"text": "graphics.DrawImage(bitmap,0,0,200,200);\n graphics.DrawImage(bitmap,0,0,2000,2000);\n"
}
] |
2008/11/07
|
[
"https://Stackoverflow.com/questions/271428",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/25749/"
] |
271,438
|
<p>I am having a .cs file, i need to execute that file..
I don't have experience in C#.. Please help.. Do we have to install any software to run it.. </p>
<p>Currently i am using windows XP.. </p>
<p>Please help me... </p>
|
[
{
"answer_id": 272151,
"author": "Xiaofu",
"author_id": 31967,
"author_profile": "https://Stackoverflow.com/users/31967",
"pm_score": 0,
"selected": false,
"text": "csc /out:your_app_name.exe your_cs_filename.cs\n"
},
{
"answer_id": 53193120,
"author": "NanoWar",
"author_id": 1436044,
"author_profile": "https://Stackoverflow.com/users/1436044",
"pm_score": 1,
"selected": false,
"text": "@echo off\nIF \"%1\"==\"\" GOTO HELP\n\nREM => copy .net core project file into temp folder\nmkdir _temp 2>NUL\necho ^<Project Sdk=\"Microsoft.NET.Sdk.Web\"^>^<PropertyGroup^>^<TargetFramework^>netcoreapp2.0^</TargetFramework^>^</PropertyGroup^>^</Project^> > _temp\\p.csproj\ncopy %1 _temp 1>NUL\ncd _temp\n\nREM => run program\ndotnet run\n\nREM => clean-up\ncd ..\nrmdir /Q /S _temp 1>NUL\nGOTO EXIT\n\n:HELP\necho Runs any C# file with a static Main() directly\necho Usage: %0 [file.cs]\n\n:EXIT\n"
}
] |
2008/11/07
|
[
"https://Stackoverflow.com/questions/271438",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
271,440
|
<p>I met an interesting issue about C#. I have code like below.</p>
<pre><code>List<Func<int>> actions = new List<Func<int>>();
int variable = 0;
while (variable < 5)
{
actions.Add(() => variable * 2);
++ variable;
}
foreach (var act in actions)
{
Console.WriteLine(act.Invoke());
}
</code></pre>
<p>I expect it to output 0, 2, 4, 6, 8. However, it actually outputs five 10s.</p>
<p>It seems that it is due to all actions referring to one captured variable. As a result, when they get invoked, they all have same output.</p>
<p>Is there a way to work round this limit to have each action instance have its own captured variable?</p>
|
[
{
"answer_id": 271447,
"author": "Jon Skeet",
"author_id": 22656,
"author_profile": "https://Stackoverflow.com/users/22656",
"pm_score": 9,
"selected": true,
"text": "while (variable < 5)\n{\n int copy = variable;\n actions.Add(() => copy * 2);\n ++ variable;\n}\n for foreach for (int i=0; i < 10; i++) // Just one variable\nforeach (string x in foo) // And again, despite how it reads out loud\n foreach"
},
{
"answer_id": 271449,
"author": "cfeduke",
"author_id": 5645,
"author_profile": "https://Stackoverflow.com/users/5645",
"pm_score": 3,
"selected": false,
"text": "variable List<Func<int>> actions = new List<Func<int>>();\n\nint variable = 0;\nwhile (variable < 5)\n{\n int variable1 = variable;\n actions.Add(() => variable1 * 2);\n ++variable;\n}\n\nforeach (var act in actions)\n{\n Console.WriteLine(act.Invoke());\n}\n\nConsole.ReadLine();\n"
},
{
"answer_id": 271450,
"author": "Tyler Levine",
"author_id": 35339,
"author_profile": "https://Stackoverflow.com/users/35339",
"pm_score": 4,
"selected": false,
"text": "while( variable < 5 )\n{\n int copy = variable;\n actions.Add( () => copy * 2 );\n ++variable;\n}\n"
},
{
"answer_id": 4829027,
"author": "Sunil",
"author_id": 593932,
"author_profile": "https://Stackoverflow.com/users/593932",
"pm_score": 3,
"selected": false,
"text": "for (int counter = 1; counter <= 5; counter++)\n{\n new Thread (() => Console.Write (counter)).Start();\n}\n for (int counter = 1; counter <= 5; counter++)\n{\n int localVar= counter;\n new Thread (() => Console.Write (localVar)).Start();\n}\n"
},
{
"answer_id": 15707665,
"author": "gerrard00",
"author_id": 1011470,
"author_profile": "https://Stackoverflow.com/users/1011470",
"pm_score": 4,
"selected": false,
"text": "void Main()\n{\n List<Func<int>> actions = new List<Func<int>>();\n\n int variable = 0;\n\n var closure = new CompilerGeneratedClosure();\n\n Func<int> anonymousMethodAction = null;\n\n while (closure.variable < 5)\n {\n if(anonymousMethodAction == null)\n anonymousMethodAction = new Func<int>(closure.YourAnonymousMethod);\n\n //we're re-adding the same function \n actions.Add(anonymousMethodAction);\n\n ++closure.variable;\n }\n\n foreach (var act in actions)\n {\n Console.WriteLine(act.Invoke());\n }\n}\n\nclass CompilerGeneratedClosure\n{\n public int variable;\n\n public int YourAnonymousMethod()\n {\n return this.variable * 2;\n }\n}\n"
},
{
"answer_id": 50837161,
"author": "Maverick Meerkat",
"author_id": 6296435,
"author_profile": "https://Stackoverflow.com/users/6296435",
"pm_score": 3,
"selected": false,
"text": "() => variable * 2 variable variable ClosureClass.variable ClosureClass.variable ClosureClass.variable List<Func<int>> actions = new List<Func<int>>();\nint variable = 0;\nwhile (variable < 5)\n{\n var t = variable; // now t will be closured (i.e. replaced by a field in the new class)\n actions.Add(() => t * 2);\n ++variable; // changing variable won't affect the closured variable t\n}\nforeach (var act in actions)\n{\n Console.WriteLine(act.Invoke());\n}\n List<Func<int>> actions = new List<Func<int>>();\n\nint variable = 0;\nwhile (variable < 5)\n{\n actions.Add(Mult(variable));\n ++variable;\n}\n\nforeach (var act in actions)\n{\n Console.WriteLine(act.Invoke());\n}\n static Func<int> Mult(int i)\n{\n return () => i * 2;\n}\n public class Helper\n{\n public int _i;\n public Helper(int i)\n {\n _i = i;\n }\n public int Method()\n {\n return _i * 2;\n }\n}\n\nstatic Func<int> Mult(int i)\n{\n Helper help = new Helper(i);\n return help.Method;\n}\n"
},
{
"answer_id": 53744561,
"author": "Junaid Pathan",
"author_id": 8304176,
"author_profile": "https://Stackoverflow.com/users/8304176",
"pm_score": -1,
"selected": false,
"text": "List<Func<int>> actions = new List<Func<int>>();\n\nint variable = 0;\nwhile (variable < 5)\n{\n int i = variable;\n actions.Add(() => i * 2);\n ++ variable;\n}\n\nforeach (var act in actions)\n{\n Console.WriteLine(act.Invoke());\n}\n"
},
{
"answer_id": 60474255,
"author": "Nathan Chappell",
"author_id": 6084517,
"author_profile": "https://Stackoverflow.com/users/6084517",
"pm_score": -1,
"selected": false,
"text": "for (for-initializer; for-condition; for-iterator) embedded-statement\n {\n for-initializer;\n while (for-condition) {\n embedded-statement;\n LLoop: for-iterator;\n }\n}\n x static void F() {\n for (int i = 0; i < 3; i++) {\n int x = i * 2 + 1;\n ...\n }\n}\n x x static void F() {\n int x;\n for (int i = 0; i < 3; i++) {\n x = i * 2 + 1;\n ...\n }\n}\n using System;\n\ndelegate void D();\n\nclass Test{\n static D[] F() {\n D[] result = new D[3];\n for (int i = 0; i < 3; i++) {\n int x = i * 2 + 1;\n result[i] = () => { Console.WriteLine(x); };\n }\n return result;\n }\n static void Main() {\n foreach (D d in F()) d();\n }\n}\n 1\n3\n5\n x static D[] F() {\n D[] result = new D[3];\n int x;\n for (int i = 0; i < 3; i++) {\n x = i * 2 + 1;\n result[i] = () => { Console.WriteLine(x); };\n }\n return result;\n}\n 5\n5\n5\n static D[] F() {\n D[] result = new D[3];\n for (int i = 0; i < 3; i++) {\n result[i] = () => { Console.WriteLine(i); };\n }\n return result;\n}\n 3\n3\n3\n"
},
{
"answer_id": 65439550,
"author": "Arshman Saleem",
"author_id": 6366945,
"author_profile": "https://Stackoverflow.com/users/6366945",
"pm_score": 0,
"selected": false,
"text": "for (int n=0; n < 10; n++) //forloop syntax\nforeach (string item in foo) foreach syntax\n"
}
] |
2008/11/07
|
[
"https://Stackoverflow.com/questions/271440",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/26349/"
] |
271,464
|
<p>I have a multiline text string (e.g. "Stuff\nMore Stuff\nYet More Stuff"), and I want to paint it, along with a bitmap into a tooltip. Since I am painting the bitmap, I need to set OwnerDraw to true, which I am doing. I am also handling the Popup event, so I can size the tooltip to be large enough to hold the text and the bitmap.</p>
<p>I am calling e.DrawBackground and e.DrawBorder(), and then painting my bitmap on the left side of the tooltip area. </p>
<p>Is there a set of flags I can pass to e.DrawText() in order to left-align the text, but to offset it so that it doesn't get painted over my bitmap? Or do I need to custom draw all the text as well (which will probably involve splitting the string on newlines, etc)?</p>
<p>UPDATED: The final code looks like this:</p>
<pre><code>private void _ItemTip_Draw(object sender, DrawToolTipEventArgs e)
{
e.DrawBackground();
e.DrawBorder();
// Reserve a square of size e.Bounds.Height x e.Bounds.Height
// for the image. Keep a margin around it so that it looks good.
int margin = 2;
Image i = _ItemTip.Tag as Image;
if (i != null)
{
int side = e.Bounds.Height - 2 * margin;
e.Graphics.DrawImage(i, new Rectangle(margin, margin, side, side));
}
// Construct bounding rectangle for text (don't want to paint it over the image).
int textOffset = e.Bounds.Height + 2 * margin;
RectangleF rText = e.Bounds;
rText.Offset(textOffset, 0);
rText.Width -= textOffset;
e.Graphics.DrawString(e.ToolTipText, e.Font, Brushes.Black, rText);
}
</code></pre>
|
[
{
"answer_id": 271628,
"author": "Robert Jeppesen",
"author_id": 9436,
"author_profile": "https://Stackoverflow.com/users/9436",
"pm_score": 3,
"selected": true,
"text": " RectangleF rect = new RectangleF(100,100,100,100);\n e.Graphics.DrawString(myString, myFont, myBrush, rect);\n"
},
{
"answer_id": 271658,
"author": "tamberg",
"author_id": 3588,
"author_profile": "https://Stackoverflow.com/users/3588",
"pm_score": 0,
"selected": false,
"text": "double MeasureStringHeight (Graphics g, string s, Font f, int w) {\n double result = 0;\n int n = s.Length;\n int i = 0;\n while (i < n) {\n StringBuilder line = new StringBuilder();\n int iLineStart = i;\n int iSpace = -1;\n SizeF sLine = new SizeF(0, 0);\n while ((i < n) && (sLine.Width <= w)) {\n char ch = s[i];\n if ((ch == ' ') || (ch == '-')) {\n iSpace = i;\n }\n line.Append(ch);\n sLine = g.MeasureString(line.ToString(), f);\n i++;\n }\n if (sLine.Width > w) {\n if (iSpace >= 0) {\n i = iSpace + 1;\n } else {\n i--;\n }\n // Assert(w > largest ch in line)\n }\n result += sLine.Height;\n }\n return result;\n}\n"
}
] |
2008/11/07
|
[
"https://Stackoverflow.com/questions/271464",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2683/"
] |
271,485
|
<p>whats the best way to export a Datagrid to excel? I have no experience whatsoever in exporting datagrid to excel, so i want to know how you guys export datagrid to excel.
i read that there are a lot of ways, but i am thinking to just make a simple export excel to datagrid function.i am using asp.net C#</p>
<p>cheers.. </p>
|
[
{
"answer_id": 271487,
"author": "Marc Gravell",
"author_id": 23354,
"author_profile": "https://Stackoverflow.com/users/23354",
"pm_score": 4,
"selected": true,
"text": "<table><tr><td>...</td></tr>...</table> DataTable public static void WriteCsv(string[] headers, IEnumerable<string[]> data, string filename)\n {\n if (data == null) throw new ArgumentNullException(\"data\");\n if (string.IsNullOrEmpty(filename)) filename = \"export.csv\";\n\n HttpResponse resp = System.Web.HttpContext.Current.Response;\n resp.Clear();\n // remove this line if you don't want to prompt the user to save the file\n resp.AddHeader(\"Content-Disposition\", \"attachment;filename=\" + filename);\n // if not saving, try: \"application/ms-excel\"\n resp.ContentType = \"text/csv\";\n string csv = GetCsv(headers, data);\n byte[] buffer = resp.ContentEncoding.GetBytes(csv);\n resp.AddHeader(\"Content-Length\", buffer.Length.ToString());\n resp.BinaryWrite(buffer);\n resp.End();\n }\n static void WriteRow(string[] row, StringBuilder destination)\n {\n if (row == null) return;\n int fields = row.Length;\n for (int i = 0; i < fields; i++)\n {\n string field = row[i];\n if (i > 0)\n {\n destination.Append(',');\n }\n if (string.IsNullOrEmpty(field)) continue; // empty field\n\n bool quote = false;\n if (field.Contains(\"\\\"\"))\n {\n // if contains quotes, then needs quoting and escaping\n quote = true;\n field = field.Replace(\"\\\"\", \"\\\"\\\"\");\n }\n else\n {\n // commas, line-breaks, and leading-trailing space also require quoting\n if (field.Contains(\",\") || field.Contains(\"\\n\") || field.Contains(\"\\r\")\n || field.StartsWith(\" \") || field.EndsWith(\" \"))\n {\n quote = true;\n }\n }\n if (quote)\n {\n destination.Append('\\\"');\n destination.Append(field);\n destination.Append('\\\"');\n }\n else\n {\n destination.Append(field);\n }\n\n }\n destination.AppendLine();\n }\n static string GetCsv(string[] headers, IEnumerable<string[]> data)\n {\n StringBuilder sb = new StringBuilder();\n if (data == null) throw new ArgumentNullException(\"data\");\n WriteRow(headers, sb);\n foreach (string[] row in data)\n {\n WriteRow(row, sb);\n\n }\n return sb.ToString();\n }\n"
},
{
"answer_id": 271496,
"author": "Christian C. Salvadó",
"author_id": 5445,
"author_profile": "https://Stackoverflow.com/users/5445",
"pm_score": 2,
"selected": false,
"text": "private void ExportButton_Click(object sender, System.EventArgs e)\n{\n Response.Clear();\n Response.Buffer = true;\n Response.ContentType = \"application/vnd.ms-excel\";\n Response.Charset = \"\";\n this.EnableViewState = false;\n System.IO.StringWriter oStringWriter = new System.IO.StringWriter();\n System.Web.UI.HtmlTextWriter oHtmlTextWriter = new System.Web.UI.HtmlTextWriter(oStringWriter);\n this.ClearControls(dataGrid);\n dataGrid.RenderControl(oHtmlTextWriter);\n Response.Write(oStringWriter.ToString());\n Response.End();\n}\n"
}
] |
2008/11/07
|
[
"https://Stackoverflow.com/questions/271485",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23491/"
] |
271,488
|
<p>I asked <a href="https://stackoverflow.com/questions/269417/which-language-should-i-use">a question</a> earlier about which language to use for an AI prototype. The consensus seemed to be that if I want it to be fast, I need to use a language like Java or C++, but that Python / Perl / Ruby would be good for the interface bits. </p>
<p>So, this leads me on to another question. How easy is it to link these languages together? And which combination works best? So, if I wanted to have a Ruby CGI-type program calling C++ or Java AI functions, is that easy to do? Any pointers for where I look for information on doing that kind of thing? Or would a different combination be better?</p>
<p>My main experience with writing web applications started with C++ CGI and then moved on to Java servlets (about 10 years ago) and then after a long gap away from programming I did some PHP. But I've not had experience of writing a web application in a scripting language which then calls out to a compiled language for the speed-critical bits. So any advice will be welcome!</p>
|
[
{
"answer_id": 271494,
"author": "VonC",
"author_id": 6309,
"author_profile": "https://Stackoverflow.com/users/6309",
"pm_score": 2,
"selected": false,
"text": "require \"java\"\n# The next line exposes Java's String as JString\ninclude_class(\"java.lang.String\") { |pkg, name| \"J\" + name }\ns = JString.new(\"f\")\n"
},
{
"answer_id": 271642,
"author": "Pieter",
"author_id": 5822,
"author_profile": "https://Stackoverflow.com/users/5822",
"pm_score": 5,
"selected": true,
"text": "char const* greet()\n{\n return \"hello, world\";\n}\n #include <boost/python.hpp>\n\nBOOST_PYTHON_MODULE(hello_ext)\n{\n using namespace boost::python;\n def(\"greet\", greet);\n}\n >>> import hello_ext\n>>> print hello.greet()\nhello, world\n"
},
{
"answer_id": 272363,
"author": "Brad Gilbert",
"author_id": 1337,
"author_profile": "https://Stackoverflow.com/users/1337",
"pm_score": 3,
"selected": false,
"text": "use Inline C => <<'END_C';\n\n void greet() {\n printf(\"Hello, world\\n\");\n }\nEND_C\n\ngreet;\n use v6.c;\n\nsub c-print ( Str() $s ){\n use NativeCall;\n\n # restrict the function to inside of this subroutine because printf is\n # vararg based, and we only handle '%s' based inputs here\n\n # it should be possible to handle more but it requires generating\n # a Signature object based on the format string and then do a\n # nativecast with that Signature, and a pointer to printf\n\n sub printf ( str, str --> int32 ) is native('libc:6') {}\n\n printf '%s', $s\n}\n\nc-print 'Hello World';\n is symbol"
}
] |
2008/11/07
|
[
"https://Stackoverflow.com/questions/271488",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11522/"
] |
271,506
|
<p>I am refering to the <a href="https://stackoverflow.com/questions/252893/how-do-you-change-the-classpath-within-java#252905">question</a> on changing the classpath programmatically.</p>
<p>I read and found out that there is some function under <strong>System</strong> class as getproperties where we can retrieve the properties and then also can set it using setProperties().</p>
<p>The answers however I got was that It Wont work. I have not tried this myself, however, i am taking the call.</p>
<p>Just to clarify, then why these setProperty() and getProperty() methods are there if they cannot alter it at run time. Or is this specific to the classpath property only ?</p>
<p>I will appreciate if someone can present a scenario where they are really helpful?</p>
|
[
{
"answer_id": 271522,
"author": "VonC",
"author_id": 6309,
"author_profile": "https://Stackoverflow.com/users/6309",
"pm_score": 3,
"selected": false,
"text": "/*\nAdd the URL handler to the handler property. This informs \nIBMJSSE what URL handler to use to handle the safkeyring \nsupport. In this case IBMJCE.\n*/\nSystem.setProperty(\"java.protocol.handler.pkgs\", \"com.ibm.crypto.provider\");\n System.setProperty(\"javax.net.ssl.keyStore\", context.getRealPath(KEYSTORE));\nSystem.setProperty(\"javax.net.ssl.keyStorePassword\", \"password\");\nSystem.setProperty(\"javax.net.ssl.trustStore\", context.getRealPath(TRUSTSTORE));\nSystem.setProperty(\"javax.net.debug\", \"ssl\");\nHttpClient httpClient = new HttpClient();\nGetMethod httpGet = new GetMethod(\"https://something.com\");\nhttpClient.executeMethod(httpGet);\nreturn new String(httpGet.getResponseBody());\n"
},
{
"answer_id": 272049,
"author": "Martin Probst",
"author_id": 22227,
"author_profile": "https://Stackoverflow.com/users/22227",
"pm_score": 0,
"selected": false,
"text": "getProperty() java -Dfoo=bar setProperty() classpath"
},
{
"answer_id": 1198693,
"author": "Dave Jarvis",
"author_id": 59087,
"author_profile": "https://Stackoverflow.com/users/59087",
"pm_score": 4,
"selected": false,
"text": "addURL import java.lang.reflect.InvocationTargetException;\nimport java.lang.reflect.Method; \n\nimport java.io.File;\nimport java.io.IOException;\n\nimport java.net.URL;\nimport java.net.URLClassLoader;\n\n/**\n * Allows programs to modify the classpath during runtime. \n */ \npublic class ClassPathUpdater { \n /** Used to find the method signature. */ \n private static final Class[] PARAMETERS = new Class[]{ URL.class }; \n\n /** Class containing the private addURL method. */\n private static final Class<?> CLASS_LOADER = URLClassLoader.class;\n\n /**\n * Adds a new path to the classloader. If the given string points to a file,\n * then that file's parent file (i.e., directory) is used as the\n * directory to add to the classpath. If the given string represents a\n * directory, then the directory is directly added to the classpath.\n *\n * @param s The directory to add to the classpath (or a file, which\n * will relegate to its directory).\n */\n public static void add( String s )\n throws IOException, NoSuchMethodException, IllegalAccessException,\n InvocationTargetException {\n add( new File( s ) );\n }\n\n /**\n * Adds a new path to the classloader. If the given file object is\n * a file, then its parent file (i.e., directory) is used as the directory\n * to add to the classpath. If the given string represents a directory,\n * then the directory it represents is added.\n *\n * @param f The directory (or enclosing directory if a file) to add to the\n * classpath.\n */\n public static void add( File f )\n throws IOException, NoSuchMethodException, IllegalAccessException,\n InvocationTargetException {\n f = f.isDirectory() ? f : f.getParentFile();\n add( f.toURI().toURL() );\n }\n\n /**\n * Adds a new path to the classloader. The class must point to a directory,\n * not a file.\n *\n * @param url The path to include when searching the classpath.\n */\n public static void add( URL url )\n throws IOException, NoSuchMethodException, IllegalAccessException,\n InvocationTargetException {\n Method method = CLASS_LOADER.getDeclaredMethod( \"addURL\", PARAMETERS );\n method.setAccessible( true );\n method.invoke( getClassLoader(), new Object[]{ url } );\n }\n\n private static URLClassLoader getClassLoader() {\n return (URLClassLoader)ClassLoader.getSystemClassLoader();\n }\n}\n /home/user/dev/java/app/build/com/package try {\n ClassPathUpdater.add( \"/home/user/dev/java/app/build/com/package/Filename.class\" );\n}\ncatch( Exception e ) {\n e.printStackTrace();\n}\n"
},
{
"answer_id": 8598258,
"author": "Zorkus",
"author_id": 1965110,
"author_profile": "https://Stackoverflow.com/users/1965110",
"pm_score": 2,
"selected": false,
"text": "System.setProperty( \"java.library.path\", newPath);\nField fieldSysPath = ClassLoader.class.getDeclaredField(\"sys_paths\");\nfieldSysPath.setAccessible(true);\nfieldSysPath.set(null, null); // that's the key.\n"
}
] |
2008/11/07
|
[
"https://Stackoverflow.com/questions/271506",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11614/"
] |
271,520
|
<p>I could do this in C#..</p>
<pre><code>int number = 2;
string str = "Hello " + number + " world";
</code></pre>
<p>..and str ends up as "Hello 2 world".</p>
<p>In VB.NET i could do this..</p>
<pre><code>Dim number As Integer = 2
Dim str As String = "Hello " + number + " world"
</code></pre>
<p>..but I get an InvalidCastException "Conversion from string "Hello " to type 'Double' is not valid."</p>
<p>I am aware that I should use .ToString() in both cases, but whats going on here with the code as it is?</p>
|
[
{
"answer_id": 271529,
"author": "Jon Skeet",
"author_id": 22656,
"author_profile": "https://Stackoverflow.com/users/22656",
"pm_score": 5,
"selected": true,
"text": "Dim number As Integer = 2\nDim str As String = \"Hello \" & number & \" world\"\n System.String String.Concat"
},
{
"answer_id": 271531,
"author": "TheCodeJunkie",
"author_id": 25319,
"author_profile": "https://Stackoverflow.com/users/25319",
"pm_score": 3,
"selected": false,
"text": "+ & & & + +"
},
{
"answer_id": 271532,
"author": "chakrit",
"author_id": 3055,
"author_profile": "https://Stackoverflow.com/users/3055",
"pm_score": 1,
"selected": false,
"text": "Dim str = 1 + \"2\"\n Dim str = \"Hello \" & number & \" world\"\n"
},
{
"answer_id": 271585,
"author": "Loris",
"author_id": 23824,
"author_profile": "https://Stackoverflow.com/users/23824",
"pm_score": 2,
"selected": false,
"text": "str = String.Format(\"Hello {0} workd\", Number)\n"
}
] |
2008/11/07
|
[
"https://Stackoverflow.com/questions/271520",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15233/"
] |
271,521
|
<p>Sometimes when I am debugging code in Eclipse it happens that although I can see and inspect class member variables without any difficulty I am unable to inspect the values of variables declared locally within functions. As an aside, any parameters to the current function lose their 'real' names and instead one sees their values listed in the Variables window as arg0, arg1, arg2, etc but at least the values are visible.</p>
<p>This is occurring at present in relation to classes defined within the core JDK. I have verified that the installed and current JRE is a JDK.</p>
<p>Is anybody able to shed some light on this behaviour?</p>
|
[
{
"answer_id": 940988,
"author": "Geoffrey Zheng",
"author_id": 62479,
"author_profile": "https://Stackoverflow.com/users/62479",
"pm_score": 4,
"selected": false,
"text": "mkdir \\tmp; mkdir \\tmp\\out src.zip tmp\\src cd src find -name *.java > files.txt javac -verbose -g -d \\tmp\\out -J-Xmx512m -cp \"<jdk>\\jre\\lib\\rt.jar\";\"<jdk>\\lib\\tools.jar\" @files.txt cd \\tmp\\out; jar cvf rt.jar *"
},
{
"answer_id": 31980261,
"author": "Naresh",
"author_id": 3359659,
"author_profile": "https://Stackoverflow.com/users/3359659",
"pm_score": 0,
"selected": false,
"text": "<compilerarg line=\"-g\" />"
}
] |
2008/11/07
|
[
"https://Stackoverflow.com/questions/271521",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/35138/"
] |
271,526
|
<p>I use <code>x != null</code> to avoid <a href="https://docs.oracle.com/javase/9/docs/api/java/lang/NullPointerException.html" rel="noreferrer"><code>NullPointerException</code></a>. Is there an alternative?</p>
<pre class="lang-java prettyprint-override"><code>if (x != null) {
// ...
}
</code></pre>
|
[
{
"answer_id": 271576,
"author": "Johannes Schaub - litb",
"author_id": 34509,
"author_profile": "https://Stackoverflow.com/users/34509",
"pm_score": 6,
"selected": false,
"text": "a.f(b); <-> b.f(a);\n foo.equals(\"bar\"); \"bar\".equals(foo);"
},
{
"answer_id": 271587,
"author": "javamonkey79",
"author_id": 27657,
"author_profile": "https://Stackoverflow.com/users/27657",
"pm_score": 7,
"selected": false,
"text": "String foo;\n...\nif( StringUtils.isBlank( foo ) ) {\n ///do something\n}\n String foo;\n...\nif( StringUtils.isEmpty( foo ) ) {\n ///do something\n}\n public DOCUMENT read(String xml, ValidationEventHandler validationEventHandler) {\n Validate.notNull(validationEventHandler,\"ValidationHandler not Injected\");\n return read(new StringReader(xml), true, validationEventHandler);\n}\n Assert.notNull(validationEventHandler,\"ValidationHandler not Injected\");\n"
},
{
"answer_id": 271616,
"author": "myplacedk",
"author_id": 28683,
"author_profile": "https://Stackoverflow.com/users/28683",
"pm_score": 8,
"selected": false,
"text": "public void method(Object object) {\n if (object == null) {\n throw new IllegalArgumentException(\"...\");\n }\n object public String getFirst3Chars(String text) {\n return text.subString(0, 3);\n}\n if (object == null) {\n // something\n} else {\n // something else\n}\n if (object != null && ..."
},
{
"answer_id": 271617,
"author": "xtofl",
"author_id": 6610,
"author_profile": "https://Stackoverflow.com/users/6610",
"pm_score": 5,
"selected": false,
"text": "if( o == null ) handleNull()"
},
{
"answer_id": 271735,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 3,
"selected": false,
"text": "public class NonNullThing {\n\n Vector vectorField = new Vector();\n\n int[] arrayField = new int[0];\n\n public NonNullThing() {\n\n // etc\n\n }\n\n}\n"
},
{
"answer_id": 271874,
"author": "cletus",
"author_id": 18393,
"author_profile": "https://Stackoverflow.com/users/18393",
"pm_score": 12,
"selected": true,
"text": "Objects.requireNonNull(foo) assert NullPointerException public Foo(Bar bar) {\n this.bar = Objects.requireNonNull(bar);\n}\n assert Objects.requireNonNull(someobject, \"if someobject is null then something is wrong\");\nsomeobject.doCalc();\n NullPointerException AssertionError NullPointerException IllegalArgumentException public interface Action {\n void doSomething();\n}\n\npublic interface Parser {\n Action findAction(String userInput);\n}\n public class MyParser implements Parser {\n private static Action DO_NOTHING = new Action() {\n public void doSomething() { /* do nothing */ }\n };\n\n public Action findAction(String userInput) {\n // ...\n if ( /* we can't find any actions */ ) {\n return DO_NOTHING;\n }\n }\n}\n Parser parser = ParserFactory.getParser();\nif (parser == null) {\n // now what?\n // this would be an example of where null isn't (or shouldn't be) a valid response\n}\nAction action = parser.findAction(someInput);\nif (action == null) {\n // do nothing\n} else {\n action.doSomething();\n}\n ParserFactory.getParser().findAction(someInput).doSomething();\n try {\n ParserFactory.getParser().findAction(someInput).doSomething();\n} catch(ActionNotFoundException anfe) {\n userConsole.err(anfe.getMessage());\n}\n public Action findAction(final String userInput) {\n /* Code to return requested Action if found */\n return new Action() {\n public void doSomething() {\n userConsole.err(\"Action not found: \" + userInput);\n }\n }\n}\n"
},
{
"answer_id": 275869,
"author": "echox",
"author_id": 35915,
"author_profile": "https://Stackoverflow.com/users/35915",
"pm_score": 8,
"selected": false,
"text": "if ( foo.equals(\"bar\") ) {\n // ...\n}\n NullPointerException foo String if ( \"bar\".equals(foo) ) {\n // ...\n}\n"
},
{
"answer_id": 288524,
"author": "OscarRyz",
"author_id": 20654,
"author_profile": "https://Stackoverflow.com/users/20654",
"pm_score": 5,
"selected": false,
"text": "NullObjectPattern NullPointerException object"
},
{
"answer_id": 397740,
"author": "user2427",
"author_id": 1356709,
"author_profile": "https://Stackoverflow.com/users/1356709",
"pm_score": 6,
"selected": false,
"text": "static <T> T checkNotNull(T e) {\n if (e == null) {\n throw new NullPointerException();\n }\n return e;\n}\n import static ...\nvoid foo(int a, Person p) {\n if (checkNotNull(p).getAge() > a) {\n ...\n }\n else {\n ...\n }\n}\n...\n checkNotNull(someobject).doCalc();\n"
},
{
"answer_id": 452820,
"author": "erickson",
"author_id": 3474,
"author_profile": "https://Stackoverflow.com/users/3474",
"pm_score": 8,
"selected": false,
"text": "NullObject pattern public String getPostcode(Person person) { \n return person?.getAddress()?.getPostcode(); \n} \n ?. null null"
},
{
"answer_id": 1202969,
"author": "Michael Borgwardt",
"author_id": 16883,
"author_profile": "https://Stackoverflow.com/users/16883",
"pm_score": 6,
"selected": false,
"text": "nil"
},
{
"answer_id": 2064441,
"author": "thSoft",
"author_id": 90874,
"author_profile": "https://Stackoverflow.com/users/90874",
"pm_score": 8,
"selected": false,
"text": "Optional Optional Option ?: ?."
},
{
"answer_id": 2386013,
"author": "Luca Molteni",
"author_id": 4206,
"author_profile": "https://Stackoverflow.com/users/4206",
"pm_score": 9,
"selected": false,
"text": "@Nullable @NotNull @NotNull public static String helloWorld() {\n return \"Hello World\";\n}\n @Nullable public static String helloWorld() {\n return \"Hello World\";\n}\n helloWorld() public static void main(String[] args)\n{\n String result = helloWorld();\n if(result != null) {\n System.out.println(result);\n }\n}\n helloWorld() null void someMethod(@NotNull someParameter) { }\n someMethod(null);\n @Nullable @Nullable iWantToDestroyEverything() { return null; }\n iWantToDestroyEverything().something();\n @Nullable @NotNull"
},
{
"answer_id": 3499225,
"author": "fastcodejava",
"author_id": 184730,
"author_profile": "https://Stackoverflow.com/users/184730",
"pm_score": 5,
"selected": false,
"text": "assert if (someobject == null) {\n // Handle null here then move on.\n}\n if (someobject != null) {\n .....\n .....\n\n\n\n .....\n}\n"
},
{
"answer_id": 3925191,
"author": "tltester",
"author_id": 474659,
"author_profile": "https://Stackoverflow.com/users/474659",
"pm_score": 4,
"selected": false,
"text": "public static <T> T ifNull(T toCheck, T ifNull) {\n if (toCheck == null) {\n return ifNull;\n }\n return toCheck;\n}\n"
},
{
"answer_id": 5311857,
"author": "Oleg",
"author_id": 634475,
"author_profile": "https://Stackoverflow.com/users/634475",
"pm_score": 5,
"selected": false,
"text": "ValidationUtils.getNullValidator().addParam(plans, \"plans\").addParam(persons, \"persons\").validate();\n validate() ValidationException ValidationException void validate() throws ValidationException;\n"
},
{
"answer_id": 6101200,
"author": "Alex Worden",
"author_id": 181551,
"author_profile": "https://Stackoverflow.com/users/181551",
"pm_score": 7,
"selected": false,
"text": "NullPointerException IllegalArgumentException"
},
{
"answer_id": 7847199,
"author": "jeha",
"author_id": 571271,
"author_profile": "https://Stackoverflow.com/users/571271",
"pm_score": 3,
"selected": false,
"text": "public static <T> boolean isNull(T argument) {\n return (argument == null);\n}\n if (!isNull(someobject)) {\n someobject.doCalc();\n}\n != null"
},
{
"answer_id": 8212184,
"author": "Mike",
"author_id": 448078,
"author_profile": "https://Stackoverflow.com/users/448078",
"pm_score": 6,
"selected": false,
"text": "public Photo getPhotoOfThePerson(Person person) {\n if (person == null)\n return null;\n // Grabbing some resources or intensive calculation\n // using person object anyhow.\n}\n getPhotoOfThePerson(me.getGirlfriend())\n getPhotoByName(me.getGirlfriend()?.getName())\n public static MyEnum parseMyEnum(String value); // throws IllegalArgumentException\npublic static MyEnum parseMyEnumOrNull(String value);\n <alt> + <shift> + <j> /**\n * @return photo or null\n */\n /**\n * @return photo, never null\n */\n NullPointerException Exception Throwable NullPointerException public Photo getGirlfriendPhoto() {\n try {\n return appContext.getPhotoDataSource().getPhotoByName(me.getGirlfriend().getName());\n } catch (NullPointerException e) {\n return null;\n }\n}\n getPhotoDataSource() getPhotoByName() PreparedStatement public SomeValue calculateSomeValueUsingSophisticatedLogic(Predicate predicate) {\n try {\n Result1 result1 = performSomeCalculation(predicate);\n Result2 result2 = performSomeOtherCalculation(result1.getSomeProperty());\n Result3 result3 = performThirdCalculation(result2.getSomeProperty());\n Result4 result4 = performLastCalculation(result3.getSomeProperty());\n return result4.getSomeProperty();\n } catch (NullPointerException e) {\n return null;\n }\n}\n\npublic SomeValue calculateSomeValueUsingSophisticatedLogic(Predicate predicate) {\n SomeValue result = null;\n if (predicate != null) {\n Result1 result1 = performSomeCalculation(predicate);\n if (result1 != null && result1.getSomeProperty() != null) {\n Result2 result2 = performSomeOtherCalculation(result1.getSomeProperty());\n if (result2 != null && result2.getSomeProperty() != null) {\n Result3 result3 = performThirdCalculation(result2.getSomeProperty());\n if (result3 != null && result3.getSomeProperty() != null) {\n Result4 result4 = performLastCalculation(result3.getSomeProperty());\n if (result4 != null) {\n result = result4.getSomeProperty();\n }\n }\n }\n }\n }\n return result;\n}\n Exception ThreadDeath Error Error ThreadDeath public void updatePersonPhoneNumber(Long personId, String phoneNumber) {\n if (personId == null)\n return;\n DataSource dataSource = appContext.getStuffDataSource();\n Person person = dataSource.getPersonById(personId);\n if (person != null) {\n person.setPhoneNumber(phoneNumber);\n dataSource.updatePerson(person);\n } else {\n Person = new Person(personId);\n person.setPhoneNumber(phoneNumber);\n dataSource.insertPerson(person);\n }\n}\n public void updatePersonPhoneNumber(Long personId, String phoneNumber) {\n if (personId == null)\n return;\n DataSource dataSource = appContext.getStuffDataSource();\n Person person = dataSource.getPersonById(personId);\n if (person == null)\n throw new SomeReasonableUserException(\"What are you thinking about ???\");\n person.setPhoneNumber(phoneNumber);\n dataSource.updatePerson(person);\n}\n"
},
{
"answer_id": 9845966,
"author": "Murat Derya Özen",
"author_id": 396216,
"author_profile": "https://Stackoverflow.com/users/396216",
"pm_score": 5,
"selected": false,
"text": "Optional<T> Optional<Integer> possible = Optional.of(5);\npossible.isPresent(); // returns true\npossible.get(); // returns 5\n"
},
{
"answer_id": 11896966,
"author": "Stuart Marks",
"author_id": 1441122,
"author_profile": "https://Stackoverflow.com/users/1441122",
"pm_score": 6,
"selected": false,
"text": "java.util.Objects requireNonNull() NullPointerException Objects.requireNonNull(someObject);\nsomeObject.doCalc();\n Parent(Child child) {\n if (child == null) {\n throw new NullPointerException(\"child\");\n }\n this.child = child;\n}\n Parent(Child child) {\n this.child = Objects.requireNonNull(child, \"child\");\n}\n"
},
{
"answer_id": 12390983,
"author": "drzymala",
"author_id": 1391568,
"author_profile": "https://Stackoverflow.com/users/1391568",
"pm_score": 1,
"selected": false,
"text": "public void simpleFunc(SomeObject someObject){\n someObject = someObject != null ? someObject : new SomeObject(null);\n someObject.doSomething();\n}\n"
},
{
"answer_id": 12946734,
"author": "ianpojman",
"author_id": 1342121,
"author_profile": "https://Stackoverflow.com/users/1342121",
"pm_score": 5,
"selected": false,
"text": "if = null else class C {\n private final MyType mustBeSet;\n public C(MyType mything) {\n mustBeSet=Contract.notNull(mything);\n }\n private String name = \"<unknown>\";\n public void setName(String s) {\n name = Contract.notNull(s);\n }\n}\n\n\nclass Contract {\n public static <T> T notNull(T t) { if (t == null) { throw new ContractException(\"argument must be non-null\"); return t; }\n}\n"
},
{
"answer_id": 13676682,
"author": "abishkar bhattarai",
"author_id": 1564766,
"author_profile": "https://Stackoverflow.com/users/1564766",
"pm_score": 2,
"selected": false,
"text": "M2(Object test2) test2 != null"
},
{
"answer_id": 14253016,
"author": "Vinay Lodha",
"author_id": 212665,
"author_profile": "https://Stackoverflow.com/users/212665",
"pm_score": 2,
"selected": false,
"text": "@NotNull @Nullable Nullable NotNull @Guarded\npublic class BusinessObject\n{\n public BusinessObject(@NotNull String name)\n {\n this.name = name;\n }\n\n ...\n}\n // Throws a ConstraintsViolatedException because parameter name is null\nBusinessObject bo = new BusinessObject(null);\n"
},
{
"answer_id": 16218718,
"author": "Pierre Henry",
"author_id": 315677,
"author_profile": "https://Stackoverflow.com/users/315677",
"pm_score": 8,
"selected": false,
"text": "java.util.Optional Fruit Fruit public static Optional<Fruit> find(String name, List<Fruit> fruits) {\n for (Fruit fruit : fruits) {\n if (fruit.getName().equals(name)) {\n return Optional.of(fruit);\n }\n }\n return Optional.empty();\n}\n Fruit fruits Optional<Fruit> found = find(\"lemon\", fruits);\nif (found.isPresent()) {\n Fruit fruit = found.get();\n String name = fruit.getName();\n}\n map() orElse() String nameOrNull = find(\"lemon\", fruits)\n .map(f -> f.getName())\n .orElse(\"empty-name\");\n Optional null Optional Optional orElse ifPresent NullPointerException Optional"
},
{
"answer_id": 17109182,
"author": "Stuart Axon",
"author_id": 62709,
"author_profile": "https://Stackoverflow.com/users/62709",
"pm_score": 4,
"selected": false,
"text": "// Bad\nArrayList<String> lemmings;\nString[] names;\n\nvoid checkLemmings() {\n if (lemmings != null) for(lemming: lemmings) {\n // do something\n }\n}\n\n\n\n// Good\nArrayList<String> lemmings = new ArrayList<String>();\nString[] names = {};\n\nvoid checkLemmings() {\n for(lemming: lemmings) {\n // do something\n }\n}\n"
},
{
"answer_id": 19714883,
"author": "iowatiger08",
"author_id": 552782,
"author_profile": "https://Stackoverflow.com/users/552782",
"pm_score": 1,
"selected": false,
"text": "ObjectUtils.equals(object, null)\n CollectionUtils.isEmpty(myCollection);\n StringUtils.isEmpty(\"string\");\n"
},
{
"answer_id": 21391466,
"author": "Tobb",
"author_id": 1054021,
"author_profile": "https://Stackoverflow.com/users/1054021",
"pm_score": 2,
"selected": false,
"text": "null-checks You need to know which variables can be null, and which cannot, and you need to be confident about which category a given variable fall into. confident Single responsibility principle S SOLID null null exception null null null null null null null Validate.notNull(someParam, \"Can't function when someParam is null!\"); IllegalArgumentException NullPointerException null Collection not null public String nullSafeToString(final Object o) {\n return o != null ? o.toString() : \"null\";\n}\n"
},
{
"answer_id": 21726959,
"author": "Alireza Fattahi",
"author_id": 2648077,
"author_profile": "https://Stackoverflow.com/users/2648077",
"pm_score": 4,
"selected": false,
"text": "if(object == null){\n //you called my method badly!\n if(str.length() == 0){\n //you called my method badly again!\n}\n getCustomerAccounts(@NotEmpty String customerId,@Size(min = 1) String accountType)\n public class Car {\n\n @NotNull\n private String manufacturer;\n\n @NotNull\n @Size(min = 2, max = 14)\n private String licensePlate;\n\n @Min(2)\n private int seatCount;\n\n // ...\n}\n"
},
{
"answer_id": 22211014,
"author": "Gal Morad",
"author_id": 1940722,
"author_profile": "https://Stackoverflow.com/users/1940722",
"pm_score": 3,
"selected": false,
"text": "Preconditions.checkNotNull(paramVal, \"Method foo received null paramVal\");\n"
},
{
"answer_id": 23021801,
"author": "Sireesh Yarlagadda",
"author_id": 2057902,
"author_profile": "https://Stackoverflow.com/users/2057902",
"pm_score": 4,
"selected": false,
"text": "org.apache.commons.lang.Validate //using apache framework\n if(someObject!=null){ // simply checking against null\n}\n @isNull @Nullable // using annotation based validation\n // by writing static method and calling it across whereever we needed to check the validation\n\nstatic <T> T isNull(someObject e){ \n if(e == null){\n throw new NullPointerException();\n }\n return e;\n}\n"
},
{
"answer_id": 29887121,
"author": "Yogesh Devatraj",
"author_id": 1646333,
"author_profile": "https://Stackoverflow.com/users/1646333",
"pm_score": 5,
"selected": false,
"text": "java.util.Optional<T> if public Optional<Service> getRefrigertorControl() {\n Service s = new RefrigeratorService();\n //...\n return Optional.ofNullable(s);\n }\n Optional.ofNullable() Optional.empty() Optional.of() Optional ref = homeServices.getRefrigertorControl();\nref.ifPresent(HomeServices::switchItOn);\n @FunctionalInterface\npublic interface Consumer<T>\n HomeService.switchOn(Service) public static Optional<HomeServices> get() {\n service = Optional.of(service.orElse(new HomeServices()));\n return service;\n}\n import java.util.Optional;\npublic class HomeServices {\n private static final int NOW = 0;\n private static Optional<HomeServices> service;\n\npublic static Optional<HomeServices> get() {\n service = Optional.of(service.orElse(new HomeServices()));\n return service;\n}\n\npublic Optional<Service> getRefrigertorControl() {\n Service s = new RefrigeratorService();\n //...\n return Optional.ofNullable(s);\n}\n\npublic static void main(String[] args) {\n /* Get Home Services handle */\n Optional<HomeServices> homeServices = HomeServices.get();\n if(homeServices != null) {\n Optional<Service> refrigertorControl = homeServices.get().getRefrigertorControl();\n refrigertorControl.ifPresent(HomeServices::switchItOn);\n }\n}\n\npublic static void switchItOn(Service s){\n //...\n }\n}\n"
},
{
"answer_id": 33763493,
"author": "Lii",
"author_id": 452775,
"author_profile": "https://Stackoverflow.com/users/452775",
"pm_score": 1,
"selected": false,
"text": "void example() {\n Entry entry = new Entry();\n // This is the same as H-MANs solution \n Person person = getNullsafe(entry, e -> e.getPerson()); \n // Get object in several steps\n String givenName = getNullsafe(entry, e -> e.getPerson(), p -> p.getName(), n -> n.getGivenName());\n // Call void methods\n doNullsafe(entry, e -> e.getPerson(), p -> p.getName(), n -> n.nameIt()); \n}\n\n/** Return result of call to f1 with o1 if it is non-null, otherwise return null. */\npublic static <R, T1> R getNullsafe(T1 o1, Function<T1, R> f1) {\n if (o1 != null) return f1.apply(o1);\n return null; \n}\n\npublic static <R, T0, T1> R getNullsafe(T0 o0, Function<T0, T1> f1, Function<T1, R> f2) {\n return getNullsafe(getNullsafe(o0, f1), f2);\n}\n\npublic static <R, T0, T1, T2> R getNullsafe(T0 o0, Function<T0, T1> f1, Function<T1, T2> f2, Function<T2, R> f3) {\n return getNullsafe(getNullsafe(o0, f1, f2), f3);\n}\n\n\n/** Call consumer f1 with o1 if it is non-null, otherwise do nothing. */\npublic static <T1> void doNullsafe(T1 o1, Consumer<T1> f1) {\n if (o1 != null) f1.accept(o1);\n}\n\npublic static <T0, T1> void doNullsafe(T0 o0, Function<T0, T1> f1, Consumer<T1> f2) {\n doNullsafe(getNullsafe(o0, f1), f2);\n}\n\npublic static <T0, T1, T2> void doNullsafe(T0 o0, Function<T0, T1> f1, Function<T1, T2> f2, Consumer<T2> f3) {\n doNullsafe(getNullsafe(o0, f1, f2), f3);\n}\n\n\nclass Entry {\n Person getPerson() { return null; }\n}\n\nclass Person {\n Name getName() { return null; }\n}\n\nclass Name {\n void nameIt() {}\n String getGivenName() { return null; }\n}\n"
},
{
"answer_id": 34996504,
"author": "Ravindra babu",
"author_id": 4999394,
"author_profile": "https://Stackoverflow.com/users/4999394",
"pm_score": 3,
"selected": false,
"text": "final final A.java HashMap public B.java Map A.java // Avoid\na.getMap().put(key,value)\n\n//recommended\n\npublic void addElement(Object key, Object value){\n // Have null checks for both key and value here : single place\n map.put(key,value);\n}\n try{} catch{} finally{}"
},
{
"answer_id": 36167495,
"author": "Raghu K Nair",
"author_id": 2194364,
"author_profile": "https://Stackoverflow.com/users/2194364",
"pm_score": 5,
"selected": false,
"text": "Optional Optional stringToUse = Optional.of(\"optional is there\");\nstringToUse.ifPresent(System.out::println);\n Optional<Integer> i = Optional.ofNullable(wsObject.getFoo())\n .map(f -> f.getBar())\n .map(b -> b.getBaz())\n .map(b -> b.getInt());\n Optional optionalCarNull = Optional.ofNullable(someNull);\noptionalCarNull.orElseThrow(IllegalStateException::new);\n Objects.requireNonNull String lowerVal = Objects.requireNonNull(someVar, \"input cannot be null or empty\").toLowerCase();\n"
},
{
"answer_id": 38207227,
"author": "Ivan Golovach",
"author_id": 6546993,
"author_profile": "https://Stackoverflow.com/users/6546993",
"pm_score": 3,
"selected": false,
"text": "T null null Optional<T> null map T -> flatMap T -> Optional<R> class SomeService {\n @Inject\n private CompanyDao companyDao;\n\n // return Optional<String>\n public Optional<String> selectCeoCityByCompanyId0(int companyId) {\n return companyDao.selectById(companyId)\n .map(Company::getCeo)\n .flatMap(Person::getHomeAddress)\n .flatMap(Address::getCity);\n }\n\n // return String + default value\n public String selectCeoCityByCompanyId1(int companyId) {\n return companyDao.selectById(companyId)\n .map(Company::getCeo)\n .flatMap(Person::getHomeAddress)\n .flatMap(Address::getCity)\n .orElse(\"UNKNOWN\");\n }\n\n // return String + exception\n public String selectCeoCityByCompanyId2(int companyId) throws NoSuchElementException {\n return companyDao.selectById(companyId)\n .map(Company::getCeo)\n .flatMap(Person::getHomeAddress)\n .flatMap(Address::getCity)\n .orElseThrow(NoSuchElementException::new);\n }\n}\n\ninterface CompanyDao {\n // real situation: no company for such id -> use Optional<Company> \n Optional<Company> selectById(int id);\n}\n\nclass Company {\n // company always has ceo -> use Person \n Person ceo;\n public Person getCeo() {return ceo;}\n}\n\nclass Person {\n // person always has name -> use String\n String firstName;\n // person can be without address -> use Optional<Address>\n Optional<Address> homeAddress = Optional.empty();\n\n public String getFirstName() {return firstName;} \n public Optional<Address> getHomeAddress() {return homeAddress;}\n}\n\nclass Address {\n // address always contains country -> use String\n String country;\n // city field is optional -> use Optional<String>\n Optional<String> city = Optional.empty();\n\n String getCountry() {return country;} \n Optional<String> getCity() {return city;}\n}\n"
},
{
"answer_id": 39848137,
"author": "Vidura Mudalige",
"author_id": 3719179,
"author_profile": "https://Stackoverflow.com/users/3719179",
"pm_score": -1,
"selected": false,
"text": "public abstract class SomeObject {\n public abstract boolean isNil();\n}\n\npublic class NullObject extends SomeObject {\n @Override\n public boolean isNil() {\n return true;\n }\n}\npublic class RealObject extends SomeObject {\n @Override\n public boolean isNil() {\n return false;\n }\n}\n if (someobject != null) {\n someobject.doCalc();\n}\n if (!someObject.isNil()) {\n someobject.doCalc();\n}\n"
},
{
"answer_id": 40840957,
"author": "Philip John",
"author_id": 4256410,
"author_profile": "https://Stackoverflow.com/users/4256410",
"pm_score": 3,
"selected": false,
"text": "Java 7 java.util.Objects Java 8 Objects.isNull(var) Objects.nonNull(var) Objects String var1 = null;\nDate var2 = null;\nLong var3 = null;\n\nif(Objects.isNull(var1) && Objects.isNull(var2) && Objects.isNull(var3))\n System.out.println(\"All Null\");\nelse if (Objects.nonNull(var1) && Objects.nonNull(var2) && Objects.nonNull(var3))\n System.out.println(\"All Not Null\");\n"
},
{
"answer_id": 44902405,
"author": "Jobin",
"author_id": 2893693,
"author_profile": "https://Stackoverflow.com/users/2893693",
"pm_score": 3,
"selected": false,
"text": "isNull(yourObject) java.util.Objects String myObject = null;\n\nObjects.isNull(myObject); //will return true\n final String name = \"Jobin\";\nString nonNullValue = Optional.ofNullable(name).orElse(\"DefaultName\");\n"
},
{
"answer_id": 47285263,
"author": "yanefedor",
"author_id": 4545552,
"author_profile": "https://Stackoverflow.com/users/4545552",
"pm_score": 4,
"selected": false,
"text": "if (object != null) {\n ....\n}\n Objects object.ifPresent(obj -> ...); object.ifPresentOrElse(obj -> ..., () -> ...); @javax.annotation.Nullable @javax.annotation.Nonnnul"
},
{
"answer_id": 47986378,
"author": "Binod Pant",
"author_id": 1119386,
"author_profile": "https://Stackoverflow.com/users/1119386",
"pm_score": 1,
"selected": false,
"text": "@RequiresNonNull(value = { \"#1\" })\nstatic void check( Boolean x) {\n if (x) System.out.println(\"true\");\n else System.out.println(\"false\");\n}\n\npublic static void main(String[] args) {\n\n\n check(null);\n\n}\n [ERROR] found : null\n[ERROR] required: @Initialized @NonNull Boolean\n[ERROR] -> [Help 1]\n"
},
{
"answer_id": 48671389,
"author": "nilesh",
"author_id": 503804,
"author_profile": "https://Stackoverflow.com/users/503804",
"pm_score": 2,
"selected": false,
"text": "if(CommonUtil.resolve(()-> a.b().c()).isPresent()) {\n\n}\n if(a!=null && a.b()!=null && a.b().c()!=null) {\n\n}\n public static <T> Optional<T> resolve(Supplier<T> resolver) {\n try {\n T result = resolver.get();\n return Optional.ofNullable(result);\n } catch (NullPointerException var2) {\n return Optional.empty();\n }\n }\n"
},
{
"answer_id": 51311500,
"author": "Mukesh A",
"author_id": 4014678,
"author_profile": "https://Stackoverflow.com/users/4014678",
"pm_score": 3,
"selected": false,
"text": "NullPointerException Java 9 public static boolean isNull(Object obj) public static boolean nonNull(Object obj) public static <T> T requireNonNullElse(T obj, T defaultObj) public static <T> T requireNonNullElseGet(T obj, Supplier<? extends T> supplier) public static <T> T requireNonNull(T obj, Supplier<String> messageSupplier)"
},
{
"answer_id": 54017256,
"author": "Ramprabhu",
"author_id": 7236932,
"author_profile": "https://Stackoverflow.com/users/7236932",
"pm_score": 0,
"selected": false,
"text": " BiConsumer<Object, Consumer<Object>> consumeIfPresent = (s,f) ->{\n if(s!=null) {\n f.accept(s);\n }\n };\n\n consumeIfPresent.accept(null, (s)-> System.out.println(s) );\n consumeIfPresent.accept(\"test\", (s)-> System.out.println(s));\n\n BiFunction<Object, Function<Object,Object>,Object> executeIfPresent = (a,b) ->{\n if(a!=null) {\n return b.apply(a);\n }\n return null;\n };\n executeIfPresent.apply(null, (s)-> {System.out.println(s);return s;} );\n executeIfPresent.apply(\"test\", (s)-> {System.out.println(s);return s;} );\n"
},
{
"answer_id": 56145630,
"author": "Sebastian3000",
"author_id": 2785025,
"author_profile": "https://Stackoverflow.com/users/2785025",
"pm_score": 2,
"selected": false,
"text": "Optional.ofNullable(someobject).ifPresent(someobject -> someobject.doCalc());\n Optional.ofNullable(someobject).ifPresent(SomeClass::doCalc);\n"
},
{
"answer_id": 56543966,
"author": "rohit prakash",
"author_id": 6024604,
"author_profile": "https://Stackoverflow.com/users/6024604",
"pm_score": 3,
"selected": false,
"text": "java.util NullPointerException NullPointerExceptions Collections arrays"
},
{
"answer_id": 63325067,
"author": "Satish Hawalppagol",
"author_id": 12079719,
"author_profile": "https://Stackoverflow.com/users/12079719",
"pm_score": 0,
"selected": false,
"text": "public static String getNullString(Object someobject)\n{\n if(null==someobject )\n return null;\n\n else if(someobject.getClass().isInstance(\"\") && \n (((String)someobject).trim().equalsIgnoreCase(\"null\")|| \n ((String)someobject).trim().equalsIgnoreCase(\"\")))\n return null;\n\n else if(someobject.getClass().isInstance(\"\"))\n return (String)someobject;\n\n else\n return someobject.toString().trim();\n}\n if (StringUtilities.getNullString(someobject) != null)\n{ \n //Do something\n}\n"
},
{
"answer_id": 64437815,
"author": "Dan Chase",
"author_id": 3152516,
"author_profile": "https://Stackoverflow.com/users/3152516",
"pm_score": 0,
"selected": false,
"text": "try\n{\n myvar = get_user_supplied_value(); \n if (myvar == null || myvar.length() == 0) { alert_the_user_somehow(); return; };\n\n process_user_input(myvar);\n} catch (Exception ex) {\n handle_exception(ex);\n}\n if (myvar && myvar.length() > 0) { };\n if (myvar == null || myvar.length() == 0) {\n throw new Exception(\"You must supply a name!\");\n};\n"
},
{
"answer_id": 64455793,
"author": "Allen",
"author_id": 12716256,
"author_profile": "https://Stackoverflow.com/users/12716256",
"pm_score": 2,
"selected": false,
"text": " /**\n * Returns an {@code Optional} describing the specified value, if non-null,\n * otherwise returns an empty {@code Optional}.\n *\n * @param <T> the class of the value\n * @param value the possibly-null value to describe\n * @return an {@code Optional} with a present value if the specified value\n * is non-null, otherwise an empty {@code Optional}\n */\n public static <T> Optional<T> ofNullable(T value) {\n return value == null ? empty() : of(value);\n }\n /**\n * Return {@code true} if there is a value present, otherwise {@code false}.\n *\n * @return {@code true} if there is a value present, otherwise {@code false}\n */\n public boolean isPresent() {\n return value != null;\n }\n /**\n * If a value is present, invoke the specified consumer with the value,\n * otherwise do nothing.\n *\n * @param consumer block to be executed if a value is present\n * @throws NullPointerException if value is present and {@code consumer} is\n * null\n */\n public void ifPresent(Consumer<? super T> consumer) {\n if (value != null)\n consumer.accept(value);\n }\n"
},
{
"answer_id": 64747393,
"author": "vidy",
"author_id": 9993935,
"author_profile": "https://Stackoverflow.com/users/9993935",
"pm_score": 2,
"selected": false,
"text": "public class Null {\n\npublic static void main(String[] args) {\n String str1 = null;\n String str2 = \"\";\n\n if(isNullOrEmpty(str1))\n System.out.println(\"First string is null or empty.\");\n else\n System.out.println(\"First string is not null or empty.\");\n\n if(isNullOrEmpty(str2))\n System.out.println(\"Second string is null or empty.\");\n else\n System.out.println(\"Second string is not null or empty.\");\n}\n\npublic static boolean isNullOrEmpty(String str) {\n if(str != null && !str.isEmpty())\n return false;\n return true;\n}\n}\n str1 is null or empty.\nstr2 is null or empty.\n"
},
{
"answer_id": 69973748,
"author": "Premakumar Tatireddy",
"author_id": 5671333,
"author_profile": "https://Stackoverflow.com/users/5671333",
"pm_score": 1,
"selected": false,
"text": "Objects.isNull(null) Object ob=null;\nif(ob==null){ **do something}\n"
},
{
"answer_id": 72436784,
"author": "Greg7000",
"author_id": 6210975,
"author_profile": "https://Stackoverflow.com/users/6210975",
"pm_score": 0,
"selected": false,
"text": "import lombok.NonNull;\n\npublic class NonNullExample extends Something {\n private String name;\n \n public NonNullExample(@NonNull Person person) {\n super(\"Hello\");\n this.name = person.getName();\n }\n}\n"
}
] |
2008/11/07
|
[
"https://Stackoverflow.com/questions/271526",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/34856/"
] |
271,530
|
<p>There is an application with an extensive object graph. This graph mainly consists of a set of subgraphs which are connected to the rest of the graph through the only reference. But internally each such subgraph has some number of cross-references among objects. Once in a while such a sub graph needs to be thrown away. Would it be enough just to set to null the only referece which points to that subgraph to make it eligible for garbage collection?</p>
<p>My concern is that internal cross-references may "protect" the entire subgraph from garbage collection. In other words, is the garbage collector wise enough to figure out that all references in a subgraph do not leave the boundaries of the subgraph and therefore entire subgraph can be purged.</p>
|
[
{
"answer_id": 271556,
"author": "VonC",
"author_id": 6309,
"author_profile": "https://Stackoverflow.com/users/6309",
"pm_score": 5,
"selected": true,
"text": "public void buidDog() {\n Dog newDog = new Dog();\n Tail newTail = new Tail();\n newDog.tail = newTail;\n newTail.dog = newDog;\n}\n buildDog Dog Tail buildDog Dog Tail"
}
] |
2008/11/07
|
[
"https://Stackoverflow.com/questions/271530",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/31993/"
] |
271,546
|
<p>I have an object instance which I access with the ME as it accesses the instantiated object. I have a method that gets a collection of these objects and I wish to assign the first one to the instantiated object. </p>
<p>This is some of the code</p>
<pre><code>Dim Books As New BookCollection(True)
Books.ListByThemeFeatured(ThemeID, 1) ' Fills the collection
If Books.Count > 0 Then
Me = Books(0) ' Should set the first item to the current object
End If
</code></pre>
<p>Is this possible?</p>
<p>EDIT: Me refers to the class that was instantiated. In this case it is a BookEntity Class. THis method would have been called using the following code</p>
<pre><code> Dim Book As New BookEntity
Book.FeaturedBook() ' Should fill the book entity with a featured book
</code></pre>
|
[
{
"answer_id": 271556,
"author": "VonC",
"author_id": 6309,
"author_profile": "https://Stackoverflow.com/users/6309",
"pm_score": 5,
"selected": true,
"text": "public void buidDog() {\n Dog newDog = new Dog();\n Tail newTail = new Tail();\n newDog.tail = newTail;\n newTail.dog = newDog;\n}\n buildDog Dog Tail buildDog Dog Tail"
}
] |
2008/11/07
|
[
"https://Stackoverflow.com/questions/271546",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23230/"
] |
271,561
|
<p>In c#, is there any difference in the excecution speed for the order in which you state the condition?</p>
<pre><code>if (null != variable) ...
if (variable != null) ...
</code></pre>
<p>Since recently, I saw the first one quite often, and it caught my attention since I was used to the second one.</p>
<p>If there is no difference, what is the advantage of the first one?</p>
|
[
{
"answer_id": 271573,
"author": "Lasse V. Karlsen",
"author_id": 267,
"author_profile": "https://Stackoverflow.com/users/267",
"pm_score": 3,
"selected": false,
"text": "int i = 0;\nif (i = 1)\n{\n ...\n}\n"
},
{
"answer_id": 271575,
"author": "Jon Skeet",
"author_id": 22656,
"author_profile": "https://Stackoverflow.com/users/22656",
"pm_score": 8,
"selected": true,
"text": "// Probably wrong\nif (x = 5)\n if (x == 5)\n if (5 == x)\n x=5 Int32 Boolean"
},
{
"answer_id": 970563,
"author": "Gad",
"author_id": 25152,
"author_profile": "https://Stackoverflow.com/users/25152",
"pm_score": -1,
"selected": false,
"text": "int i;\nif(i==1){ // Exception raised: i is not initialized. (C/C++)\n doThis();\n}\n int i;\nif(1==i){ // OK, but the condition is not met.\n doThis();\n}\n"
},
{
"answer_id": 10741601,
"author": "DanW",
"author_id": 1415586,
"author_profile": "https://Stackoverflow.com/users/1415586",
"pm_score": 4,
"selected": false,
"text": "if(null == myDuck) class Duck == if(myDuck == null) null public class myDuck\n{\n public int quacks;\n static override bool operator ==(myDuck a, myDuck b)\n {\n // these will overflow the stack - because the a==null reenters this function from the top again\n if (a == null && b == null)\n return true;\n if (a == null || b == null)\n return false;\n\n // these wont loop\n if (null == a && null == b)\n return true;\n if (null == a || null == b)\n return false;\n return a.quacks == b.quacks; // this goes to the integer comparison\n }\n}\n"
},
{
"answer_id": 14622883,
"author": "Oliver",
"author_id": 1838048,
"author_profile": "https://Stackoverflow.com/users/1838048",
"pm_score": 4,
"selected": false,
"text": "if(someVariableThatShouldBeChecked != null\n && anotherOne != null\n && justAnotherCheckThatIsNeededForTestingNullity != null\n && allTheseChecksAreReallyBoring != null\n && thereSeemsToBeADesignFlawIfSoManyChecksAreNeeded != null)\n{\n // ToDo: Everything is checked, do something...\n}\n if(null != someVariableThatShouldBeChecked\n && null != anotherOne\n && null != justAnotherCheckThatIsNeededForTestingNullity\n && null != allTheseChecksAreReallyBoring\n && null != thereSeemsToBeADesignFlawIfSoManyChecksAreNeeded)\n{\n // ToDo: Everything is checked, do something...\n}\n if(null ...\n"
},
{
"answer_id": 26175819,
"author": "Gokkula Sudan R",
"author_id": 4089930,
"author_profile": "https://Stackoverflow.com/users/4089930",
"pm_score": 2,
"selected": false,
"text": "if( 5 == variable)\n if (variable == 5)\n if (variable = 5)\n if (CONSTANT.equals(myString))\n if (myString.equals(CONSTANT))\n"
}
] |
2008/11/07
|
[
"https://Stackoverflow.com/questions/271561",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/26070/"
] |
271,588
|
<p>Is there a way to pass null arguments to C# methods (something like null arguments in c++)?</p>
<p>For example:</p>
<p>Is it possible to translate the following c++ function to C# method:</p>
<pre><code>private void Example(int* arg1, int* arg2)
{
if(arg1 == null)
{
//do something
}
if(arg2 == null)
{
//do something else
}
}
</code></pre>
|
[
{
"answer_id": 271593,
"author": "Marcin K",
"author_id": 28722,
"author_profile": "https://Stackoverflow.com/users/28722",
"pm_score": 3,
"selected": false,
"text": "private void Example(int? arg1, int? arg2)\n{\n if(arg1 == null)\n {\n //do something\n }\n if(arg2 == null)\n {\n //do something else\n }\n}\n"
},
{
"answer_id": 271594,
"author": "MADMap",
"author_id": 17558,
"author_profile": "https://Stackoverflow.com/users/17558",
"pm_score": 3,
"selected": false,
"text": "private void Example(int? arg1, int? arg2)\n{\n if(!arg1.HasValue)\n {\n //do something\n }\n if(!arg2.HasValue)\n {\n //do something else\n }\n}\n"
},
{
"answer_id": 271597,
"author": "user35412",
"author_id": 35412,
"author_profile": "https://Stackoverflow.com/users/35412",
"pm_score": 2,
"selected": false,
"text": "private void Example(int? arg1, int? arg2)\n{\n if(arg1 == null)\n {\n //do something\n }\n if(arg2 == null)\n {\n //do something else\n }\n}\n"
},
{
"answer_id": 271600,
"author": "Sander",
"author_id": 2928,
"author_profile": "https://Stackoverflow.com/users/2928",
"pm_score": 7,
"selected": true,
"text": "// Both of these types mean the same thing, the ? is just C# shorthand.\nprivate void Example(int? arg1, Nullable<int> arg2)\n{\n if (arg1.HasValue)\n DoSomething();\n\n arg1 = null; // Valid.\n arg1 = 123; // Also valid.\n\n DoSomethingWithInt(arg1); // NOT valid!\n DoSomethingWithInt(arg1.Value); // Valid.\n}\n"
},
{
"answer_id": 271667,
"author": "mackenir",
"author_id": 25457,
"author_profile": "https://Stackoverflow.com/users/25457",
"pm_score": 3,
"selected": false,
"text": "int* ref int? ref int? int* ref int?"
},
{
"answer_id": 13724965,
"author": "ruffin",
"author_id": 1028230,
"author_profile": "https://Stackoverflow.com/users/1028230",
"pm_score": 2,
"selected": false,
"text": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\n\nnamespace consolePlay\n{\n class Program\n {\n static void Main(string[] args)\n {\n Program.test(new DateTime());\n Program.test(null);\n //Program.test(); // <<< Error. \n // \"No overload for method 'test' takes 0 arguments\" \n // So don't mistake nullable to be optional.\n\n Console.WriteLine(\"Done. Return to quit\");\n Console.Read();\n }\n\n static public void test(DateTime? dteIn)\n {\n Console.WriteLine(\"#\" + dteIn.ToString() + \"#\");\n }\n }\n}\n #1/1/0001 12:00:00 AM#\n##\nDone. Return to quit\n"
},
{
"answer_id": 31465371,
"author": "juancalbarran",
"author_id": 3119676,
"author_profile": "https://Stackoverflow.com/users/3119676",
"pm_score": 2,
"selected": false,
"text": "private void Example(int? arg1, int? arg2)\n {\n if (arg1.HasValue)\n {\n //do something\n }\n if (arg1.HasValue)\n {\n //do something else\n }\n }\n private void Example(Nullable<int> arg1, Nullable<int> arg2)\n {\n if (arg1.HasValue)\n {\n //do something\n }\n if (arg1.HasValue)\n {\n //do something else\n }\n }\n private void Example(int arg1 = 0, int arg2 = 1)\n {\n //do something else\n }\n"
}
] |
2008/11/07
|
[
"https://Stackoverflow.com/questions/271588",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/22996/"
] |
271,595
|
<p>I need to get all the dates present in the date range using SQL Server 2005</p>
|
[
{
"answer_id": 271607,
"author": "Ed Guiness",
"author_id": 4200,
"author_profile": "https://Stackoverflow.com/users/4200",
"pm_score": 3,
"selected": false,
"text": "select * from yourTable where yourDate between date1 and date2\n"
},
{
"answer_id": 271775,
"author": "ConcernedOfTunbridgeWells",
"author_id": 15401,
"author_profile": "https://Stackoverflow.com/users/15401",
"pm_score": -1,
"selected": false,
"text": "if object_id ('ods.uf_DateHierarchy') is not null\n drop function ods.uf_DateHierarchy\ngo\n\ncreate function ods.uf_DateHierarchy (\n @DateFrom datetime\n ,@DateTo datetime\n) returns @DateHierarchy table (\n DateKey datetime\n) as begin\n declare @today datetime \n set @today = @Datefrom\n\n while @today <= @DateTo begin\n insert @DateHierarchy (DateKey) values (@today)\n set @today = dateadd (dd, 1, @today)\n end\n\n return\nend\n\ngo\n"
},
{
"answer_id": 271878,
"author": "Incidently",
"author_id": 34187,
"author_profile": "https://Stackoverflow.com/users/34187",
"pm_score": 6,
"selected": false,
"text": "DECLARE @DateFrom smalldatetime, @DateTo smalldatetime;\nSET @DateFrom='20000101';\nSET @DateTo='20081231';\n-------------------------------\nWITH T(date)\nAS\n( \nSELECT @DateFrom \nUNION ALL\nSELECT DateAdd(day,1,T.date) FROM T WHERE T.date < @DateTo\n)\nSELECT date FROM T OPTION (MAXRECURSION 32767);\n"
},
{
"answer_id": 271910,
"author": "Soraz",
"author_id": 24610,
"author_profile": "https://Stackoverflow.com/users/24610",
"pm_score": -1,
"selected": false,
"text": "select distinct(orderPlacedDate) \nfrom orders \nwhere orderPlacedDate between '2008-07-01' and 2008-09-30' \norder by orderPlacedDate\n"
},
{
"answer_id": 272568,
"author": "user34850",
"author_id": 34850,
"author_profile": "https://Stackoverflow.com/users/34850",
"pm_score": 1,
"selected": false,
"text": "SELECT TO_DATE ('01-OCT-2008') + ROWNUM - 1 g_date\n FROM all_objects\n WHERE ROWNUM <= 15\n"
},
{
"answer_id": 1271024,
"author": "Chris Moutray",
"author_id": 81053,
"author_profile": "https://Stackoverflow.com/users/81053",
"pm_score": 0,
"selected": false,
"text": "/* holds a sequential set of number ie 0 to max */\n/* where max is the total number of rows expected */\ndeclare @Numbers table ( Number int )\n\ndeclare @max int \ndeclare @cnt int\n\nset @cnt = 0\n/* this value could be limited if you knew the total rows expected */\nset @max = 999 \n\n/* we are building the NUMBERS table on the fly */\n/* but this could be a proper table in the database */\n/* created at the point of first deployment */\nwhile (@cnt <= @max)\nbegin\n insert into @Numbers select @cnt\n set @cnt = @cnt + 1\nend\n\n/* EXAMPLE of creating dates with different intervals */\n\ndeclare @DateRanges table ( \n StartDateTime datetime, EndDateTime datetime, Interval int )\n\n/* example set of date ranges */\ninsert into @DateRanges\nselect '01 Jan 2009', '10 Jan 2009', 1 /* 1 day interval */\nunion select '01 Feb 2009', '10 Feb 2009', 2 /* 2 day interval */\n\n/* heres the important bit generate the dates */\nselect\n StartDateTime\nfrom\n(\n select\n d.StartDateTime as RangeStart,\n d.EndDateTime as RangeEnd,\n dateadd(DAY, d.Interval * n.Number, d.StartDateTime) as StartDateTime\n from \n @DateRanges d, @Numbers n\n) as dates\nwhere\n StartDateTime between RangeStart and RangeEnd\norder by StartDateTime\n /* EXAMPLE of creating times with different intervals */\n\ndelete from @DateRanges \n\n/* example set of date ranges */\ninsert into @DateRanges\nselect '01 Jan 2009 09:00:00', '01 Jan 2009 12:00:00', 30 /* 30 minutes interval */\nunion select '02 Feb 2009 09:00:00', '02 Feb 2009 10:00:00', 5 /* 5 minutes interval */\n\n/* heres the import bit generate the times */\nselect\n StartDateTime,\n EndDateTime\nfrom\n(\n select\n d.StartDateTime as RangeStart,\n d.EndDateTime as RangeEnd,\n dateadd(MINUTE, d.Interval * n.Number, d.StartDateTime) as StartDateTime,\n dateadd(MINUTE, d.Interval * (n.Number + 1) , StartDateTime) as EndDateTime\n from \n @DateRanges d, @Numbers n\n) as dates\nwhere\n StartDateTime >= RangeStart and EndDateTime <= RangeEnd\norder by StartDateTime\n"
},
{
"answer_id": 40958788,
"author": "Surinder Singh",
"author_id": 6892711,
"author_profile": "https://Stackoverflow.com/users/6892711",
"pm_score": 3,
"selected": false,
"text": "DECLARE @Date1 DATE='2016-12-21', @Date2 DATE='2016-12-25'\nSELECT DATEADD(DAY,number,@Date1) [Date] FROM master..spt_values WHERE type = 'P' AND DATEADD(DAY,number,@Date1) <= @Date2\n"
}
] |
2008/11/07
|
[
"https://Stackoverflow.com/questions/271595",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
271,596
|
<p>I've got a Java application that I'm writing an installer for. We're using the AdvancedInstaller program to create our installer (well, we're evaluating it currently, but will definitely purchase a license soon), and although it has special support for Java applications, it is geared more towards repackaging them as desktop-type apps, and our software is a series of Java services and other utilities which doesn't make sense to distribute in EXE-wrappers. The target audience for this software is very specific, and we know that our software will probably be automatically distributed on freshly-imaged Windows 2003 Server machines. So requiring Java as a prerequisite basically makes more work for some poor sysadmin, and I'd rather avoid that if at all possible by repackaging the JRE's installer inside of our own.</p>
<p>I discovered that if I tried to execute the JRE's installer as a pre-install step from my MSI, it complains that another installer is already running (mine, of course), so it bails out. When I try to add the JRE installer as a software prerequisite in the AdvancedInstaller project (as a bundled EXE, not a URL link), it never seems to actually get installed, despite me trying to force-install it.</p>
<p>What's the best way to repackage the JRE? I'm not really a Java guy, so I don't know too much about how other developers deal with this same problem, short of requiring their users to hunt out and install the JRE on their own. The ideal solution here would be for us to find a EXE installer which can be executed from inside of another MSI installer, or if it's possible, to just package all of the files inside of the JRE and then create the appropriate registry and environment variables. How should I go about doing this?</p>
|
[
{
"answer_id": 271622,
"author": "bdumitriu",
"author_id": 35415,
"author_profile": "https://Stackoverflow.com/users/35415",
"pm_score": 2,
"selected": false,
"text": "java ... ..\\..\\jre\\bin\\java ..."
}
] |
2008/11/07
|
[
"https://Stackoverflow.com/questions/271596",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14302/"
] |
271,598
|
<p>How do I save a Tlistviews layout in Delphi 2007?</p>
<p>I have been asked to write some code to allow users to re-order columns in a TListview (well all TListviews in our application), I have the code working (by manipulating the columns index and setting width to zero to hide columns not needed) but now I need a way to save the state of the view when to form exits.</p>
<p>What is the best way to do this? I thought about serialization, but I dont need the data or sort order so that seamed a bit overkill to me.</p>
<p>Some things to ponder
It needs to be on a per user basis
It needs to be flexible, in-case we add a new column in the middle of the listview
There is no garantee that the Column headding will be unique
The listview name may not be unique across the application</p>
<p>Any ideas?</p>
|
[
{
"answer_id": 271619,
"author": "Toon Krijthe",
"author_id": 18061,
"author_profile": "https://Stackoverflow.com/users/18061",
"pm_score": 2,
"selected": false,
"text": "[Settings]\n\n[Col_1]\nposition=1\nwidth=500\ntitle=hello world\nalign=left\nsort=ascending\n\n.. etc for more fields and more columns.\n TListviewHelper = class helper for TListView;\npublic\n procedure SaveToFile(const AFilename: string);\n procedure LoadFromFile(const AFileName: string);\nend;\n\nprocedure TListviewHelper.SaveToFile(const AFilename: string);\nvar\n ini : TIniFile;\nbegin\n ini := TIniFile.Create(AFileName);\n try\n // Save to ini file\n finally\n ini.Free;\n end;\nend;\n\nprocedure TListviewHelper.LoadFromFile(const AFileName: string);\nvar\n ini : TIniFile;\nbegin\n ini := TIniFile.Create(AFileName);\n try\n // Load from ini file\n finally\n ini.Free;\n end;\nend;\n"
},
{
"answer_id": 44900707,
"author": "C. MARIN",
"author_id": 8237709,
"author_profile": "https://Stackoverflow.com/users/8237709",
"pm_score": 0,
"selected": false,
"text": "Name | First name | Age | Job title\n \"Name,FName,Age,JTitle\"\n HCKU\\SOFTWARE\\MyApplication ColumnOrder"
}
] |
2008/11/07
|
[
"https://Stackoverflow.com/questions/271598",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2098/"
] |
271,609
|
<p>We have a couple of applications running on Java 5 and would like now to bring in an application based on Java 6. Can both java versions live together under Windows? </p>
<p>Is there any control panel to set the appropriate Java version for different applications, or any other way to set up, what version of Java will be used to run that particular application?</p>
|
[
{
"answer_id": 271623,
"author": "reallyinsane",
"author_id": 35407,
"author_profile": "https://Stackoverflow.com/users/35407",
"pm_score": 7,
"selected": true,
"text": "java ...\n JAVA6HOME C:\\java\\java6 %JAVA6HOME%\\bin\\java ...\n"
},
{
"answer_id": 271630,
"author": "Ruben",
"author_id": 26919,
"author_profile": "https://Stackoverflow.com/users/26919",
"pm_score": 2,
"selected": false,
"text": "set JAVA_HOME=C:\\...\\j2dskXXX PATH set PATH=%JAVA_HOME%\\bin;%PATH%"
},
{
"answer_id": 49688921,
"author": "Felipe Ferreira",
"author_id": 6489237,
"author_profile": "https://Stackoverflow.com/users/6489237",
"pm_score": 2,
"selected": false,
"text": "setlocal\nset JAVA_HOME=\"c:\\java8\"\nset PATH=%JAVA_HOME%\\bin;%PATH%;\njava -version\n"
},
{
"answer_id": 55476231,
"author": "Naresh Joshi",
"author_id": 2078093,
"author_profile": "https://Stackoverflow.com/users/2078093",
"pm_score": 3,
"selected": false,
"text": "_HOME PATH $ curl -s \"https://get.sdkman.io\" | bash \n$ source \"$HOME/.sdkman/bin/sdkman-init.sh\" \n sdk list java $ sdk install java 8.0.201-oracle\n $ sdk install java 9.0.4-open \n $ sdk install java 11.0.2-open\n $ sdk uninstall java 11.0.2-open\n sdk default java <your-java_version>\n"
}
] |
2008/11/07
|
[
"https://Stackoverflow.com/questions/271609",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/35061/"
] |
271,612
|
<p>I have the following file/line:</p>
<pre><code>pc=1 ct=1 av=112 cv=1100 cp=1700 rec=2 p=10001 g=0 a=0 sz=5 cr=200
pc=1 ct=1 av=113 cv=1110 cp=1800 rec=2 p=10001 g=0 a=10 sz=5 cr=200
</code></pre>
<p>and so on.
I wish to parse this and take the key value pairs and put them in a structure:</p>
<pre><code>struct pky
{
pky() :
a_id(0),
sz_id(0),
cr_id(0),
cp_id(0),
cv_id(0),
ct_id(0),
fr(0),
g('U'),
a(0),
pc(0),
p_id(0)
{ }
};
</code></pre>
<p>wherein either all the structure fields are used or some might be omitted.</p>
<p>How do I create a C++ class, which will do the same? I am new to C++ and not aware of any functions or library which would do this work.</p>
<p>Each line is to be processed, and the structure will be populated with one line each time and used, before it is flushed. The structure is later used as a parameter to a function.</p>
|
[
{
"answer_id": 271654,
"author": "Johannes Schaub - litb",
"author_id": 34509,
"author_profile": "https://Stackoverflow.com/users/34509",
"pm_score": 4,
"selected": true,
"text": "std::string line;\nstd::map<std::string, std::string> props;\nstd::ifstream file(\"foo.txt\");\nwhile(std::getline(file, line)) {\n std::string token;\n std::istringstream tokens(line);\n while(tokens >> token) {\n std::size_t pos = token.find('=');\n if(pos != std::string::npos) {\n props[token.substr(0, pos)] = token.substr(pos + 1);\n }\n }\n\n /* work with those keys/values by doing properties[\"name\"] */\n Line l(props[\"pc\"], props[\"ct\"], ...);\n\n /* clear the map for the next line */\n props.clear();\n}\n struct Line { \n std::string pc, ct; \n Line(std::string const& pc, std::string const& ct):pc(pc), ct(ct) {\n\n }\n};\n while(tokens >> token) {\n while(std::getline(tokens, token, ';')) {\n std::string token;\n std::istringstream tokens(line);\n while(tokens >> token) {\n std::size_t pos = token.find('=');\n if(pos != std::string::npos) {\n props[token.substr(0, pos)] = token.substr(pos + 1);\n }\n }\n int value;\n std::string key;\n std::istringstream tokens(line);\n while(tokens >> std::ws && std::getline(tokens, key, '=') && \n tokens >> std::ws >> value) {\n props[key] = value;\n }\n std::ws std::map<std::string, int> props;\n"
},
{
"answer_id": 271670,
"author": "korona",
"author_id": 25731,
"author_profile": "https://Stackoverflow.com/users/25731",
"pm_score": 2,
"selected": false,
"text": "#include <sstream>\n#include <string>\n#include <vector>\n#include <map>\n\nusing namespace std;\n\nvector<string> Tokenize(const string &str, const string &delim)\n{\n vector<string> tokens;\n\n size_t p0 = 0, p1 = string::npos;\n while(p0 != string::npos)\n {\n p1 = str.find_first_of(delim, p0);\n if(p1 != p0)\n {\n string token = str.substr(p0, p1 - p0);\n tokens.push_back(token);\n }\n p0 = str.find_first_not_of(delim, p1);\n }\n\n return tokens;\n}\n\nint main()\n{\n string data = \"pc=1 ct=1 av=112 cv=1100 cp=1700 rec=2 p=10001 g=0 a=0 sz=5 cr=200 pc=1 ct=1 av=113 cv=1110 cp=1800 rec=2 p=10001 g=0 a=10 sz=5 cr=200\";\n vector<string> entries = Tokenize(data, \" \");\n map<string, int> items;\n\n for (size_t i = 0; i < entries.size(); ++i)\n {\n string item = entries[i];\n\n size_t pos = item.find_first_of('=');\n if(pos == string::npos)\n continue;\n\n string key = item.substr(0, pos);\n int value;\n stringstream stream(item.substr(pos + 1));\n stream >> value;\n items.insert (pair<string, int>(key, value));\n }\n\n}\n"
},
{
"answer_id": 272265,
"author": "Martin York",
"author_id": 14065,
"author_profile": "https://Stackoverflow.com/users/14065",
"pm_score": 2,
"selected": false,
"text": "#include <string>\n#include <fstream>\n#include <sstream>\n#include <istream>\n#include <vector>\n#include <algorithm>\n#include <iterator>\n\nstd::istream& operator>> (std::istream& str,pky& value)\n{\n std::string line;\n std::getline(str,line);\n\n std::stringstream dataStr(line);\n\n static const std::streamsize max = std::numeric_limits<std::streamsize>::max();\n\n // Code assumes the ordering is always as follows\n // pc=1 ct=1 av=112 cv=1100 cp=1700 rec=2 p=10001 g=0 a=0 sz=5 cr=200\n dataStr.ignore(max,'=') >> value.pc;\n dataStr.ignore(max,'=') >> value.ct_id;\n dataStr.ignore(max,'=') >> value.a; // Guessing av=\n dataStr.ignore(max,'=') >> value.cv_id;\n dataStr.ignore(max,'=') >> value.cp_id;\n dataStr.ignore(max,'=') >> value.fr; // Guessing rec=\n dataStr.ignore(max,'=') >> value.p_id;\n dataStr.ignore(max,'=') >> value.g;\n dataStr.ignore(max,'=') >> value.a_id;\n dataStr.ignore(max,'=') >> value.sz_id;\n dataStr.ignore(max,'=') >> value.cr_id;\n\n return str;\n}\n\nint main()\n{\n std::ifstream file(\"plop\");\n\n std::vector<pky> v;\n pky data;\n\n while(file >> data)\n {\n // Do Somthing with data\n v.push_back(data);\n }\n\n // Even use the istream_iterators\n std::ifstream file2(\"plop2\");\n std::vector<pky> v2;\n\n std::copy(std::istream_iterator<pky>(file2),\n std::istream_iterator<pky>(),\n std::back_inserter(v2)\n );\n}\n"
},
{
"answer_id": 1727555,
"author": "3yE",
"author_id": 207427,
"author_profile": "https://Stackoverflow.com/users/207427",
"pm_score": 1,
"selected": false,
"text": "std::tr1::regex boost::regex"
}
] |
2008/11/07
|
[
"https://Stackoverflow.com/questions/271612",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/35416/"
] |
271,613
|
<p>I was reading <em><a href="http://java.sun.com/docs/books/performance/1st_edition/html/JPAppGC.fm.html" rel="nofollow noreferrer">Java Platform Performance</a></em> (sadly the link seems to have disappeared from the internet since I originally posed this question) and section A.3.3 worried me.</p>
<p>I had been working on the assumption that a variable that dropped out of scope would no longer be considered a GC root, but this paper appears to contradict that.</p>
<p>Do recent JVMs, in particular Sun's 1.6.0_07 version, still have this limitation? If so, then I have a lot of code to analyse...</p>
<p>I ask the question because the paper is from 1999 - sometimes things change, particularly in the world of GC.</p>
<hr/>
<p>As the paper is no longer available, I'd like to paraphrase the concern. The paper implied that variables that were defined inside a method would be considered a GC root until the method exited, and not until the code block ended. Therefore setting the variable to null was necessary to permit the Object referenced to be garbage collected.</p>
<p>This meant that a local variable defined in a conditional block in the main() method (or similar method that contained an infinite loop) would cause a one-off memory leak unless you nulled a variable just before it dropped out of scope.</p>
<p>The code from the <a href="https://stackoverflow.com/a/271824/7938">chosen answer</a> illustrates the issue well. On the version of the JVM referenced in the document, the foo object can not be garbage collected when it drops out of scope at the end of the try block. Instead, the JVM will hold open the reference until the end of the main() method, even though it is impossible for anything to use that reference.</p>
<p>This appears to be the origin of the idea that nulling a variable reference would help the garbage collector out, even if the variable was just about to drop out of scope.</p>
|
[
{
"answer_id": 271824,
"author": "Rasmus Faber",
"author_id": 5542,
"author_profile": "https://Stackoverflow.com/users/5542",
"pm_score": 4,
"selected": true,
"text": "public class TestInvisibleObject{\n public static class PrintWhenFinalized{\n private String s;\n public PrintWhenFinalized(String s){\n System.out.println(\"Constructing from \"+s);\n this.s = s;\n }\n protected void finalize() throws Throwable {\n System.out.println(\"Finalizing from \"+s);\n } \n }\n public static void main(String[] args) {\n try {\n PrintWhenFinalized foo = new PrintWhenFinalized(\"main\");\n } catch (Exception e) {\n // whatever\n }\n while (true) {\n // Provoke garbage-collection by allocating lots of memory\n byte[] o = new byte[1024];\n } \n }\n}\n"
},
{
"answer_id": 271932,
"author": "bruno conde",
"author_id": 31136,
"author_profile": "https://Stackoverflow.com/users/31136",
"pm_score": 2,
"selected": false,
"text": "public void doSomething() { \n for(int i = 0; i < 10 ; i++) {\n String s = new String(\"boo\");\n System.out.println(s);\n }\n}\n public void run() {\n try {\n Object foo = new Object();\n foo.doSomething();\n } catch (Exception e) {\n // whatever\n }\n while (true) { // do stuff } // loop forever\n}\n public class A {\n\n public static void main(String[] args) {\n A a = new A(); \n a.test4();\n }\n\n public void test1() { \n for(int i = 0; i < 10 ; i++) {\n B b = new B();\n System.out.println(b.toString());\n }\n System.out.println(\"b is collected\");\n }\n\n public void test2() {\n try {\n B b = new B();\n System.out.println(b.toString());\n } catch (Exception e) {\n }\n System.out.println(\"b is invisible\");\n }\n\n public void test3() {\n if (true) {\n B b = new B();\n System.out.println(b.toString());\n }\n System.out.println(\"b is invisible\");\n }\n\n public void test4() {\n int i = 0;\n while (i < 10) {\n B b = new B();\n System.out.println(b.toString());\n i++;\n }\n System.out.println(\"b is collected\");\n }\n\n public A() {\n }\n\n class B {\n public B() {\n }\n\n @Override\n public String toString() {\n return \"I'm B.\";\n }\n }\n}\n"
},
{
"answer_id": 18406054,
"author": "Holger",
"author_id": 2711488,
"author_profile": "https://Stackoverflow.com/users/2711488",
"pm_score": 2,
"selected": false,
"text": "import java.lang.ref.*;\n\npublic class Test {\n static final ReferenceQueue<Object> RQ=new ReferenceQueue<>();\n static Reference<Object> A, B;\n public static void main(String[] s) {\n {\n Object a=new Object();\n A=new PhantomReference<>(a, RQ);\n }\n {\n Object b=new Object();\n B=new PhantomReference<>(b, RQ);\n }\n forceGC();\n checkGC();\n }\n\n private static void forceGC() {\n try {\n for(int i=100000;;i+=i) {\n byte[] b=new byte[i];\n }\n } catch(OutOfMemoryError err){ err.printStackTrace();}\n }\n\n private static void checkGC() {\n for(;;) {\n Reference<?> r=RQ.poll();\n if(r==null) break;\n if(r==A) System.out.println(\"Object a collected\");\n if(r==B) System.out.println(\"Object b collected\");\n }\n }\n}\n"
}
] |
2008/11/07
|
[
"https://Stackoverflow.com/questions/271613",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7938/"
] |
271,615
|
<p>I have two lists of custom objects and want to update a field for all objects in one list if there is an object in the other list which matches on another pair of fields.</p>
<p>This code explains the problem better and produces the results I want. However for larger lists 20k, and a 20k list with matching objects, this takes a considerable time (31s). I can improve this with ~50% by using the generic lists Find(Predicate) method.</p>
<pre><code>using System;
using System.Linq;
using System.Linq.Expressions;
using System.Collections.Generic;
namespace ExperimentFW3
{
public class PropValue
{
public string Name;
public decimal Val;
public decimal Total;
}
public class Adjustment
{
public string PropName;
public decimal AdjVal;
}
class Program
{
static List<PropValue> propList;
static List<Adjustment> adjList;
public static void Main()
{
propList = new List<PropValue>{
new PropValue{Name = "Alfa", Val=2.1M},
new PropValue{Name = "Beta", Val=1.0M},
new PropValue{Name = "Gamma", Val=8.0M}
};
adjList = new List<Adjustment>{
new Adjustment{PropName = "Alfa", AdjVal=-0.1M},
new Adjustment{PropName = "Beta", AdjVal=3M}
};
foreach (var p in propList)
{
Adjustment a = adjList.SingleOrDefault(
av => av.PropName.Equals(p.Name)
);
if (a != null)
p.Total = p.Val + a.AdjVal;
else
p.Total = p.Val;
}
}
}
}
</code></pre>
<p>The desired result is: Alfa total=2,Beta total=4,Gamma total=8</p>
<p>But I wonder if this is possible to do even faster. Inner joining the two lists takes very little time, even when looping over 20k items in the resultset.</p>
<pre><code>var joined = from p in propList
join a in adjList on p.Name equals a.PropName
select new { p.Name, p.Val, p.Total, a.AdjVal };
</code></pre>
<p>So my question is if it's possible to do something like I would do with T-SQL? An UPDATE from a left join using ISNULL(val,0) on the adjustment value.</p>
|
[
{
"answer_id": 271645,
"author": "Jon Skeet",
"author_id": 22656,
"author_profile": "https://Stackoverflow.com/users/22656",
"pm_score": 4,
"selected": true,
"text": "adjList propList ToLookup ToDictionary adjList ToDictionary var adjDictionary = adjList.ToDictionary(av => av.PropName);\nforeach (var p in propList)\n{\n Adjustment a;\n if (adjDictionary.TryGetValue(p.Name, out a))\n {\n p.Total = p.Val + a.AdjVal;\n }\n else\n {\n p.Total = p.Val;\n }\n}\n"
},
{
"answer_id": 272155,
"author": "Amy B",
"author_id": 8155,
"author_profile": "https://Stackoverflow.com/users/8155",
"pm_score": 0,
"selected": false,
"text": "Dictionary<string, decimal> adjDictionary = adjList\n .GroupBy(a => a.PropName)\n .ToDictionary(g => g.Key, g => g.Sum(a => a.AdjVal))\n\npropList.ForEach(p => \n {\n decimal a;\n adjDictionary.TryGetValue(p.Name, out a);\n p.Total = p.Val + a;\n });\n"
},
{
"answer_id": 2093104,
"author": "DRBlaise",
"author_id": 234720,
"author_profile": "https://Stackoverflow.com/users/234720",
"pm_score": 0,
"selected": false,
"text": "var adjLookUp = adjList.ToLookUp(a => a.PropName);\nforeach (var p in propList) \n p.Total = p.Val + adjLookUp[p.Name].Sum(a => a.AdjVal);\n"
}
] |
2008/11/07
|
[
"https://Stackoverflow.com/questions/271615",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2006748/"
] |
271,657
|
<p>I have many emails coming in from different sources.
they all have attachments, many of them have attachment names in chinese, so these
names are converted to base64 by their email clients.</p>
<p>When I receive these emails, I wish to decode the name. but there are other names which are
not base64. How can I differentiate whether a string is base64 or not, using the <strong>jython</strong> programming language?</p>
<p>Ie. </p>
<p>First attachment: </p>
<pre><code>------=_NextPart_000_0091_01C940CC.EF5AC860
Content-Type: application/vnd.ms-excel;
name="Copy of Book1.xls"
Content-Transfer-Encoding: base64
Content-Disposition: attachment;
filename="Copy of Book1.xls"
</code></pre>
<p>second attachment:</p>
<pre><code>------=_NextPart_000_0091_01C940CC.EF5AC860
Content-Type: application/vnd.ms-excel;
name="=?gb2312?B?uLGxvmhlbrixsb5nLnhscw==?="
Content-Transfer-Encoding: base64
Content-Disposition: attachment;
filename="=?gb2312?B?uLGxvmhlbrixsb5nLnhscw==?="
</code></pre>
<p>Please note both "<strong>Content-Transfer-Encoding</strong>" have base64</p>
|
[
{
"answer_id": 271832,
"author": "bobince",
"author_id": 18936,
"author_profile": "https://Stackoverflow.com/users/18936",
"pm_score": 5,
"selected": true,
"text": "Content-Transfer-Encoding Content-Transfer-Encoding =?gb2312?B?uLGxvmhlbrixsb5nLnhscw==?=\n email.header.decode_header import email.header\nx= '=?gb2312?B?uLGxvmhlbrixsb5nLnhscw==?='\ntry:\n name= u''.join([\n unicode(b, e or 'ascii') for b, e in email.header.decode_header(x)\n ])\nexcept email.Errors.HeaderParseError:\n pass # leave name as it was\n Content-Type: application/vnd.ms-excel;\n name=\"=?gb2312?B?uLGxvmhlbrixsb5nLnhscw==?=\"\n '=?' =?gb2312?B?uLGxvmhlbrixsb5nLnhscw==?="
},
{
"answer_id": 1687765,
"author": "Ringding",
"author_id": 135811,
"author_profile": "https://Stackoverflow.com/users/135811",
"pm_score": 2,
"selected": false,
"text": "decode_header name = unicode(email.header.make_header(email.header.decode_header(x)))\n"
},
{
"answer_id": 2955981,
"author": "John Machin",
"author_id": 84270,
"author_profile": "https://Stackoverflow.com/users/84270",
"pm_score": 0,
"selected": false,
"text": "Content-Type: application/vnd.ms-excel;\n name=\"=?gb2312?B?uLGxvmhlbrixsb5nLnhscw==?=\"\n .xls .doc >>> import base64\n>>> base64.b64decode(\"uLGxvmhlbrixsb5nLnhscw==\")\n'\\xb8\\xb1\\xb1\\xbehen\\xb8\\xb1\\xb1\\xbeg.xls'\n>>>\n .xls gb2312 XYhenXYg.xls"
}
] |
2008/11/07
|
[
"https://Stackoverflow.com/questions/271657",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21537/"
] |
271,661
|
<p>I have a problem with Lucene.NET. During an index, I receive the error 'Access to the path segments is denied'. Or sometimes 'Access to the path deletable is denied'. I eventually gave 'Everyone' full security rights to the index directory, but the problem still existed.</p>
<p>I then found out that during the index run, lucene renames the segments file to 'segments.new', and <em>then</em> this error happens. I guess some process still tries to read from the old segments file after it has been renamed? I have no clue as to why this happens, or how to fix this. Strangely enough, my co-developers can run the index on their computer without a problem.</p>
<p>The error happens at happens in Lucene.Net.Index.IndexModifier.AddDocument(Document).</p>
<p>Any ideas would be much appreciated.</p>
|
[
{
"answer_id": 1325676,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": " doc.Add(new Field(\"URL\", \"C:/Users/blabla/(convert-csharp)/IMssg\", Field.Store.YES, Field.Index.TOKENIZED));\n\n writer.AddDocument(doc);\n Document doc = new Document();\n\n doc.Add(new Field(\"URL\", \"C:/Users/blabla/(convert-csharp)/IMssg\", Field.Store.YES, Field.Index.TOKENIZED));\n\n writer.AddDocument(doc);\n\n }\n catch (Exception t) \n {\n\n y = (y < 0) ? 0 : y - 1;\n\n string gfff = t.Message.ToString();\n\n }\n"
},
{
"answer_id": 1885765,
"author": "msr",
"author_id": 229350,
"author_profile": "https://Stackoverflow.com/users/229350",
"pm_score": 1,
"selected": false,
"text": " int attemptNo = 0;\n while (attemptNo < 2)\n {\n try\n {\n writer.AddDocument(doc);\n break;\n }\n catch (Exception e)\n {\n String ErrMsg = String.Format(\"{0} ({1}): While adding Document {2}/{3}, caught {4}\", DateTime.Now, attemptNo, doc.GetField(\"kanji\").StringValue(), doc.GetField(\"kana\").StringValue(), e.Message);\n attemptNo++;\n System.Threading.Thread.Sleep(30);\n Application.Current.Dispatcher.Invoke(System.Windows.Threading.DispatcherPriority.Normal, (Action)delegate()\n {\n ViewModel.Log.Add(ErrMsg);\n });\n }\n"
}
] |
2008/11/07
|
[
"https://Stackoverflow.com/questions/271661",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
271,665
|
<p>I have a client sending me requests without HTTP chunking (they use content-length). When my server responds, chunking is enabled, and the client can't handle this - even though they should be able to as they are using HTTP 1.1..... </p>
<p>I have tried to disable chunking by removing the entry below from the axis2 config file (axis2.xml) but the response is still going back chunked.</p>
<p>chunked</p>
<p>So the question is, is there somewhere else that the chunking is being enabled that is over-riding the axis2 setting? In tomcat setting perhaps?</p>
<p>Webserver details - tomcat 6.0.16, axis2 2.1.3</p>
<p>Thanks
Mike</p>
|
[
{
"answer_id": 1394439,
"author": "Chochos",
"author_id": 10165,
"author_profile": "https://Stackoverflow.com/users/10165",
"pm_score": 2,
"selected": false,
"text": "myStub._getServiceClient().getOptions().setProperty(HTTPConstants.CHUNKED, false);"
}
] |
2008/11/07
|
[
"https://Stackoverflow.com/questions/271665",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
271,668
|
<p>Is there a way of converting special folder paths to a full file name (and back) or do I need to code my own (not hard I know, but no point if it exists)</p>
<p>e.g. I want to store the file name of a template for an application, which the user can then change, it exists in the LocalApplicationData folder.</p>
<p>what I would like to store is the location of the file in the format:</p>
<p>%LOCALAPPDATA%\MyApp\Templates\Report Template.xls</p>
<p>so that this application file can be used by many users, each user when they open it will get the Report Template from their own local app directory.</p>
<p>I can write</p>
<pre><code>replace("%LOCALAPPDATA%", _
System.Environment.GetFolderPath(
System.Environment.SpecialFolder.LocalApplicationData))
and vice versa
</code></pre>
<p>when I come to save the file location, however is there a System.IO (or similar) call to do this for me, rather than having to go through every possible special folder?</p>
|
[
{
"answer_id": 271683,
"author": "chakrit",
"author_id": 3055,
"author_profile": "https://Stackoverflow.com/users/3055",
"pm_score": 3,
"selected": true,
"text": "static void Main(string[] args)\n{\n var values = Enum.GetValues(typeof(Environment.SpecialFolder));\n\n foreach (Environment.SpecialFolder value in values)\n Console.WriteLine(value + \" : \" + Environment.GetFolderPath(value));\n\n Console.ReadKey();\n}\n"
}
] |
2008/11/07
|
[
"https://Stackoverflow.com/questions/271668",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6684/"
] |
271,672
|
<p>I tried this on J2ME</p>
<pre><code>try {
Image immutableThumb = Image.createImage( temp, 0, temp.length);
} catch (Exception ex) {
System.out.println(ex);
}
</code></pre>
<p>I hit this error:
<code>java.lang.IllegalArgumentException:</code></p>
<p>How do I solve this?</p>
|
[
{
"answer_id": 2461625,
"author": "Cipi",
"author_id": 191164,
"author_profile": "https://Stackoverflow.com/users/191164",
"pm_score": 0,
"selected": false,
"text": "FFD8 FFD8 createImage() (temp[0] == 0xFF && temp[1] == 0xD8) temp temp FFD8 FFD9 temp temp"
}
] |
2008/11/07
|
[
"https://Stackoverflow.com/questions/271672",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
271,675
|
<p>I have a binded DataGridView where depending on some BoundItem property value that line will be read only. What is the best way to implement this?
Thanks</p>
|
[
{
"answer_id": 271679,
"author": "CestLaGalere",
"author_id": 6684,
"author_profile": "https://Stackoverflow.com/users/6684",
"pm_score": 0,
"selected": false,
"text": "private sub MyView_RowEnter(...) handles MyView.RowEnter\n MyView.Rows(e.Rowindex).ReadOnly = (condition)\nend sub\n"
},
{
"answer_id": 3176471,
"author": "x77",
"author_id": 494800,
"author_profile": "https://Stackoverflow.com/users/494800",
"pm_score": 2,
"selected": false,
"text": "Private Sub Dgv_CellBeginEdit(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewCellCancelEventArgs) Handles Dgv.CellBeginEdit\n If YourCondition(BoundItem.Property) then e.cancel = true\nEnd Sub\n"
}
] |
2008/11/07
|
[
"https://Stackoverflow.com/questions/271675",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
271,688
|
<p><a href="http://dl.getdropbox.com/u/240752/stars.gif" rel="nofollow noreferrer">My screenshot http://dl.getdropbox.com/u/240752/stars.gif</a></p>
<p>I want to have it so that only the text is underlined. The only way I can see of doing this is this:</p>
<pre><code>.no-underline {
text-decoration:none;
}
.underline {
text-decoration:underline;
}
<a href="#" class="no-underline"><span class="underline">Average customer review rating</span><img src="img/five-stars.gif" alt="five stars" width="78" height="16" title="5 star review rating" /></a>
</code></pre>
<p>Is this the best way? or does someone know a leaner way? Thanks.</p>
|
[
{
"answer_id": 271697,
"author": "Lasar",
"author_id": 9438,
"author_profile": "https://Stackoverflow.com/users/9438",
"pm_score": 4,
"selected": true,
"text": "<a href=\"#\" class=\"imgLink\"><span>Link Text</span> <img src=\"...\"></a>\n\na.imgLink { text-decoration: none; }\na.imgLink span { text-decoration: underline; }\n"
},
{
"answer_id": 271732,
"author": "jishi",
"author_id": 33663,
"author_profile": "https://Stackoverflow.com/users/33663",
"pm_score": 0,
"selected": false,
"text": "<a class=\"imgLink\" href=\"\">some text<img src=\"\" /></a>"
},
{
"answer_id": 1915596,
"author": "elliott",
"author_id": 230861,
"author_profile": "https://Stackoverflow.com/users/230861",
"pm_score": 0,
"selected": false,
"text": "a.externalLink{\n padding-right: 15px;\n background: transparent url('badge.png') no-repeat center right;\n}\n <a href=\"foo\" class=\"externalLink\">bar</a>\n"
}
] |
2008/11/07
|
[
"https://Stackoverflow.com/questions/271688",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/26107/"
] |
271,699
|
<p>Is there any way to (unit) test my own HtmlHelpers? In case when I'd like to have custom control (rendered by HtmlHelper) and I know requierements for that control how could I write tests first - and then write code? Is there a specific (nice) way to do that? </p>
<p>Is it worth?</p>
|
[
{
"answer_id": 747186,
"author": "Marc Climent",
"author_id": 58791,
"author_profile": "https://Stackoverflow.com/users/58791",
"pm_score": 6,
"selected": true,
"text": " public static HtmlHelper CreateHtmlHelper(ViewDataDictionary viewData)\n {\n var mocks = new MockRepository();\n\n var cc = mocks.DynamicMock<ControllerContext>(\n mocks.DynamicMock<HttpContextBase>(),\n new RouteData(),\n mocks.DynamicMock<ControllerBase>());\n\n var mockViewContext = mocks.DynamicMock<ViewContext>(\n cc,\n mocks.DynamicMock<IView>(),\n viewData,\n new TempDataDictionary());\n\n var mockViewDataContainer = mocks.DynamicMock<IViewDataContainer>();\n\n mockViewDataContainer.Expect(v => v.ViewData).Return(viewData);\n\n return new HtmlHelper(mockViewContext, mockViewDataContainer);\n }\n"
},
{
"answer_id": 5957990,
"author": "CRice",
"author_id": 55693,
"author_profile": "https://Stackoverflow.com/users/55693",
"pm_score": 3,
"selected": false,
"text": "HtmlHelper<T> public static HtmlHelper<Model> CreateHtmlHelper()\n{\n ViewDataDictionary vd = new ViewDataDictionary(new Model());\n\n var controllerContext = new ControllerContext(new Mock<HttpContextBase>().Object,\n new RouteData(),\n new Mock<ControllerBase>().Object);\n\n var viewContext = new ViewContext(controllerContext, new Mock<IView>().Object, vd, new TempDataDictionary(), new Mock<TextWriter>().Object);\n\n var mockViewDataContainer = new Mock<IViewDataContainer>();\n mockViewDataContainer.Setup(v => v.ViewData).Returns(vd);\n\n return new HtmlHelper<Model>(viewContext, mockViewDataContainer.Object);\n}\n public HtmlHelper<T> CreateHtmlHelper<T>() where T : new()\n {\n var vd = new ViewDataDictionary(new T());\n\n var controllerContext = new ControllerContext(new Mock<HttpContextBase>().Object,\n new RouteData(),\n new Mock<ControllerBase>().Object);\n\n var viewContext = new ViewContext(controllerContext, new Mock<IView>().Object, vd, new TempDataDictionary(), new Mock<TextWriter>().Object);\n\n var mockViewDataContainer = new Mock<IViewDataContainer>();\n mockViewDataContainer.Setup(v => v.ViewData).Returns(vd);\n\n return new HtmlHelper<T>(viewContext, mockViewDataContainer.Object);\n }\n"
}
] |
2008/11/07
|
[
"https://Stackoverflow.com/questions/271699",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3182/"
] |
271,700
|
<p>As far as i know the EAP editions of JBoss Application Server (AS) are just a bunch of community edition JBoss projects with some sugar.</p>
<p>So, what is the <strong>community edition</strong> of the JBoss Application Server that <strong>JBoss EAP 4.3.0</strong> corresponds to?</p>
|
[
{
"answer_id": 17274131,
"author": "Ondra Žižka",
"author_id": 145989,
"author_profile": "https://Stackoverflow.com/users/145989",
"pm_score": 1,
"selected": false,
"text": "settings.xml"
}
] |
2008/11/07
|
[
"https://Stackoverflow.com/questions/271700",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23428/"
] |
271,706
|
<p>I basically have a page which shows a "processing" screen which has been flushed to the browser. Later on I need to redirect this page, currently we use meta refresh and this normally works fine. </p>
<p>With a new payment system, which includes 3D secure, we potentially end up within an iframe being directed back to our site from a third party.</p>
<p>I need to be able to redirect from this page, either using javascript or meta-refresh, and bust out of the iframe if it exists.</p>
<p>Cheers!</p>
<p>(I have done busting out of iframes before but can't find my old code and a google search was useless, thought it was the perfect time to try Stackoverflow out!)</p>
|
[
{
"answer_id": 271902,
"author": "Ben Lynch",
"author_id": 15363,
"author_profile": "https://Stackoverflow.com/users/15363",
"pm_score": 3,
"selected": true,
"text": "<script type=\"text/javascript\" language=\"javascript\">\n if (top.frames.length>0)\n setTimeout(\"top.location = window.location;\",100);\n</script>\n"
},
{
"answer_id": 272218,
"author": "Adam Tuttle",
"author_id": 751,
"author_profile": "https://Stackoverflow.com/users/751",
"pm_score": 0,
"selected": false,
"text": "<SCRIPT TYPE=\"text/JavaScript\">\n if (window == top){top.location.replace(\"/foo.html\");}\n</SCRIPT>\n"
},
{
"answer_id": 11338554,
"author": "Devaroop",
"author_id": 909297,
"author_profile": "https://Stackoverflow.com/users/909297",
"pm_score": 0,
"selected": false,
"text": "parent.document.location = \"http://www.google.com\"\n <a href=\"http://www.google.com\" target=_top >Google</a>\n"
}
] |
2008/11/07
|
[
"https://Stackoverflow.com/questions/271706",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15363/"
] |
271,710
|
<p>The code looks like below:</p>
<pre><code>namespace Test
{
public interface IMyClass
{
List<IMyClass> GetList();
}
public class MyClass : IMyClass
{
public List<IMyClass> GetList()
{
return new List<IMyClass>();
}
}
}
</code></pre>
<p>When I Run Code Analysis i get the following recommendation.</p>
<blockquote>
<p>Warning 3 CA1002 : Microsoft.Design : Change 'List' in 'IMyClass.GetList()' to use Collection, ReadOnlyCollection or KeyedCollection</p>
</blockquote>
<p>How should I fix this and what is good practice here?</p>
|
[
{
"answer_id": 271711,
"author": "Jon Skeet",
"author_id": 22656,
"author_profile": "https://Stackoverflow.com/users/22656",
"pm_score": 6,
"selected": false,
"text": "IList<T> ICollection<T> IEnumerable<T>"
},
{
"answer_id": 271719,
"author": "Tamas Czinege",
"author_id": 8954,
"author_profile": "https://Stackoverflow.com/users/8954",
"pm_score": -1,
"selected": false,
"text": "//using System.Collections.ObjectModel;\n\nCollection<MyClass> myCollection = new Collection<MyClass>(myList);\n"
},
{
"answer_id": 271726,
"author": "Timothy Khouri",
"author_id": 11917,
"author_profile": "https://Stackoverflow.com/users/11917",
"pm_score": 3,
"selected": false,
"text": "Collection<T> List<T> List<T> Collection<T> public int[] MyIntegers { get; }\n someObject.MyIngegers[3] = 12345;\n List<T>"
},
{
"answer_id": 271842,
"author": "Greg Beech",
"author_id": 13552,
"author_profile": "https://Stackoverflow.com/users/13552",
"pm_score": 9,
"selected": true,
"text": "List<T> List<T> Add Insert Remove Collection<T> IList<T> ICollection<T> IEnumerable<T> List<T> BinarySearch Sort"
},
{
"answer_id": 8859865,
"author": "Konstantin Isaev",
"author_id": 1026676,
"author_profile": "https://Stackoverflow.com/users/1026676",
"pm_score": 0,
"selected": false,
"text": "this.InternalData.Filter(crteria).ToList();\n List<TItem> IEnumerable<TItem>"
},
{
"answer_id": 33654749,
"author": "NullReference",
"author_id": 2170850,
"author_profile": "https://Stackoverflow.com/users/2170850",
"pm_score": 1,
"selected": false,
"text": "List<T> Collection<T> Collection<T> List<T> List<T> Collection<T>"
}
] |
2008/11/07
|
[
"https://Stackoverflow.com/questions/271710",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11135/"
] |
271,718
|
<p>In a detailsview, how can I prepopulate one of the textboxes on the insertcommand (When the user clicks insert and the view is insert).</p>
<p>I think this would work for codebehind:</p>
<p>Dim txtBox As TextBox = FormView1.FindControl("txtbox")</p>
<p>txtbox.Text = "Whatever I want"</p>
<p>Is this right? What do I need in the aspx (not as sure)? Also, I'm assuming the server-side code will go in the itemcommand or insertcreating event.</p>
<p>I have typed this in VB.NET but I am using C# (I can do both so on a language agnostic forum I might type the problem in another language). I am also using a SqlDataSource, with my parameters and insert/delete/edit commands all created.</p>
<p>I am trying to generate a random GUID (using the GUID object), which will be prepopulated in the textbox.</p>
<p>Also, is the postbackurl property of a button not another way of preserving form state?</p>
<p>Thanks</p>
|
[
{
"answer_id": 684039,
"author": "Anthony K",
"author_id": 1682,
"author_profile": "https://Stackoverflow.com/users/1682",
"pm_score": 0,
"selected": false,
"text": "dvDetails.ChangeMode(DetailsViewMode.Insert)\npnlDetailMenu.Visible = True\nDim ColumnTextBox As TextBox\nColumnTextBox = dvDetails.Rows(0).Cells(1).Controls(0)\nIf Not ColumnTextBox Is Nothing Then\n ColumnTextBox.Text = \"Initial Value\"\nEnd If\n"
},
{
"answer_id": 696436,
"author": "Mark Glorie",
"author_id": 952,
"author_profile": "https://Stackoverflow.com/users/952",
"pm_score": 1,
"selected": false,
"text": "<asp:TemplateField>\n <InsertItemTemplate>\n <asp:TextBox ID=\"txtField\" runat=\"server\" Text='<%# Bind(\"GUID\") %>'/>\n </InsertItemTemplate>\n <ItemTemplate>\n <asp:Label ID=\"lblField\" runat=\"server\" Text='<%# Bind(\"GUID\") %>'/>\n </ItemTemplate>\n</asp:TemplateField>\n Private Sub dv_DataBound(ByVal sender As Object, ByVal e As EventArgs) Handles dv.DataBound\n dim txt as Textbox = dv.FindControl(\"txtField\")\n txt.Text = GenerateGUID()\nEnd Sub\n"
}
] |
2008/11/07
|
[
"https://Stackoverflow.com/questions/271718",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/32484/"
] |
271,724
|
<p>I am playing around with ASP.NET MVC for the first time, so I apologize in advance if this sounds academic. </p>
<p>I have created a simple content management system using ASP.NET MVC. The url to retrieve a list of content, in this case, announcements, looks like:</p>
<pre><code>http://www.mydomain.com/announcements/list/10
</code></pre>
<p>This will return the top ten most recent announcements.</p>
<p>My questions are as follows:</p>
<ol>
<li><p>Is it possible for any website to consume this service? Or would I also have to expose it using something like WCF?</p></li>
<li><p>What are some examples, of how to consume this service to display this data on another website? I'm primarily programming in the .NET world, but I'm thinking if I could consume the service using javascript, or do something with Json, it could really work for any technology.</p></li>
</ol>
<p>I am looking to dynamically generate something like the following output:</p>
<pre><code><div class="announcement">
<h1>Title</h1>
<h2>Posted Date</h3>
<p>Teaser</p>
<a href="www.someotherdomain.com">More</a>
</div>
</code></pre>
<hr>
<p>For now ... is it possible to return an Html representation and display it in a webpage? Is this possible using just Javascript?</p>
|
[
{
"answer_id": 684039,
"author": "Anthony K",
"author_id": 1682,
"author_profile": "https://Stackoverflow.com/users/1682",
"pm_score": 0,
"selected": false,
"text": "dvDetails.ChangeMode(DetailsViewMode.Insert)\npnlDetailMenu.Visible = True\nDim ColumnTextBox As TextBox\nColumnTextBox = dvDetails.Rows(0).Cells(1).Controls(0)\nIf Not ColumnTextBox Is Nothing Then\n ColumnTextBox.Text = \"Initial Value\"\nEnd If\n"
},
{
"answer_id": 696436,
"author": "Mark Glorie",
"author_id": 952,
"author_profile": "https://Stackoverflow.com/users/952",
"pm_score": 1,
"selected": false,
"text": "<asp:TemplateField>\n <InsertItemTemplate>\n <asp:TextBox ID=\"txtField\" runat=\"server\" Text='<%# Bind(\"GUID\") %>'/>\n </InsertItemTemplate>\n <ItemTemplate>\n <asp:Label ID=\"lblField\" runat=\"server\" Text='<%# Bind(\"GUID\") %>'/>\n </ItemTemplate>\n</asp:TemplateField>\n Private Sub dv_DataBound(ByVal sender As Object, ByVal e As EventArgs) Handles dv.DataBound\n dim txt as Textbox = dv.FindControl(\"txtField\")\n txt.Text = GenerateGUID()\nEnd Sub\n"
}
] |
2008/11/07
|
[
"https://Stackoverflow.com/questions/271724",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1768/"
] |
271,725
|
<p>I'm working on a search module that searches in text columns that contains html code. The queries are constructed like: WHERE htmlcolumn LIKE '% searchterm %';</p>
<p>Default the modules searches with spaces at both end of the searchterms, with wildcards at the beginning and/or the end of the searchterms these spaces are removed (*searchterm -> LIKE '%searchterm %'; Also i've added the possibility to exclude results with certain words (-searchterm -> NOT LIKE '% searchterm %'). So far so good.</p>
<p>The problem is that words that that are preceded by an html-tag are not found (<code><br/></code>searchterm is not found when searching on LIKE '% searchterm.., also words that come after a comma or end with a period etc.).
What i would like to do is search for words that are not preceded or followed by the characters A-Z and a-z. Every other characters are ok.</p>
<p>Any ideas how i should achieve this? Thanks!</p>
|
[
{
"answer_id": 272043,
"author": "Incidently",
"author_id": 34187,
"author_profile": "https://Stackoverflow.com/users/34187",
"pm_score": 1,
"selected": false,
"text": "SELECT * FROM `t` WHERE `htmlcolumn` REGEXP '[[:<:]]term[[:>:]]'\n"
}
] |
2008/11/07
|
[
"https://Stackoverflow.com/questions/271725",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21238/"
] |
271,730
|
<p>I run a website where users can post items (e.g. pictures). The items are stored in a MySQL database. </p>
<p>I want to query for the last ten posted items BUT with the constraint of a maximum of 3 items can come from any single user. </p>
<p>What is the best way of doing it? My preferred solution is a constraint that is put on the SQL query requesting the last ten items. But ideas on how to set up the database design is very welcome.</p>
<p>Thanks in advance!</p>
<p>BR</p>
|
[
{
"answer_id": 271768,
"author": "Tomalak",
"author_id": 18771,
"author_profile": "https://Stackoverflow.com/users/18771",
"pm_score": 2,
"selected": false,
"text": "SELECT\n i.UserId,\n i.ImageId\nFROM\n UserSuppliedImages i\nWHERE\n /* second valid ImageId */\n ImageId = (\n SELECT MAX(ImageId)\n FROM UserSuppliedImages\n WHERE UserId = i.UserId\n )\n OR\n /* second valid ImageId */\n ImageId = (\n SELECT MAX(ImageId)\n FROM UserSuppliedImages\n WHERE UserId = i.UserId\n AND ImageId < (\n SELECT MAX(ImageId)\n FROM UserSuppliedImages\n WHERE UserId = i.UserId\n )\n )\n /* you get the picture... \n the more \"per user\" images you want, the more complex this will get */\nLIMIT 10;\n ImageId SELECT TOP 10\n img.ImageId,\n img.ImagePath,\n img.UserId\nFROM\n UserSuppliedImages img\nWHERE\n ImageId IN (\n SELECT TOP 3 ImageId\n FROM UserSuppliedImages \n WHERE UserId = img.UserId\n )\n"
},
{
"answer_id": 271996,
"author": "Incidently",
"author_id": 34187,
"author_profile": "https://Stackoverflow.com/users/34187",
"pm_score": 4,
"selected": true,
"text": "SELECT `img`.`id` , `img`.`userid`\nFROM `img`\nWHERE 3 > (\nSELECT count( * )\nFROM `img` AS `img1`\nWHERE `img`.`userid` = `img1`.`userid`\nAND `img`.`id` > `img1`.`id` )\nORDER BY `img`.`id` DESC\nLIMIT 10 \n id"
}
] |
2008/11/07
|
[
"https://Stackoverflow.com/questions/271730",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/103373/"
] |
271,736
|
<p>Given a html document, what is the most correct and concise regular expression pattern to remove the query strings from each url in the document?</p>
|
[
{
"answer_id": 271778,
"author": "nickf",
"author_id": 9021,
"author_profile": "https://Stackoverflow.com/users/9021",
"pm_score": 0,
"selected": false,
"text": "/href=\"([^\\?\"]*?)\\?[^\\\"]*\"/\n href=\"\\1\"\n <link>"
}
] |
2008/11/07
|
[
"https://Stackoverflow.com/questions/271736",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6691/"
] |
271,741
|
<p>I'm trying to parse a html page and extract 2 values from a table row.
The html for the table row is as follows: -</p>
<pre><code><tr>
<td title="Associated temperature in (ºC)" class="TABLEDATACELL" nowrap="nowrap" align="Left" colspan="1" rowspan="1">Max Temperature (ºC)</td>
<td class="TABLEDATACELLNOTT" nowrap="nowrap" align="Center" colspan="1" rowspan="1">6</td>
<td class="TABLEDATACELLNOTT" nowrap="nowrap" align="Center" colspan="1" rowspan="1"> 13:41:30</td>
</tr>
</code></pre>
<p>and the expression I have at the moment is:</p>
<pre><code><tr>[\s]<td[^<]+?>Max Temperature[\w\s]*</td>[\s]
<td[^<]+?>(?<value>([\d]+))</td>[\s]
<td[^<]+?>(?<time>([\d\:]+))</td>[\s]</tr>
</code></pre>
<p>However I don't seem to be able to extract any matches.
Could anyone point me in the right direction, thanks.</p>
|
[
{
"answer_id": 271748,
"author": "siukurnin",
"author_id": 35273,
"author_profile": "https://Stackoverflow.com/users/35273",
"pm_score": 0,
"selected": false,
"text": "<td[^<]+?> <td[^>]*>"
},
{
"answer_id": 271750,
"author": "The Archetypal Paul",
"author_id": 21755,
"author_profile": "https://Stackoverflow.com/users/21755",
"pm_score": 0,
"selected": false,
"text": "<tr>[\\s]<td[^<]+?>Max Temperature[\\w\\s]*</td>[\\s]\n"
},
{
"answer_id": 271751,
"author": "Stefan Gehrig",
"author_id": 11354,
"author_profile": "https://Stackoverflow.com/users/11354",
"pm_score": 2,
"selected": true,
"text": "<tr>\\s*\n<td[^>]*>.*?</td>\\s*\n<td[^>]*>\\s*(?<value>\\d+)\\s*</td>\\s*\n<td[^>]*>\\s*(?<time>\\d{2}:\\d{2}:\\d{2})\\s*</td>\\s*\n</tr>\\s*\n"
},
{
"answer_id": 271754,
"author": "chakrit",
"author_id": 3055,
"author_profile": "https://Stackoverflow.com/users/3055",
"pm_score": 0,
"selected": false,
"text": "<tr>[\\s]<td[^<]+?>Max Temperature[^<]*</td>[\\s]\n <td[^<]+?>[\\s]?(?<time>([\\d\\:]+))</td>[\\s]</tr>\n"
}
] |
2008/11/07
|
[
"https://Stackoverflow.com/questions/271741",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
271,742
|
<p>What are the advantages of rendering a control like this:</p>
<pre><code><% Html.RenderPartial("MyControl") %> or
<%=Html.TextBox("txtName", Model.Name) %>
</code></pre>
<p>over the web Forms style:</p>
<pre><code><uc1:MyControl ID=MyControl runat=server />
</code></pre>
<p>I understand that performance can be one reason because no object needs to be created but having the possibility of calling it from the codebehing just to do some basic rendering logic can be very useful. </p>
<p>If this is discouraged then how you are suposed to deal with this scenarios:</p>
<ul>
<li><p>You need to make the control visible conditionally and you dont want to fill your HTML with rendering logic.</p></li>
<li><p>You have <code><input type="text" value="<%= Model.Name %>" /></code> but you need to check if Model is null because otherways a NullPointerException will raise.</p></li>
</ul>
<p><strong>[EDIT]</strong> I asked this when I was beginning with ASP MVC, now I see the advantages of the MVC way like in Cristian answer.</p>
|
[
{
"answer_id": 272531,
"author": "Santiago Corredoira",
"author_id": 4264,
"author_profile": "https://Stackoverflow.com/users/4264",
"pm_score": 0,
"selected": false,
"text": "<custom:HtmlTextBox ID=\"txtName\" runat=\"server\" />\n if(this.Model != null) \n{\n this.txtName.Text = Model.Name;\n}\n <% if(this.Model != null) { %>\n <input type=\"text\" name=\"txtName\" value=\"<%= Model.Name %>\" />\n<% } else { %>\n <input type=\"text\" name=\"txtName\" value=\"\" />\n<% } %>\n"
},
{
"answer_id": 272737,
"author": "Cristian Libardo",
"author_id": 16526,
"author_profile": "https://Stackoverflow.com/users/16526",
"pm_score": 3,
"selected": true,
"text": "<%= Html.BindTextBox(\"txtName\", Model, \"Person.Name\") %>\n"
}
] |
2008/11/07
|
[
"https://Stackoverflow.com/questions/271742",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4264/"
] |
271,743
|
<p>What's the difference between <code><b></code> and <code><strong></code>, <code><i></code> and <code><em></code> in HTML/XHTML? When should you use each?</p>
|
[
{
"answer_id": 271755,
"author": "Tony Andrews",
"author_id": 18747,
"author_profile": "https://Stackoverflow.com/users/18747",
"pm_score": 8,
"selected": false,
"text": "<b> <i> <strong> <em>"
},
{
"answer_id": 271756,
"author": "James",
"author_id": 7837,
"author_profile": "https://Stackoverflow.com/users/7837",
"pm_score": 5,
"selected": false,
"text": "<strong> <em> <b> <i>"
},
{
"answer_id": 271761,
"author": "nickf",
"author_id": 9021,
"author_profile": "https://Stackoverflow.com/users/9021",
"pm_score": 0,
"selected": false,
"text": "<b> <i> <strong> <em>"
},
{
"answer_id": 271763,
"author": "Antonio Louro",
"author_id": 15528,
"author_profile": "https://Stackoverflow.com/users/15528",
"pm_score": 0,
"selected": false,
"text": "<strong> <strong> <b> <i> <em>"
},
{
"answer_id": 271776,
"author": "splattne",
"author_id": 6461,
"author_profile": "https://Stackoverflow.com/users/6461",
"pm_score": 11,
"selected": true,
"text": "<b> <strong> <strong>"
},
{
"answer_id": 271788,
"author": "Kariem",
"author_id": 12039,
"author_profile": "https://Stackoverflow.com/users/12039",
"pm_score": 3,
"selected": false,
"text": "<b> <i> <em> <strong> <i> <em> <em> <strong> <i> <b>"
},
{
"answer_id": 271798,
"author": "Mecki",
"author_id": 15809,
"author_profile": "https://Stackoverflow.com/users/15809",
"pm_score": 0,
"selected": false,
"text": "<b> <i> font [i] <i> span <em> <strong> em strong em strong"
},
{
"answer_id": 275515,
"author": "mwiik",
"author_id": 35863,
"author_profile": "https://Stackoverflow.com/users/35863",
"pm_score": 3,
"selected": false,
"text": "<strong> <em> <b> <i>"
},
{
"answer_id": 275576,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "<b> <i> <strong> <em> <strong> <em> style= <div>"
},
{
"answer_id": 5576545,
"author": "ritakriti",
"author_id": 696155,
"author_profile": "https://Stackoverflow.com/users/696155",
"pm_score": -1,
"selected": false,
"text": "<strong> <b> <em> <i>"
},
{
"answer_id": 8521088,
"author": "Danubian Sailor",
"author_id": 531954,
"author_profile": "https://Stackoverflow.com/users/531954",
"pm_score": 1,
"selected": false,
"text": "<b> <strong>"
},
{
"answer_id": 19988223,
"author": "Rick Westera",
"author_id": 672086,
"author_profile": "https://Stackoverflow.com/users/672086",
"pm_score": 3,
"selected": false,
"text": "<b> <strong> <i> <em>"
},
{
"answer_id": 25671886,
"author": "Thomas Eding",
"author_id": 239916,
"author_profile": "https://Stackoverflow.com/users/239916",
"pm_score": 3,
"selected": false,
"text": "<em> <strong> <i> <b>"
},
{
"answer_id": 32511723,
"author": "ahnbizcad",
"author_id": 2951835,
"author_profile": "https://Stackoverflow.com/users/2951835",
"pm_score": -1,
"selected": false,
"text": "<strong> <em> <b> <i> <strong> <b> <em> <i>"
},
{
"answer_id": 37764775,
"author": "Muhammad Awais",
"author_id": 3901944,
"author_profile": "https://Stackoverflow.com/users/3901944",
"pm_score": 0,
"selected": false,
"text": "<b>This text is bold</b>\n <strong>This text is strong</strong>\n <i>This text is italic</i>\n <em>This text is emphasized</em>\n"
},
{
"answer_id": 43477006,
"author": "adnan2nd",
"author_id": 985754,
"author_profile": "https://Stackoverflow.com/users/985754",
"pm_score": 2,
"selected": false,
"text": "<i> <b> <em> <strong> <i> <b> <i> <b> <i> <b> <i> <p><i>I hope this works</i>, he thought.</p>\n <b> <p><b class=\"lead\">The event takes place this upcoming Saturday, and over 3,000 people have already registered.</b></p>\n <em> <strong> <em> <strong> <p>Make sure to sign up <em>before</em> the day of the event, September 16, 2016</p>\n <strong> <p>Make sure to sign up <em>before</em> the day of the event, <strong>September 16, 2016</strong></p>\n"
},
{
"answer_id": 60089299,
"author": "Touhidur Rahaman",
"author_id": 12098890,
"author_profile": "https://Stackoverflow.com/users/12098890",
"pm_score": 1,
"selected": false,
"text": "<b> <strong> <i> <em>"
},
{
"answer_id": 62904344,
"author": "squarecandy",
"author_id": 947370,
"author_profile": "https://Stackoverflow.com/users/947370",
"pm_score": 4,
"selected": false,
"text": "<strong> <b> b i <strong> <b> <strong> <b> <b> <strong> b,\nstrong {\n font-weight: 700;\n /* ... more styles here */\n}\n\ni,\nem {\n font-style: italic;\n /* ... more styles here */\n}\n b strong"
},
{
"answer_id": 63466498,
"author": "hammad khan",
"author_id": 5307595,
"author_profile": "https://Stackoverflow.com/users/5307595",
"pm_score": -1,
"selected": false,
"text": "simple text this is test text normal text\n\n\n\nsimple text this is important textwith normal text\n"
},
{
"answer_id": 68564761,
"author": "Junaga",
"author_id": 6655130,
"author_profile": "https://Stackoverflow.com/users/6655130",
"pm_score": 1,
"selected": false,
"text": "<b> <i> <!DOCTYPE html> <b> <p>Here at company XYZ, we use <b>HTML</b> and <b>Javascript</b>.</p>\n <i> <p>I <i>did</i> tell him, to arrive on time for the meeting.</p>\n <b> <strong> <strong> <i> <em> <em> <i> <b> <i> <strong> <em>"
},
{
"answer_id": 72599307,
"author": "Al Mamun Khan",
"author_id": 15274012,
"author_profile": "https://Stackoverflow.com/users/15274012",
"pm_score": 1,
"selected": false,
"text": "<em> <i> <strong></strong> <em></em>"
}
] |
2008/11/07
|
[
"https://Stackoverflow.com/questions/271743",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21709/"
] |
271,747
|
<p>I'd like to send mail without bothering with the SMTP-Server which is used for delivery.</p>
<p>So <a href="http://java.sun.com/products/javamail/" rel="noreferrer">JavaMail API</a> doesn't work for me because I have to specify a SMTP server to connect to.</p>
<p>I'd like the library to find out on its own which SMTP server is responsible for which email address by querying the MX record of the mail address domain.</p>
<p>I'm looking for something like <a href="https://aspirin.dev.java.net/" rel="noreferrer">Aspirin</a>. Unfortunately I can't use Aspirin itself because the development stopped 2004 and the library fails to communicate with modern spam hardened servers correctly.</p>
<p>An embeddable version of <a href="http://james.apache.org/" rel="noreferrer">James</a> would do the task. But I haven't found documentation concerning whether this is possible.</p>
<p>Or does anyone know about other libraries I could use?</p>
|
[
{
"answer_id": 271829,
"author": "Eduard Wirch",
"author_id": 17428,
"author_profile": "https://Stackoverflow.com/users/17428",
"pm_score": 4,
"selected": false,
"text": "<dependency>\n <groupId>dnsjava</groupId>\n <artifactId>dnsjava</artifactId>\n <version>2.0.1</version>\n</dependency>\n public static String getMXRecordsForEmailAddress(String eMailAddress) {\n String returnValue = null;\n\n try {\n String hostName = getHostNameFromEmailAddress(eMailAddress);\n Record[] records = new Lookup(hostName, Type.MX).run();\n if (records == null) { throw new RuntimeException(\"No MX records found for domain \" + hostName + \".\"); }\n\n if (log.isTraceEnabled()) {\n // log found entries for debugging purposes\n for (int i = 0; i < records.length; i++) {\n MXRecord mx = (MXRecord) records[i];\n String targetString = mx.getTarget().toString();\n log.trace(\"MX-Record for '\" + hostName + \"':\" + targetString);\n }\n }\n\n // return first entry (not the best solution)\n if (records.length > 0) {\n MXRecord mx = (MXRecord) records[0];\n returnValue = mx.getTarget().toString();\n }\n } catch (TextParseException e) {\n throw new RuntimeException(e);\n }\n\n if (log.isTraceEnabled()) {\n log.trace(\"Using: \" + returnValue);\n }\n return returnValue;\n}\n\nprivate static String getHostNameFromEmailAddress(String mailAddress) throws TextParseException {\n String parts[] = mailAddress.split(\"@\");\n if (parts.length != 2) throw new TextParseException(\"Cannot parse E-Mail-Address: '\" + mailAddress + \"'\");\n return parts[1];\n}\n public static void sendMail(String toAddress, String fromAddress, String subject, String body) throws AddressException, MessagingException {\n String smtpServer = getMXRecordsForEmailAddress(toAddress);\n\n // create session\n Properties props = new Properties();\n props.put(\"mail.smtp.host\", smtpServer);\n Session session = Session.getDefaultInstance(props);\n\n // create message\n Message msg = new MimeMessage(session);\n msg.setFrom(new InternetAddress(fromAddress));\n msg.setRecipient(Message.RecipientType.TO, new InternetAddress(toAddress));\n msg.setSubject(subject);\n msg.setText(body);\n\n // send message\n Transport.send(msg);\n}\n"
}
] |
2008/11/07
|
[
"https://Stackoverflow.com/questions/271747",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17428/"
] |
271,762
|
<p>Can someone supply me with a regex to match a search term that is not preceded or followed by <code>[a-z]</code> and <code>[A-Z]</code>? (Other characters are OK.) I.e., when searching for <code>key</code>, I don't want <code>keyboard</code> in my search results, but <code>key.</code> is okay.</p>
|
[
{
"answer_id": 271769,
"author": "siukurnin",
"author_id": 35273,
"author_profile": "https://Stackoverflow.com/users/35273",
"pm_score": 1,
"selected": false,
"text": "\\b m/\\bkey\\b/\n"
},
{
"answer_id": 271770,
"author": "Greg",
"author_id": 24181,
"author_profile": "https://Stackoverflow.com/users/24181",
"pm_score": 3,
"selected": false,
"text": "\\bkey\\b \\b"
},
{
"answer_id": 271801,
"author": "paxdiablo",
"author_id": 14860,
"author_profile": "https://Stackoverflow.com/users/14860",
"pm_score": 3,
"selected": false,
"text": "[^A-Za-z]key[^A-Za-z] ^key[^A-Aa-z] [^A-Aa-z]key$"
},
{
"answer_id": 271883,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "[^\\w]key[^\\w]"
},
{
"answer_id": 271898,
"author": "Anders Waldenborg",
"author_id": 24082,
"author_profile": "https://Stackoverflow.com/users/24082",
"pm_score": 2,
"selected": false,
"text": "[[:<:]]key[[:>:]]"
},
{
"answer_id": 1639703,
"author": "davew",
"author_id": 198408,
"author_profile": "https://Stackoverflow.com/users/198408",
"pm_score": 0,
"selected": false,
"text": "OR (^|[^A-Za-z])key([^A-Za-z]|$)\n"
}
] |
2008/11/07
|
[
"https://Stackoverflow.com/questions/271762",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21238/"
] |
271,767
|
<p>I have in my Form constructor, after the InitializeComponent the following code:</p>
<pre><code>using (WebClient client = new WebClient())
{
client.DownloadDataCompleted += new DownloadDataCompletedEventHandler(client_DownloadDataCompleted);
client.DownloadDataAsync("http://example.com/version.txt");
}
</code></pre>
<p>When I start my form, the UI doesn't appears till client_DownloadDataCompleted is raised.
The client_DownloadDataCompleted method is empty, so there's no problem there.</p>
<p>What I'm doing wrong?
How is supposed to do this without freezing the UI?</p>
<p>Thanks for your time.<br>
Best regards.</p>
<p><strong>FULL CODE:</strong> </p>
<p><strong>Program.cs</strong></p>
<pre><code>using System;
using System.Windows.Forms;
namespace Lala
{
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
}
}
}
</code></pre>
<p><strong>Form1.cs</strong></p>
<pre><code>using System;
using System.Net;
using System.Windows.Forms;
namespace Lala
{
public partial class Form1 : Form
{
WebClient client = new WebClient();
public Form1()
{
client.DownloadDataCompleted += new DownloadDataCompletedEventHandler(client_DownloadDataCompleted);
client.DownloadDataAsync(new Uri("http://www.google.com"));
InitializeComponent();
}
void client_DownloadDataCompleted(object sender, DownloadDataCompletedEventArgs e)
{
textBox1.Text += "A";
}
}
partial class Form1
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.button1 = new System.Windows.Forms.Button();
this.textBox1 = new System.Windows.Forms.TextBox();
this.SuspendLayout();
//
// button1
//
this.button1.Location = new System.Drawing.Point(12, 12);
this.button1.Name = "button1";
this.button1.Size = new System.Drawing.Size(75, 23);
this.button1.TabIndex = 0;
this.button1.Text = "button1";
this.button1.UseVisualStyleBackColor = true;
//
// textBox1
//
this.textBox1.Location = new System.Drawing.Point(12, 41);
this.textBox1.Multiline = true;
this.textBox1.Name = "textBox1";
this.textBox1.Size = new System.Drawing.Size(468, 213);
this.textBox1.TabIndex = 1;
//
// Form1
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(492, 266);
this.Controls.Add(this.textBox1);
this.Controls.Add(this.button1);
this.Name = "Form1";
this.Text = "Form1";
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.Button button1;
private System.Windows.Forms.TextBox textBox1;
}
}
</code></pre>
|
[
{
"answer_id": 271790,
"author": "Robert Wagner",
"author_id": 10784,
"author_profile": "https://Stackoverflow.com/users/10784",
"pm_score": 0,
"selected": false,
"text": " int a, b;\n ThreadPool.GetMaxThreads(out a, out b);\n"
},
{
"answer_id": 5544274,
"author": "Roman Pushkin",
"author_id": 337085,
"author_profile": "https://Stackoverflow.com/users/337085",
"pm_score": 1,
"selected": false,
"text": "client.Proxy = GlobalProxySelection.GetEmptyProxy();\n"
},
{
"answer_id": 22886642,
"author": "Wiseman",
"author_id": 125264,
"author_profile": "https://Stackoverflow.com/users/125264",
"pm_score": 3,
"selected": false,
"text": "WebClient webClient = new WebClient();\nwebClient.Proxy = null;\n... Do whatever else ...\n"
}
] |
2008/11/07
|
[
"https://Stackoverflow.com/questions/271767",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4386/"
] |
271,815
|
<p>Is there a better way to write this code? </p>
<p>I want to show a default value ('No data') for any empty fields returned by the query:</p>
<pre><code>$archivalie_id = $_GET['archivalie_id'];
$query = "SELECT
a.*,
ip.description AS internal_project,
o.description AS origin,
to_char(ad.origin_date,'YYYY') AS origin_date
FROM archivalie AS a
LEFT JOIN archivalie_dating AS ad ON a.id = ad.archivalie_id
LEFT JOIN internal_project AS ip ON a.internal_project_id = ip.id
LEFT JOIN origin AS o ON a.origin_id = o.id
WHERE a.id = $archivalie_id";
$result = pg_query($db, $query);
while ($row = pg_fetch_object($result))
{
$no_data = '<span class="no-data">No data</span>';
$internal_project = ($row->internal_project != '') ? $row->internal_project : $no_data;
$incoming_date = ($row->incoming_date != '') ? $row->incoming_date : $no_data;
$origin = ($row->origin != '') ? $row->origin : $no_data;
}
</code></pre>
|
[
{
"answer_id": 271826,
"author": "Stefan Gehrig",
"author_id": 11354,
"author_profile": "https://Stackoverflow.com/users/11354",
"pm_score": 3,
"selected": true,
"text": "function dbValue($value, $default=null)\n{\n if ($default===null) {\n $default='<span class=\"no-data\">No data</span>';\n }\n if (!empty($value)) {\n return $value;\n } else {\n return $default;\n }\n}\n"
},
{
"answer_id": 271844,
"author": "markus",
"author_id": 11995,
"author_profile": "https://Stackoverflow.com/users/11995",
"pm_score": 1,
"selected": false,
"text": "$archivalie_id = pg_escape_string($_GET['archivalie_id']);\n define('_MYPROJECT_NODATA', '<span class=\"no-data\">No data</span>');\n"
},
{
"answer_id": 271887,
"author": "Tomalak",
"author_id": 18771,
"author_profile": "https://Stackoverflow.com/users/18771",
"pm_score": 1,
"selected": false,
"text": "SELECT \n IFNULL(NULLIF(a.field1, ''), 'No data') AS field1, \n IFNULL(NULLIF(a.field2, ''), 'No data') AS field2, \n IFNULL(NULLIF(ip.description, ''), 'No data') AS internal_project,\n IFNULL(NULLIF(o.description, ''), 'No data') AS origin,\n to_char(ad.origin_date,'YYYY') AS origin_date \nFROM \n archivalie AS a \n LEFT JOIN archivalie_dating AS ad ON a.id = ad.archivalie_id \n LEFT JOIN internal_project AS ip ON a.internal_project_id = ip.id\n LEFT JOIN origin AS o ON a.origin_id = o.id \nWHERE \n a.id = $archivalie_id\n IFNULL(NULLIF()) NULL NULL 'No data' IFNULL()"
},
{
"answer_id": 271915,
"author": "Tony Andrews",
"author_id": 18747,
"author_profile": "https://Stackoverflow.com/users/18747",
"pm_score": 0,
"selected": false,
"text": "$query = \"SELECT \n a.*, \n COALESCE(ip.description,'NO_DATA') AS internal_project,\n COALESCE(o.description,'NO_DATA') AS origin,\n COALESCE(to_char(ad.origin_date,'YYYY'),'NO_DATA') AS origin_date \n"
}
] |
2008/11/07
|
[
"https://Stackoverflow.com/questions/271815",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4196/"
] |
271,821
|
<p>I have a site that usually has news items at the top of the homepage, and sometimes (for specific periods) will have one or more 'quicklinks' beneath the news items, to guide users to pages of topical interest. Beneath those is the usual blurb.</p>
<p>We have alternative language versions of these sites, which often don't contain either the news items or the quicklinks, but may do from time to time.</p>
<p>Previously, when the appearance was less dynamic, each section was absolutely positioned, with a top attribute configured appropriately. But as more subtle variations were required, I find myself chopping and changing both the base HTML and the stylesheet rules. </p>
<p>My question is what do people think about the different approaches to this problem, and do they have any suggestions that I haven't considered. Achieving the desired result is easy, but I'm thinking of good coding practice that makes the site easier to read & debug.</p>
<p>I could have separate style classes for each variation of each item:</p>
<pre><code>.news {top: 100px; etc...;}
.news2 {top: 150px; etc...;}
.ql {top: 150px; etc...;}
.ql2 {top: 200px; etc...;}
.main {top: 200px; etc...;}
.main2 {top: 250px; etc...;}
</code></pre>
<p>...which seems a little too verbose.</p>
<p>Or, perhaps:</p>
<pre><code>.news {etc...;}
.ql {etc...;}
.main {etc...;}
.top100 {top: 100px;}
.top150 {top: 150px;}
.top200 {top: 200px;}
.top250 {top: 250px;}
</code></pre>
<p>Somewhat more compact, and it keeps the styling in the stylesheet and away from the HTML.</p>
<p>Or, perhaps even:</p>
<pre><code>.news {etc...;}
.ql {etc...;}
.main {etc...;}
</code></pre>
<p>in HTML:</p>
<pre><code><div class="news" style="top:100px;">
<div class="ql" style="top:150px;">
<div class="main" style="top:200px;">
</code></pre>
<p>This is the most 'direct' solution, but clearly some of the styling is in the HTML which from a purists point of view is a 'no-no'; There are practical reasons for this view, but in this case, this is probably the easiest way to handle the varied and arbitrary changes that will be requested.</p>
<p>Note: The site was (poorly) designed by a 3rd party, although I have tried to rescue it without entirely re-writing it. However, the site will be re-developed, possibly as early as Q3 or Q4 2009. At that stage, I'd hope to be moving away from a absolutely positioned approach, to one that is more fluid - so this question is about what to do in the interim, and also as a general question of style.</p>
|
[
{
"answer_id": 271827,
"author": "Toon Krijthe",
"author_id": 18061,
"author_profile": "https://Stackoverflow.com/users/18061",
"pm_score": 3,
"selected": true,
"text": ".top100 {top: 100px;}\n.top150 {top: 150px;}\n.top200 {top: 200px;}\n.top250 {top: 250px;}\n .news {top: 100px; etc...;}\n.news2, .ql {top: 150px; etc...;}\n.ql2, .main {top: 200px; etc...;}\n.main2 {top: 250px; etc...;}\n"
},
{
"answer_id": 275745,
"author": "Lee Kowalkowski",
"author_id": 30945,
"author_profile": "https://Stackoverflow.com/users/30945",
"pm_score": 1,
"selected": false,
"text": "\"<classname>\" <classname>2\" <elem class=\"<classname> quicklinks\">"
},
{
"answer_id": 281352,
"author": "CJM",
"author_id": 6898,
"author_profile": "https://Stackoverflow.com/users/6898",
"pm_score": 0,
"selected": false,
"text": ".news, .news2 {top: 100px; etc...;}\n.news2 {top: 150px;}\n.ql, .ql2 {top: 150px; etc...;}\n.ql2 {top: 200px;}\n.main, .main2 {top: 200px; etc...;}\n.main2 {top: 250px;}\n"
}
] |
2008/11/07
|
[
"https://Stackoverflow.com/questions/271821",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6898/"
] |
271,843
|
<p>Does that mean that I can't share a Form between delphi 2007 and 2009?</p>
|
[
{
"answer_id": 275156,
"author": "Ondrej Kelle",
"author_id": 11480,
"author_profile": "https://Stackoverflow.com/users/11480",
"pm_score": 4,
"selected": false,
"text": "unit Delphi2009Form;\n\ninterface\n\nuses\n Windows, Classes, SysUtils, Controls, Forms;\n\ntype\n{$IFDEF VER200}\n TDelphi2009Form = class(TForm);\n{$ELSE}\n TDelphi2009Form = class(TForm)\n private\n procedure ReaderError(Reader: TReader; const Message: string; var Handled: Boolean);\n protected\n procedure ReadState(Reader: TReader); override;\n end;\n\n TReaderErrorProc = procedure(const Message: string);\n\nvar\n ReaderErrorProc: TReaderErrorProc = nil;\n{$ENDIF}\n\nimplementation\n\n{$IFNDEF VER200}\ntype\n THackReader = class(TReader);\n\nprocedure TDelphi2009Form.ReaderError(Reader: TReader; const Message: string; var Handled: Boolean);\nbegin\n with THackReader(Reader) do\n Handled := AnsiSameText(PropName, 'DoubleBuffered') or AnsiSameText(PropName, 'ParentDoubleBuffered');\n if Handled and Assigned(ReaderErrorProc) then\n ReaderErrorProc(Message);\nend;\n\nprocedure TDelphi2009Form.ReadState(Reader: TReader);\nbegin\n Reader.OnError := ReaderError;\n inherited ReadState(Reader);\nend;\n{$ENDIF}\n\nend.\n type\n TFormMain = class(TDelphi2009Form)\n ...\n unit Delphi2009FormReg;\n\ninterface\n\nuses\n Delphi2009Form;\n\nprocedure Register;\n\nimplementation\n\nuses\n DesignIntf, DesignEditors, ToolsAPI;\n\nprocedure ShowReaderError(const Message: string);\nbegin\n with BorlandIDEServices as IOTAMessageServices do\n AddTitleMessage(Message);\nend;\n\nprocedure Register;\nbegin\n RegisterCustomModule(TDelphi2009Form, TCustomModule);\n ReaderErrorProc := ShowReaderError;\nend;\n\ninitialization\n\nfinalization\n ReaderErrorProc := nil;\n\nend.\n"
}
] |
2008/11/07
|
[
"https://Stackoverflow.com/questions/271843",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/727/"
] |
271,850
|
<p>After upgrading a project from Delphi 2007 to Delphi 2009 I'm getting an Unknown memory leak, so far I've been tryin to track it down using fastMM, here is what fastMM stack trace reports:</p>
<pre><code>A memory block has been leaked. The size is: 20
This block was allocated by thread 0x111C, and the stack trace (return addresses)
at the time was:
40339E [System.pas][System][@GetMem][3412] 534873 [crtl][_malloc]
56D1C4 [canex.cpp][MidasLib][DllGetDataSnapClassObject][3918]
56D316 [canex.cpp][MidasLib][DllGetDataSnapClassObject][3961]
56D5EE [canex.cpp][MidasLib][DllGetDataSnapClassObject][4085]
562D48 [DBCommon.pas][DBCommon][TFilterExpr.PutExprNode][1583]
408E46 [System.pas][System][DynArraySetLength][20464]
56D5EE [canex.cpp][MidasLib][DllGetDataSnapClassObject][4085]
408E92 [System.pas][System][@DynArraySetLength][20486]
528C1B [Forms.pas][Forms][TCustomForm.DoCreate][3260]
171A1A [GetRawStackTrace]
The block is currently used for an object of class: Unknown
The allocation number is: 302844
</code></pre>
<p>And sometimes I get this:</p>
<pre><code>A memory block has been leaked. The size is: 20
This block was allocated by thread 0x111C, and the stack trace (return addresses)
at the time was:
40339E [System.pas][System][@GetMem][3412]
534873 [crtl][_malloc]
56D1C4 [canex.cpp][MidasLib][DllGetDataSnapClassObject][3918]
56D316 [canex.cpp][MidasLib][DllGetDataSnapClassObject][3961]
77DC921A [RtlAnsiStringToUnicodeString]
56D5EE [canex.cpp][MidasLib][DllGetDataSnapClassObject][4085]
7726B8F5 [GetProcAddress]
7726B907 [GetProcAddress]
589B1E [ossrv.cpp][MidasLib][DllGetDataSnapClassObject][3163]
56D5EE [canex.cpp][MidasLib][DllGetDataSnapClassObject][4085]
408E92 [System.pas][System][@DynArraySetLength][20486]
The block is currently used for an object of class: Unknown
</code></pre>
<p>Is there some better way to figure out what really is causing the Memory leak?</p>
|
[
{
"answer_id": 272370,
"author": "zendar",
"author_id": 25732,
"author_profile": "https://Stackoverflow.com/users/25732",
"pm_score": 1,
"selected": false,
"text": "@DynArraySetLength"
}
] |
2008/11/07
|
[
"https://Stackoverflow.com/questions/271850",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/727/"
] |
271,870
|
<p>I have a form whose controls I want to enable/disable depending on the values in a ComboBox control. This ComboBox control is linked, like all the other controls in the form, to a table. Inside the ComboBox's Change event, I placed the code that enables/disables the other controls.</p>
<p>The problem I have is that when I open the form, the controls are not enabled/disabled. I have to re-choose the ComboBox value to make all other controls enable or disable.</p>
<p>One thing I noticed is that the RecordSet control inside the ComboBox often does not change to the value shown in the value property of the ComboBox.</p>
<p>I tried using <br>
<code>combobox.recordset.filter = "Key = " & combobox.value</code><br>
but I get the error <br>
<code>Operation is not supported for this type of object.</code></p>
<hr>
<h2>Update</h2>
<p>I think my problem has to do more in how I'm accessing the values in the combobox.recordset. I was under the impression that combobox.recordset held the value received from the table. But, it seems to hold the first record from the recordsource.</p>
<p>I'm guessing that I will need to search those values I need by using another recordset object.</p>
|
[
{
"answer_id": 274294,
"author": "David-W-Fenton",
"author_id": 9787,
"author_profile": "https://Stackoverflow.com/users/9787",
"pm_score": 1,
"selected": false,
"text": " Private Sub cmbComboBox1_AfterUpdate()\n Dim strRowsource As String\n\n strRowsource = \"SELECT * FROM MyTable\"\n If Not IsNull(Me!cmbComboBox1) Then\n strRowsource = strRowsource & \" WHERE MyField = \" & Me!cmbComboBox1\n End If\n Me!cmbComboBox2.Rowsource = strRowsource\n End Sub\n SELECT * FROM MyTable \nWHERE (MyField=[Forms]![MyForm]![cmbComboBox1] \n AND IsNull([Forms]![MyForm]![cmbComboBox1])=False) \n OR IsNull([Forms]![MyForm]![cmbComboBox1])=True\n Private Sub cmbComboBox1_AfterUpdate()\n Me!cmbComboBox2.Requery\n End Sub\n PARAMETERS [Forms]![MyForm]![cmbComboBox1] Long;\nSELECT * FROM MyTable \nWHERE (MyField=[Forms]![MyForm]![cmbComboBox1] \n AND IsNull([Forms]![MyForm]![cmbComboBox1])=False) \n OR IsNull([Forms]![MyForm]![cmbComboBox1])=True\n"
}
] |
2008/11/07
|
[
"https://Stackoverflow.com/questions/271870",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15884/"
] |
271,881
|
<p>I am using a JEditorPane as an editor to write comments in my application. The content type is set "text/plain". When I am writing text in it and the text fills the available space and I go on typing, the text is not moving upward to show the cursor. So I dont know where I am typing and what I am typing since it would be visible.</p>
<p>Could you tell me how to always show the caret by moving the above text upwards?</p>
<p>Instead, it could be better if I can auto-resize the editor as I am typing. The JEditorPane is inside a JPanel, so I have to resize that too. any Ideas?</p>
|
[
{
"answer_id": 5837644,
"author": "Raze",
"author_id": 142716,
"author_profile": "https://Stackoverflow.com/users/142716",
"pm_score": 1,
"selected": false,
"text": "scrollPane.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);\nscrollPane.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_NEVER);\n import java.awt.BorderLayout;\nimport java.awt.Dimension;\n\nimport javax.swing.JEditorPane;\nimport javax.swing.JFrame;\nimport javax.swing.JLabel;\nimport javax.swing.JPanel;\nimport javax.swing.JScrollPane;\nimport javax.swing.ScrollPaneConstants;\nimport javax.swing.event.CaretEvent;\nimport javax.swing.event.CaretListener;\n\n\npublic class SPTest extends JFrame {\n\n private static final long serialVersionUID = 1L;\n\n private JEditorPane editor;\n private JScrollPane scrollPane;\n private JPanel topPanel;\n private JLabel labelTop;\n\n public SPTest() {\n super(\"Editor test\");\n initComponents();\n setDefaultCloseOperation(EXIT_ON_CLOSE);\n setVisible(true);\n }\n\n private void initComponents() {\n editor = new JEditorPane(\"text/plain\", null);\n scrollPane = new JScrollPane(editor);\n topPanel = new JPanel();\n labelTop = new JLabel(\"main contents here\");\n topPanel.add(labelTop);\n\n setSize(600, 400);\n editor.setMinimumSize(new Dimension(100, 30));\n editor.setPreferredSize(new Dimension(100, 60));\n scrollPane.setPreferredSize(new Dimension(600, 60));\n scrollPane.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);\n scrollPane.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_NEVER);\n scrollPane.setMinimumSize(new Dimension(100, 30));\n\n final int MAX_HEIGHT_RSZ = 120;\n editor.addCaretListener(new CaretListener() {\n\n public void caretUpdate(CaretEvent e) {\n int height = Math.min(editor.getPreferredSize().height, MAX_HEIGHT_RSZ);\n Dimension preferredSize = scrollPane.getPreferredSize();\n preferredSize.height = height;\n scrollPane.setPreferredSize(preferredSize);\n SPTest.this.validate();\n }\n });\n\n setLayout(new BorderLayout());\n add(topPanel, BorderLayout.NORTH);\n add(scrollPane, BorderLayout.SOUTH);\n }\n\n public static void main(String[] args) {\n new SPTest();\n }\n\n}\n"
}
] |
2008/11/07
|
[
"https://Stackoverflow.com/questions/271881",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/22550/"
] |
271,888
|
<p>In my database application I sometimes have to deal with <code>null</code> strings in the database. In most cases this is fine, but when it comes do displaying data in a form the Swing components - using <code>JTextField</code> for example - cannot handle null strings. (<code>.setText(null)</code> fails)</p>
<p>(<strong>EDIT:</strong> I just noticed that <code>JTextField</code> actually accepts a <code>null</code> string, but the question remains for all other cases where unexpected <code>null</code> values can lead to problems.)</p>
<p>The null values have no special meaning, they can (must) be treated as empty strings. </p>
<p>What is the best practice to deal with this problem? <em>Unfortunatly I cannot change the database</em>.</p>
<ul>
<li>Checking every value if it is <code>null</code> before calling <code>setText()</code>?</li>
<li>Adding a try-catch handler to every <code>setText()</code> call?</li>
<li>Introducing a static method which filters all <code>null</code> strings?</li>
<li>Replace all <code>null</code> values to empty strings immediatly after reading from the database?</li>
<li>... [your suggestions]</li>
</ul>
|
[
{
"answer_id": 271921,
"author": "Ron Tuffin",
"author_id": 939,
"author_profile": "https://Stackoverflow.com/users/939",
"pm_score": 2,
"selected": false,
"text": "select ISNULL(column_name,'') from ...\n"
}
] |
2008/11/07
|
[
"https://Stackoverflow.com/questions/271888",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23368/"
] |
271,892
|
<p>I have a <select>. Using JavaScript, I need to get a specific <option> from the list of options, and all I know is the value of the option. The option may or may not be selected.</p>
<p>Here's the catch: there are thousands of options and I need to do this a few hundred times in a loop. Right now I loop through the "options" array and look for the option I want. This is too slow (in the sense that on my very fast machine the browser locked up until I killed it after a few minutes).</p>
<p>Is there any faster way to do this? I'll take browser-specific ways, but of course a DOM-standard way would be nice.</p>
|
[
{
"answer_id": 271903,
"author": "Davide Gualano",
"author_id": 28582,
"author_profile": "https://Stackoverflow.com/users/28582",
"pm_score": -1,
"selected": false,
"text": "$(\"#idselect option[value='yourval']\")\n"
},
{
"answer_id": 271906,
"author": "Lasar",
"author_id": 9438,
"author_profile": "https://Stackoverflow.com/users/9438",
"pm_score": 0,
"selected": false,
"text": "myOptions[valueImLookingFor]"
},
{
"answer_id": 271911,
"author": "Tomalak",
"author_id": 18771,
"author_profile": "https://Stackoverflow.com/users/18771",
"pm_score": 4,
"selected": true,
"text": "// first, build a reverse lookup\nvar optCount = mySelect.options.length;\nvar reverseLookup = {};\nfor (var i = 0; i < optCount; i++)\n{\n var option = mySelect.options[i];\n if (!reverseLookup[option.value])\n {\n // use an array to account for multiple options with the same value\n reverseLookup[option.value] = [];\n }\n // store a reference to the DOM element\n reverseLookup[option.value].push(option);\n}\n\n// then, use it to find the option\nvar foundOptions = reverseLookup[\"Value that you are looking for\"];\nif (foundOptions && foundOptions.length)\n{\n alert(foundOptions[0].id);\n}\n"
},
{
"answer_id": 273448,
"author": "Mr. Muskrat",
"author_id": 2657951,
"author_profile": "https://Stackoverflow.com/users/2657951",
"pm_score": 1,
"selected": false,
"text": "var i = mySelect.options.length - 1;\nvar reverseLookup = {};\nwhile ( i >= 0 )\n{\n var option = mySelect.options[i];\n if (!reverseLookup[option.value])\n {\n // use an array to account for multiple options with the same value\n reverseLookup[option.value] = [];\n }\n // store a reference to the DOM element\n reverseLookup[option.value].push(option);\n i--;\n}\n\n// then, use it to find the option\nvar foundOptions = reverseLookup[\"Value that you are looking for\"];\nif (foundOptions && foundOptions.length)\n{\n alert(foundOptions[0].id);\n}\n"
}
] |
2008/11/07
|
[
"https://Stackoverflow.com/questions/271892",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4641/"
] |
271,904
|
<p>Say you have a class declaration, e.g.:</p>
<pre><code>
class MyClass
{
int myInt=7;
int myOtherInt;
}
</code></pre>
<p>Now, is there a way in generic code, using reflection (or any other means, for that matter), that I can deduce that myInt has a default value assigned, whereas myOtherInt does not?
Note the difference between being initialised with an explicit default value, and being left to it's implicit default value (myOtherInt will be initialised to 0, by default).</p>
<p>From my own research it looks like there is no way to do this - but I thought I'd ask here before giving up.</p>
<p>[Edit]</p>
<p>Even with nullable and reference types I want to distingush between those that have been left as null, and those that have been explicitly initialised to null. This is so that I can say that fields with an initialiser are "optional" and other fields are "mandatory". At the moment I'm having to do this using attributes - which niggles me with their redundancy of information in this case.</p>
|
[
{
"answer_id": 271919,
"author": "John Lemp",
"author_id": 12915,
"author_profile": "https://Stackoverflow.com/users/12915",
"pm_score": 2,
"selected": false,
"text": "class MyClass\n{\n int? myInt = 7;\n int? myOtherInt = null;\n}\n"
},
{
"answer_id": 271925,
"author": "Sander",
"author_id": 2928,
"author_profile": "https://Stackoverflow.com/users/2928",
"pm_score": 2,
"selected": false,
"text": "int explicitly = 0;\nint implicitly;\n"
},
{
"answer_id": 271929,
"author": "chakrit",
"author_id": 3055,
"author_profile": "https://Stackoverflow.com/users/3055",
"pm_score": 5,
"selected": true,
"text": ".method public hidebysig specialname rtspecialname \n instance void .ctor() cil managed\n{\n // Code size 15 (0xf)\n .maxstack 8\n IL_0000: ldarg.0\n IL_0001: ldc.i4.7\n IL_0002: stfld int32 dummyCSharp.MyClass::myInt\n IL_0007: ldarg.0\n IL_0008: call instance void [mscorlib]System.Object::.ctor()\n IL_000d: nop\n IL_000e: ret\n} // end of method MyClass::.ctor\n ldc.i4.7 stfld int32 dummyCSharp.MyClass::myInt stfld class MyClass\n{\n public int myInt = 7;\n public int myOtherInt;\n\n public MyClass()\n {\n myOtherInt = 8;\n }\n}\n .method public hidebysig specialname rtspecialname \n instance void .ctor() cil managed\n{\n // Code size 24 (0x18)\n .maxstack 8\n IL_0000: ldarg.0\n IL_0001: ldc.i4.7\n IL_0002: stfld int32 dummyCSharp.MyClass::myInt\n IL_0007: ldarg.0\n IL_0008: call instance void [mscorlib]System.Object::.ctor()\n IL_000d: nop\n IL_000e: nop\n IL_000f: ldarg.0\n IL_0010: ldc.i4.8\n IL_0011: stfld int32 dummyCSharp.MyClass::myOtherInt\n IL_0016: nop\n IL_0017: ret\n} // end of method MyClass::.ctor\n IL_0008: call instance void [mscorlib]System.Object::.ctor()\n"
},
{
"answer_id": 271935,
"author": "huseyint",
"author_id": 39,
"author_profile": "https://Stackoverflow.com/users/39",
"pm_score": -1,
"selected": false,
"text": "bool isAssigned = (myOtherInt == default(int));\n"
},
{
"answer_id": 271951,
"author": "Jack Ryan",
"author_id": 28882,
"author_profile": "https://Stackoverflow.com/users/28882",
"pm_score": 1,
"selected": false,
"text": "int mandatoryInt;\nint? optionalInt;\n"
},
{
"answer_id": 272020,
"author": "Doug L.",
"author_id": 19179,
"author_profile": "https://Stackoverflow.com/users/19179",
"pm_score": 0,
"selected": false,
"text": " class myClass\n {\n #region Property: MyInt\n private int _myIntDefault = 7;\n private bool _myIntChanged = false;\n private int _myInt;\n private int MyInt\n {\n get\n {\n if (_myIntChanged)\n {\n return _myInt;\n }\n else\n {\n return _myIntDefault;\n }\n }\n set\n {\n _myInt = value;\n _myIntChanged = true;\n }\n }\n\n private bool MyIntIsDefault\n {\n get\n {\n if (_myIntChanged)\n {\n return (_myInt == _myIntDefault);\n }\n else\n {\n return true;\n }\n }\n }\n #endregion\n }\n"
},
{
"answer_id": 272074,
"author": "Javier Suero Santos",
"author_id": 34432,
"author_profile": "https://Stackoverflow.com/users/34432",
"pm_score": 1,
"selected": false,
"text": "private int myNumber = 3;\n[System.ComponentModel.DefaultValue(3)]\npublic int MyNumber\n{\n get\n {\n return myNumber;\n }\n set\n {\n myNumber = value;\n }\n}\n PropertyInfo prop = this.GetType().GetProperty(\"MyNumber\");\nMessageBox.Show(((DefaultValueAttribute)(prop.GetCustomAttributes(typeof(DefaultValueAttribute), true).GetValue(0))).Value.ToString());\n"
},
{
"answer_id": 272359,
"author": "dviljoen",
"author_id": 29021,
"author_profile": "https://Stackoverflow.com/users/29021",
"pm_score": 0,
"selected": false,
"text": "class MyClass\n{\n\n public MyClass()\n {\n myInt = 7;\n }\n\n int? _myInt;\n protected int myInt\n {\n set { _myInt = value; }\n get { return _myInt ?? 0; }\n }\n\n int? _myOtherInt;\n protected int myOtherInt\n {\n set { _myOtherInt = value; }\n get { return _myOtherInt ?? 0; }\n }\n}\n"
},
{
"answer_id": 272422,
"author": "Edward Kmett",
"author_id": 34707,
"author_profile": "https://Stackoverflow.com/users/34707",
"pm_score": 1,
"selected": false,
"text": "public struct InitializationKnown<T> {\n private T m_value;\n private bool m_initialized;\n\n // the default constructor leaves m_initialized = false, m_value = default(T)\n // InitializationKnown() {}\n\n InitializationKnown(T value) : m_value(value), m_initialized(true) {}\n\n public bool initialized { \n get { return m_initialized; }\n }\n public static operator T (InitializationKnown that) {\n return that.m_value;\n }\n // ... other operators including assignment go here\n}\n"
},
{
"answer_id": 272516,
"author": "plinth",
"author_id": 20481,
"author_profile": "https://Stackoverflow.com/users/20481",
"pm_score": 1,
"selected": false,
"text": "using System;\nusing System.Collections.Generic;\nusing System.Text;\nusing System.Reflection;\nusing System.Linq;\nusing System.Data;\n\n\nnamespace FieldAttribute\n{\n [global::System.AttributeUsage(AttributeTargets.All, Inherited = false, AllowMultiple = true)]\n sealed class DefaultValueAttribute : Attribute\n {\n public DefaultValueAttribute(int i)\n {\n IntVal = i;\n }\n\n public DefaultValueAttribute(bool b)\n {\n BoolVal = b;\n }\n\n public int IntVal { get; set; }\n public bool BoolVal { get; set; }\n\n private static FieldInfo[] GetAttributedFields(object o, string matchName)\n {\n Type t = o.GetType();\n FieldInfo[] fields = t.GetFields(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);\n\n return fields.Where(fi => ((matchName != null && fi.Name == matchName) || matchName == null) &&\n (fi.GetCustomAttributes(false).Where(attr => attr is DefaultValueAttribute)).Count() > 0).ToArray();\n }\n\n public static void SetDefaultFieldValues(object o)\n {\n FieldInfo[] fields = GetAttributedFields(o, null);\n foreach (FieldInfo fi in fields)\n {\n IEnumerable<object> attrs = fi.GetCustomAttributes(false).Where(attr => attr is DefaultValueAttribute);\n foreach (Attribute attr in attrs)\n {\n DefaultValueAttribute def = attr as DefaultValueAttribute;\n Type fieldType = fi.FieldType;\n if (fieldType == typeof(Boolean))\n {\n fi.SetValue(o, def.BoolVal);\n }\n if (fieldType == typeof(Int32))\n {\n fi.SetValue(o, def.IntVal);\n }\n }\n }\n }\n\n public static bool HasDefaultValue(object o, string fieldName)\n {\n FieldInfo[] fields = GetAttributedFields(o, null);\n foreach (FieldInfo fi in fields)\n {\n IEnumerable<object> attrs = fi.GetCustomAttributes(false).Where(attr => attr is DefaultValueAttribute);\n foreach (Attribute attr in attrs)\n {\n DefaultValueAttribute def = attr as DefaultValueAttribute;\n Type fieldType = fi.FieldType;\n if (fieldType == typeof(Boolean))\n {\n return (Boolean)fi.GetValue(o) == def.BoolVal;\n }\n if (fieldType == typeof(Int32))\n {\n return (Int32)fi.GetValue(o) == def.IntVal;\n }\n }\n }\n return false;\n }\n }\n\n class Program\n {\n [DefaultValue(3)]\n int foo;\n\n [DefaultValue(true)]\n bool b;\n\n public Program()\n {\n DefaultValueAttribute.SetDefaultFieldValues(this);\n Console.WriteLine(b + \" \" + foo);\n Console.WriteLine(\"b has default value? \" + DefaultValueAttribute.HasDefaultValue(this, \"b\"));\n foo = 2;\n Console.WriteLine(\"foo has default value? \" + DefaultValueAttribute.HasDefaultValue(this, \"foo\"));\n }\n\n static void Main(string[] args)\n {\n Program p = new Program();\n }\n }\n}\n"
},
{
"answer_id": 272843,
"author": "Robert Giesecke",
"author_id": 35443,
"author_profile": "https://Stackoverflow.com/users/35443",
"pm_score": 0,
"selected": false,
"text": "\nvar inst1 := new Sample();\nvar inst2 := new Sample(X := 2);\n\nvar test1 := new DefaultValueInspector<Sample>(true);\nvar test2 := new DefaultValueInspector<Sample>(inst2, true);\n\nvar d := test1.DefaultValueByName[\"X\"];\n\nvar inst1HasDefault := test1.HasDefaultValue(inst1, \"X\");\nvar inst2HasDefault := test1.HasDefaultValue(inst2, \"X\");\n\nConsole.WriteLine(\"Value: {0}; inst1HasDefault: {1}; inst2HasDefault {2}\",\n d, inst1HasDefault, inst2HasDefault);\n\nd := test2.DefaultValueByName[\"X\"];\n\ninst1HasDefault := test2.HasDefaultValue(inst1, \"X\");\ninst2HasDefault := test2.HasDefaultValue(inst2, \"X\");\n\nConsole.WriteLine(\"Value: {0}; inst1HasDefault: {1}; inst2HasDefault {2}\",\n d, inst1HasDefault, inst2HasDefault);\n \nuses \n System.Collections.Generic, \n System.Reflection;\n\ntype\n DefaultValueInspector<T> = public class\n private\n method get_DefaultValueByName(memberName : String): Object;\n method get_DefaultValueByMember(memberInfo : MemberInfo) : Object;\n protected\n class method GetMemberErrorMessage(memberName : String) : String;\n method GetMember(memberName : String) : MemberInfo;\n\n property MembersByName : Dictionary<String, MemberInfo> \n := new Dictionary<String, MemberInfo>(); readonly;\n\n property GettersByMember : Dictionary<MemberInfo, Converter<T, Object>> \n := new Dictionary<MemberInfo, Converter<T, Object>>(); readonly;\n\n property DefaultValuesByMember : Dictionary<MemberInfo, Object> \n := new Dictionary<MemberInfo, Object>(); readonly;\n public\n property UseHiddenMembers : Boolean; readonly;\n\n property DefaultValueByName[memberName : String] : Object\n read get_DefaultValueByName;\n property DefaultValueByMember[memberInfo : MemberInfo] : Object\n read get_DefaultValueByMember;\n\n method GetGetMethod(memberName : String) : Converter<T, Object>;\n method GetGetMethod(memberInfo : MemberInfo) : Converter<T, Object>;\n\n method HasDefaultValue(instance : T; memberName : String) : Boolean;\n method HasDefaultValue(instance : T; memberInfo : MemberInfo) : Boolean;\n\n constructor(useHiddenMembers : Boolean);\n constructor(defaultInstance : T; useHiddenMembers : Boolean); \n end;\n\nimplementation\n\nconstructor DefaultValueInspector<T>(useHiddenMembers : Boolean);\nbegin\n var ctorInfo := typeOf(T).GetConstructor([]);\n constructor(ctorInfo.Invoke([]) as T, useHiddenMembers);\nend;\n\nconstructor DefaultValueInspector<T>(defaultInstance : T; useHiddenMembers : Boolean);\nbegin\n var bf := iif(useHiddenMembers, \n BindingFlags.NonPublic)\n or BindingFlags.Public\n or BindingFlags.Instance;\n\n for mi in typeOf(T).GetMembers(bf) do\n case mi.MemberType of\n MemberTypes.Field :\n with matching fi := FieldInfo(mi) do\n begin\n MembersByName.Add(fi.Name, fi);\n GettersByMember.Add(mi, obj -> fi.GetValue(obj));\n end;\n MemberTypes.Property :\n with matching pi := PropertyInfo(mi) do\n if pi.GetIndexParameters().Length = 0 then\n begin\n MembersByName.Add(pi.Name, pi);\n GettersByMember.Add(mi, obj -> pi.GetValue(obj, nil));\n end;\n end;\n\n for g in GettersByMember do\n with val := g.Value(DefaultInstance) do\n if assigned(val) then \n DefaultValuesByMember.Add(g.Key, val);\nend;\n\nclass method DefaultValueInspector<T>.GetMemberErrorMessage(memberName : String) : String;\nbegin\n exit \"The member '\" + memberName + \"' does not exist in type \" + typeOf(T).FullName \n + \" or it has indexers.\"\nend;\n\nmethod DefaultValueInspector<T>.get_DefaultValueByName(memberName : String): Object;\nbegin\n var mi := GetMember(memberName);\n DefaultValuesByMember.TryGetValue(mi, out result);\nend;\n\nmethod DefaultValueInspector<T>.get_DefaultValueByMember(memberInfo : MemberInfo) : Object;\nbegin\n if not DefaultValuesByMember.TryGetValue(memberInfo, out result) then\n raise new ArgumentException(GetMemberErrorMessage(memberInfo.Name),\n \"memberName\"); \nend;\n\nmethod DefaultValueInspector<T>.GetGetMethod(memberName : String) : Converter<T, Object>;\nbegin\n var mi := GetMember(memberName);\n exit GetGetMethod(mi);\nend;\n\nmethod DefaultValueInspector<T>.GetGetMethod(memberInfo : MemberInfo) : Converter<T, Object>;\nbegin\n if not GettersByMember.TryGetValue(memberInfo, out result) then\n raise new ArgumentException(GetMemberErrorMessage(memberInfo.Name),\n \"memberName\"); \nend;\n\nmethod DefaultValueInspector<T>.GetMember(memberName : String) : MemberInfo;\nbegin\n if not MembersByName.TryGetValue(memberName, out result) then\n raise new ArgumentException(GetMemberErrorMessage(memberName),\n \"memberName\"); \nend;\n\nmethod DefaultValueInspector<T>.HasDefaultValue(instance : T; memberName : String) : Boolean;\nbegin\n var getter := GetGetMethod(memberName);\n var instanceValue := getter(instance);\n exit Equals(DefaultValueByName[memberName], instanceValue);\nend;\n\nmethod DefaultValueInspector<T>.HasDefaultValue(instance : T; memberInfo : MemberInfo) : Boolean;\nbegin\n var getter := GetGetMethod(memberInfo);\n var instanceValue := getter(instance);\n exit Equals(DefaultValueByMember[memberInfo], instanceValue);\nend;\n"
}
] |
2008/11/07
|
[
"https://Stackoverflow.com/questions/271904",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/32136/"
] |
271,907
|
<p>Is there a way to find out when in a LAN anyone plugs in a pendrive to the USB port?
Programatically (in C# preferably) or through some tool. Basically I'd imagine a client application sits on each terminal and monitors the USB ports and sends the information to the server. </p>
<p>a.) Can I get the details of the file(s) being copied?
b.) Is there a way to do this without a client application? </p>
<p>EDIT</p>
<p>I dont want to disable the USB port entirely. its to be on a need to have basis. Basically just want the users on the LAN to share data responsibly and know that whatever data is tranfered is monitored and logged and can be questioned later.</p>
|
[
{
"answer_id": 272005,
"author": "MSalters",
"author_id": 15416,
"author_profile": "https://Stackoverflow.com/users/15416",
"pm_score": 5,
"selected": true,
"text": "DEV_BROADCAST_DEVICEINTERFACE dbcc_classguid=GUID_DEVINTERFACE_VOLUME RegisterDeviceNotification() DEV_BROADCAST_DEVICEINTERFACE* dbcc_name GetVolumeNameForVolumeMountPoint() GetLogicalDriveStrings() GetVolumeNameForVolumeMountPoint()"
}
] |
2008/11/07
|
[
"https://Stackoverflow.com/questions/271907",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20358/"
] |
271,938
|
<p>Background: I have a kubuntu laptop right now that I can't use wirelessly, i.e. I haven't got wireless assistant installed. But I have a windows laptop that I can download the debian packages seperately on a USB memory stick.</p>
<p>How do I install a debian package on the computer locally?</p>
|
[
{
"answer_id": 271952,
"author": "Powerlord",
"author_id": 15880,
"author_profile": "https://Stackoverflow.com/users/15880",
"pm_score": 3,
"selected": true,
"text": "dpkg --install /path/to/foo_VVV-RRR.deb\n"
},
{
"answer_id": 271989,
"author": "Sam Stokes",
"author_id": 20131,
"author_profile": "https://Stackoverflow.com/users/20131",
"pm_score": 2,
"selected": false,
"text": "dpkg -i"
}
] |
2008/11/07
|
[
"https://Stackoverflow.com/questions/271938",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3713/"
] |
271,944
|
<p>I have a scenario where users of my ASP.NET web application submit testimonials consisting of text info and images. The submit process has the following steps:</p>
<ul>
<li>First the user inputs the content and chooses a path to an image</li>
<li>When he clicks preview, the info is once again shown so that he can confirm</li>
<li>Once confirmed the info is persisted in the database</li>
</ul>
<p>The problem with this is that I don't want to store uploaded images in the DB before the user actually confirms. Instead I store them as temporary files and put them in DB only after final confirmation.</p>
<p>Since I also want my application to run in medium trust, I have write permissions only to the application directory and nowhere outside. I even want to limit write permissions for the ASPNET / NETWORK SERVICE user to the ~/App_Data folder. The problem with my scenario is that once a temporary file is created in this folder, the application pool is recycled and I don't want that on every testimonial submit.</p>
<p>How do you advise I keep these temp files instead? The pool is not restarted if I update a file - only on create or rename. But I don't think I can store whole images in a single file for all users. What do you think?</p>
<p><b>UPDATE</b>: I should note that I'm using a third party control for upload. It gives me programmatic access to the binary stream of the file contents after upload, but I cannot keep this after a second postback (the first step and postback actually does the upload).</p>
|
[
{
"answer_id": 271994,
"author": "Seb Nilsson",
"author_id": 2429,
"author_profile": "https://Stackoverflow.com/users/2429",
"pm_score": 4,
"selected": true,
"text": "IsolatedStorageFileStream stream = \n new IsolatedStorageFileStream(ISOLATED_FILE_NAME, \n FileMode.Create, isoStore);\n\nStreamWriter writer = new StreamWriter( stream );\nwriter.WriteLine( \"This is my first line in the isolated storage file.\" );\nwriter.WriteLine( \"This is second line.\" );\nwriter.Close();\n string fileName = \"isolatestorage.txt\";\n\nIsolatedStorageFile storage = IsolatedStorageFile.GetStore(\n IsolatedStorageScope.User | IsolatedStorageScope.Assembly, null, null);\n\nstring[] files = storage.GetFileNames(fileName);\nforeach(string file in files) {\n if(file == fileName) {\n storage.DeleteFile(file);\n break;\n }\n}\n"
},
{
"answer_id": 275563,
"author": "Corey Trager",
"author_id": 9328,
"author_profile": "https://Stackoverflow.com/users/9328",
"pm_score": 2,
"selected": false,
"text": " <IPermission\n class=\"FileIOPermission\"\n version=\"1\"\n Read=\"$AppDir$\"\n Write=\"$AppDir$\"\n Append=\"$AppDir$\"\n PathDiscovery=\"$AppDir$\"\n />\n"
}
] |
2008/11/07
|
[
"https://Stackoverflow.com/questions/271944",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1801/"
] |
271,953
|
<p>Got into a situation where in a schema i have a table, say table ACTION , while i got a synonym called ACTION as well which refers to another table to another schema.</p>
<p>Now, when i run the query</p>
<p>select * from ACTION</p>
<p>it will select the records from the table, but not the synonym.</p>
<p>Anyway for me to select from the synonym AND the table both together?</p>
<p>Thanx</p>
|
[
{
"answer_id": 271997,
"author": "Kieveli",
"author_id": 15852,
"author_profile": "https://Stackoverflow.com/users/15852",
"pm_score": 2,
"selected": false,
"text": "SELECT * from LOCAL_ACTION\nUNION\nSELECT * from otheruser.LOCAL_ACTION\n"
},
{
"answer_id": 272051,
"author": "Salamander2007",
"author_id": 10629,
"author_profile": "https://Stackoverflow.com/users/10629",
"pm_score": 3,
"selected": false,
"text": "select * from ACTION\nunion \nselect * from public.ACTION\n"
},
{
"answer_id": 277877,
"author": "David Aldridge",
"author_id": 6742,
"author_profile": "https://Stackoverflow.com/users/6742",
"pm_score": 1,
"selected": false,
"text": "select * from ACTION\nunion all\nselect * from public.ACTION\n"
}
] |
2008/11/07
|
[
"https://Stackoverflow.com/questions/271953",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
271,954
|
<p>I never use Access 2007 - until today.</p>
<p>I want to connect to an existing SQL Server 2008 database. I have tried using:</p>
<ul>
<li>External Data ODBC option - but get DSN errror</li>
<li>Upsizing wizard with ODBC - get an error</li>
<li>Upsizing wizard with SNAC - get ODBC error. So that one seems a none starter :-)</li>
</ul>
<p>I have done some searching and only found others with same issue. About to do some more... but hoping one of you has the answer OTTOYH. Thanks.</p>
|
[
{
"answer_id": 271984,
"author": "Eric Nelson",
"author_id": 5636,
"author_profile": "https://Stackoverflow.com/users/5636",
"pm_score": 0,
"selected": false,
"text": "[ODBC]\nDRIVER=SQL Server\nUID=ericnel\nDATABASE=AccessTest\nWSID=ERICNEL1\nAPP=2007 Microsoft Office system\nTrusted_Connection=Yes\nSERVER=ericnel1\nDescription=test\n"
}
] |
2008/11/07
|
[
"https://Stackoverflow.com/questions/271954",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5636/"
] |
271,957
|
<p>I got a row structure looks like ID bigint, ScanRept XML</p>
<p>I want to wind up with a file named 4.xml containing just the xml from the ScanRept column where the ID number is 4.</p>
<p>I don't want to do it interactively (by going into Manager Studio, finding the row, right-clicking the field and doing Save AS) - that's what I'll do if I can't figure out a better way. </p>
<p>I do have C# available; if this is doable with sqlcmd, that's my preference (cause there will probably be a lot of variations I can't anticipate right now).</p>
|
[
{
"answer_id": 271984,
"author": "Eric Nelson",
"author_id": 5636,
"author_profile": "https://Stackoverflow.com/users/5636",
"pm_score": 0,
"selected": false,
"text": "[ODBC]\nDRIVER=SQL Server\nUID=ericnel\nDATABASE=AccessTest\nWSID=ERICNEL1\nAPP=2007 Microsoft Office system\nTrusted_Connection=Yes\nSERVER=ericnel1\nDescription=test\n"
}
] |
2008/11/07
|
[
"https://Stackoverflow.com/questions/271957",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/35458/"
] |
271,965
|
<p>Is there a function in glut which moves the mouse to a specific position?
There is a similar function in SDL (SDL_WarpMouse) but I want to stick to glut.</p>
|
[
{
"answer_id": 271975,
"author": "Alexander Stolz",
"author_id": 2450,
"author_profile": "https://Stackoverflow.com/users/2450",
"pm_score": 4,
"selected": true,
"text": "glutWarpPointer(middleX, middleY)"
}
] |
2008/11/07
|
[
"https://Stackoverflow.com/questions/271965",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2450/"
] |
271,966
|
<p>There are no builtin matrix functions in C#, but there are in the F# powerpack.</p>
<p>Rather than using a third party or open source C# library, I wonder about rolling my own in F#, and exposing the useful bits to C#. </p>
<p>Wondered if anybody has already thought of this, or tried it, and whether it's a good idea.</p>
<p>Should I expose it as a class, or a load of static functions?</p>
<p>Or should I create a C# wrapper class, and have that call down to F#? Or have the F# use the C# class as input and output?</p>
<p>Any thoughts?</p>
<p>Answer thanks to <a href="https://stackoverflow.com/questions/271966/about-using-f-to-create-a-matrix-assembly-usable-from-c#272250">Hath</a> below: you can use the F# library directly in C# (operators as well!):</p>
<pre><code>using System;
using System.Text;
using Microsoft.FSharp.Math;
namespace CSharp
{
class Program
{
static void Main(string[] args)
{
double[,] x = { { 1.0, 2.0 }, { 4.0, 5.0 } };
double[,] y = { { 1.0, 2.0 }, { 7.0, 8.0 } };
Matrix<double> m1 = MatrixModule.of_array2(x);
Matrix<double> m2 = MatrixModule.of_array2(y);
var mp = m1 * m2;
var output = mp.ToArray2();
Console.WriteLine(output.StringIt());
Console.ReadKey();
}
}
public static class Extensions
{
public static string StringIt(this double[,] array)
{
var sb = new StringBuilder();
for (int r = 0; r < array.Length / array.Rank; r++)
{
for (int c = 0; c < array.Rank; c++)
{
if (c > 0) sb.Append("\t");
sb.Append(array[r, c].ToString());
}
sb.AppendLine();
}
return sb.ToString();
}
}
}
</code></pre>
|
[
{
"answer_id": 272250,
"author": "Hath",
"author_id": 5186,
"author_profile": "https://Stackoverflow.com/users/5186",
"pm_score": 4,
"selected": true,
"text": "Microsoft.FSharp.Math.BigInt class.\n Microsoft.FSharp.Math.Matrix<A> class\n"
}
] |
2008/11/07
|
[
"https://Stackoverflow.com/questions/271966",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11410/"
] |
271,971
|
<p>Through profiling I've discovered that the sprintf here takes a long time. Is there a better performing alternative that still handles the leading zeros in the y/m/d h/m/s fields?</p>
<pre><code>SYSTEMTIME sysTime;
GetLocalTime( &sysTime );
char buf[80];
for (int i = 0; i < 100000; i++)
{
sprintf(buf, "%4d-%02d-%02d %02d:%02d:%02d",
sysTime.wYear, sysTime.wMonth, sysTime.wDay,
sysTime.wHour, sysTime.wMinute, sysTime.wSecond);
}
</code></pre>
<hr>
<p>Note: The OP explains in the comments that this is a stripped-down example. The "real" loop contains additional code that uses varying time values from a database. Profiling has pinpointed <code>sprintf()</code> as the offender.</p>
|
[
{
"answer_id": 271993,
"author": "Roddy",
"author_id": 1737,
"author_profile": "https://Stackoverflow.com/users/1737",
"pm_score": 3,
"selected": false,
"text": "buf[0] = (sysTime.wYear / 1000) % 10 + '0' ;\nbuf[1] = (sysTime.wYear / 100) % 10 + '0';\nbuf[2] = (sysTime.wYear / 10) % 10 + '0';\nbuf[3] = sysTime.wYear % 10 + '0';\nbuf[4] = '-';\n"
},
{
"answer_id": 272016,
"author": "Adam Liss",
"author_id": 29157,
"author_profile": "https://Stackoverflow.com/users/29157",
"pm_score": 2,
"selected": false,
"text": "sprintf() sprintf() sprintf() sprintf()"
},
{
"answer_id": 272021,
"author": "Jaywalker",
"author_id": 382974,
"author_profile": "https://Stackoverflow.com/users/382974",
"pm_score": 2,
"selected": false,
"text": "SYSTEMTIME sysTime, oldSysTime;\n char datePart[80];\nchar timePart[80];\n"
},
{
"answer_id": 272024,
"author": "John Carter",
"author_id": 8331,
"author_profile": "https://Stackoverflow.com/users/8331",
"pm_score": 5,
"selected": true,
"text": "strftime() char LeadingZeroIntegerValues[62][] = { \"00\", \"01\", \"02\", ... \"59\", \"60\", \"61\" };\n strftime()"
},
{
"answer_id": 272113,
"author": "Tom Barta",
"author_id": 29839,
"author_profile": "https://Stackoverflow.com/users/29839",
"pm_score": 2,
"selected": false,
"text": "printf { \"00\", \"01\", \"02\", ..., \"99\" }"
},
{
"answer_id": 272146,
"author": "shank",
"author_id": 24697,
"author_profile": "https://Stackoverflow.com/users/24697",
"pm_score": 2,
"selected": false,
"text": "\nstatic char fbuf[80];\nstatic SYSTEMTIME lastSysTime = {0, ..., 0}; // initialize to all zeros.\n\nfor (int i = 0; i < 100000; i++)\n{\n if ((lastSysTime.wHour != sysTime.wHour)\n || (lastSysTime.wDay != sysTime.wDay)\n || (lastSysTime.wMonth != sysTime.wMonth)\n || (lastSysTime.wYear != sysTime.wYear))\n {\n sprintf(fbuf, \"%4d-%02s-%02s %02s:%%02s:%%02s\",\n sysTime.wYear, n2s[sysTime.wMonth],\n n2s[sysTime.wDay], n2s[sysTime.wHour]);\n\n lastSysTime.wHour = sysTime.wHour;\n lastSysTime.wDay = sysTime.wDay;\n lastSysTime.wMonth = sysTime.wMonth;\n lastSysTime.wYear = sysTime.wYear;\n }\n\n sprintf(buf, fbuf, n2s[sysTime.wMinute], n2s[sysTime.wSecond]);\n\n}\n"
},
{
"answer_id": 814222,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "void log(int channel, char *filename, int lineno, format, ...) strcpy LOG(channel, ...etc) log(#channel, ...etc) memcpy LOG(channel, ...) log(\"....\"#channel - sizeof(\"....\"#channel) + *11*) digit = ((value /= value) % 10) void itoa03(char *string, unsigned int value)\n{\n *string++ = '0' + ((value = value * 2684355) >> 28);\n *string++ = '0' + ((value = ((value & 0x0FFFFFFF)) * 10) >> 28);\n *string++ = '0' + ((value = ((value & 0x0FFFFFFF)) * 10) >> 28);\n *string++ = ' ';/* null terminate here if thats what you need */\n}\n void itoa05(char *string, unsigned int value)\n{\n *string++ = ' ';\n *string++ = '0' + ((value = value * 26844 + 12) >> 28);\n *string++ = '0' + ((value = ((value & 0x0FFFFFFF)) * 10) >> 28);\n *string++ = '0' + ((value = ((value & 0x0FFFFFFF)) * 10) >> 28);\n *string++ = '0' + ((value = ((value & 0x0FFFFFFF)) * 10) >> 28);\n *string++ = '0' + ((value = ((value & 0x0FFFFFFF)) * 10) >> 28);\n *string++ = ' ';/* null terminate here if thats what you need */\n}\n vsnprintf() vsprintf()"
}
] |
2008/11/07
|
[
"https://Stackoverflow.com/questions/271971",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9328/"
] |
271,979
|
<p>I need to pull some BLOB data from a SQL Server 2005 database and generate a SQL script to insert this same data in another database, in another server.</p>
<p>I am only allowed to do this using SQL scripts, I can't use any other utility or write a program in Java or .NET to do it.</p>
<p>The other big restriction I have is that I don't have access to the original database (where the original BLOB data is) when I run the script, to copy the BLOB data to the target database, so the data should already be encoded within the SQL script file.</p>
<p>Summing up: is there a way to encode the BLOB data into text so that I can dump it into a SQL INSERT command within a script text file and run it?</p>
<p>I am able to run special T-SQL statements and stored procedures if needed to.</p>
|
[
{
"answer_id": 271999,
"author": "splattne",
"author_id": 6461,
"author_profile": "https://Stackoverflow.com/users/6461",
"pm_score": 1,
"selected": false,
"text": "CREATE PROCEDURE sp_textcopy (\n @srvname varchar (30),\n @login varchar (30),\n @password varchar (30),\n @dbname varchar (30),\n @tbname varchar (30),\n @colname varchar (30),\n @filename varchar (30),\n @whereclause varchar (40),\n @direction char(1))\n\nAS\n\nDECLARE @exec_str varchar (255)\nSELECT @exec_str =\n 'textcopy /S ' + @srvname +\n ' /U ' + @login +\n ' /P ' + @password +\n ' /D ' + @dbname +\n ' /T ' + @tbname +\n ' /C ' + @colname +\n ' /W \"' + @whereclause +\n '\" /F ' + @filename +\n ' /' + @direction\nEXEC master..xp_cmdshell @exec_str\n"
}
] |
2008/11/07
|
[
"https://Stackoverflow.com/questions/271979",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/407003/"
] |
272,003
|
<p>I have a MS-access database. But it is on the shared drive. And it is required that only some selected number of people can use it. Is there a way to authenticate the user?</p>
|
[
{
"answer_id": 417801,
"author": "Mike",
"author_id": 51350,
"author_profile": "https://Stackoverflow.com/users/51350",
"pm_score": 0,
"selected": false,
"text": "AuthorizedUser = True\nSelect Case user\n Case \"USER_A\":\n Case \"USER_B\":\n Case \"USER_C\": \n Case Else: AuthorizedUser = False\nEnd Select\n\nIf AuthorizedUser = True Then\n MsgBox \"Welcome authorized user \" & user\nElse\n MsgBox user & \"is not Authorized. For access to this database contact User_A\"\n DoCmd.Quit\nEnd If\n"
}
] |
2008/11/07
|
[
"https://Stackoverflow.com/questions/272003",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6613/"
] |
272,007
|
<p>I am using jQuery to try and trigger a method when an <a href="http://en.wikipedia.org/wiki/ASP.NET" rel="nofollow noreferrer">ASP.NET</a> (2.0) dropdown list's change event is handled by jQuery. The problem is that the drop down list is located inside a gridview and even then only when a user has decided to edit a row within that gridview.</p>
<p>I think I have it picking up the object using an ASP code block, but the problem with that is that when the page first loads the edit index of the row does not exist and it throws an error. Putting the block inside a <code>IF</code> statement also does not work.</p>
<pre><code>$(document).ready(function() //when DOM is ready, run containing code
{
<% if (grvTimeSheets.EditIndex > -1) {%>
$(#<%=grvTimeSheets.Rows[grvTimeSheets.EditIndex].FindControl("ddlClients").ClientID %>).change(function() {
$(#<%= grvTimeSheets.ClientID %>).block({ message: null }
});
}
);
<% } %>
</code></pre>
<p>It is one attempt I made, and I also tried putting the IF statement ASP code outside the JavaScript block. It doesn't work either.</p>
<p>How could I apply the jQuery event to the drop drop box? Ideally as concise as possible.</p>
<hr>
<p>Thanks for the answer but nope, it doesn't work :(. The JavaScript code seems not to be outputted... Confusing...</p>
<pre><code><script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="jquery.tablesorter.js"></script>
<script type="text/javascript" src="jquery.blockUI.js"></script>
<script type="text/javascript">
$(document).ready(function() //When DOM is ready, run the containing code
{
}
);
</script>
</code></pre>
<p>Is the output. Even though this is the code:</p>
<pre><code><script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="jquery.tablesorter.js"></script>
<script type="text/javascript" src="jquery.blockUI.js"></script>
<script type="text/javascript">
$(document).ready(function() //when DOM is ready, run containing code
{<% if (grvTimeSheets.EditIndex > -1) {%>
var id = '#<%=grvTimeSheets.Rows[grvTimeSheets.EditIndex].FindControl("ddlClients").ClientID %>';
$(id).change(function() {
$(id).block({ message: null }
});
<% } %>
}
);
</script>
</code></pre>
<p>It was doing that before as well, driving me CRAZY.</p>
<hr>
<p>Sorry, could you make that slightly clearer. I tried defining the entire thing in code behind like so:</p>
<pre><code>DropDownList ddl (DropDownList)grvTimeSheets.Rows[grvTimeSheets.EditIndex].FindControl("ddlClients");
if (ddl != null)
{
ClientScriptManager csm = Page.ClientScript;
Type cstype = this.GetType();
String csname1 = "PopupScript";
string script = @"
<script language='javascript' type='text/javascript'>
$(#" + ddl.ClientID + ").change(function() { $(" + grvTimeSheets.ClientID + ").blockUI({ message: null }});} </script>";
csm.RegisterStartupScript(cstype, csname1, script, true);
}
</code></pre>
<p>Is that what you meant?</p>
<p>BTW, the above didn't work. No errors, just no events worked.</p>
|
[
{
"answer_id": 272311,
"author": "MrKurt",
"author_id": 35296,
"author_profile": "https://Stackoverflow.com/users/35296",
"pm_score": 3,
"selected": true,
"text": "$() $(#some-generated-id) $(document).ready(function() //when DOM is ready, run containing code\n{\n <% if (grvTimeSheets.EditIndex > -1) {%>\n var id = '#<%=grvTimeSheets.Rows[grvTimeSheets.EditIndex].FindControl(\"ddlClients\").ClientID %>';\n $(id).change(function() { \n $(id).block({ message: null }\n }); \n <% } %>\n}\n);\n"
},
{
"answer_id": 272752,
"author": "OutOFTouch",
"author_id": 35166,
"author_profile": "https://Stackoverflow.com/users/35166",
"pm_score": 1,
"selected": false,
"text": "var myFancySelector = '#' + myControlId;\nselectedValue = $(myFancySelector).val();\n"
},
{
"answer_id": 272788,
"author": "OutOFTouch",
"author_id": 35166,
"author_profile": "https://Stackoverflow.com/users/35166",
"pm_score": 1,
"selected": false,
"text": "cs.RegisterClientScriptBlock(cstype, csname, cstext2.ToString(), False)\n"
},
{
"answer_id": 272853,
"author": "Damien",
"author_id": 35454,
"author_profile": "https://Stackoverflow.com/users/35454",
"pm_score": 0,
"selected": false,
"text": "DropDownList ddl = (DropDownList)grvTimeSheets.Rows[grvTimeSheets.EditIndex].FindControl(\"ddlClients\");\nif (ddl != null)\n{\n ClientScriptManager csm = Page.ClientScript;\n Type cstype = this.GetType();\n String csname1 = \"PopupScript\";\n\n string script = @\"\n <script language='javascript' type='text/javascript'>\n jQuery(#\" + ddl.ClientID + \").change(function() { $(\" + grvTimeSheets.ClientID + \").blockUI({ message: null }});} </script>\";\n csm.RegisterStartupScript(cstype, csname1, script, false);\n"
},
{
"answer_id": 272871,
"author": "OutOFTouch",
"author_id": 35166,
"author_profile": "https://Stackoverflow.com/users/35166",
"pm_score": 1,
"selected": false,
"text": "string script = @\"<script type=text/javascript> var myControlId = '\" + ddl.ClientId \"';\") + \"</script>\"\n grvTimeSheets.ClientID"
},
{
"answer_id": 272883,
"author": "Ben Scheirman",
"author_id": 3381,
"author_profile": "https://Stackoverflow.com/users/3381",
"pm_score": 1,
"selected": false,
"text": "$(function() {\n $(\"select.yourMarkerClass\").change(....);\n});\n"
},
{
"answer_id": 272884,
"author": "Adam Lassek",
"author_id": 1249,
"author_profile": "https://Stackoverflow.com/users/1249",
"pm_score": 1,
"selected": false,
"text": "$('[id$=ddlClients]')\n"
}
] |
2008/11/07
|
[
"https://Stackoverflow.com/questions/272007",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/35454/"
] |
272,010
|
<p>I'm looking for a PHP (with MYSQL) nested sets class with all needed functions.
For example:</p>
<p>createLeftNode, createRightNode,createRootNode, createSubNode,deleteNode and <strong>moveTree</strong>. Not only 1 left, 1 right, 1 up and 1 down but also a part of a tree in a nother tree.</p>
<p>Thanks!</p>
|
[
{
"answer_id": 42076840,
"author": "Kim Pepper",
"author_id": 668727,
"author_profile": "https://Stackoverflow.com/users/668727",
"pm_score": 0,
"selected": false,
"text": "revision_id"
}
] |
2008/11/07
|
[
"https://Stackoverflow.com/questions/272010",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/35459/"
] |
272,013
|
<p>Why is it called a single in VB.net? I'm sure there is a good reason but it doesn't seem intuitive to a non formally trained programmer like me.</p>
|
[
{
"answer_id": 272023,
"author": "chakrit",
"author_id": 3055,
"author_profile": "https://Stackoverflow.com/users/3055",
"pm_score": 2,
"selected": false,
"text": "shorthand \"Single-precision\" Double Double-precision\" C-style int float \"integer\" \"floating point\""
},
{
"answer_id": 272186,
"author": "Jon Skeet",
"author_id": 22656,
"author_profile": "https://Stackoverflow.com/users/22656",
"pm_score": 4,
"selected": false,
"text": "System.Single System.Double System.Float32 System.Float64"
}
] |
2008/11/07
|
[
"https://Stackoverflow.com/questions/272013",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2763/"
] |
272,030
|
<p>I have a VS 2005 C# project that uses a special Plugin folder to load extra DLLs (for use as nodes in an asset conversion process).</p>
<p>I have a mixture of C# and C++ DLLs in this folder.</p>
<p>The issue I have is that when Shadow Copying is enabled, the C++ DLLs refuse to load using Assembly.LoadFrom. I have attempted to create a custom app domain, and used Load, but this also failed.</p>
<p>Finally, I tried reading the DLL in as byte[] data and using Load on that - again, only the C# DLLs would work this way, with an error "Additional information: Unverifiable code failed policy check. (Exception from HRESULT: 0x80131402)".</p>
<p>An article on the net prompted me to attempt to use /clr:safe when building that particular DLL, but then it simply failed to build due to thousands of errors in Microsoft code... (apparently)</p>
<p>With Shadow Copying disabled, LoadFrom works fine for all DLLs. The app is itself a plugin for Maya, and this used to work with Maya 8.5 but fails with 2008 / 2009 (if Shadow Copying is enabled).</p>
<p>We really would prefer to use Shadow Copying, because it prevents DLL file locks when the app is running (the Plugins folder is stored in a location that Perforce can update while the app is running).</p>
<p>Any ideas as to how I can persuade Shadow Copying to work with a custom folder AND a mix of C# / C++ DLLs without these problems?</p>
|
[
{
"answer_id": 272307,
"author": "Sunlight",
"author_id": 33650,
"author_profile": "https://Stackoverflow.com/users/33650",
"pm_score": 1,
"selected": false,
"text": "/clr:safe caspol -s"
}
] |
2008/11/07
|
[
"https://Stackoverflow.com/questions/272030",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/35444/"
] |
272,035
|
<p>I have a form that displays file information in a TabControl, and I'd like the pages to have the file's icon in their tab. How do I get the icon associated with a file type?</p>
<p>I'd prefer solutions that don't involve looking things up in the registry, but if that's the only way then so be it.</p>
|
[
{
"answer_id": 272044,
"author": "Bill the Lizard",
"author_id": 1288,
"author_profile": "https://Stackoverflow.com/users/1288",
"pm_score": 5,
"selected": true,
"text": "FileAssociationInfo ProgramAssociationInfo pai FileAssociationInfo fai = new FileAssociationInfo(\".bob\");\nProgramAssociationInfo pai = new ProgramAssociationInfo(fai.ProgID);\nProgramIcon icon = pai.DefaultIcon;\n"
}
] |
2008/11/07
|
[
"https://Stackoverflow.com/questions/272035",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15371/"
] |
272,036
|
<p>I've accidentally removed Win2K compatibility from an application by using <a href="http://msdn.microsoft.com/en-us/library/ms683215(VS.85).aspx" rel="nofollow noreferrer">GetProcessID</a>.</p>
<p>I use it like this, to get the main HWND for the launched application.</p>
<pre><code>ShellExecuteEx(&info); // Launch application
HANDLE han = info.hProcess; // Get process
cbinfo.han = han;
//Call EnumWindows to enumerate windows....
//with this as the callback
static BOOL CALLBACK enumproc(HWND hwnd, LPARAM lParam)
{
DWORD id;
GetWIndowThreadProcessID(hwnd, &id);
if (id == GetProcessID(cbinfo.han))
setResult(hwnd)
...
}
</code></pre>
<p>Any ideas how the same function could be acheived on Win2K?</p>
|
[
{
"answer_id": 280533,
"author": "Roddy",
"author_id": 1737,
"author_profile": "https://Stackoverflow.com/users/1737",
"pm_score": 2,
"selected": false,
"text": "#include \"Winternl.h\"\n\ntypedef DWORD (WINAPI* pfnGetProcID)(HANDLE h);\n\ntypedef NTSTATUS (WINAPI* pfnQueryInformationProcess)(\n HANDLE ProcessHandle,\n PROCESSINFOCLASS ProcessInformationClass,\n PVOID ProcessInformation,\n ULONG ProcessInformationLength,\n PULONG ReturnLength);\n\nDWORD MyGetProcessId(HANDLE h)\n{\n static pfnQueryInformationProcess ntQIP = (pfnQueryInformationProcess) GetProcAddress(GetModuleHandle(\"NTDLL.DLL\"),\"NtQueryInformationProcess\");\n static pfnGetProcID getPId = (pfnGetProcID) GetProcAddress(GetModuleHandle(\"KERNEL32.DLL\"),\"GetProcessId\");\n\n if ((ntQIP == NULL) && (getPId == NULL))\n throw Exception(\"Can't retrieve process ID : GetProcessID not supported\");\n\n if (getPId != NULL)\n return getPId(h);\n else\n {\n PROCESS_BASIC_INFORMATION info;\n ULONG returnSize;\n ntQIP(h, ProcessBasicInformation, &info, sizeof(info), &returnSize); // Get basic information.\n return info.UniqueProcessId;\n }\n}\n"
}
] |
2008/11/07
|
[
"https://Stackoverflow.com/questions/272036",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1737/"
] |
272,038
|
<p>In my Seam application, I have a Seam component that returns a (<code>@Datamodel</code>) list of items I want to transform into a set of <code><li></code> HTML elements. I have this working without a problem. </p>
<p>But now, I want to split up the list according to an EL expression. So the EL expression determines if a new <code><ul></code> element should be started. I tried the following:</p>
<pre><code><s:fragment rendered="#{action.isNewList(index)}">
<ul>
</s:fragment>
<!-- stuff that does the <li>'s goes here -->
<s:fragment rendered="#{action.isNewList(index)}">
</ul>
</s:fragment>
</code></pre>
<p>But that's invalid, because the nesting for <code><ul></code> is wrong.</p>
<p>How should I do this?</p>
|
[
{
"answer_id": 483930,
"author": "phloopy",
"author_id": 8507,
"author_profile": "https://Stackoverflow.com/users/8507",
"pm_score": 0,
"selected": false,
"text": "<!-- before your loop, open your first <ul> if the (@Datamodel) is not empty -->\n\n<s:fragment rendered=\"#{action.isNewList(index)}\">\n </ul>\n <ul>\n</s:fragment>\n<!-- stuff that does the <li>'s goes here -->\n\n<!-- after your loop, close your last </ul> if the (@Datamodel) is not empty -->\n"
},
{
"answer_id": 485578,
"author": "Eduard Wirch",
"author_id": 17428,
"author_profile": "https://Stackoverflow.com/users/17428",
"pm_score": 0,
"selected": false,
"text": "<ul>\n <s:for items=\"itemList\" ...>\n\n <s:fragment rendered=\"#{action.isNewList(index) && index > 0}\">\n </ul>\n <ul>\n </s:fragment>\n <li>\n <!-- stuff that does the <li>'s goes here -->\n </li>\n\n </s:for>\n</ul>\n"
},
{
"answer_id": 487676,
"author": "Peter Hilton",
"author_id": 2670,
"author_profile": "https://Stackoverflow.com/users/2670",
"pm_score": 2,
"selected": true,
"text": "<f:verbatim> <f:verbatim rendered=\"#{action.isNewList(index)}\">\n <ul>\n</f:verbatim>\n<!-- stuff that does the <li>'s goes here -->\n<f:verbatim rendered=\"#{action.isNewList(index)}\">\n </ul>\n</f:verbatim>\n"
}
] |
2008/11/07
|
[
"https://Stackoverflow.com/questions/272038",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6400/"
] |
272,045
|
<p>I have two tables A and B. I would like to delete all the records from table A that are returned in the following query:</p>
<pre><code>SELECT A.*
FROM A , B
WHERE A.id = B.a_id AND
b.date < '2008-10-10'
</code></pre>
<p>I have tried:</p>
<pre><code>DELETE A
WHERE id in (
SELECT a_id
FROM B
WHERE date < '2008-10-10')
</code></pre>
<p>but that only works if the inner select actually returns a value (not if the result set is empty)</p>
<p><strong>NB:</strong> this has to work on <strong>both SQLServer AND MySQL</strong></p>
<p>EDIT: More information</p>
<p>The above delete works 100% on SQLServer</p>
<p>When running it on MySQL I get an "error in you SQL syntax" message which points to the start of the SELECT as the problem. if I substitute the inner select with (1,2) then it works. </p>
<p><em>@Kibbee You are right it actually makes no difference if the inner select returns rows or not.</em></p>
<p><em>@Fred I get a "not unique table.alias: a" message</em></p>
|
[
{
"answer_id": 272056,
"author": "Fred",
"author_id": 33630,
"author_profile": "https://Stackoverflow.com/users/33630",
"pm_score": 1,
"selected": false,
"text": "DELETE FROM A\nWHERE A.id in (\n SELECT B.a_id \n FROM B\n WHERE B.date < '2008-10-10');\n"
},
{
"answer_id": 272083,
"author": "lmop",
"author_id": 22260,
"author_profile": "https://Stackoverflow.com/users/22260",
"pm_score": 4,
"selected": true,
"text": "DELETE a.* FROM A a JOIN B b ON b.id = a.id WHERE b.date < '2008-10-10';\n DELETE A.* FROM A JOIN B ON B.id = A.id WHERE B.date < '2008-10-10';\n"
},
{
"answer_id": 272156,
"author": "Shawn",
"author_id": 26,
"author_profile": "https://Stackoverflow.com/users/26",
"pm_score": 0,
"selected": false,
"text": "delete from a inner join b on a.id = b.a_id and b.date < '2008-10-10'\n"
},
{
"answer_id": 272221,
"author": "Charles Bretana",
"author_id": 32632,
"author_profile": "https://Stackoverflow.com/users/32632",
"pm_score": 2,
"selected": false,
"text": "Delete A \nFrom A\nWhere Exists \n (Select * From B \n Where B.Id = A.Id\n And B.date < '2008-10-10');\n"
},
{
"answer_id": 277377,
"author": "EJ.",
"author_id": 35109,
"author_profile": "https://Stackoverflow.com/users/35109",
"pm_score": 0,
"selected": false,
"text": "select b.ID\ninto #T\nfrom \n [Table b] with (nolock) \nwhere \n b.date > '2008-10-10'\n\nif exists (select * from #T with (nolock))\n delete from [Table a] where a.id in (select id from #T with (nolock))\n drop table #T\n"
}
] |
2008/11/07
|
[
"https://Stackoverflow.com/questions/272045",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/939/"
] |
272,097
|
<p>How do I dynamically reload the app.config in a .net Windows application? I need to turn logging on and off dynamically and not just based upon the value at application start.</p>
<p>ConfigurationManager.RefreshSection("appSettings") does not work and I've also tried explicitly opening the config file using OpenExeConfiguration but I always get the cached value at application startup and not the current value. </p>
<p>I've accepted the answer of creating a custom configuration section. As a side note and foolish mistake - if you're running from the IDE there's no point in updating the app.config file and expecting changes. Yuo have to modify the .exe.config file in the bin\debug folder. Doh!</p>
|
[
{
"answer_id": 272114,
"author": "Patrick Desjardins",
"author_id": 13913,
"author_profile": "https://Stackoverflow.com/users/13913",
"pm_score": 6,
"selected": true,
"text": "ConfigurationManager.RefreshSection(\"yoursection/subsection\");\n"
},
{
"answer_id": 272120,
"author": "Mitch Wheat",
"author_id": 16076,
"author_profile": "https://Stackoverflow.com/users/16076",
"pm_score": 3,
"selected": false,
"text": "app.config web.config FileSystemWatcher [assembly: log4net.Config.XmlConfigurator(ConfigFile=\"Log4Net.config\", Watch = true)]\n Log4Net.config log4net.config"
},
{
"answer_id": 748467,
"author": "foson",
"author_id": 22539,
"author_profile": "https://Stackoverflow.com/users/22539",
"pm_score": 2,
"selected": false,
"text": "Application.Start(new Form1()) System.Xml System.Configuration.ConfigurationManager string configFile = Application.ExecutablePath + \".config\"; //c:\\path\\exename.exe.config\nXmlDocument xdoc = new XmlDocument();\nxdoc.Load(configFile);\nXmlNode node = xdoc.SelectSingleNode(\"/configuration/appSettings/add[@key='nodeToChange']/@value\");\nnode.Value = \"new value\";\nFile.WriteAllText(setFile, xdoc.InnerXml);\n"
},
{
"answer_id": 3607822,
"author": "Ruchir",
"author_id": 435781,
"author_profile": "https://Stackoverflow.com/users/435781",
"pm_score": 3,
"selected": false,
"text": "ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None).Save(ConfigurationSaveMode.Modified);\n ConfigurationManager.RefreshSection(\"appSettings\");\n"
},
{
"answer_id": 6841134,
"author": "froeschli",
"author_id": 431657,
"author_profile": "https://Stackoverflow.com/users/431657",
"pm_score": 1,
"selected": false,
"text": "internal interface ILoggingConfiguration\n{\n void SetLogLevel(string level);\n\n string GetLogLevel();\n}\n internal sealed class LoggingConfigurationImpl : ILoggingConfiguration\n{\n #region Members\n\n private static readonly ILog _logger = \n ObjectManager.Common.Logger.GetLogger();\n private const string DEFAULT_NAME_SPACE = \"Default.Name.Space\";\n\n #endregion\n\n #region Implementation of ILoggingConfiguration\n\n public void SetLogLevel(string level)\n {\n Level threshold = Log4NetUtils.ConvertToLevel(level);\n ILoggerRepository[] repositories = LogManager.GetAllRepositories();\n\n foreach (ILoggerRepository repository in repositories)\n {\n try\n {\n SetLogLevelOnRepository(repository, threshold);\n }\n catch (Exception ex)\n {\n _logger.ErrorFormat(\"Exception while changing log-level: {0}\", ex);\n }\n }\n PersistLogLevel(level);\n }\n\n public string GetLogLevel()\n {\n ILoggerRepository repository = LogManager.GetRepository();\n Hierarchy hierarchy = (Hierarchy) repository;\n ILogger logger = hierarchy.GetLogger(DEFAULT_NAME_SPACE);\n return ((Logger) logger).Level.DisplayName;\n }\n\n private void SetLogLevelOnRepository(ILoggerRepository repository,\n Level threshold)\n {\n repository.Threshold = threshold;\n Hierarchy hierarchy = (Hierarchy)repository;\n ILogger[] loggers = hierarchy.GetCurrentLoggers();\n foreach (ILogger logger in loggers)\n {\n try\n {\n SetLogLevelOnLogger(threshold, logger);\n }\n catch (Exception ex)\n {\n _logger.ErrorFormat(\"Exception while changing log-level for \n logger: {0}{1}{2}\", logger, Environment.NewLine, ex);\n }\n }\n }\n\n private void SetLogLevelOnLogger(Level threshold, ILogger logger)\n {\n ((Logger)logger).Level = threshold;\n }\n\n private void PersistLogLevel(string level)\n {\n XmlDocument config = new XmlDocument();\n config.Load(AppDomain.CurrentDomain.SetupInformation.ConfigurationFile);\n string xpath =\n String.Format(\"configuration/log4net/logger[@name='{0}']/level\",\n DEFAULT_NAME_SPACE);\n XmlNode rootLoggerNode = config.SelectSingleNode(xpath);\n\n try\n {\n rootLoggerNode.Attributes[\"value\"].Value = level;\n config.Save(AppDomain.CurrentDomain.SetupInformation.ConfigurationFile);\n\n ConfigurationManager.RefreshSection(\"log4net\");\n }\n catch(Exception ex)\n {\n _logger.ErrorFormat(\"error while persisting new log-level: {0}\", ex);\n }\n }\n\n #endregion\n}\n public sealed class Log4NetUtils\n{\n private static readonly ILoggerRepository _loggerRepository =\n LoggerManager.GetAllRepositories().First();\n\n public static Level ConvertToLevel(string level)\n {\n return _loggerRepository.LevelMap[level];\n }\n}\n <ComboBox Name=\"cbxLogLevel\" Text=\"{Binding LogLevel}\">\n <ComboBoxItem Content=\"DEBUG\" />\n <ComboBoxItem Content=\"INFO\" />\n <ComboBoxItem Content=\"WARN\" />\n <ComboBoxItem Content=\"ERROR\" />\n</ComboBox>\n<Button Name=\"btnChangeLogLevel\" \n Command=\"{Binding SetLogLevelCommand}\"\n CommandParameter=\"{Binding ElementName=cbxLogLevel, Path=Text}\" >\n Change log level\n</Button>\n"
},
{
"answer_id": 11425940,
"author": "Sudhanshu Mishra",
"author_id": 190476,
"author_profile": "https://Stackoverflow.com/users/190476",
"pm_score": 0,
"selected": false,
"text": "class Program\n {\n static void Main(string[] args)\n {\n string value = string.Empty, key = \"mySetting\";\n Program program = new Program();\n\n program.GetValue(program, key);\n Console.WriteLine(\"--------------------------------------------------------------\");\n Console.WriteLine(\"Press any key to exit...\");\n Console.ReadLine();\n }\n\n /// <summary>\n /// Gets the value of the specified key from app.config file.\n /// </summary>\n /// <param name=\"program\">The instance of the program.</param>\n /// <param name=\"key\">The key.</param>\n private void GetValue(Program program, string key)\n {\n string value;\n if (ConfigurationManager.AppSettings.AllKeys.Contains(key))\n {\n Console.WriteLine(\"--------------------------------------------------------------\");\n Console.WriteLine(\"Key found, evaluating value...\");\n value = ConfigurationManager.AppSettings[key];\n Console.WriteLine(\"Value read from app.confg for Key = {0} is {1}\", key, value);\n Console.WriteLine(\"--------------------------------------------------------------\");\n\n //// Update the value\n program.UpdateAppSettings(key, \"newValue\");\n //// Re-read from config file\n value = ConfigurationManager.AppSettings[key];\n Console.WriteLine(\"New Value read from app.confg for Key = {0} is {1}\", key, value);\n }\n else\n {\n Console.WriteLine(\"Specified key not found in app.config\");\n }\n }\n\n /// <summary>\n /// Updates the app settings.\n /// </summary>\n /// <param name=\"key\">The key.</param>\n /// <param name=\"value\">The value.</param>\n public void UpdateAppSettings(string key, string value)\n {\n Configuration configuration = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);\n\n if (configuration.AppSettings.Settings.AllKeys.Contains(key))\n {\n configuration.AppSettings.Settings[key].Value = value;\n }\n\n configuration.Save(ConfigurationSaveMode.Modified);\n ConfigurationManager.RefreshSection(\"appSettings\");\n }\n"
}
] |
2008/11/07
|
[
"https://Stackoverflow.com/questions/272097",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
272,109
|
<p>I have a csv file of the format:</p>
<pre><code>270291014011 ED HARDY - TRUE TO MY LOVE - Cap NEU 2008 NEU 0,00 € 0,00 € 0 1 0 22.10.2008 03:37:10 21.11.2008 02:37:10 21.11.2008 02:42:10 50 0 0 0 39,99 € http://i7.ebayimg.com/02/i/001/16/0d/68af_1.JPG?set_id=800005007 0 2 8.10.2008 13:40:20 8.10.2008 13:40:20 80587 0 <table bordercolordark="#999900" bordercolorlight="#666666" bgcolor="#ffffff" border="10" bordercolor="#666666" width="100%">
<tbody>
<tr>
<td><b><font color="#990000" face="arial" size="5"><br>
</font></b><blockquote>
<div align="center"><b><font color="#990000" face="arial" size="5"><font color="#ff0000">
</font></font></b><h1><font size="6"><b><font color="#990000" face="arial"><font color="#ff0000">100% ORGINAL MARKENWARE AUS DEN USA</font></font></b></font></h1>
<p style="color: rgb(0, 0, 0);"><font size="6"><b><font face="arial">ED HARDY</font></b></font></p><p style="color: rgb(0, 0, 0);"><b><font face="arial" size="5">CAP<br></font></b></p></div><div style="text-align: center;"><font size="5"><br><b><font color="#990000" face="arial"><font color="#ff0000"><b><font color="black" face="arial">Style: TRUE ROSE<br></font></b></font></font></b><b><font color="#990000" face="arial"><font color="#ff0000"><b><font color="black" face="arial"><br></font></b></font></font></b></font><font size="5"><b><font color="#990000" face="arial"><font color="#ff0000"><b><font color="black" face="arial">Die Kollektion von der trend Marke Ed Hardy kreiert sportlich, hipe Mode die bei den Stars in Hollywood der absolute Renner ist. In diesem super Trucker Cap fallen Sie auf !!&nbsp; </font></b></font></font></b></font><font size="5"><b><font color="#990000" face="arial"><font color="#ff0000"><b><font color="black" face="arial">Dieses Cap ist nagelneu mit Etikett und</font></b></font></font></b></font><font size="5"><b><font color="#990000" face="arial"><font color="#ff0000"><b><font color="black" face="arial"> 100% orginal.</font></b></font></font></b></font><font size="5"><br><b><font color="#990000" face="arial"><font color="#ff0000"><b><font color="black" face="arial"><br><br></font></b></font></font></b><br><b><font color="#990000" face="arial"><font color="#ff0000"><b><font color="black" face="arial">Wir tragen die ebay Kosten und der Kaeufer die Versandkosten.</font></b></font></font></b><br><b><font color="#990000" face="arial"><font color="#ff0000"><b><font color="black" face="arial">Versandkosten nach Europa sind folgend:</font></b></font></font></b><br><b><font color="#990000" face="arial"><font color="#ff0000"><b><font color="black" face="arial">fuer unversicherten Versand 6,00 Euro<br></font></b></font></font></b></font><font size="5"><b><font color="#990000" face="arial"><font color="#ff0000"><b><font color="black" face="arial">fuer versicherten Versand 12,00 Euro</font></b></font></font></b></font><br>
<font size="5"><span style="font-family: arial;"><span style="font-weight: bold;">Bei paypal Bezahlungen akzeptieren wir nur noch versicherten Versand!</span></span></font><br><font size="5"><b><font color="#990000" face="arial"><font color="#ff0000"><b><font color="black" face="arial">Auf Ihren Wunsch versenden wir die Ware auch versichert. Ansonsten trägt das Risiko beim Versand der Käufer. </font></b></font></font></b><br><b><font color="#990000" face="arial"><font color="#ff0000"><b><font color="black" face="arial">Wir bitten um Ihre Zahlung innerhalb 10 Tage nach Auktionsende.</font></b></font></font></b><br></font></div><b><font color="#990000" face="arial" size="5"><font color="#ff0000"><b><font color="black" face="arial" size="3"><br>
</font></b></font></font></b><div align="center"><b><font color="#990000" face="arial" size="5"><font color="#ff0000"><b><font color="black" face="arial" size="3"><font color="#ff0000">
</font></font></b></font></font></b><marquee width="70%" bgcolor="#ffffff">
<h2><b><font color="#990000" face="arial" size="5"><font color="#ff0000"><b><font color="black" face="arial" size="3"><font color="#ff0000">Schauen Sie unbedingt bei unserem Shop "cheap-and-hip" vorbei!!!</font></font></b></font></font></b></h2></marquee><b><font color="#990000" face="arial" size="5"><font color="#ff0000"><font color="black" face="arial" size="3"><br><b><font color="black" face="arial" size="5"><br>
</font></b></font></font></font></b><blockquote>
<div align="center">
<center>
<h1><b><font color="#990000" face="arial" size="5"><font color="#ff0000"><font color="black" face="arial" size="3"><b><font color="black" face="arial" size="5">Abwicklung Ihres Einkaufs bei uns</font></b></font></font></font></b></h1><b><font color="#990000" face="arial" size="5"><font color="#ff0000"><font color="black" face="arial" size="3"><b><font color="black" face="arial" size="5"><br></font></b></font></font></font></b></center><b><font color="#990000" face="arial" size="5"><font color="#ff0000"><font color="black" face="arial" size="3"><br></font></font></font></b></div><b><font color="#990000" face="arial" size="5"><font color="#ff0000"><font color="black" face="arial" size="3"><font color="black" face="arial" size="3">Jeder Käufer erhält innerhalb von 24 Stunden nach Auktionsende eine e-mail mit allen für die Kaufabwicklung relevanten Informationen. Sollten Sie nach 24 Stunden noch keine e-mail erhalten haben, setzen Sie sich bitte mit uns per e-mail in Verbindung. <br><br>
</font></font></font></font></b><h2><b><font color="#990000" face="arial" size="5"><font color="#ff0000"><font color="black" face="arial" size="3"><font color="black" face="arial" size="3">Kauf von mehreren Artikeln</font></font></font></font></b></h2><b><font color="#990000" face="arial" size="5"><font color="#ff0000"><font color="black" face="arial" size="3"><font color="black" face="arial" size="3">Da das Porto aus den USA nach Gewicht berechnet wird, werden die Versandkosten beim Einkauf von mehreren Artikeln neu berechnet. Bitte teilen Sie uns per e-mail mit, wenn Sie mehrere Artikel ersteigert/gekauft haben, bzw. noch ersteigern/kaufen moechten, Sie erhalten von uns dann die kompletten Versandkosten. Die Kosten fuer den Versand werden von dem Kaeufer getragen. Die Versanddauer betraegt bei Luftversand zirka 5-10 Tage.<br><br>
</font></font></font></font></b><h2><b><font color="#990000" face="arial" size="5"><font color="#ff0000"><font color="black" face="arial" size="3"><font color="black" face="arial" size="3">Versand</font></font></font></font></b></h2><b><font color="#990000" face="arial" size="5"><font color="#ff0000"><font color="black" face="arial" size="3"><font color="black" face="arial" size="3">Der Versand erfolgt innerhalb von 2-3 Werktagen nach Zahlungseingang (Gutschrift der Überweisung auf unserem Konto bei der Postbank oder bei paypal). Bitte beachten Sie, dass es je nach Kreditinstitut 2-4 Werktage dauern kann, bis Ihre Überweisung auf unserem Konto gutgeschrieben wird. Kreditkarten Gutbuchung ueber paypal erfolgt noch am gleichen Tag.<br>Als Betreff einer Ueberweisung muß unbedingt die eBay-Artikelnummer der Auktion angegeben werden. Ohne diese Information ist eine Zuordnung der Überweisung leider fast nicht möglich! <br>ZOLL: Bitte beachten Sie das Zollgebuehren anfallen koennen auch wenn es nur selten vorkommt sollten Sie sich mit den Einfuhrbestimmungen Ihres Landes vertraut machen. <br></font></font></font></font></b><br><b><font color="#990000" face="arial" size="5"><font color="#ff0000"><font color="black" face="arial" size="3"><font color="black" face="arial" size="3"><br>
</font></font></font></font></b><h2><b><font color="#990000" face="arial" size="5"><font color="#ff0000"><font color="black" face="arial" size="3"><font color="black" face="arial" size="3">Umtausch</font></font></font></font></b></h2><b><font color="#990000" face="arial" size="5"><font color="#ff0000"><font color="black" face="arial" size="3"><font color="black" face="arial" size="3">Wir tauschen gerne Ihren Artikel um sofern Sie die Ware innerhalb von 14 Tagen nach erhalt den Artikel uns wieder zuschicken. Wir nehmen nur ungetragene Ware zurueck und alle Etiketten muessen noch an dem Artikel befestigt sein<br><br>
</font></font></font></font></b><h2><b><font color="#990000" face="arial" size="5"><font color="#ff0000"><font color="black" face="arial" size="3"><font color="black" face="arial" size="3">Falls Sie Reklamationen haben</font></font></font></font></b></h2><b><font color="#990000" face="arial" size="5"><font color="#ff0000"><font color="black" face="arial" size="3"><font color="black" face="arial" size="3">Wir bitten bei Beanstandungen der Ware sich erst mit uns in Verbindung zu setzten. Wir pruefen unsere Ware immer auf Defekte aber es kann vorkommen das uns etwas entgeht und bevor Sie eine "negative Bewertung" abgeben moechten wir die Chance bekommen Sie zufrieden zustellen.
</font></font></font></font></b><p><b><font color="#990000" face="arial" size="5"><font color="#ff0000"><font color="black" face="arial" size="3"><font color="black" face="arial" size="3"><b><font color="#ff0000" face="arial" size="5">
</font></b></font></font></font></font></b></p><center><b><font color="#990000" face="arial" size="5"><font color="#ff0000"><font color="black" face="arial" size="3"><font color="black" face="arial" size="3"><b><font color="#ff0000" face="arial" size="5">Vielen Dank fuer Ihr Intresse!</font></b></font></font></font></font></b></center><p><b><font color="#990000" face="arial" size="5"><font color="#ff0000"><font color="black" face="arial" size="3"><font color="black" face="arial" size="3"><b><font color="#ff0000" face="arial" size="5"><br></font></b></font></font></font></font></b></p></blockquote></div></blockquote></td></tr></tbody></table><br><br> 1 Baltimore 1 0 1 0 0 0,10 € 0,00 € 0,00 € 0 0 1 77
</code></pre>
<p>I would like to know if there is an easy way with sed or awk to remove the HTML tags except for <code><p></code> tags. I would also like to know if it is possible for any link html embedding a Flash SWF file, to change the HTML automatically to link to this file.</p>
<p>So, in essence, to replace any code such as</p>
<pre><code><embed src="http://backend.supremeauction.com/app/gallery/loader.swf">
</code></pre>
<p>with something like <code><a href="http://backend.supremeauction.com/app/gallery/loader.swf">Click here for external description</a></code> and then remove all other HTML tags except for <code><p></code></p>
<p>Is this even possible?</p>
|
[
{
"answer_id": 272353,
"author": "Axeman",
"author_id": 11289,
"author_profile": "https://Stackoverflow.com/users/11289",
"pm_score": 2,
"selected": true,
"text": "perl -pe 's/<\\/?(?>[^p]|p\\w+)[^>]*>//ig'\n perl -pe 's/<embed\\s+src=\"(.*?\\.swf)\"\\/?>/<a href=\"$1\">Click here for external description<\\/a>/i;s/<\\/?(?>[^ap]|[ap]\\w+)[^>]*>//ig'\n"
},
{
"answer_id": 272376,
"author": "Steve Baker",
"author_id": 13566,
"author_profile": "https://Stackoverflow.com/users/13566",
"pm_score": 1,
"selected": false,
"text": "sed -e 's/[<][/][^Pp][^>]*[>]//g' -e 's/[<][^/Pp][^>]*[>]//g' file\n"
},
{
"answer_id": 272478,
"author": "Charles Duffy",
"author_id": 14122,
"author_profile": "https://Stackoverflow.com/users/14122",
"pm_score": 0,
"selected": false,
"text": "& select A format"
}
] |
2008/11/07
|
[
"https://Stackoverflow.com/questions/272109",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1246613/"
] |
272,118
|
<p>I know, it depends on the webapp. But in the normal case, what do you do: one servlet, that serves different pages (like an standalone-application with changing content) or for every page a single servlet.</p>
<p>Take for instance a blog. There is the start-page with the most recent blog-entries, an article-view for displaying one blog-entry and an archive. Do you implement this with three different servlets, or one that is dispatching to the functions. At least a good part of the stuff is shared, like http-headers.</p>
<p>So, what are your experiences, what works best?</p>
|
[
{
"answer_id": 272506,
"author": "Miguel Ping",
"author_id": 22992,
"author_profile": "https://Stackoverflow.com/users/22992",
"pm_score": 3,
"selected": false,
"text": "@Controller\npublic class MyController {\n @RequestMapping(\"/viewPosts\")\n public void doViewPosts(HttpRequest r, HttpResponse res) {\n //...\n }\n}\n"
},
{
"answer_id": 272651,
"author": "alex",
"author_id": 26787,
"author_profile": "https://Stackoverflow.com/users/26787",
"pm_score": 2,
"selected": false,
"text": "for(Handler handler : handlers) {\n if(handler.handle(request, response)) {\n return;\n }\n}\n"
}
] |
2008/11/07
|
[
"https://Stackoverflow.com/questions/272118",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21005/"
] |
272,124
|
<p>since JTree & TreeModel don't provide tooltips straight out-of-the-box, what do you think, what would be the best way to have item-specific tooltips for JTree?</p>
<p>Edit: (Answering my own question afterwards.) </p>
<p>@Zarkonnen: Thanks for the getTooltipText idea. </p>
<p>I found out another (maybe still a bit nicer) way with overriding DefaultTreeCellRenderer and thought to share it:</p>
<pre><code>public class JTreeWithToolTips {
private static class OwnRenderer extends DefaultTreeCellRenderer {
@Override
public Component getTreeCellRendererComponent(JTree tree, Object value,
boolean sel, boolean expanded, boolean leaf, int row,
boolean hasFocus) {
setToolTipText("foobar" + row);
return super.getTreeCellRendererComponent(tree, value, sel,
expanded, leaf, row, hasFocus);
}
}
public static void main(String[] args) {
JTree tree = new JTree(new Object[] { "foo", "bar", "foobar" });
tree.setCellRenderer(new OwnRenderer());
ToolTipManager.sharedInstance().registerComponent(tree);
JFrame frame = new JFrame();
frame.getContentPane().add(tree);
frame.pack();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
</code></pre>
|
[
{
"answer_id": 1774609,
"author": "Agustin",
"author_id": 215965,
"author_profile": "https://Stackoverflow.com/users/215965",
"pm_score": 1,
"selected": false,
"text": "onMouseMoved"
},
{
"answer_id": 46084789,
"author": "Matthieu",
"author_id": 1098603,
"author_profile": "https://Stackoverflow.com/users/1098603",
"pm_score": 1,
"selected": false,
"text": "TreeNode TreeNode value Tooltipable TreeCellRenderer public static interface Tooltipable {\n public String getToolTip();\n}\n\npublic static class TheNode extends DefaultMutableTreeNode implements Tooltipable {\n\n private String shortDesc, longDesc;\n\n public TheNode(String shortDesc, String longDesc) {\n super();\n this.shortDesc = shortDesc;\n this.longDesc = longDesc;\n }\n\n @Override\n public String getToolTip() {\n return longDesc;\n }\n\n @Override\n public String toString() {\n return shortDesc;\n }\n}\n\npublic static class TheModel extends DefaultTreeModel {\n public TheModel() {\n super(new TheNode(\"Root\", \"The base of everything\"));\n TheNode root = (TheNode)getRoot();\n root.add(new TheNode(\"Second\", \"I am a number two\"));\n TheNode node = new TheNode(\"Third\", \"Another one bites the dust\");\n root.add(node);\n node.add(new TheNode(\"Last\", null)); // No tooltip for this one\n }\n}\n\npublic static class TreeTooltipRenderer extends DefaultTreeCellRenderer {\n @Override\n public Component getTreeCellRendererComponent(JTree tree, Object value, boolean sel, boolean expanded, boolean leaf, int row, boolean hasFocus) {\n if (value instanceof Tooltipable)\n setToolTipText(((Tooltipable)value).getToolTip());\n return super.getTreeCellRendererComponent(tree, value, sel, expanded, leaf, row, hasFocus);\n }\n}\n\npublic static void main(String[] args) {\n JFrame frame = new JFrame();\n frame.setBounds(100, 100, 300, 300);\n frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);\n JTree tree = new JTree(new TheModel());\n ToolTipManager.sharedInstance().registerComponent(tree);\n tree.setCellRenderer(new TreeTooltipRenderer());\n frame.add(new JScrollPane(tree), BorderLayout.CENTER);\n frame.setVisible(true);\n}\n"
}
] |
2008/11/07
|
[
"https://Stackoverflow.com/questions/272124",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/28482/"
] |
272,131
|
<h2>Setup</h2>
<p>I have a website that draws RSS feeds and displays them on the page. Currently, I use percentages on the divs that contain each feed, so that multiples can appear next to each other.</p>
<p>However, I only have two next to each other, and if the window resizes, there can be some ugly empty space on the screen.</p>
<h2>Desire</h2>
<p>What I'd like to be able to do, but have not figured out a way yet, is to put all the feeds linearly into the page, and have:</p>
<ul>
<li>a 'pre-built' multicolumn view where the feeds would "balance" themselves into the columns</li>
</ul>
<p>which leads me to:</p>
<ul>
<li>the number of columns change depending on how wide the screen is currently\</li>
</ul>
<p>This is akin to how word processing applications handle columnar layouts.</p>
<h2>Question</h2>
<p>I presume that I will need to implement some form of AJAXy happiness, but currently know very little about Javascript.</p>
<p>Is there a way to do this with <strong><em>just</em></strong> CSS/HTML/PHP?</p>
<p>If not, how should I go about solving this?</p>
<p><br/></p>
<h3>final solution:</h3>
<p>(based on <a href="https://stackoverflow.com/a/272183/4418">@warpr</a>'s and <a href="https://stackoverflow.com/a/272229/4418">@joh6nn</a>'s answers)</p>
<pre><code>#rss
{min-width: 10em;
max-width: 25em;
min-height: 15em;
max-height: 25em;
font-size: .97em;
float: left;
}
</code></pre>
|
[
{
"answer_id": 272351,
"author": "Raithlin",
"author_id": 6528,
"author_profile": "https://Stackoverflow.com/users/6528",
"pm_score": 0,
"selected": false,
"text": "var columns = $(\".feed\").size();\nvar size = 100/columns;\n$(\".feed\").css(\"width\",size+\"%\");\n"
},
{
"answer_id": 274595,
"author": "Pim Jager",
"author_id": 35197,
"author_profile": "https://Stackoverflow.com/users/35197",
"pm_score": 0,
"selected": false,
"text": "var docwidth = $(document).width();\nvar numOfCollums = $('.feed').length;\nvar colWidth = docwidth/numOfCollums;\n$('.feed').each( function() {\n $(this).width(colWidth);\n});\n .feed{\n float:left;\n}\n"
}
] |
2008/11/07
|
[
"https://Stackoverflow.com/questions/272131",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4418/"
] |
272,152
|
<p>What do I have to do to convert a DIB to a BMP?</p>
|
[
{
"answer_id": 18292271,
"author": "Jeff Barnes",
"author_id": 1919288,
"author_profile": "https://Stackoverflow.com/users/1919288",
"pm_score": 2,
"selected": false,
"text": "BITMAPFILEHEADER *bmp = ...;\nchar * bmpBytes = reinterpret_cast<char *>(bmp);\nvoid * myDib = (void *)bmpBytes + BMP_HEADER_LENGTH; /* (14 bytes) */\n/* cast and do something with myDib */\n...\n"
}
] |
2008/11/07
|
[
"https://Stackoverflow.com/questions/272152",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1100/"
] |
272,153
|
<p>If I define a struct in C# using automatic properties like this:</p>
<pre><code>public struct Address
{
public Address(string line1, string line2, string city, string state, string zip)
{
Line1 = line1;
Line2 = line2;
City = city;
State = state;
Zip = zip;
}
public string Line1 { get; protected set; }
public string Line2 { get; protected set; }
public string City { get; protected set; }
public string State { get; protected set; }
public string Zip { get; protected set; }
}
</code></pre>
<p>When I attempt to build the file, I get a compilation error saying <code>The 'this' object cannot be used before all of its fields are assigned to</code>. This can be solved by changing the constructor to make a chained call to the default constructor like this:</p>
<pre><code>public Address(string line1, string line2, string city, string state, string zip): this()
{
Line1 = line1;
Line2 = line2;
City = city;
State = state;
Zip = zip;
}
</code></pre>
<p>My question is, why does this work, and what is happening? I have a guess, and I tried to prove it by looking at IL, but I'm only kidding myself if I think I can break down IL. But my guess is, auto properties work by having the compiler generate fields for your properties behind the scenes. Those fields cannot be accessed through code, all setting and getting must be done through the properties. When creating a struct, a default constructor cannot be explicitly defined. So behind the scenes, the compiler must be generating a default constructor that sets the values of the fields that the developer can't see.</p>
<p>Any and all IL wizards are welcome to prove or disprove my theory.</p>
|
[
{
"answer_id": 272164,
"author": "Jon Skeet",
"author_id": 22656,
"author_profile": "https://Stackoverflow.com/users/22656",
"pm_score": 7,
"selected": true,
"text": "this()"
},
{
"answer_id": 12676594,
"author": "supercat",
"author_id": 363751,
"author_profile": "https://Stackoverflow.com/users/363751",
"pm_score": 0,
"selected": false,
"text": "Get Set X Foo Foo.X += 5 Foo.SET_X_METHOD(Foo.GET_X_METHOD() + 5) Foo.X = 5; Foo.SET_X_METHOD(5) Foo HexDecet<HexDecet<HexDecet<Integer>>> HexDecet<T> F0 F15 T Foo = MyThing.F3.F6.F9; MyThing Foo MyThing MyThing.F3.F6.F9 += 26; F0 F15 Foo = MyThing.F3.F6.F9 MyThing.F3 temp1 temp1.F6 temp2 temp2.F9 MyThing.F3.F6.F9 var t1 = MyThing.F3; var t2 = t1.F6; t2.F9 += 26; t1.F6 = f2; MyThing.F3 = t1; ArraySegment<T> Var foo[] = new int[100]; Var MyArrSeg = New ArraySegment<int>(foo, 25, 25); MyArrSeg[6] += 9; foo"
}
] |
2008/11/07
|
[
"https://Stackoverflow.com/questions/272153",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6146/"
] |
272,157
|
<p>I have a triangle mesh that has no texture, but a set color (sort of blue) and alpha (0.7f). This mesh is run time generated and the normals are correct. I find that with lighting on, the color of my object changes as it moves around the level. Also, the lighting doesn't look right. When I draw this object, this is the code:</p>
<pre><code>glEnable( GL_COLOR_MATERIAL );
float matColor[] = { cur->GetRed(), cur->GetGreen(), cur->GetBlue(), cur->GetAlpha() };
float white[] = { 0.3f, 0.3f, 0.3f, 1.0f };
glMaterialfv(GL_FRONT_AND_BACK, GL_DIFFUSE, matColor);
glMaterialfv(GL_FRONT_AND_BACK, GL_SPECULAR, white);
</code></pre>
<p>Another odd thing I noticed is that the lighting fails, when I disable <code>GL_FRONT_AND_BACK</code> and use just <code>GL_FRONT</code> or <code>GL_BACK</code>.
Here is my lighting setup (done once at beginning of renderer):</p>
<pre><code>m_lightAmbient[] = { 0.2f, 0.2f, 0.2f, 1.0f };
m_lightSpecular[] = { 1.0f, 1.0f, 1.0f, 1.0f };
m_lightPosition[] = { 0.0f, 1200.0f, 0.0f, 1.0f };
glLightfv(GL_LIGHT0, GL_AMBIENT, m_lightAmbient);
glLightfv(GL_LIGHT0, GL_SPECULAR, m_lightSpecular);
glLightfv(GL_LIGHT0, GL_POSITION, m_lightPosition);
</code></pre>
<p>EDIT: I've done a lot to make the normals "more" correct (since I am generating the surface myself), but the objects color still changes depending where it is. Why is this? Does openGL have some special environment blending I don't know about?</p>
<p>EDIT: Turns out the color changing was because a previous texture was on the texture stack, and even though it wasn't being drawn, <code>glMaterialfv</code> was blending with it.</p>
|
[
{
"answer_id": 277381,
"author": "DavidG",
"author_id": 25893,
"author_profile": "https://Stackoverflow.com/users/25893",
"pm_score": 0,
"selected": false,
"text": "// Vertices!\nglEnableClientState(GL_VERTEX_ARRAY);\n\n// Depth func\nglEnable(GL_DEPTH_TEST);\nglDepthFunc( GL_LESS );\n\n// Enable alpha blending\nglEnable(GL_BLEND);\nglBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);\n\n// Lighting\nglEnable(GL_LIGHTING);\nglEnable(GL_LIGHT0);\nglLightfv(GL_LIGHT0, GL_AMBIENT, m_lightAmbient);\nglLightfv(GL_LIGHT0, GL_SPECULAR, m_lightSpecular);\nglLightfv(GL_LIGHT0, GL_POSITION, m_lightPosition);\n\n// Culling\nglDisable( GL_CULL_FACE );\n// Smooth Shading\nglShadeModel(GL_SMOOTH);\n\nm_glSetupDone = true;\n"
},
{
"answer_id": 277421,
"author": "korona",
"author_id": 25731,
"author_profile": "https://Stackoverflow.com/users/25731",
"pm_score": 1,
"selected": false,
"text": " /\\ /\\\n / \\ / \\\n / \\/ \\\n / /\\ \\\n/_____/__\\_____\\\n"
},
{
"answer_id": 413184,
"author": "Manuel",
"author_id": 50770,
"author_profile": "https://Stackoverflow.com/users/50770",
"pm_score": 0,
"selected": false,
"text": "glEnable(GL_NORMALIZE);\n"
}
] |
2008/11/07
|
[
"https://Stackoverflow.com/questions/272157",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/25893/"
] |
272,159
|
<p>I have the following one route, registered in my global.asax.</p>
<pre><code>routes.MapRoute(
"Home", // Unique name
"", // Root url
new { controller = "Home", action = "Index",
tag = string.Empty, page = 1 }
);
</code></pre>
<p>kewl. when I start the site, it correctly picks up this route.</p>
<p>Now, when I try to programmatically do the following, it returns NULL.</p>
<pre><code>var pageLinkValueDictionary =
new RouteValueDictionar(linkWithoutPageValuesDictionary)
{{"page", 2}};
VirtualPathData virtualPathData =
RouteTable.Routes.GetVirtualPath(viewContext, "Home"
pageLinkValueDictionary);
// NOTE: pageLinkValueDictionary ==
// Key: Action, Value: Index; Key: page, Value: 2
</code></pre>
<p>Why would this be happening?</p>
<p>I was under the impression that it would find the Home route but append any values not found as query string items?</p>
<h2>Update</h2>
<p>Still no luck with this. Also, using the <a href="https://www.microsoft.com/downloads/details.aspx?FamilyID=f4e4ee26-4bc5-41ed-80c9-261336b2a5b6&displaylang=en" rel="nofollow noreferrer">MVC RC</a>, I now need to change the viewContext to veiwContext.RequestContext .. which compiles but I'm still getting a null result.</p>
<h2>Update 2</h2>
<p>When I have the route without the <code>page=1</code> default item, the route <em>IS FOUND</em>.
eg.</p>
<pre><code>routes.MapRoute(
"Home",
"",
new { controller = "Post", action = "Index", tags = string.Empty }
);
</code></pre>
<p>.. and <code>RouteTable.Routes.GetVirtualPath</code> returns a <code>VirtualPathData</code> instance. When I add the <code>page=1</code> (default value) back in, the <code>VirtualPathData</code> instance returned is null?</p>
|
[
{
"answer_id": 272527,
"author": "Torkel",
"author_id": 24425,
"author_profile": "https://Stackoverflow.com/users/24425",
"pm_score": 2,
"selected": true,
"text": "return RedirectToRoute(\"IndexDefault\", new {page = \"2\"}); \n"
},
{
"answer_id": 272917,
"author": "Ben Scheirman",
"author_id": 3381,
"author_profile": "https://Stackoverflow.com/users/3381",
"pm_score": 1,
"selected": false,
"text": "route.MapRoute(\"theRoute\", \"{controller}/{action}/{tag}/{page}\",\n new { controller=\"Post\", action=\"Index\", tag=\"\", page=1 });\n route.MapRoute(\"theRoute\", \"/{tag}/{page}\",\n new { controller=\"Post\", action=\"Index\", tag=\"\", page=1 });\n"
}
] |
2008/11/07
|
[
"https://Stackoverflow.com/questions/272159",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/30674/"
] |
272,161
|
<p>When I write code like this in VS 2008:<br><br></p>
<pre><code>.h
struct Patterns {
string ptCreate;
string ptDelete;
string ptDrop;
string ptUpdate;
string ptInsert;
string ptSelect;
};
class QueryValidate {
string query;
string pattern;
static Patterns pts;
public:
friend class Query;
QueryValidate(const string& qr, const string& ptn):
query(qr), pattern(ptn) {}
bool validate() {
boost::regex rg(pattern);
return boost::regex_match(query, rg);
}
virtual ~QueryValidate() {}
};
</code></pre>
<p>I then initialize my structure like this: </p>
<pre><code>.cpp
string QueryValidate::pts::ptCreate = "something";
string QueryValidate::pts::ptDelete = "something";
//...
</code></pre>
<p>The compiler gives the following errors: </p>
<blockquote>
<p>'Patterns': the symbol to the left of a '::' must be a type 'ptSelect'
: is not a member of 'QueryValidate'</p>
</blockquote>
<p>What am I doing wrong? Is this a problem with Visual Studio or with my code? I know that static members except for const ones must be defined outside the class they were declared in.</p>
|
[
{
"answer_id": 272240,
"author": "Pieter",
"author_id": 5822,
"author_profile": "https://Stackoverflow.com/users/5822",
"pm_score": 4,
"selected": true,
"text": "Patterns QueryValidate::pts = {\"CREATE\", \"DELETE\"}; // etc. for every string\n struct Patterns {\n Patterns() { /*...*/ }\n /* ... */\n}\n"
},
{
"answer_id": 272295,
"author": "peterchen",
"author_id": 31317,
"author_profile": "https://Stackoverflow.com/users/31317",
"pm_score": 2,
"selected": false,
"text": "Patterns QueryValidate::pts = { \"something\", \"something\", ... };\n"
},
{
"answer_id": 272336,
"author": "T.E.D.",
"author_id": 29639,
"author_profile": "https://Stackoverflow.com/users/29639",
"pm_score": 0,
"selected": false,
"text": "Patterns QueryValidate::pts;\n\nvoid foo () {\n QueryValidate::pts.ptCreate = \"something\";\n QueryValidate::pts.ptDelete = \"something\";\n}\n"
}
] |
2008/11/07
|
[
"https://Stackoverflow.com/questions/272161",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/28298/"
] |
272,188
|
<p>I have already visited <a href="https://stackoverflow.com/questions/191673/preferred-python-unit-testing-framework">Preferred Python unit-testing framework</a>. I am not just looking at Python Unit Testing Framework, but also code coverage with respect to unit tests. So far I have only come across <a href="http://nedbatchelder.com/code/modules/coverage.html" rel="nofollow noreferrer">coverage.py</a>. Is there any better option?</p>
<p>An interesting option for me is to integrate <a href="http://www.python.org/" rel="nofollow noreferrer">cpython</a>, unit testing of Python code and code coverage of Python code with Visual Studio 2008 through plugins (something similar to <a href="http://www.codeplex.com/IronPythonStudio" rel="nofollow noreferrer">IronPython Studio</a>). What can be done to achieve this? I look forward to suggestions.</p>
|
[
{
"answer_id": 288711,
"author": "orip",
"author_id": 37020,
"author_profile": "https://Stackoverflow.com/users/37020",
"pm_score": 0,
"selected": false,
"text": "--coverage"
}
] |
2008/11/07
|
[
"https://Stackoverflow.com/questions/272188",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/30289/"
] |
272,190
|
<p>I basically created some tables to play around with: I have Two main tables, and a Many-Many join table. Here is the DDL: (I am using HSQLDB)</p>
<pre><code>CREATE TABLE PERSON
(
PERSON_ID INTEGER GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY,
NAME VARCHAR(50), MAIN_PERSON_ID INTEGER
)
CREATE TABLE JOB
(
JOB_ID INTEGER GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY,
NAME VARCHAR(50)
)
CREATE TABLE JOB_PERSON
(
PERSON_ID INTEGER,
JOB_ID INTEGER
)
ALTER TABLE JOB_PERSON ADD
CONSTRAINT FK_PERSON_JOB FOREIGN KEY(PERSON_ID)
REFERENCES PERSON ON DELETE CASCADE ON UPDATE CASCADE
ALTER TABLE JOB_PERSON ADD
CONSTRAINT FK_JOB_PERSON FOREIGN KEY(JOB_ID)
REFERENCES JOB ON DELETE CASCADE ON UPDATE CASCADE
ALTER TABLE PERSON ADD
CONSTRAINT FK_PERSON_PERSON FOREIGN KEY(MAIN_PERSON_ID)
REFERENCES PERSON ON DELETE CASCADE ON UPDATE CASCADE
insert into person values(null,'Arthur', null);
insert into person values(null,'James',0);
insert into job values(null, 'Programmer')
insert into job values(null, 'Manager')
insert into job_person values(0,0);
insert into job_person values(0,1);
insert into job_person values(1,1);
</code></pre>
<p>I want to create a delete statement that deletes orphans from JOB (if there exists only one entry in the join table for a specific job) based on the PERSON.PERSON_ID. </p>
<p>In pseudo language: </p>
<pre><code>delete from job where job_person.job_id=job.job_id
AND count(job_person.job_id)=1 AND job_person.person_id=X
</code></pre>
<p>Where X is some person_id. I have tried a lot of different ways; I think it is the "COUNT" part that is causing problems. I am an SQL rookie, so any help would be much appreciated.</p>
|
[
{
"answer_id": 272243,
"author": "Cade Roux",
"author_id": 18255,
"author_profile": "https://Stackoverflow.com/users/18255",
"pm_score": 3,
"selected": true,
"text": "JOB JOB_PERSON JOB PERSON JOB_PERSON JOB PERSON JOB JOB_PERSON DELETE FROM JOB\nWHERE JOB_ID NOT IN (\n SELECT JOB_ID\n FROM JOB_PERSON\n)\n JOB_PERSON DELETE FROM JOB_PERSON\nWHERE PERSON_ID = X\n\nDELETE FROM JOB\nWHERE JOB_ID NOT IN (\n SELECT JOB_ID\n FROM JOB_PERSON\n)\n JOB INSERT INTO TEMP_TABLE\nSELECT JOB.JOB_ID\nFROM JOB\nINNER JOIN JOB_PERSON\n ON JOB_PERSON.JOB_ID = JOB.JOB_ID\nWHERE JOB_PERSON.PERSON_ID = X\n\nDELETE FROM PERSON\nWHERE PERSON_ID = X\n\n-- YOUR CASCADING DELETE DOES THIS:\n/*\nDELETE FROM JOB_PERSON\nWHERE PERSON_ID = X\n*/\n\n-- Now clean up (only) new orphans on the other side\nDELETE FROM JOB\nWHERE JOB_ID NOT IN (\n SELECT JOB_ID\n FROM JOB_PERSON\n)\nAND JOB_ID IN (\n SELECT JOB_ID\n FROM TEMP_TABLE\n)\n"
},
{
"answer_id": 272251,
"author": "Fred",
"author_id": 33630,
"author_profile": "https://Stackoverflow.com/users/33630",
"pm_score": 1,
"selected": false,
"text": "DELETE FROM JOB\nWHERE JOB_ID NOT IN (\n SELECT JOB_ID\n FROM JOB_PERSON\n)\n"
}
] |
2008/11/07
|
[
"https://Stackoverflow.com/questions/272190",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/33863/"
] |
272,194
|
<p>My webapp is part of a larger EAR that is deployed into a websphere server. The server hosts number of other apps on the same virtual server. My webapp has some initialisation/health checks in a servletContextListener->contextInitialized method. I want to make the webapp unavailable if initialisation/health checks fail. What is a realiable way of doing this? Will throwing a RuntimeException from within contextInitialized suffice? Is the rest of the EAR still expected to be available? Thank you.</p>
|
[
{
"answer_id": 272747,
"author": "erickson",
"author_id": 3474,
"author_profile": "https://Stackoverflow.com/users/3474",
"pm_score": 4,
"selected": true,
"text": "RuntimeException ServletContextListener.contextInitialized"
}
] |
2008/11/07
|
[
"https://Stackoverflow.com/questions/272194",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/33434/"
] |
272,199
|
<p>I have a solution which contains many class libraries and an ASP .NET website which references those assemblies.</p>
<p>When I build the solution from within the IDE, all assemblies referenced by the website end up in the bin directory. Great!</p>
<p>When I use MsBuild from the command line, all the referenced assemblies are not copied to the bin directory. Why?</p>
<p>My command line is simply:</p>
<pre><code>msbuild.exe d:\myproject\mysolution.sln
</code></pre>
|
[
{
"answer_id": 287900,
"author": "kenny",
"author_id": 3225,
"author_profile": "https://Stackoverflow.com/users/3225",
"pm_score": 0,
"selected": false,
"text": "%windir%\\Microsoft.Net\\framework\\v2.0.50727\\aspnet_compiler -v \\%~n1 -f -p .\\%1 .\\Website\n"
},
{
"answer_id": 2315626,
"author": "benPearce",
"author_id": 4490,
"author_profile": "https://Stackoverflow.com/users/4490",
"pm_score": 0,
"selected": false,
"text": "md \"$(SolutionDir)Assemblies\"\ndel \"$(SolutionDir)Assemblies\\$(TargetFileName)\"\ncopy \"$(TargetPath)\" \"$(SolutionDir)Assemblies\" /y\n"
},
{
"answer_id": 11551469,
"author": "vangorra",
"author_id": 1267536,
"author_profile": "https://Stackoverflow.com/users/1267536",
"pm_score": 1,
"selected": false,
"text": "msbuild.exe myproject.vbproj /T:Rebuild\nmsbuild.exe myproject.vbproj /T:Package\n msbuild.exe myproject.vbproj /T:Rebuild;Package\n"
},
{
"answer_id": 21729974,
"author": "Henry Aloni",
"author_id": 938982,
"author_profile": "https://Stackoverflow.com/users/938982",
"pm_score": 0,
"selected": false,
"text": " c:\\Windows\\Microsoft.NET\\Framework\\v4.0.30319\\MSBuild.exe <yourSolutionFile>.sln\n"
}
] |
2008/11/07
|
[
"https://Stackoverflow.com/questions/272199",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5449/"
] |
272,203
|
<p>I'm thinking of using PDO in all of my future webapp. Currently (using what I've learned from SO so far), what I have in my site to handle database connection is a Singleton class like this :</p>
<pre><code>class DB {
private static $instance = NULL;
private static $dsn = "mysql:host=localhost;dbname=mydatabase;";
private static $db_user = 'root';
private static $db_pass = '0O0ooIl1';
private function __construct()
{
}
private function __clone()
{
}
public static function getInstance() {
if (!self::$instance)
{
self::$instance = new PDO(self::$dsn, self::$db_user, self::$db_pass);
self::$instance-> setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
return self::$instance;
}
}
</code></pre>
<p>and another file (functions.php) with content-specific functions looking exactly like this one :</p>
<pre><code>function get_recent_activities ()
{
try
{
$db = DB::getInstance();
// --prepare and execute query here, fetch the result--
return $my_list_of_recent_activities;
}
catch (PDOException $e)
{
return "some fail-messages";
}
}
...
</code></pre>
<p>meaning that I have to repeat the <code>try .. catch</code> part in all of the functions.</p>
<p>My questions are :</p>
<ol>
<li>How should I make that more efficient ? (eg. not having to repeat <code>try..catch</code> in all functions, and yet still able to return different "fail-message" on each one)</li>
<li>Is this already a good practice ? I'm still new at PDO and OOP (still a lot more to learn), so (as of now), I can't really see any disadvantages or things that can be improved in there.</li>
</ol>
<p>I'm sorry if that seems unclear or too long. Thanks in advance.</p>
|
[
{
"answer_id": 272274,
"author": "Noah Goodrich",
"author_id": 20178,
"author_profile": "https://Stackoverflow.com/users/20178",
"pm_score": 2,
"selected": false,
"text": "class DB extends PDO \n{\n // Allows implementation of the singleton pattern -- ndg 5/24/2008\n private static $instance;\n\n // Public static variables for configuring the DB class for a particular database -- ndg 6/16/2008\n public static $error_table;\n public static $host_name;\n public static $db_name;\n public static $username;\n public static $password;\n public static $driver_options;\n public static $db_config_path;\n\n\n\n function __construct($dsn=\"\", $username=\"\", $password=\"\", $driver_options=array()) \n {\n if(isset(self::$db_config_path))\n {\n try \n {\n if(!require_once self::$db_config_path)\n {\n throw new error('Failed to require file: ' . self::$db_config_path); \n }\n } \n catch(error $e) \n {\n $e->emailAdmin();\n }\n }\n elseif(isset($_ENV['DB']))\n {\n self::$db_config_path = 'config.db.php';\n\n try \n {\n if(!require_once self::$db_config_path)\n {\n throw new error('Failed to require file: ' . self::$db_config_path); \n }\n } \n catch(error $e) \n {\n $e->emailAdmin();\n }\n }\n\n parent::__construct(\"mysql:host=\" . self::$host_name . \";dbname=\" .self::$db_name, self::$username, self::$password, self::$driver_options);\n $this->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);\n $this->setAttribute(PDO::ATTR_STATEMENT_CLASS, array('QueryStatement', array($this)));\n\n if(!isset(self::$error_table))\n {\n self::$error_table = 'errorlog_rtab';\n }\n }\n\n /**\n * Return a DB Connection Object\n *\n * @return DB\n */\n public static function connect()\n {\n\n // New PDO Connection to be used in NEW development and MAINTENANCE development\n try \n {\n if(!isset(self::$instance))\n { \n if(!self::$instance = new DB())\n {\n throw new error('PDO DB Connection failed with error: ' . self::errorInfo());\n }\n }\n\n return self::$instance;\n }\n catch(error $e)\n {\n $e->printErrMsg();\n }\n }\n\n /**\n * Returns a QueryBuilder object which can be used to build dynamic queries\n *\n * @return QueryBuilder\n * \n */\n public function createQuery()\n {\n return new QueryBuilder();\n }\n\n public function executeStatement($statement, $params = null, $FETCH_MODE = null)\n {\n if($FETCH_MODE == 'scalar')\n {\n return $this->executeScalar($statement, $params); \n }\n\n\n try {\n try {\n if(!empty($params))\n {\n $stmt = $this->prepare($statement);\n $stmt->execute($params);\n }\n else \n {\n $stmt = $this->query($statement);\n }\n }\n catch(PDOException $pdo_error)\n {\n throw new error(\"Failed to execute query:\\n\" . $statement . \"\\nUsing Parameters:\\n\" . print_r($params, true) . \"\\nWith Error:\\n\" . $pdo_error->getMessage());\n }\n }\n catch(error $e)\n {\n $this->logDBError($e);\n $e->emailAdmin();\n return false;\n }\n\n try \n {\n if($FETCH_MODE == 'all')\n {\n $tmp = $stmt->fetchAll();\n }\n elseif($FETCH_MODE == 'column')\n {\n $arr = $stmt->fetchAll();\n\n foreach($arr as $key => $val)\n {\n foreach($val as $var => $value)\n {\n $tmp[] = $value;\n }\n } \n }\n elseif($FETCH_MODE == 'row') \n {\n $tmp = $stmt->fetch();\n }\n elseif(empty($FETCH_MODE))\n {\n return true;\n }\n }\n catch(PDOException $pdoError)\n {\n return true;\n }\n\n $stmt->closeCursor();\n\n return $tmp;\n\n }\n\n public function executeScalar($statement, $params = null)\n {\n $stmt = $this->prepare($statement);\n\n if(!empty($this->bound_params) && empty($params))\n {\n $params = $this->bound_params;\n }\n\n try {\n try {\n if(!empty($params))\n {\n $stmt->execute($params);\n }\n else \n {\n $stmt = $this->query($statement);\n }\n }\n catch(PDOException $pdo_error)\n {\n throw new error(\"Failed to execute query:\\n\" . $statement . \"\\nUsing Parameters:\\n\" . print_r($params, true) . \"\\nWith Error:\\n\" . $pdo_error->getMessage());\n }\n }\n catch(error $e)\n {\n $this->logDBError($e);\n $e->emailAdmin();\n }\n\n $count = $stmt->fetchColumn();\n\n $stmt->closeCursor();\n\n //echo $count;\n return $count; \n }\n\n protected function logDBError($e)\n {\n $error = $e->getErrorReport();\n\n $sql = \"\n INSERT INTO \" . self::$error_table . \" (message, time_date) \n VALUES (:error, NOW())\";\n\n $this->executeStatement($sql, array(':error' => $error));\n }\n}\n\nclass QueryStatement extends PDOStatement \n{\n public $conn;\n\n protected function __construct() \n {\n $this->conn = DB::connect();\n $this->setFetchMode(PDO::FETCH_ASSOC);\n }\n\n public function execute($bound_params = null)\n {\n return parent::execute($bound_params); \n }\n}\n"
},
{
"answer_id": 273090,
"author": "pd.",
"author_id": 19066,
"author_profile": "https://Stackoverflow.com/users/19066",
"pm_score": 7,
"selected": true,
"text": "try {\n $rs = $db->prepare('SELECT * FROM foo');\n $rs->execute();\n $foo = $rs->fetchAll();\n} catch (Exception $e) {\n die(\"Oh noes! There's an error in the query!\");\n}\n $rs = $db->prepare('SELECT * FROM foo');\n$rs->execute();\n$foo = $rs->fetchAll();\n // We're handling a file upload here.\ntry {\n $rs = $db->prepare('INSERT INTO files (fileID, filename) VALUES (?, ?)');\n $rs->execute(array(1234, '/var/tmp/file1234.txt'));\n} catch (Exception $e) {\n unlink('/var/tmp/file1234.txt');\n throw $e;\n}\n"
}
] |
2008/11/07
|
[
"https://Stackoverflow.com/questions/272203",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/26721/"
] |
272,207
|
<p>I have a weird issue. I had a web service that was compiled under the 2.0 framework that was being consumed by a windows app that was compiled with the 1.1 framework. This worked just fine. Now, after upgrading the web service to the 3.5 framework, the windows app is no longer able to call it.</p>
<p>Creating a little windows app in 3.5 as a test is able to call the web service without problems so I know it still works.</p>
<p>Nothing has changed in the code at all, it's just compiled as a 3.5 project instead of a 2.0 project.</p>
<p>For those who care what error I get back, it's this:</p>
<blockquote>
<p>An unhandled exception of type
'System.Net.WebException' occurred in
system.web.services.dll</p>
<p>Additional information: The underlying connection was closed: An
unexpected error occurred on a
receive.</p>
</blockquote>
<p>Is there anything I can do to the web service to make it backwards compatible (if that's even the issue)?</p>
<p>[Edit] Responses to answers below (so far): Re-Discovering did not work, nor did removing and re-adding the webservice. I don't believe it's a SOAP issue becuase the WSDLs are identical (both show SOAP 1.2). Browsing to the webservice from the server works just fine.</p>
|
[
{
"answer_id": 274277,
"author": "denis phillips",
"author_id": 748,
"author_profile": "https://Stackoverflow.com/users/748",
"pm_score": 1,
"selected": false,
"text": " // Put this override in the generated Reference.cs of the client proxy\n protected override System.Net.WebRequest GetWebRequest(Uri uri)\n {\n HttpWebRequest webRequest = (HttpWebRequest)base.GetWebRequest(uri);\n\n webRequest.KeepAlive = false;\n webRequest.ProtocolVersion = HttpVersion.Version10;\n return webRequest;\n }\n"
}
] |
2008/11/07
|
[
"https://Stackoverflow.com/questions/272207",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2849/"
] |
272,210
|
<p>What is the accepted practice for indenting SQL statements? For example, consider the following SQL statement:</p>
<pre><code>SELECT column1, column2
FROM table1
WHERE column3 IN
(
SELECT TOP(1) column4
FROM table2
INNER JOIN table3
ON table2.column1 = table3.column1
)
</code></pre>
<p>How should this be indented? Many thanks.</p>
|
[
{
"answer_id": 272227,
"author": "LeppyR64",
"author_id": 16592,
"author_profile": "https://Stackoverflow.com/users/16592",
"pm_score": 4,
"selected": false,
"text": "SELECT\n column1,\n column2\nFROM\n table1\nWHERE\n column3 IN ( \n SELECT TOP(1)\n column4\n FROM\n table2\n INNER JOIN table3 ON table2.column1 = table3.column1\n )\n\n\nSELECT\n column1,\n column2\nFROM\n table1\nWHERE\n column3 IN ( \n SELECT TOP(1)\n column4\n FROM\n table2\n INNER JOIN table3\n ON table2.column1 = table3.column1 -- for long ones\n )\n"
},
{
"answer_id": 272228,
"author": "Bill the Lizard",
"author_id": 1288,
"author_profile": "https://Stackoverflow.com/users/1288",
"pm_score": 5,
"selected": false,
"text": "SELECT column1, column2\nFROM table\nWHERE column3 IN (\n SELECT TOP(1) column4\n FROM table2\n INNER JOIN table3 ON table2.column1 = table3.column1\n)\n"
},
{
"answer_id": 272231,
"author": "Codewerks",
"author_id": 17729,
"author_profile": "https://Stackoverflow.com/users/17729",
"pm_score": 5,
"selected": false,
"text": "SELECT \n column1, \n column2 \nFROM \n table1 \nWHERE \n column3 IN \n ( \n SELECT TOP(1) \n column4 \n FROM \n table2 \n INNER JOIN \n table3 \n ON table2.column1 = table3.column1 \n )\n"
},
{
"answer_id": 272232,
"author": "Patrick Desjardins",
"author_id": 13913,
"author_profile": "https://Stackoverflow.com/users/13913",
"pm_score": 7,
"selected": true,
"text": "SELECT column1\n , column2\nFROM table1\nWHERE column3 IN\n(\n SELECT TOP(1) column4\n FROM table2\n INNER JOIN table3\n ON table2.column1 = table3.column1\n)\n SELECT sdcolumn123\n , dscolumn234\n , sdcolumn343\n , ffcolumn434\n , sdcolumn543\n , bvcolumn645\n vccolumn754\n , cccolumn834\n , vvcolumn954\n , cvcolumn104\nFROM table1\nWHERE column3 IN\n(\n ...\n)\n\nSELECT sdcolumn123, dscolumn234, asdcolumn345, dscolumn456, ascolumn554, gfcolumn645 sdcolumn754, fdcolumn845, sdcolumn954, fdcolumn1054\nFROM table1\nWHERE column3 IN\n(\n ...\n)\n"
},
{
"answer_id": 272236,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "print(\"SELECT column1, column2\n FROM table1\n WHERE column3 IN (SELECT TOP(1) column4\n FROM table2 INNER JOIN \n table3 ON table2.column1 = table3.column1)\");\n"
},
{
"answer_id": 272238,
"author": "Bullines",
"author_id": 27870,
"author_profile": "https://Stackoverflow.com/users/27870",
"pm_score": 2,
"selected": false,
"text": "SELECT column1, column2\nFROM table1\nWHERE column3 IN(SELECT TOP(1) column4\n FROM table2\n INNER JOIN table3 ON\n table2.column1 = table3.column1\n )\n"
},
{
"answer_id": 272242,
"author": "Mitch Wheat",
"author_id": 16076,
"author_profile": "https://Stackoverflow.com/users/16076",
"pm_score": 2,
"selected": false,
"text": "SELECT\n column1, \n column2\nFROM \n table1\nWHERE \n column3 IN (SELECT TOP(1) \n column4 \n FROM \n table2 \n INNER JOIN table3 ON table2.column1 = table3.column1)\n SELECT\n column1, \n column2\nFROM \n table1\nWHERE \n column3 IN (SELECT TOP(1) column4 \n FROM table2 \n INNER JOIN table3 ON table2.column1 = table3.column1)\n"
},
{
"answer_id": 272245,
"author": "Nelson Miranda",
"author_id": 1130097,
"author_profile": "https://Stackoverflow.com/users/1130097",
"pm_score": 1,
"selected": false,
"text": "SELECT column1, column2\n FROM table1\nWHERE column3 IN\n(\n SELECT TOP(1) column4\n FROM table2\n INNER JOIN table3\n ON table2.column1 = table3.column1\n)\n"
},
{
"answer_id": 272264,
"author": "jalbert",
"author_id": 1360388,
"author_profile": "https://Stackoverflow.com/users/1360388",
"pm_score": 4,
"selected": false,
"text": "SELECT column1,\n column2\n FROM table1\n WHERE column3 IN (SELECT column4\n FROM table2\n JOIN table3\n ON table2.column1 = table3.column1);\n"
},
{
"answer_id": 272267,
"author": "Cade Roux",
"author_id": 18255,
"author_profile": "https://Stackoverflow.com/users/18255",
"pm_score": 2,
"selected": false,
"text": " SELECT column1\n ,column2\n FROM table1\n WHERE column3 IN (\n SELECT TOP(1) column4\n FROM table2\n INNER JOIN table3\n ON table2.column1 = table3.column1\n )\n"
},
{
"answer_id": 272278,
"author": "JosephStyons",
"author_id": 672,
"author_profile": "https://Stackoverflow.com/users/672",
"pm_score": 0,
"selected": false,
"text": "SELECT \n column1\n ,column2\nFROM\n table1\nWHERE column3 IN (\n SELECT TOP(1) column4\n FROM \n table2\n INNER JOIN table3\n ON table2.column1 = table3.column1\n )\n"
},
{
"answer_id": 272282,
"author": "Jack Ryan",
"author_id": 28882,
"author_profile": "https://Stackoverflow.com/users/28882",
"pm_score": 3,
"selected": false,
"text": "SELECT column1, \n column2\nFROM table1\nWHERE column3 IN\n(\n SELECT TOP(1) column4\n FROM table2\n INNER JOIN table3\n ON table2.column1 = table3.column1\n)\n"
},
{
"answer_id": 272305,
"author": "Mark Brackett",
"author_id": 2199,
"author_profile": "https://Stackoverflow.com/users/2199",
"pm_score": 2,
"selected": false,
"text": "SELECT\n Column1,\n Column2\nFROM Table1\nWHERE \n Column3 IN (\n SELECT Column4\n FROM Table2\n JOIN Table3 ON\n Table2.Column1 = Table3.Column1\n )\n SELECT\n Column1,\n Column2\nFROM Table1\nJOIN Table2 ON\n Table1.Column3 = Table2.Column4\nJOIN Table3 ON\n Table2.Column1 = Table3.Column1\n"
},
{
"answer_id": 272339,
"author": "Charles Bretana",
"author_id": 32632,
"author_profile": "https://Stackoverflow.com/users/32632",
"pm_score": 3,
"selected": false,
"text": "Select column1, column2\nFrom table1 T1\nWhere column3 In (Select Top(1) column4\n From table2 T2\n Join table3 T3\n On T2.column1 = T3.column1)\n Select column1, column2\nFrom table1 T1\nWhere column3 In \n (Select Top(1) column4\n From table2 T2\n Join table3 T3\n On T2.column1 = T3.column1)\n Select column1, column2, Col3, Col4, column5,\n column6, Column7, isNull(Column8, 'FedEx') Shipper,\n Case Upper(Column9) \n When 'EAST' Then 'JFK'\n When 'SOUTH' Then 'ATL'\n When 'WEST' Then 'LAX'\n When 'NORTH' Then 'CHI' End HubPoint\nFrom table1 T1\nWhere column3 In \n (Select Top(1) column4\n From table2 T2\n Join table3 T3\n On T2.column1 = T3.column1)\n"
},
{
"answer_id": 272344,
"author": "Slapout",
"author_id": 19072,
"author_profile": "https://Stackoverflow.com/users/19072",
"pm_score": 4,
"selected": false,
"text": "\nSELECT column1, \n column2 \n FROM table1, table2 \n WHERE table1.column1 = table2.column4 \n AND table1.col5 = \"hi\" \n OR table2.myfield = 678 \n"
},
{
"answer_id": 272391,
"author": "Mike Burton",
"author_id": 22225,
"author_profile": "https://Stackoverflow.com/users/22225",
"pm_score": 3,
"selected": false,
"text": "SELECT \n column1, \n column2\nFROM \n table1\nWHERE \n column3 IN\n (\n SELECT TOP(1) \n column4\n FROM \n table2\n INNER JOIN table3 ON table2.column1 = table3.column1\n )\n SELECT\n Column1,\n Column2,\n Function1\n (\n Column1,\n Column2\n ) as Function1,\n CASE\n WHEN Column1 = 1 THEN\n a\n ELSE\n B\n END as Case1 \nFROM\n Table1 t1\n INNER JOIN Table2 t2 ON t1.column12 = t2.column21\nWHERE\n (\n FilterClause1\n AND FilterClause2\n )\n OR\n (\n FilterClause3\n AND FilterClause4\n )\n"
},
{
"answer_id": 272655,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "SELECT column1, column2\nFROM table1\nWHERE column3 IN\n(\nSELECT TOP(1) column4\n FROM table2\n INNER JOIN table3\n ON table2.column1 = table3.column1\n)\n"
},
{
"answer_id": 3535810,
"author": "José Américo Antoine Jr",
"author_id": 426870,
"author_profile": "https://Stackoverflow.com/users/426870",
"pm_score": 3,
"selected": false,
"text": "SELECT \n produtos_cesta.cod_produtos_cesta, \n produtos.nome_pequeno,\n tab_contagem.cont,\n produtos_cesta.sku, \n produtos_kits.sku_r AS sku_kit, \n sku_final = CASE\n WHEN produtos_kits.sku_r IS NOT NULL THEN produtos_kits.sku_r\n ELSE produtos_cesta.sku\n END,\n estoque = CASE\n WHEN produtos2.estoque IS NOT NULL THEN produtos2.estoque\n ELSE produtos.estoque\n END,\n produtos_cesta.unidades as unidades1, \n unidades_x_quantidade = CASE\n WHEN produtos.cod_produtos_kits_tipo = 1 THEN CAST(produtos_cesta.quantidade * (produtos_cesta.unidades / tab_contagem.cont) * produtos_kits.quantidade AS int)\n ELSE CAST(produtos_cesta.quantidade * produtos_cesta.unidades AS int)\n END,\n unidades = CASE\n WHEN produtos.cod_produtos_kits_tipo = 1 THEN produtos_cesta.unidades / tab_contagem.cont * produtos_kits.quantidade\n ELSE produtos_cesta.unidades\n END,\n unidades_parent = produtos_cesta.unidades,\n produtos_cesta.quantidade,\n produtos.controla_estoque, \n produtos.status\nFROM \n produtos_cesta \nINNER JOIN produtos \n ON (produtos_cesta.sku = produtos.sku) \nINNER JOIN produtos_pacotes \n ON (produtos_cesta.sku = produtos_pacotes.sku) \nINNER JOIN (\n SELECT \n produtos_cesta.cod_produtos_cesta,\n cont = SUM(\n CASE\n WHEN produtos_kits.quantidade IS NOT NULL THEN produtos_kits.quantidade\n ELSE 1\n END\n )\n FROM \n produtos_cesta \n LEFT JOIN produtos_kits \n ON (produtos_cesta.sku = produtos_kits.sku) \n LEFT JOIN produtos \n ON (produtos_cesta.sku = produtos.sku) \n WHERE \n shopper_id = '\" + mscsShopperId + @\"' \n GROUP BY \n produtos_cesta.cod_produtos_cesta, \n produtos_cesta.sku, \n produtos_cesta.unidades \n) \nAS tab_contagem\n ON (produtos_cesta.cod_produtos_cesta = tab_contagem.cod_produtos_cesta)\nLEFT JOIN produtos_kits \n ON (produtos.sku = produtos_kits.sku) \nLEFT JOIN produtos as produtos2\n ON (produtos_kits.sku_r = produtos2.sku) \nWHERE \n shopper_id = '\" + mscsShopperId + @\"' \nGROUP BY \n produtos_cesta.cod_produtos_cesta, \n tab_contagem.cont,\n produtos_cesta.sku, \n produtos_kits.sku_r, \n produtos.cod_produtos_kits_tipo, \n produtos2.estoque,\n produtos.controla_estoque, \n produtos.estoque, \n produtos.status, \n produtos.nome_pequeno, \n produtos_cesta.unidades, \n produtos_cesta.quantidade,\n produtos_kits.quantidade\nORDER BY \n produtos_cesta.sku, \n produtos_cesta.unidades DESC\n"
},
{
"answer_id": 4582352,
"author": "S. Goldberg",
"author_id": 560893,
"author_profile": "https://Stackoverflow.com/users/560893",
"pm_score": 1,
"selected": false,
"text": "SELECT\n Column1,\n Column2\nFROM\n Table1\nWHERE\n Column3 IN\n (\n SELECT TOP (1)\n Column4\n FROM \n Table2\n INNER JOIN \n Table3\n ON\n Table2.Column1 = Table3.Column1\n )\n"
},
{
"answer_id": 9910379,
"author": "Jens Frandsen",
"author_id": 1298535,
"author_profile": "https://Stackoverflow.com/users/1298535",
"pm_score": 3,
"selected": false,
"text": "SELECT \n column1, \n column2\nFROM \n table1\nWHERE \n column3 IN\n (\n SELECT TOP(1) \n column4\n FROM \n table2 INNER JOIN \n table3 ON table2.column1 = table3.column1\n )\n SELECT\n Column1,\n Column2\nFROM \n Table1 JOIN \n Table2 ON \n Table1.Column3 = Table2.Column4 JOIN \n Table3 ON \n Table2.Column1 = Table3.Column1 and\n Table2.ColumnX = @x and\n Table3.ColumnY = @y\nWHERE\n Condition1=xxx and\n Condition2=yyy and\n (\n Condition3=aaa or\n Condition4=bbb\n )\n"
},
{
"answer_id": 18098922,
"author": "John Doe",
"author_id": 2659987,
"author_profile": "https://Stackoverflow.com/users/2659987",
"pm_score": 3,
"selected": false,
"text": "select column1, column2\n from table1\n where (column3 in (\n select top(1) column4\n from table2\n inner join table3\n on (table2.column1 = table3.column1)\n ))\n;\n"
}
] |
2008/11/07
|
[
"https://Stackoverflow.com/questions/272210",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/35483/"
] |
272,270
|
<pre><code> <object height="25" width="75" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=5,0,0,0" classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000">
<param value="http://click-here-to-listen.com/players/iaPlay13.swf?x=1058286910FTRZGK" name="movie"/>
<param value="high" name="quality"/>
<param value="#FFFFFF" name="bgcolor"/>
<param value="opaque" name="wmode"/>
<embed height="25" width="75" wmode="opaque" pluginspage="http://www.macromedia.com/go/getflashplayer" type="application/x-shockwave-flash" bgcolor="#FFFFFF" quality="high" src="http://click-here-to-listen.com/players/iaPlay13.swf?x=1058286910FTRZGK"/>
</object>
</code></pre>
<p>I am having to insert this legacy markup into a new site that I'm building. Problem is its using an <code><embed></code> tag. </p>
<p>Would I just do away with the <code><embed></code> and put some content in as an alternative, for those that do not have flash? Basically I'm just trying to bring this piece of html into the 21st century.</p>
|
[
{
"answer_id": 272308,
"author": "Vincent Ramdhanie",
"author_id": 27439,
"author_profile": "https://Stackoverflow.com/users/27439",
"pm_score": 2,
"selected": false,
"text": "<P> <!-- First, try the Python applet -->\n<OBJECT title=\"The Earth as seen from space\" \n classid=\"http://www.observer.mars/TheEarth.py\">\n <!-- Else, try the MPEG video -->\n <OBJECT data=\"TheEarth.mpeg\" type=\"application/mpeg\">\n <!-- Else, try the GIF image -->\n <OBJECT data=\"TheEarth.gif\" type=\"image/gif\">\n <!-- Else render the text -->\n The <STRONG>Earth</STRONG> as seen from space.\n </OBJECT>\n </OBJECT>\n</OBJECT>\n"
},
{
"answer_id": 272328,
"author": "Raithlin",
"author_id": 6528,
"author_profile": "https://Stackoverflow.com/users/6528",
"pm_score": 1,
"selected": false,
"text": "<!--[if !IE]> -->\n<object type=\"application/x-shockwave-flash\" data=\"http://click-here-to-listen.com/players/iaPlay13.swf?x=1058286910FTRZGK\" width=\"75\" height=\"25\">\n<!-- <![endif]-->\n\n<!--[if IE]>\n<object classid=\"clsid:D27CDB6E-AE6D-11cf-96B8-444553540000\" codebase=\"http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=5,0,0,0\" width=\"75\" height=\"25\">\n <param name=\"movie\" value=\"http://click-here-to-listen.com/players/iaPlay13.swf?x=1058286910FTRZGK\" />\n<!--><!--dgx-->\n <param name=\"loop\" value=\"false\">\n <param name=\"menu\" value=\"false\">\n <param name=\"quality\" value=\"high\">\n</object>\n<!-- <![endif]-->\n"
},
{
"answer_id": 272362,
"author": "Keltex",
"author_id": 28260,
"author_profile": "https://Stackoverflow.com/users/28260",
"pm_score": 2,
"selected": false,
"text": "<script type=\"text/javascript\" src=\"swfobject.js\"></script>\n<script type=\"text/javascript\">\n swfobject.embedSWF(\"http://click-here-to-listen.com/players/iaPlay13.swf?x=1058286910FTRZGK\", \n \"myContent\", \"25\", \"75\", \"9.0.0\");\n</script>\n<div id=\"myContent\">\n <p>Alternative content</p>\n</div>\n"
}
] |
2008/11/07
|
[
"https://Stackoverflow.com/questions/272270",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/26107/"
] |
272,313
|
<p>I have the requirement to support different Master pages on my application (ASP.NET MVC).
What is the recommended way to:</p>
<ol>
<li>Pass the master page name to the view from.</li>
<li>Store the master page (in session, or something) so it sticks during a user's visit.</li>
</ol>
|
[
{
"answer_id": 460828,
"author": "Slee",
"author_id": 34548,
"author_profile": "https://Stackoverflow.com/users/34548",
"pm_score": 4,
"selected": true,
"text": "Public Class CustomBaseController\n Inherits System.Web.Mvc.Controller\n\n Protected Overrides Function View(ByVal viewName As String, ByVal masterName As String, ByVal model As Object) As System.Web.Mvc.ViewResult\n\n Return MyBase.View(viewName, Session(\"MasterPage\"), model)\n\n End Function\n\nEnd Class\n Sub Session_Start(ByVal sender As Object, ByVal e As EventArgs)\n\n//programming to figure out your session\nSession(\"MasterPage\")=\"MyMasterPage\"\n\nEnd Sub\n"
}
] |
2008/11/07
|
[
"https://Stackoverflow.com/questions/272313",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7277/"
] |
272,360
|
<p>If so, does it effectively deprecate the <code>visibility</code> property?</p>
<p>(I realize that Internet Explorer does not yet support this CSS2 property.)
<br/>
<a href="http://en.wikipedia.org/wiki/Comparison_of_layout_engines_(CSS)#Properties" rel="noreferrer">Comparisons of layout engines</a></p>
<p><a href="https://stackoverflow.com/questions/133051/what-is-the-difference-between-visibilityhidden-and-displaynone">See also: What is the difference between visibility:hidden and display:none</a></p>
|
[
{
"answer_id": 272380,
"author": "Andrew Bullock",
"author_id": 28543,
"author_profile": "https://Stackoverflow.com/users/28543",
"pm_score": 2,
"selected": false,
"text": "opacity: 0.6;\n-moz-opacity: 0.6;\nfilter: alpha(opacity=60);\n"
},
{
"answer_id": 272381,
"author": "Diodeus - James MacFarlane",
"author_id": 12579,
"author_profile": "https://Stackoverflow.com/users/12579",
"pm_score": 0,
"selected": false,
"text": "filter:alpha(opacity=0);\n"
},
{
"answer_id": 742324,
"author": "Kornel",
"author_id": 27009,
"author_profile": "https://Stackoverflow.com/users/27009",
"pm_score": 4,
"selected": false,
"text": "opacity:0 visibility:hidden"
},
{
"answer_id": 43482222,
"author": "MalcolmOcean",
"author_id": 985026,
"author_profile": "https://Stackoverflow.com/users/985026",
"pm_score": 2,
"selected": false,
"text": "contenteditable visibility: hidden <div contenteditable><span style='visibility: hidden;'></span></div>\n opacity: 0"
},
{
"answer_id": 50027026,
"author": "Mr Lister",
"author_id": 1016716,
"author_profile": "https://Stackoverflow.com/users/1016716",
"pm_score": 3,
"selected": false,
"text": "visibility opacity"
}
] |
2008/11/07
|
[
"https://Stackoverflow.com/questions/272360",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14749/"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.