qid
int64
4
8.14M
question
stringlengths
20
48.3k
answers
list
date
stringlengths
10
10
metadata
list
input
stringlengths
12
45k
output
stringlengths
2
31.8k
261,663
<p>Is it possible to define an implicit conversion of enums in c#?</p> <p>something that could achieve this?</p> <pre><code>public enum MyEnum { one = 1, two = 2 } MyEnum number = MyEnum.one; long i = number; </code></pre> <p>If not, why not?</p>
[ { "answer_id": 261676, "author": "Ash", "author_id": 31128, "author_profile": "https://Stackoverflow.com/users/31128", "pm_score": 2, "selected": false, "text": "<p>If you define the base of the enum as a long then you can perform explicit conversion. I don't know if you can use implicit conversions as enums cannot have methods defined on them.</p>\n\n<pre><code>public enum MyEnum : long\n{\n one = 1,\n two = 2,\n}\n\nMyEnum number = MyEnum.one;\nlong i = (long)number;\n</code></pre>\n\n<p>Also, be aware with this that an uninitalised enumeration will default to the 0 value, or the first item - so in the situation above it would probably be best to define <code>zero = 0</code> as well.</p>\n" }, { "answer_id": 261691, "author": "Igal Tabachnik", "author_id": 8205, "author_profile": "https://Stackoverflow.com/users/8205", "pm_score": 3, "selected": false, "text": "<p>You cannot declare implicit conversions on enum types, because they can't define methods. The C# <a href=\"http://msdn.microsoft.com/en-us/library/z5z9kes2(VS.80).aspx\" rel=\"noreferrer\">implicit</a> keyword compiles into a method starting with 'op_', and it wouldn't work in this case.</p>\n" }, { "answer_id": 261696, "author": "Keith", "author_id": 905, "author_profile": "https://Stackoverflow.com/users/905", "pm_score": 3, "selected": false, "text": "<p>You probably could, but not for the enum (you can't add a method to it). You could add an implicit conversion to you own class to allow an enum to be converted to it, </p>\n\n<pre><code>public class MyClass {\n\n public static implicit operator MyClass ( MyEnum input ) {\n //...\n }\n}\n\nMyClass m = MyEnum.One;\n</code></pre>\n\n<p>The question would be why?</p>\n\n<p>In general .Net avoids (and you should too) any implicit conversion where data can be lost.</p>\n" }, { "answer_id": 261701, "author": "OregonGhost", "author_id": 20363, "author_profile": "https://Stackoverflow.com/users/20363", "pm_score": -1, "selected": false, "text": "<p>Introducing implicit conversions for enum types would break type safety, so I'd not recommend to do that. Why would you want to do that? The only use case for this I've seen is when you want to put the enum values into a structure with a pre-defined layout. But even then, you can use the enum type in the structure and just tell the Marshaller what he should do with this.</p>\n" }, { "answer_id": 261708, "author": "Marc Gravell", "author_id": 23354, "author_profile": "https://Stackoverflow.com/users/23354", "pm_score": 5, "selected": false, "text": "<p>You can't do implict conversions (except for zero), and you can't write your own instance methods - however, you can probably write your own extension methods:</p>\n\n<pre><code>public enum MyEnum { A, B, C }\npublic static class MyEnumExt\n{\n public static int Value(this MyEnum foo) { return (int)foo; }\n static void Main()\n {\n MyEnum val = MyEnum.A;\n int i = val.Value();\n }\n}\n</code></pre>\n\n<p>This doesn't give you a lot, though (compared to just doing an explicit cast).</p>\n\n<p>One of the main times I've seen people want this is for doing <code>[Flags]</code> manipulation via generics - i.e. a <code>bool IsFlagSet&lt;T&gt;(T value, T flag);</code> method. Unfortunately, C# 3.0 doesn't support operators on generics, but you can get around this using <a href=\"http://www.pobox.com/~skeet/csharp/miscutil/usage/genericoperators.html\" rel=\"noreferrer\">things like this</a>, which make operators fully available with generics.</p>\n" }, { "answer_id": 2949340, "author": "Mark", "author_id": 64084, "author_profile": "https://Stackoverflow.com/users/64084", "pm_score": 8, "selected": true, "text": "<p>There is a solution. Consider the following:</p>\n\n<pre><code>public sealed class AccountStatus\n{\n public static readonly AccountStatus Open = new AccountStatus(1);\n public static readonly AccountStatus Closed = new AccountStatus(2);\n\n public static readonly SortedList&lt;byte, AccountStatus&gt; Values = new SortedList&lt;byte, AccountStatus&gt;();\n private readonly byte Value;\n\n private AccountStatus(byte value)\n {\n this.Value = value;\n Values.Add(value, this);\n }\n\n\n public static implicit operator AccountStatus(byte value)\n {\n return Values[value];\n }\n\n public static implicit operator byte(AccountStatus value)\n {\n return value.Value;\n }\n}\n</code></pre>\n\n<p>The above offers implicit conversion:</p>\n\n<pre><code> AccountStatus openedAccount = 1; // Works\n byte openedValue = AccountStatus.Open; // Works\n</code></pre>\n\n<p>This is a fair bit more work than declaring a normal enum (though you can refactor some of the above into a common generic base class). You can go even further by having the base class implement IComparable &amp; IEquatable, as well as adding methods to return the value of DescriptionAttributes, declared names, etc, etc.</p>\n\n<p>I wrote a base class (RichEnum&lt;>) to handle most fo the grunt work, which eases the above declaration of enums down to:</p>\n\n<pre><code>public sealed class AccountStatus : RichEnum&lt;byte, AccountStatus&gt;\n{\n public static readonly AccountStatus Open = new AccountStatus(1);\n public static readonly AccountStatus Closed = new AccountStatus(2);\n\n private AccountStatus(byte value) : base (value)\n {\n }\n\n public static implicit operator AccountStatus(byte value)\n {\n return Convert(value);\n }\n}\n</code></pre>\n\n<p>The base class (RichEnum) is listed below.</p>\n\n<pre><code>using System;\nusing System.Collections.Generic;\nusing System.ComponentModel;\nusing System.Diagnostics;\nusing System.Linq;\nusing System.Reflection;\nusing System.Resources;\n\nnamespace Ethica\n{\n using Reflection;\n using Text;\n\n [DebuggerDisplay(\"{Value} ({Name})\")]\n public abstract class RichEnum&lt;TValue, TDerived&gt;\n : IEquatable&lt;TDerived&gt;,\n IComparable&lt;TDerived&gt;,\n IComparable, IComparer&lt;TDerived&gt;\n where TValue : struct , IComparable&lt;TValue&gt;, IEquatable&lt;TValue&gt;\n where TDerived : RichEnum&lt;TValue, TDerived&gt;\n {\n #region Backing Fields\n\n /// &lt;summary&gt;\n /// The value of the enum item\n /// &lt;/summary&gt;\n public readonly TValue Value;\n\n /// &lt;summary&gt;\n /// The public field name, determined from reflection\n /// &lt;/summary&gt;\n private string _name;\n\n /// &lt;summary&gt;\n /// The DescriptionAttribute, if any, linked to the declaring field\n /// &lt;/summary&gt;\n private DescriptionAttribute _descriptionAttribute;\n\n /// &lt;summary&gt;\n /// Reverse lookup to convert values back to local instances\n /// &lt;/summary&gt;\n private static SortedList&lt;TValue, TDerived&gt; _values;\n\n private static bool _isInitialized;\n\n\n #endregion\n\n #region Constructors\n\n protected RichEnum(TValue value)\n {\n if (_values == null)\n _values = new SortedList&lt;TValue, TDerived&gt;();\n this.Value = value;\n _values.Add(value, (TDerived)this);\n }\n\n #endregion\n\n #region Properties\n\n public string Name\n {\n get\n {\n CheckInitialized();\n return _name;\n }\n }\n\n public string Description\n {\n get\n {\n CheckInitialized();\n\n if (_descriptionAttribute != null)\n return _descriptionAttribute.Description;\n\n return _name;\n }\n }\n\n #endregion\n\n #region Initialization\n\n private static void CheckInitialized()\n {\n if (!_isInitialized)\n {\n ResourceManager _resources = new ResourceManager(typeof(TDerived).Name, typeof(TDerived).Assembly);\n\n var fields = typeof(TDerived)\n .GetFields(BindingFlags.Static | BindingFlags.GetField | BindingFlags.Public)\n .Where(t =&gt; t.FieldType == typeof(TDerived));\n\n foreach (var field in fields)\n {\n\n TDerived instance = (TDerived)field.GetValue(null);\n instance._name = field.Name;\n instance._descriptionAttribute = field.GetAttribute&lt;DescriptionAttribute&gt;();\n\n var displayName = field.Name.ToPhrase();\n }\n _isInitialized = true;\n }\n }\n\n #endregion\n\n #region Conversion and Equality\n\n public static TDerived Convert(TValue value)\n {\n return _values[value];\n }\n\n public static bool TryConvert(TValue value, out TDerived result)\n {\n return _values.TryGetValue(value, out result);\n }\n\n public static implicit operator TValue(RichEnum&lt;TValue, TDerived&gt; value)\n {\n return value.Value;\n }\n\n public static implicit operator RichEnum&lt;TValue, TDerived&gt;(TValue value)\n {\n return _values[value];\n }\n\n public static implicit operator TDerived(RichEnum&lt;TValue, TDerived&gt; value)\n {\n return value;\n }\n\n public override string ToString()\n {\n return _name;\n }\n\n #endregion\n\n #region IEquatable&lt;TDerived&gt; Members\n\n public override bool Equals(object obj)\n {\n if (obj != null)\n {\n if (obj is TValue)\n return Value.Equals((TValue)obj);\n\n if (obj is TDerived)\n return Value.Equals(((TDerived)obj).Value);\n }\n return false;\n }\n\n bool IEquatable&lt;TDerived&gt;.Equals(TDerived other)\n {\n return Value.Equals(other.Value);\n }\n\n\n public override int GetHashCode()\n {\n return Value.GetHashCode();\n }\n\n #endregion\n\n #region IComparable Members\n\n int IComparable&lt;TDerived&gt;.CompareTo(TDerived other)\n {\n return Value.CompareTo(other.Value);\n }\n\n int IComparable.CompareTo(object obj)\n {\n if (obj != null)\n {\n if (obj is TValue)\n return Value.CompareTo((TValue)obj);\n\n if (obj is TDerived)\n return Value.CompareTo(((TDerived)obj).Value);\n }\n return -1;\n }\n\n int IComparer&lt;TDerived&gt;.Compare(TDerived x, TDerived y)\n {\n return (x == null) ? -1 :\n (y == null) ? 1 :\n x.Value.CompareTo(y.Value);\n }\n\n #endregion\n\n public static IEnumerable&lt;TDerived&gt; Values\n {\n get\n {\n return _values.Values;\n }\n }\n\n public static TDerived Parse(string name)\n {\n foreach (TDerived value in _values.Values)\n if (0 == string.Compare(value.Name, name, true) || 0 == string.Compare(value.DisplayName, name, true))\n return value;\n\n return null;\n }\n }\n}\n</code></pre>\n" }, { "answer_id": 5480173, "author": "sehe", "author_id": 85371, "author_profile": "https://Stackoverflow.com/users/85371", "pm_score": 4, "selected": false, "text": "<p>I adapted Mark's excellent RichEnum generic baseclass.</p>\n\n<p>Fixing</p>\n\n<ol>\n<li>a number of compilation problems due to missing bits from his libraries (notably: the resource dependent display names weren't completely removed; they are now)</li>\n<li>initialization wasn't perfect: if the first thing you did was access the static .Values property from the base class, you'd get a NPE. Fixed this by forcing the base class to <em>curiously-recursively</em> (<a href=\"http://en.wikipedia.org/wiki/Curiously_recurring_template_pattern\" rel=\"nofollow noreferrer\">CRTP</a>) force the static construction of TDerived just in time during CheckInitialized</li>\n<li>finally moved CheckInitialized logic into a static constructor (to avoid the penalty of checking each time, the race condition on multithreaded initialization; perhaps this was an impossibility solved by my bullet 1.?)</li>\n</ol>\n\n<p>Kudos to Mark for the splendid idea + implementation, here's to you all:</p>\n\n<pre><code>using System;\nusing System.Collections.Generic;\nusing System.ComponentModel;\nusing System.Diagnostics;\nusing System.Linq;\nusing System.Reflection;\nusing System.Resources;\n\nnamespace NMatrix\n{\n\n [DebuggerDisplay(\"{Value} ({Name})\")]\n public abstract class RichEnum&lt;TValue, TDerived&gt;\n : IEquatable&lt;TDerived&gt;,\n IComparable&lt;TDerived&gt;,\n IComparable, IComparer&lt;TDerived&gt;\n where TValue : struct, IComparable&lt;TValue&gt;, IEquatable&lt;TValue&gt;\n where TDerived : RichEnum&lt;TValue, TDerived&gt;\n {\n #region Backing Fields\n\n /// &lt;summary&gt;\n /// The value of the enum item\n /// &lt;/summary&gt;\n public readonly TValue Value;\n\n /// &lt;summary&gt;\n /// The public field name, determined from reflection\n /// &lt;/summary&gt;\n private string _name;\n\n /// &lt;summary&gt;\n /// The DescriptionAttribute, if any, linked to the declaring field\n /// &lt;/summary&gt;\n private DescriptionAttribute _descriptionAttribute;\n\n /// &lt;summary&gt;\n /// Reverse lookup to convert values back to local instances\n /// &lt;/summary&gt;\n private static readonly SortedList&lt;TValue, TDerived&gt; _values = new SortedList&lt;TValue, TDerived&gt;();\n\n #endregion\n\n #region Constructors\n\n protected RichEnum(TValue value)\n {\n this.Value = value;\n _values.Add(value, (TDerived)this);\n }\n\n #endregion\n\n #region Properties\n\n public string Name\n {\n get\n {\n return _name;\n }\n }\n\n public string Description\n {\n get\n {\n if (_descriptionAttribute != null)\n return _descriptionAttribute.Description;\n\n return _name;\n }\n }\n\n #endregion\n\n #region Initialization\n\n static RichEnum()\n {\n var fields = typeof(TDerived)\n .GetFields(BindingFlags.Static | BindingFlags.GetField | BindingFlags.Public)\n .Where(t =&gt; t.FieldType == typeof(TDerived));\n\n foreach (var field in fields)\n {\n /*var dummy =*/ field.GetValue(null); // forces static initializer to run for TDerived\n\n TDerived instance = (TDerived)field.GetValue(null);\n instance._name = field.Name;\n instance._descriptionAttribute = field.GetCustomAttributes(true).OfType&lt;DescriptionAttribute&gt;().FirstOrDefault();\n }\n }\n\n #endregion\n\n #region Conversion and Equality\n\n public static TDerived Convert(TValue value)\n {\n return _values[value];\n }\n\n public static bool TryConvert(TValue value, out TDerived result)\n {\n return _values.TryGetValue(value, out result);\n }\n\n public static implicit operator TValue(RichEnum&lt;TValue, TDerived&gt; value)\n {\n return value.Value;\n }\n\n public static implicit operator RichEnum&lt;TValue, TDerived&gt;(TValue value)\n {\n return _values[value];\n }\n\n public static implicit operator TDerived(RichEnum&lt;TValue, TDerived&gt; value)\n {\n return value;\n }\n\n public override string ToString()\n {\n return _name;\n }\n\n #endregion\n\n #region IEquatable&lt;TDerived&gt; Members\n\n public override bool Equals(object obj)\n {\n if (obj != null)\n {\n if (obj is TValue)\n return Value.Equals((TValue)obj);\n\n if (obj is TDerived)\n return Value.Equals(((TDerived)obj).Value);\n }\n return false;\n }\n\n bool IEquatable&lt;TDerived&gt;.Equals(TDerived other)\n {\n return Value.Equals(other.Value);\n }\n\n\n public override int GetHashCode()\n {\n return Value.GetHashCode();\n }\n\n #endregion\n\n #region IComparable Members\n\n int IComparable&lt;TDerived&gt;.CompareTo(TDerived other)\n {\n return Value.CompareTo(other.Value);\n }\n\n int IComparable.CompareTo(object obj)\n {\n if (obj != null)\n {\n if (obj is TValue)\n return Value.CompareTo((TValue)obj);\n\n if (obj is TDerived)\n return Value.CompareTo(((TDerived)obj).Value);\n }\n return -1;\n }\n\n int IComparer&lt;TDerived&gt;.Compare(TDerived x, TDerived y)\n {\n return (x == null) ? -1 :\n (y == null) ? 1 :\n x.Value.CompareTo(y.Value);\n }\n\n #endregion\n\n public static IEnumerable&lt;TDerived&gt; Values\n {\n get\n {\n return _values.Values;\n }\n }\n\n public static TDerived Parse(string name)\n {\n foreach (TDerived value in Values)\n if (0 == string.Compare(value.Name, name, true))\n return value;\n\n return null;\n }\n }\n}\n</code></pre>\n\n<p>A sample of usage that I ran on mono:</p>\n\n<pre><code>using System.ComponentModel;\nusing System;\n\nnamespace NMatrix\n{ \n public sealed class MyEnum : RichEnum&lt;int, MyEnum&gt;\n {\n [Description(\"aap\")] public static readonly MyEnum my_aap = new MyEnum(63000);\n [Description(\"noot\")] public static readonly MyEnum my_noot = new MyEnum(63001);\n [Description(\"mies\")] public static readonly MyEnum my_mies = new MyEnum(63002);\n\n private MyEnum(int value) : base (value) { } \n public static implicit operator MyEnum(int value) { return Convert(value); }\n }\n\n public static class Program\n {\n public static void Main(string[] args)\n {\n foreach (var enumvalue in MyEnum.Values)\n Console.WriteLine(\"MyEnum {0}: {1} ({2})\", (int) enumvalue, enumvalue, enumvalue.Description);\n }\n }\n}\n</code></pre>\n\n<p>Producing the output</p>\n\n<pre><code>[mono] ~/custom/demo @ gmcs test.cs richenum.cs &amp;&amp; ./test.exe \nMyEnum 63000: my_aap (aap)\nMyEnum 63001: my_noot (noot)\nMyEnum 63002: my_mies (mies)\n</code></pre>\n\n<p>Note: mono 2.6.7 requires an extra explicit cast that is not required when using mono 2.8.2...</p>\n" }, { "answer_id": 12901745, "author": "Glenn Slayden", "author_id": 147511, "author_profile": "https://Stackoverflow.com/users/147511", "pm_score": 5, "selected": false, "text": "<pre><code>struct PseudoEnum\n{\n public const int \n INPT = 0,\n CTXT = 1,\n OUTP = 2;\n};\n\n// ...\n\nvar arr = new String[3];\n\narr[PseudoEnum.CTXT] = \"can\";\narr[PseudoEnum.INPT] = \"use\";\narr[PseudoEnum.CTXT] = \"as\";\narr[PseudoEnum.CTXT] = \"array\";\narr[PseudoEnum.OUTP] = \"index\";\n</code></pre>\n" }, { "answer_id": 30395889, "author": "BatteryBackupUnit", "author_id": 684096, "author_profile": "https://Stackoverflow.com/users/684096", "pm_score": 1, "selected": false, "text": "<p>I've worked around an issue with <a href=\"https://stackoverflow.com/a/5480173/684096\">sehe's answer</a> when running the code on MS .net (non-Mono). For me specifically the issue occurred on .net 4.5.1 but other versions seem affected, too.</p>\n\n<h2>The issue</h2>\n\n<p>accessing a <code>public static TDervied MyEnumValue</code> by reflection (via <code>FieldInfo.GetValue(null)</code> does <em>not</em> initialize said field.</p>\n\n<h2>The workaround</h2>\n\n<p>Instead of assigning names to <code>TDerived</code> instances upon the static initializer of <code>RichEnum&lt;TValue, TDerived&gt;</code> this is done lazily on first access of <code>TDerived.Name</code>. The code:</p>\n\n<pre><code>public abstract class RichEnum&lt;TValue, TDerived&gt; : EquatableBase&lt;TDerived&gt;\n where TValue : struct, IComparable&lt;TValue&gt;, IEquatable&lt;TValue&gt;\n where TDerived : RichEnum&lt;TValue, TDerived&gt;\n{\n // Enforcing that the field Name (´SomeEnum.SomeEnumValue´) is the same as its \n // instances ´SomeEnum.Name´ is done by the static initializer of this class.\n // Explanation of initialization sequence:\n // 1. the static initializer of ´RichEnum&lt;TValue, TDerived&gt;´ reflects TDervied and \n // creates a list of all ´public static TDervied´ fields:\n // ´EnumInstanceToNameMapping´\n // 2. the static initializer of ´TDerive´d assigns values to these fields\n // 3. The user is now able to access the values of a field.\n // Upon first access of ´TDervied.Name´ we search the list \n // ´EnumInstanceToNameMapping´ (created at step 1) for the field that holds\n // ´this´ instance of ´TDerived´.\n // We then get the Name for ´this´ from the FieldInfo\n private static readonly IReadOnlyCollection&lt;EnumInstanceReflectionInfo&gt; \n EnumInstanceToNameMapping = \n typeof(TDerived)\n .GetFields(BindingFlags.Static | BindingFlags.GetField | BindingFlags.Public)\n .Where(t =&gt; t.FieldType == typeof(TDerived))\n .Select(fieldInfo =&gt; new EnumInstanceReflectionInfo(fieldInfo))\n .ToList();\n\n private static readonly SortedList&lt;TValue, TDerived&gt; Values =\n new SortedList&lt;TValue, TDerived&gt;();\n\n public readonly TValue Value;\n\n private readonly Lazy&lt;string&gt; _name;\n\n protected RichEnum(TValue value)\n {\n Value = value;\n\n // SortedList doesn't allow duplicates so we don't need to do\n // duplicate checking ourselves\n Values.Add(value, (TDerived)this);\n\n _name = new Lazy&lt;string&gt;(\n () =&gt; EnumInstanceToNameMapping\n .First(x =&gt; ReferenceEquals(this, x.Instance))\n .Name);\n }\n\n public string Name\n {\n get { return _name.Value; }\n }\n\n public static implicit operator TValue(RichEnum&lt;TValue, TDerived&gt; richEnum)\n {\n return richEnum.Value;\n }\n\n public static TDerived Convert(TValue value)\n {\n return Values[value];\n }\n\n protected override bool Equals(TDerived other)\n {\n return Value.Equals(other.Value);\n }\n\n protected override int ComputeHashCode()\n {\n return Value.GetHashCode();\n }\n\n private class EnumInstanceReflectionInfo\n {\n private readonly FieldInfo _field;\n private readonly Lazy&lt;TDerived&gt; _instance;\n\n public EnumInstanceReflectionInfo(FieldInfo field)\n {\n _field = field;\n _instance = new Lazy&lt;TDerived&gt;(() =&gt; (TDerived)field.GetValue(null));\n }\n\n public TDerived Instance\n {\n get { return _instance.Value; }\n }\n\n public string Name { get { return _field.Name; } }\n }\n}\n</code></pre>\n\n<p>which - in my case - is based upon <code>EquatableBase&lt;T&gt;</code>:</p>\n\n<pre><code>public abstract class EquatableBase&lt;T&gt;\n where T : class \n{\n public override bool Equals(object obj)\n {\n if (this == obj)\n {\n return true;\n }\n\n T other = obj as T;\n if (other == null)\n {\n return false;\n }\n\n return Equals(other);\n }\n\n protected abstract bool Equals(T other);\n\n public override int GetHashCode()\n {\n unchecked\n {\n return ComputeHashCode();\n }\n }\n\n protected abstract int ComputeHashCode();\n}\n</code></pre>\n\n<h2>Note</h2>\n\n<p>The above code does not incorporate all features of <a href=\"https://stackoverflow.com/users/64084/mark\">Mark</a>'s original answer!</p>\n\n<h2>Thanks</h2>\n\n<p>Thanks to <a href=\"https://stackoverflow.com/users/64084/mark\">Mark</a> for providing his <code>RichEnum</code> implementation and thanks to <a href=\"https://stackoverflow.com/users/85371/sehe\">sehe</a> for providing some improvements!</p>\n" }, { "answer_id": 39141171, "author": "adminSoftDK", "author_id": 3173203, "author_profile": "https://Stackoverflow.com/users/3173203", "pm_score": 2, "selected": false, "text": "<p>I found even easier solution taken from here <a href=\"https://codereview.stackexchange.com/questions/7566/enum-vs-int-wrapper-struct\">https://codereview.stackexchange.com/questions/7566/enum-vs-int-wrapper-struct</a> I pasted the code below from that link just in case it does not work in the future.</p>\n\n<pre><code>struct Day\n{\n readonly int day;\n\n public static readonly Day Monday = 0;\n public static readonly Day Tuesday = 1;\n public static readonly Day Wednesday = 2;\n public static readonly Day Thursday = 3;\n public static readonly Day Friday = 4;\n public static readonly Day Saturday = 5;\n public static readonly Day Sunday = 6;\n\n private Day(int day)\n {\n this.day = day;\n }\n\n public static implicit operator int(Day value)\n {\n return value.day;\n }\n\n public static implicit operator Day(int value)\n {\n return new Day(value);\n }\n}\n</code></pre>\n" }, { "answer_id": 51978313, "author": "Steven Ventura", "author_id": 7015392, "author_profile": "https://Stackoverflow.com/users/7015392", "pm_score": 3, "selected": false, "text": "<p>enums are largely useless for me because of this, OP.</p>\n\n<p>I end up doing pic-related all the time:</p>\n\n<p><a href=\"https://i.stack.imgur.com/CTOcU.png\" rel=\"noreferrer\">the simple solution</a></p>\n\n<p>classic example problem is the VirtualKey set for detecting keypresses. </p>\n\n<pre><code>enum VKeys : ushort\n{\na = 1,\nb = 2,\nc = 3\n}\n// the goal is to index the array using predefined constants\nint[] array = new int[500];\nvar x = array[VKeys.VK_LSHIFT]; \n</code></pre>\n\n<p>problem here is you can't index the array with the enum because it can't implicitly convert enum to ushort (even though we even based the enum on ushort)</p>\n\n<p>in this specific context, enums are obsoleted by the following datastructure\n. . . .</p>\n\n<pre><code>public static class VKeys\n{\npublic const ushort\na = 1,\nb = 2, \nc = 3;\n}\n</code></pre>\n" }, { "answer_id": 59968873, "author": "McKabue", "author_id": 3563013, "author_profile": "https://Stackoverflow.com/users/3563013", "pm_score": 2, "selected": false, "text": "<p>I created this utility to help me convert an <strong>Enum</strong> to <strong>PrimitiveEnum</strong> and <strong>PrimitiveEnum</strong> to <code>byte, sbyte, short, ushort, int, uint, long, or ulong</code>.</p>\n\n<p>So, this technically converts any enum to any its primitive value.</p>\n\n<pre><code>public enum MyEnum\n{\n one = 1, two = 2\n}\n\nPrimitiveEnum number = MyEnum.one;\nlong i = number;\n</code></pre>\n\n<p>See commit at <a href=\"https://github.com/McKabue/McKabue.Extentions.Utility/blob/master/src/McKabue.Extentions.Utility/Enums/PrimitiveEnum.cs\" rel=\"nofollow noreferrer\">https://github.com/McKabue/McKabue.Extentions.Utility/blob/master/src/McKabue.Extentions.Utility/Enums/PrimitiveEnum.cs</a></p>\n\n<pre><code>using System;\n\nnamespace McKabue.Extentions.Utility.Enums\n{\n /// &lt;summary&gt;\n /// &lt;see href=\"https://stackoverflow.com/q/261663/3563013\"&gt;\n /// Can we define implicit conversions of enums in c#?\n /// &lt;/see&gt;\n /// &lt;/summary&gt;\n public struct PrimitiveEnum\n {\n private Enum _enum;\n\n public PrimitiveEnum(Enum _enum)\n {\n this._enum = _enum;\n }\n\n public Enum Enum =&gt; _enum;\n\n\n public static implicit operator PrimitiveEnum(Enum _enum)\n {\n return new PrimitiveEnum(_enum);\n }\n\n public static implicit operator Enum(PrimitiveEnum primitiveEnum)\n {\n return primitiveEnum.Enum;\n }\n\n public static implicit operator byte(PrimitiveEnum primitiveEnum)\n {\n return Convert.ToByte(primitiveEnum.Enum);\n }\n\n public static implicit operator sbyte(PrimitiveEnum primitiveEnum)\n {\n return Convert.ToSByte(primitiveEnum.Enum);\n }\n\n public static implicit operator short(PrimitiveEnum primitiveEnum)\n {\n return Convert.ToInt16(primitiveEnum.Enum);\n }\n\n public static implicit operator ushort(PrimitiveEnum primitiveEnum)\n {\n return Convert.ToUInt16(primitiveEnum.Enum);\n }\n\n public static implicit operator int(PrimitiveEnum primitiveEnum)\n {\n return Convert.ToInt32(primitiveEnum.Enum);\n }\n\n public static implicit operator uint(PrimitiveEnum primitiveEnum)\n {\n return Convert.ToUInt32(primitiveEnum.Enum);\n }\n\n public static implicit operator long(PrimitiveEnum primitiveEnum)\n {\n return Convert.ToInt64(primitiveEnum.Enum);\n }\n\n public static implicit operator ulong(PrimitiveEnum primitiveEnum)\n {\n return Convert.ToUInt64(primitiveEnum.Enum);\n }\n }\n}\n</code></pre>\n" }, { "answer_id": 64711445, "author": "Shpendicus", "author_id": 12399245, "author_profile": "https://Stackoverflow.com/users/12399245", "pm_score": 0, "selected": false, "text": "<p>@BatteryBackupUnit\nHey this sounds like a cool solution but could you explain this part here?</p>\n<p>Since im getting with .NET 4.7.2 an &quot;InvalidCastException&quot; out of this sadly :/</p>\n<pre><code> _name = new Lazy&lt;string&gt;(\n () =&gt; EnumInstanceToNameMapping\n .First(x =&gt; ReferenceEquals(this, x.Instance))\n .Name);\n</code></pre>\n<p>I dont know why, i have created a derived type of the RichEnum and initialized as everything u did in the example but i getthis annyoingg exception..</p>\n<p>Would be glad of some help to this since i like this approach alot tbh.</p>\n" }, { "answer_id": 69168216, "author": "Prince Owen", "author_id": 8058709, "author_profile": "https://Stackoverflow.com/users/8058709", "pm_score": 1, "selected": false, "text": "<p>Here's a different flavour based on <a href=\"https://stackoverflow.com/a/39141171/8058709\">adminSoftDK's answer</a>.</p>\n<pre><code>/// &lt;summary&gt;\n/// Based on https://datatracker.ietf.org/doc/html/rfc4346#appendix-A.1\n/// &lt;/summary&gt;\n[DebuggerDisplay(&quot;{_value}&quot;)]\npublic struct HandshakeContentType\n{\n #region Types\n public const byte ChangeCipher = 0x14;\n public const byte Alert = 0x15;\n public const byte Handshake = 0x16;\n public const byte ApplicationData = 0x17;\n #endregion\n\n byte _value;\n private HandshakeContentType(byte value)\n {\n _value = value;\n\n switch (_value)\n {\n case ChangeCipher:\n case Alert:\n case Handshake:\n case ApplicationData:\n break;\n\n default:\n throw new InvalidOperationException($&quot;An invalid handshake content type (${value}) was provided.&quot;);\n }\n }\n\n #region Methods\n public static implicit operator byte(HandshakeContentType type) =&gt; type._value;\n public static implicit operator HandshakeContentType(byte b) =&gt; new HandshakeContentType(b);\n #endregion\n}\n</code></pre>\n<p>This allows you to use this <code>struct</code> with <code>switch</code> statements which I think is pretty awesome.</p>\n" }, { "answer_id": 72005612, "author": "RFBomb", "author_id": 12135042, "author_profile": "https://Stackoverflow.com/users/12135042", "pm_score": 0, "selected": false, "text": "<p>I don't have enough rep to add a comment, but I was inspired by the 'struct' comment here:\n<a href=\"https://stackoverflow.com/a/39141171/12135042\">https://stackoverflow.com/a/39141171/12135042</a></p>\n<p>Here is how I did it:</p>\n<pre><code>public enum DaysOfWeek\n{\n Sunday = 0,\n Monday = 1,\n Tuesday = 2,\n Wednesday = 3,\n Thursday = 4,\n Friday = 5,\n Saturday = 7,\n}\n\npublic struct Weekends\n{\n private Weekends(DaysOfWeek day){ Day = day; }\n public readonly DaysOfWeek Day;\n public static Weekends Sunday = new(DaysOfWeek.Sunday);\n public static Weekends Saturday = new(DaysOfWeek.Saturday);\n \n public static implicit operator DaysOfWeek(Weekends value) =&gt; value.Mode;\n\n}\n</code></pre>\n<p>I feel this gets the best of both worlds here, since you get your super enum, and easily accessible structs that are statically accessibly acting as subsets of the superenum.</p>\n" } ]
2008/11/04
[ "https://Stackoverflow.com/questions/261663", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17540/" ]
Is it possible to define an implicit conversion of enums in c#? something that could achieve this? ``` public enum MyEnum { one = 1, two = 2 } MyEnum number = MyEnum.one; long i = number; ``` If not, why not?
There is a solution. Consider the following: ``` public sealed class AccountStatus { public static readonly AccountStatus Open = new AccountStatus(1); public static readonly AccountStatus Closed = new AccountStatus(2); public static readonly SortedList<byte, AccountStatus> Values = new SortedList<byte, AccountStatus>(); private readonly byte Value; private AccountStatus(byte value) { this.Value = value; Values.Add(value, this); } public static implicit operator AccountStatus(byte value) { return Values[value]; } public static implicit operator byte(AccountStatus value) { return value.Value; } } ``` The above offers implicit conversion: ``` AccountStatus openedAccount = 1; // Works byte openedValue = AccountStatus.Open; // Works ``` This is a fair bit more work than declaring a normal enum (though you can refactor some of the above into a common generic base class). You can go even further by having the base class implement IComparable & IEquatable, as well as adding methods to return the value of DescriptionAttributes, declared names, etc, etc. I wrote a base class (RichEnum<>) to handle most fo the grunt work, which eases the above declaration of enums down to: ``` public sealed class AccountStatus : RichEnum<byte, AccountStatus> { public static readonly AccountStatus Open = new AccountStatus(1); public static readonly AccountStatus Closed = new AccountStatus(2); private AccountStatus(byte value) : base (value) { } public static implicit operator AccountStatus(byte value) { return Convert(value); } } ``` The base class (RichEnum) is listed below. ``` using System; using System.Collections.Generic; using System.ComponentModel; using System.Diagnostics; using System.Linq; using System.Reflection; using System.Resources; namespace Ethica { using Reflection; using Text; [DebuggerDisplay("{Value} ({Name})")] public abstract class RichEnum<TValue, TDerived> : IEquatable<TDerived>, IComparable<TDerived>, IComparable, IComparer<TDerived> where TValue : struct , IComparable<TValue>, IEquatable<TValue> where TDerived : RichEnum<TValue, TDerived> { #region Backing Fields /// <summary> /// The value of the enum item /// </summary> public readonly TValue Value; /// <summary> /// The public field name, determined from reflection /// </summary> private string _name; /// <summary> /// The DescriptionAttribute, if any, linked to the declaring field /// </summary> private DescriptionAttribute _descriptionAttribute; /// <summary> /// Reverse lookup to convert values back to local instances /// </summary> private static SortedList<TValue, TDerived> _values; private static bool _isInitialized; #endregion #region Constructors protected RichEnum(TValue value) { if (_values == null) _values = new SortedList<TValue, TDerived>(); this.Value = value; _values.Add(value, (TDerived)this); } #endregion #region Properties public string Name { get { CheckInitialized(); return _name; } } public string Description { get { CheckInitialized(); if (_descriptionAttribute != null) return _descriptionAttribute.Description; return _name; } } #endregion #region Initialization private static void CheckInitialized() { if (!_isInitialized) { ResourceManager _resources = new ResourceManager(typeof(TDerived).Name, typeof(TDerived).Assembly); var fields = typeof(TDerived) .GetFields(BindingFlags.Static | BindingFlags.GetField | BindingFlags.Public) .Where(t => t.FieldType == typeof(TDerived)); foreach (var field in fields) { TDerived instance = (TDerived)field.GetValue(null); instance._name = field.Name; instance._descriptionAttribute = field.GetAttribute<DescriptionAttribute>(); var displayName = field.Name.ToPhrase(); } _isInitialized = true; } } #endregion #region Conversion and Equality public static TDerived Convert(TValue value) { return _values[value]; } public static bool TryConvert(TValue value, out TDerived result) { return _values.TryGetValue(value, out result); } public static implicit operator TValue(RichEnum<TValue, TDerived> value) { return value.Value; } public static implicit operator RichEnum<TValue, TDerived>(TValue value) { return _values[value]; } public static implicit operator TDerived(RichEnum<TValue, TDerived> value) { return value; } public override string ToString() { return _name; } #endregion #region IEquatable<TDerived> Members public override bool Equals(object obj) { if (obj != null) { if (obj is TValue) return Value.Equals((TValue)obj); if (obj is TDerived) return Value.Equals(((TDerived)obj).Value); } return false; } bool IEquatable<TDerived>.Equals(TDerived other) { return Value.Equals(other.Value); } public override int GetHashCode() { return Value.GetHashCode(); } #endregion #region IComparable Members int IComparable<TDerived>.CompareTo(TDerived other) { return Value.CompareTo(other.Value); } int IComparable.CompareTo(object obj) { if (obj != null) { if (obj is TValue) return Value.CompareTo((TValue)obj); if (obj is TDerived) return Value.CompareTo(((TDerived)obj).Value); } return -1; } int IComparer<TDerived>.Compare(TDerived x, TDerived y) { return (x == null) ? -1 : (y == null) ? 1 : x.Value.CompareTo(y.Value); } #endregion public static IEnumerable<TDerived> Values { get { return _values.Values; } } public static TDerived Parse(string name) { foreach (TDerived value in _values.Values) if (0 == string.Compare(value.Name, name, true) || 0 == string.Compare(value.DisplayName, name, true)) return value; return null; } } } ```
261,709
<p>I have the following code:</p> <pre><code>using System; using System.Linq; using System.Linq.Expressions; public class Program { public static void Main() { Descendant d = new Descendant(); d.TestMethod(); } } public class Base { protected void FigureItOut&lt;TClass, TMember&gt;(Expression&lt;Func&lt;TClass, TMember&gt;&gt; expr) { } } public class Descendant : Base { public void TestMethod() { FigureItOut(c =&gt; c.Name); } public String Name { get; set; } } </code></pre> <p>I get this compiler error message:</p> <pre><code>The type arguments for method 'Base.FigureItOut&lt;TClass,TMember&gt; (System.Linq.Expressions.Expression&lt;System.Func&lt;TClass,TMember&gt;&gt;)' cannot be inferred from the usage. Try specifying the type arguments explicitly. </code></pre> <p>If I change the call to FigureItOut to this:</p> <pre><code>FigureItOut((Descendant c) =&gt; c.Name); </code></pre> <p>Then it works. Is there a way to get the first example to compile by changing the base class instead?</p> <p>I know that if I make the entire Base class generic, like this:</p> <pre><code>public class Base&lt;TDescendant&gt; { protected void FigureItOut&lt;TMember&gt;(Expression&lt;Func&lt;TDescendant, TMember&gt;&gt; expr) { } } public class Descendant : Base&lt;Descendant&gt; { public void TestMethod() { FigureItOut(c =&gt; c.Name); } public String Name { get; set; } } </code></pre> <p>Then it works, but I'd rather not do that, any other hacks that can be employed, perhaps on the method level (ie. change FigureItOut somehow).</p>
[ { "answer_id": 261742, "author": "Marc Gravell", "author_id": 23354, "author_profile": "https://Stackoverflow.com/users/23354", "pm_score": 4, "selected": true, "text": "<p>How about an extension method that calls the actual (<code>protected internal</code>) implementation? The only downside is you have to add <code>this.</code>.</p>\n\n<p>This works because the <code>source</code> parameter (via <code>this</code>) infers a type for <code>TClass</code>.</p>\n\n<pre><code>public class Base\n{\n protected internal void FigureItOut&lt;TClass, TMember&gt;(Expression&lt;Func&lt;TClass, TMember&gt;&gt; expr)\n {\n Debug.WriteLine(\"Got to actual method\");\n }\n}\n\npublic static class BaseExt\n{\n public static void FigureItOut&lt;TClass, TMember&gt;(this TClass source, Expression&lt;Func&lt;TClass, TMember&gt;&gt; expr)\n where TClass : Base\n { // call the actual method\n Debug.WriteLine(\"Got to extension method\");\n source.FigureItOut(expr);\n }\n}\npublic class Descendant : Base\n{\n public void TestMethod()\n {\n this.FigureItOut(c =&gt; c.Name);\n }\n\n public String Name { get; set; }\n}\n</code></pre>\n\n<hr>\n\n<p>As an alternative (if the <code>internal</code> is a pain), consider making it static, with an instance argument that is used primarily for type inference:</p>\n\n<pre><code>protected static void FigureItOut&lt;TClass, TMember&gt;(TClass source, Expression&lt;Func&lt;TClass, TMember&gt;&gt; expr)\n{\n\n}\n\npublic void TestMethod()\n{\n FigureItOut(this, c =&gt; c.Name);\n}\n</code></pre>\n" }, { "answer_id": 261744, "author": "leppie", "author_id": 15541, "author_profile": "https://Stackoverflow.com/users/15541", "pm_score": 0, "selected": false, "text": "<p>Unless it takes a parameter, it cant be inferred.\nUnless it assigns a return value, it cant be inferred.</p>\n" } ]
2008/11/04
[ "https://Stackoverflow.com/questions/261709", "https://Stackoverflow.com", "https://Stackoverflow.com/users/267/" ]
I have the following code: ``` using System; using System.Linq; using System.Linq.Expressions; public class Program { public static void Main() { Descendant d = new Descendant(); d.TestMethod(); } } public class Base { protected void FigureItOut<TClass, TMember>(Expression<Func<TClass, TMember>> expr) { } } public class Descendant : Base { public void TestMethod() { FigureItOut(c => c.Name); } public String Name { get; set; } } ``` I get this compiler error message: ``` The type arguments for method 'Base.FigureItOut<TClass,TMember> (System.Linq.Expressions.Expression<System.Func<TClass,TMember>>)' cannot be inferred from the usage. Try specifying the type arguments explicitly. ``` If I change the call to FigureItOut to this: ``` FigureItOut((Descendant c) => c.Name); ``` Then it works. Is there a way to get the first example to compile by changing the base class instead? I know that if I make the entire Base class generic, like this: ``` public class Base<TDescendant> { protected void FigureItOut<TMember>(Expression<Func<TDescendant, TMember>> expr) { } } public class Descendant : Base<Descendant> { public void TestMethod() { FigureItOut(c => c.Name); } public String Name { get; set; } } ``` Then it works, but I'd rather not do that, any other hacks that can be employed, perhaps on the method level (ie. change FigureItOut somehow).
How about an extension method that calls the actual (`protected internal`) implementation? The only downside is you have to add `this.`. This works because the `source` parameter (via `this`) infers a type for `TClass`. ``` public class Base { protected internal void FigureItOut<TClass, TMember>(Expression<Func<TClass, TMember>> expr) { Debug.WriteLine("Got to actual method"); } } public static class BaseExt { public static void FigureItOut<TClass, TMember>(this TClass source, Expression<Func<TClass, TMember>> expr) where TClass : Base { // call the actual method Debug.WriteLine("Got to extension method"); source.FigureItOut(expr); } } public class Descendant : Base { public void TestMethod() { this.FigureItOut(c => c.Name); } public String Name { get; set; } } ``` --- As an alternative (if the `internal` is a pain), consider making it static, with an instance argument that is used primarily for type inference: ``` protected static void FigureItOut<TClass, TMember>(TClass source, Expression<Func<TClass, TMember>> expr) { } public void TestMethod() { FigureItOut(this, c => c.Name); } ```
261,717
<p>I have a query on my database as such:</p> <pre><code>SELECT * FROM expenses WHERE user_id = ? AND dated_on = ? </code></pre> <p>I have added an index to the table on both the <code>user_id</code> and <code>dated_on</code> columns. When I inspect the indexes using <code>SHOW INDEXES FROM expenses</code>, there are two lines -- one with a <code>seq_in_index</code> value of 1, the other with a <code>seq_in_index</code> value of 2.</p> <p>My question is, if I then submit a query which uses only one of the two WHERE clauses, e.g.:</p> <pre><code>SELECT * FROM expenses WHERE user_id = ? </code></pre> <p>Is there any benefit to creating another index which solely indexes the <code>user_id</code> column, or will the <code>user_id</code>/<code>dated_on</code> index described above be used just as efficiently?</p> <p>Finally, how about if use the query:</p> <pre><code>SELECT * FROM expenses WHERE dated_on = ? </code></pre> <p>How does the <code>seq_in_index</code> value of 2 affect index use and performance in this situation?</p>
[ { "answer_id": 261726, "author": "Ned Batchelder", "author_id": 14343, "author_profile": "https://Stackoverflow.com/users/14343", "pm_score": 3, "selected": false, "text": "<p>If your index on user_id and dated_on is really in that order (user_id first), then it will be used for a user_id query also. You can check by using EXPLAIN to see the actual strategy for the query.</p>\n" }, { "answer_id": 261761, "author": "Greg", "author_id": 24181, "author_profile": "https://Stackoverflow.com/users/24181", "pm_score": 4, "selected": true, "text": "<p>MySQL can use <a href=\"http://dev.mysql.com/doc/refman/5.0/en/mysql-indexes.html\" rel=\"noreferrer\">any left portion of an index</a>.</p>\n\n<p>In your example <code>SELECT * FROM expenses WHERE user_id = ?</code> will use the index but <code>SELECT * FROM expenses WHERE dated_on = ?</code> won't.</p>\n\n<p>For a 3-column index A, B, C, <code>WHERE A = ? AND B = ?</code> will use an index over A and B, but <code>WHERE A = ? AND C = ?</code> will only use an index on A</p>\n" } ]
2008/11/04
[ "https://Stackoverflow.com/questions/261717", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1174/" ]
I have a query on my database as such: ``` SELECT * FROM expenses WHERE user_id = ? AND dated_on = ? ``` I have added an index to the table on both the `user_id` and `dated_on` columns. When I inspect the indexes using `SHOW INDEXES FROM expenses`, there are two lines -- one with a `seq_in_index` value of 1, the other with a `seq_in_index` value of 2. My question is, if I then submit a query which uses only one of the two WHERE clauses, e.g.: ``` SELECT * FROM expenses WHERE user_id = ? ``` Is there any benefit to creating another index which solely indexes the `user_id` column, or will the `user_id`/`dated_on` index described above be used just as efficiently? Finally, how about if use the query: ``` SELECT * FROM expenses WHERE dated_on = ? ``` How does the `seq_in_index` value of 2 affect index use and performance in this situation?
MySQL can use [any left portion of an index](http://dev.mysql.com/doc/refman/5.0/en/mysql-indexes.html). In your example `SELECT * FROM expenses WHERE user_id = ?` will use the index but `SELECT * FROM expenses WHERE dated_on = ?` won't. For a 3-column index A, B, C, `WHERE A = ? AND B = ?` will use an index over A and B, but `WHERE A = ? AND C = ?` will only use an index on A
261,721
<p>Do you know a way to organize boolean expressions in a database while allowing infinite nesting of the expressions?</p> <p>Example:</p> <pre><code>a = 1 AND (b = 1 OR b = 2) </code></pre> <p>The expression as a whole shouldn't be stored as varchar to preserve data integrity.</p>
[ { "answer_id": 261740, "author": "Toon Krijthe", "author_id": 18061, "author_profile": "https://Stackoverflow.com/users/18061", "pm_score": 3, "selected": false, "text": "<p>An expression is a treelike structure. So you need a way to present the tree in a table.</p>\n\n<p>You can for example use the fields:</p>\n\n<ul>\n<li>ID</li>\n<li>TypeExpression (and, or etc...)</li>\n<li>FirstChildID</li>\n<li>SecondChildID</li>\n</ul>\n\n<p>In this case, you have the following types:</p>\n\n<ol>\n<li>AND, Children point to other expression.</li>\n<li>OR, Children point to other expression.</li>\n<li>Equal, Children point to other expression.</li>\n<li>Literal, FirstChild points to an entry in a literal table.</li>\n<li>VariableLookup, FirstChild points to an entry in a varable table.</li>\n</ol>\n\n<p>But I think there are better ways to organise expression. I once made a simple expression evaluator that accepts a string and produces a numeric result. </p>\n" }, { "answer_id": 261754, "author": "Tomalak", "author_id": 18771, "author_profile": "https://Stackoverflow.com/users/18771", "pm_score": 4, "selected": false, "text": "<p>Option 1 would be to use a nested table (a tree with id / parent_id structure), like Gamecat suggested. This is relatively expensive to do, and requires issuing SQL queries repetitively to build the equivalent of a single nested expression.</p>\n\n<p>Option 2 would be to use a serialized object and store it into a varchar column. For example, JSON would be a good choice. It is not white-space sensitive, can be created and parsed in a vast number of languages, and it retains data integrity.</p>\n\n<p>As soon as you have parsed your expression string into a tree object in memory, you can serialize it and store it. If there was no need to manipulate the expression on the database level, I guess I would go that route.</p>\n" }, { "answer_id": 261765, "author": "Ned Batchelder", "author_id": 14343, "author_profile": "https://Stackoverflow.com/users/14343", "pm_score": 2, "selected": false, "text": "<p>This is going to be difficult to represent relationally, because by its nature it is both hierarchical and polymorphic (the leaves of your tree can be either variables or constants).</p>\n" }, { "answer_id": 261770, "author": "Ken Gentle", "author_id": 8709, "author_profile": "https://Stackoverflow.com/users/8709", "pm_score": 2, "selected": false, "text": "<p>This type of expression is most usually expressed as a tree (a hierarchy), which are notoriously annoying to query in SQL.</p>\n\n<p>We'll assume that <code>a</code> and <code>b</code> are numeric for the moment and that literals ('1', '2') are distinguished from variables.</p>\n\n<pre><code>Table Nodes\nid\ntype (Variable|Literal)\nname (nullable for literal)\nvalue\n\nTable Operators\nid\nname (=, AND, OR, NOT)\nleftNodeId\nrightNodeId\n</code></pre>\n\n<p>This structure is very flexible, but querying it to retrieve a complex expression is going to be \"fun\" (read that \"challenging\").</p>\n\n<p>And you still have to parse the structure to begin with and evaluate the expression after it has been reconstructed.</p>\n" }, { "answer_id": 261990, "author": "Hank Gay", "author_id": 4203, "author_profile": "https://Stackoverflow.com/users/4203", "pm_score": 2, "selected": false, "text": "<p>The traditional way to model Boolean functions is to use <a href=\"http://en.wikipedia.org/wiki/Binary_decision_diagram\" rel=\"nofollow noreferrer\">Binary Decision Diagrams</a>, especially Reduced Order Binary Decision Diagrams. It's possible you can find an extension for your DBMS that provides good support for the concept.</p>\n\n<p>UPDATE:\nAlternately, if you don't need to query on the Boolean logic, you could use a BDD library and just serialize the BDD into a <code>BLOB</code> or equivalent. It beats using a <code>varchar</code> field because the BDD library would ensure the data was valid.</p>\n" }, { "answer_id": 264682, "author": "Varun Mahajan", "author_id": 6613, "author_profile": "https://Stackoverflow.com/users/6613", "pm_score": 0, "selected": false, "text": "<p>Adding to @Gamechat answer</p>\n\n<p>I think it should be like this</p>\n\n<p>ID </p>\n\n<p>TypeExpression (and, or etc...) </p>\n\n<p>FirstChildID --This can be a leaf node or a pointer to another row in same table</p>\n\n<p>SecondChildID --This can be a leaf node or a pointer to another row in same table</p>\n\n<p>isFirstChildLeaf</p>\n\n<p>isSecondChildLeaf</p>\n" }, { "answer_id": 2744409, "author": "cipak", "author_id": 210550, "author_profile": "https://Stackoverflow.com/users/210550", "pm_score": 2, "selected": false, "text": "<p>I would store the expression in polish form, in a varchar/text column. An expression in polish form (operand before operands, no brackets) is much easier to parse with a recursive function (or a stack of course).</p>\n\n<p>a = 1 AND (b = 1 OR b = 2)</p>\n\n<p>in polish form shows like this:</p>\n\n<p>AND = a 1 OR = b 1 = b 2</p>\n" }, { "answer_id": 58835705, "author": "Julien", "author_id": 2240780, "author_profile": "https://Stackoverflow.com/users/2240780", "pm_score": 1, "selected": false, "text": "<p>Ok withe the answers but what if there are more than 2 expressions in an expression group ?</p>\n\n<pre><code>a = 1 AND (b = 1 OR b = 2 OR b = 3)\n</code></pre>\n\n<p>I propose this :</p>\n\n<pre><code>-------------------\n| Condition |\n-------------------\n| - id |\n| - value1 |\n| - value2 |\n| - operation |\n-------------------\n |(1)\n | --------------\n | | |\n | |(*) |\n------------------- |\n| ConditionGroup | |\n------------------- |\n| - id |--------\n| - groupType |\n| - condition |\n| - subConditionGroups\n-------------------\n</code></pre>\n\n<ul>\n<li><code>value1</code>, <code>value2</code> and <code>operation</code> model a final comparison like '<code>b = 3</code>' (in my case <code>value1 = 'b'</code>, <code>value2 = '3'</code> and <code>operation = 'EQUALS'</code>)</li>\n<li><code>groupeType</code> can be '<code>AND</code>' or '<code>OR</code>'</li>\n<li>a <code>ConditionGroup</code> can have either a sub-list of <code>ConditionGroup</code>s <strong>OR</strong> a final <code>Condition</code> but <strong>not both</strong>.</li>\n<li>Now your start expression is a <code>ConditionGroup</code>, recursively dig into its <code>subConditionGroups</code> until you find a final condition, then return the value and apply the proper <code>condition</code>.</li>\n</ul>\n\n<p>Actually that is what I'm about to try.</p>\n" } ]
2008/11/04
[ "https://Stackoverflow.com/questions/261721", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
Do you know a way to organize boolean expressions in a database while allowing infinite nesting of the expressions? Example: ``` a = 1 AND (b = 1 OR b = 2) ``` The expression as a whole shouldn't be stored as varchar to preserve data integrity.
Option 1 would be to use a nested table (a tree with id / parent\_id structure), like Gamecat suggested. This is relatively expensive to do, and requires issuing SQL queries repetitively to build the equivalent of a single nested expression. Option 2 would be to use a serialized object and store it into a varchar column. For example, JSON would be a good choice. It is not white-space sensitive, can be created and parsed in a vast number of languages, and it retains data integrity. As soon as you have parsed your expression string into a tree object in memory, you can serialize it and store it. If there was no need to manipulate the expression on the database level, I guess I would go that route.
261,731
<p>I've got a large source tree (> 2 GB, WINCE build tree) that I would like to start managing with Subversion. Up to this point, 'versioning' has been managed through keeping multiple copies of the tree, and using Beyond Compare to find differences.</p> <p>The last big stumbling block I see to using Subversion is that it modifies the file timestamp to be the commit time. This makes Beyond Compare comparisons much more time consuming, because you must do a binary compare to find changes.</p> <p>I've looked at the <a href="http://svn.haxx.se/users/archive-2006-03/0949.shtml" rel="nofollow noreferrer">meta-data versioning</a> branch of the subversion source tree, but I would prefer to not try to merge that code from 2006 into the current svn source. </p> <p>Thanks,</p> <p>Dave</p>
[ { "answer_id": 261758, "author": "Peter Parker", "author_id": 23264, "author_profile": "https://Stackoverflow.com/users/23264", "pm_score": 0, "selected": false, "text": "<p>Subversion will do the comparsion much quicker than even beyond compare will do..</p>\n\n<p>If you use tortoiseSVN you even can use beyond compare as external Diff tool.</p>\n" }, { "answer_id": 261790, "author": "Mnementh", "author_id": 21005, "author_profile": "https://Stackoverflow.com/users/21005", "pm_score": 0, "selected": false, "text": "<p>After a quick check: If you commit a file from your working copy, it keeps it's timestamp (last modification time). Even after an update (without further remote changes to this file) the file keeps the timestamp of the last modification. The test was on Linux with Subversion version 1.4.6.</p>\n\n<p>If you update a file, that was changed remotely it gets a new timestamp.</p>\n\n<p>So you keep timestamps of last modification.</p>\n\n<p>Besides: Why you want to use 'Beyond Compare' for diffs. You will no longer need to keep different directories to reflect different versions. And subversion has a diff-feature of it's own to prepare diffs for combinations of revisions.</p>\n" }, { "answer_id": 261836, "author": "Ken Gentle", "author_id": 8709, "author_profile": "https://Stackoverflow.com/users/8709", "pm_score": 3, "selected": true, "text": "<p>There is an svn config option that controls how timestamps are stored in the repository:</p>\n\n<pre><code>use-commit-times\n</code></pre>\n\n<blockquote>\n <p>Normally your working copy files have\n timestamps that reflect the last time\n they were touched by any process,\n whether that be your own editor or by\n some svn subcommand. This is generally\n convenient for people developing\n software, because build systems often\n look at timestamps as a way of\n deciding which files need to be\n recompiled.</p>\n \n <p>In other situations, however, it's\n sometimes nice for the working copy\n files to have timestamps that reflect\n the last time they were changed in the\n repository. The svn export command\n always places these “last-commit\n timestamps” on trees that it produces.\n By setting this config variable to\n yes, the svn checkout, svn update, svn\n switch, and svn revert commands will\n also set last-commit timestamps on\n files that they touch.</p>\n</blockquote>\n\n<p>See <a href=\"http://svnbook.red-bean.com/en/1.1/svn-book.html#svn-ch-7-sect-1\" rel=\"nofollow noreferrer\">Runtime Configuration Area</a> and \n<a href=\"http://svnbook.red-bean.com/en/1.1/svn-book.html#svn-ch-7-sect-1.3.2\" rel=\"nofollow noreferrer\">Configuration Options</a></p>\n\n<p>BTW, Beyond Compare <strong>rocks!</strong> I use all of the ones mentioned, svn diff, TortoiseMerge and BC2. BC2 is the most complete.</p>\n" }, { "answer_id": 12533474, "author": "user1587504", "author_id": 1587504, "author_profile": "https://Stackoverflow.com/users/1587504", "pm_score": 0, "selected": false, "text": "<p>Whether \"use-commit-times\" needs to be set to yes on every client m/c config file OR is there any option to centralize this on Subversion installation directory?.</p>\n" } ]
2008/11/04
[ "https://Stackoverflow.com/questions/261731", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5378/" ]
I've got a large source tree (> 2 GB, WINCE build tree) that I would like to start managing with Subversion. Up to this point, 'versioning' has been managed through keeping multiple copies of the tree, and using Beyond Compare to find differences. The last big stumbling block I see to using Subversion is that it modifies the file timestamp to be the commit time. This makes Beyond Compare comparisons much more time consuming, because you must do a binary compare to find changes. I've looked at the [meta-data versioning](http://svn.haxx.se/users/archive-2006-03/0949.shtml) branch of the subversion source tree, but I would prefer to not try to merge that code from 2006 into the current svn source. Thanks, Dave
There is an svn config option that controls how timestamps are stored in the repository: ``` use-commit-times ``` > > Normally your working copy files have > timestamps that reflect the last time > they were touched by any process, > whether that be your own editor or by > some svn subcommand. This is generally > convenient for people developing > software, because build systems often > look at timestamps as a way of > deciding which files need to be > recompiled. > > > In other situations, however, it's > sometimes nice for the working copy > files to have timestamps that reflect > the last time they were changed in the > repository. The svn export command > always places these “last-commit > timestamps” on trees that it produces. > By setting this config variable to > yes, the svn checkout, svn update, svn > switch, and svn revert commands will > also set last-commit timestamps on > files that they touch. > > > See [Runtime Configuration Area](http://svnbook.red-bean.com/en/1.1/svn-book.html#svn-ch-7-sect-1) and [Configuration Options](http://svnbook.red-bean.com/en/1.1/svn-book.html#svn-ch-7-sect-1.3.2) BTW, Beyond Compare **rocks!** I use all of the ones mentioned, svn diff, TortoiseMerge and BC2. BC2 is the most complete.
261,735
<p>I'm looking for a dummy SQL statement that will work from a C# SQL connection to check for connectivity.</p> <p>Basically I need to send a request to the database, I don't care what it returns I just want it to be successful if the database is still there and throw an exception if the database isn't.</p> <p>The scenario I'm testing for is a loss of connectivity to the database, where the SQLConnections State property seems to still be "Open" but there is no connectivity.</p>
[ { "answer_id": 261748, "author": "paxdiablo", "author_id": 14860, "author_profile": "https://Stackoverflow.com/users/14860", "pm_score": 4, "selected": true, "text": "<p>Most SQL databases have a 'table' for this purpose.</p>\n\n<p>In DB2, it's:</p>\n\n<pre><code>select * from sysibm.sysdummy1\n</code></pre>\n\n<p>while Oracle has, from memory,</p>\n\n<pre><code>select * from dual\n</code></pre>\n\n<p>It'll depend on the database at the back end.</p>\n" }, { "answer_id": 261771, "author": "Amy B", "author_id": 8155, "author_profile": "https://Stackoverflow.com/users/8155", "pm_score": 3, "selected": false, "text": "<p>You could do this:</p>\n\n<pre><code>Select 1\n</code></pre>\n\n<p>Ok, how about sending an empty string or blank space. Those are valid commands for Sql Server.</p>\n" }, { "answer_id": 261773, "author": "StingyJack", "author_id": 16391, "author_profile": "https://Stackoverflow.com/users/16391", "pm_score": 1, "selected": false, "text": "<p>You should get an error if you are unable to open a new connection because the db is unavailable. </p>\n\n<p>It sounds to me like you are keeping a connection open all the time (which is usually a bad idea - a new connection should be opened before a batch is executed). Is this the case?</p>\n" }, { "answer_id": 261795, "author": "devio", "author_id": 21336, "author_profile": "https://Stackoverflow.com/users/21336", "pm_score": 2, "selected": false, "text": "<p>Loss of connectivity may happen anytime.</p>\n\n<p>What if the proposed SELECT statements execute fine, but the connection breaks immediately after (successfully) executing them?</p>\n" }, { "answer_id": 261850, "author": "Corey Trager", "author_id": 9328, "author_profile": "https://Stackoverflow.com/users/9328", "pm_score": 1, "selected": false, "text": "<p>select getdate()</p>\n" }, { "answer_id": 262172, "author": "Michael Penza", "author_id": 34196, "author_profile": "https://Stackoverflow.com/users/34196", "pm_score": 2, "selected": false, "text": "<p>The simplest method is to execute a select that does nothing.</p>\n\n<pre><code>SELECT N'Test'\n</code></pre>\n" }, { "answer_id": 262592, "author": "Noah Yetter", "author_id": 30080, "author_profile": "https://Stackoverflow.com/users/30080", "pm_score": 0, "selected": false, "text": "<p>It would be better to catch your implementation's not-connected exception for EVERY sql statement you execute, rather than using a dummy statement to test for connectivity. I have seen systems where upwards of 10% of database CPU time is spent responding to these dummy queries.</p>\n" }, { "answer_id": 262640, "author": "JosephStyons", "author_id": 672, "author_profile": "https://Stackoverflow.com/users/672", "pm_score": 0, "selected": false, "text": "<p>Example Delphi code, which I trust will be easy to adapt:</p>\n\n<pre><code>function IsConnValid(var Conn: TADOConnection; DBType: TDBType): boolean;\nvar\n qry : TADOQuery;\nbegin\n //gimme a connection, and i'll create a query, try to retrieve dummy data.\n //if retrieval works, return TRUE. otherwise, return FALSE.\n qry := TADOQuery.Create(nil);\n try\n qry.Connection := Conn;\n\n case DBType of\n //syntax for a dummy query varies by vendor.\n dbOracle : qry.Sql.Add('SELECT 1 FROM DUAL');\n dbSqlServer : qry.Sql.Add('SELECT 1');\n end; //case\n\n try\n qry.Open;\n //try to open the query.\n //if we lost the connection, we'll probably get an exception.\n Result := not(qry.Eof); //a working connection will NOT have EOF.\n qry.Close;\n except on e : exception do\n //if exception when we try to open the qry, then connection went bye-bye.\n Result := False;\n end; //try-except\n finally\n qry.Free;\n end; //try-finally\nend;\n</code></pre>\n" }, { "answer_id": 268998, "author": "HAdes", "author_id": 11989, "author_profile": "https://Stackoverflow.com/users/11989", "pm_score": 0, "selected": false, "text": "<p>One way of finding out if the connection to the database still does actually exist, is to try to perform some operation on the connection. If the connection has died, the ConnectionState property still remains as \"Open\", but when you try and do something with it you will get your exception. For example:</p>\n\n<pre><code>SqlConnection sqlConn;\n private bool dbConnectionExists() {\n try\n {\n sqlConn.ChangeDatabase(\"MyDBname\");\n return true;\n }\n catch\n {\n return false;\n }\n }\n\n private void button1_Click(object sender, EventArgs e)\n {\n if (dbConnectionExists())\n {\n // Connection ok so do something \n }\n }\n</code></pre>\n\n<p>The connectionState property changes to \"Closed\" once this type of operation is performed and fails, so you can then check the state if you want aswell.</p>\n\n<p>Hope that helps.</p>\n" } ]
2008/11/04
[ "https://Stackoverflow.com/questions/261735", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20400/" ]
I'm looking for a dummy SQL statement that will work from a C# SQL connection to check for connectivity. Basically I need to send a request to the database, I don't care what it returns I just want it to be successful if the database is still there and throw an exception if the database isn't. The scenario I'm testing for is a loss of connectivity to the database, where the SQLConnections State property seems to still be "Open" but there is no connectivity.
Most SQL databases have a 'table' for this purpose. In DB2, it's: ``` select * from sysibm.sysdummy1 ``` while Oracle has, from memory, ``` select * from dual ``` It'll depend on the database at the back end.
261,738
<p>One of my co-workers has resigned and was made to leave the premises before checking in all of his code to TFS. I have access to the physical files. Is there a way for me to access his workspace and check in some of the changes that are still left unchecked in? From tfs I can see which files he has checked out but no way of seeing the exact changes unless very manually. </p>
[ { "answer_id": 261823, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<p>This is probably a quick and dirty way of doing it:</p>\n\n<ul>\n<li>Shelve or check-in your own work.</li>\n<li>Copy the relevant files from your co-worker into your own workspace</li>\n<li>Compare the files with latest in TFS</li>\n</ul>\n\n<p>//huusom</p>\n" }, { "answer_id": 261837, "author": "Jack Bolding", "author_id": 5882, "author_profile": "https://Stackoverflow.com/users/5882", "pm_score": 2, "selected": false, "text": "<p>Have your sys-admin reset the users password to a known value, login as the user on that machine and voila, you are the user...</p>\n" }, { "answer_id": 634834, "author": "dove", "author_id": 30913, "author_profile": "https://Stackoverflow.com/users/30913", "pm_score": 0, "selected": false, "text": "<p>You could use some diff tool like beyond compare to visualise the actual differences.</p>\n\n<p>To manage others' workspaces and even checked out files it is hard to beat <a href=\"http://www.attrice.info/cm/tfs/\" rel=\"nofollow noreferrer\">Team Sidekicks</a>, which is free and provides brilliant interface for this and many other routine TFS work.</p>\n" }, { "answer_id": 2545998, "author": "GWLlosa", "author_id": 18071, "author_profile": "https://Stackoverflow.com/users/18071", "pm_score": 2, "selected": false, "text": "<p><strong>1)</strong> Copy the files from his machine.</p>\n\n<p><strong>2)</strong> Administratively undo his checkout.</p>\n\n<p><strong>3)</strong> Check out the files on your machine.</p>\n\n<p><strong>4)</strong> Overwrite your files with his files.</p>\n\n<p><strong>5)</strong> Your machine state should now roughly equal his; do as many comparisons as you want. </p>\n" }, { "answer_id": 8878963, "author": "granth", "author_id": 11210, "author_profile": "https://Stackoverflow.com/users/11210", "pm_score": 4, "selected": false, "text": "<p>In TFS 2010, there is a new feature called 'Public Workspaces'. This allows multiple people to <strong>share the same workspace folders</strong> on a computer, but authenticating to TFS using their <strong>own</strong> logon.</p>\n\n<p>A TFS administrator can change a workspace to a 'Public Workspace' by running a command like the following:</p>\n\n<pre><code>tf workspace /collection:http://yourserver:8080/tfs/yourCollection WorkspaceName;domain\\CurrentWorkspaceOwner /permission:Public\n</code></pre>\n\n<p><em>(This command can be run on any computer, it doesn't need to be run on the same computer as the workspace you are trying to change)</em></p>\n\n<p>If there is only one other user that needs to use the workspace, perhaps a simpler method is to just change the owner of the workspace. This can be done by a TFS administrator with the following command:</p>\n\n<pre><code>tf workspace /collection:http://yourserver:8080/tfs/yourCollection WorkspaceName;domain\\CurrentWorkspaceOwner /newowner:domain\\NewWorkspaceOwner\n</code></pre>\n\n<p>Once you have done either of these things, you can logon to that computer as the new owner and use the workspace as if it were your own.</p>\n\n<p>You can read more about this feature in this blog post <a href=\"http://blogs.msdn.com/b/granth/archive/2009/11/08/tfs2010-public-workspaces.aspx\" rel=\"noreferrer\">TFS2010: Public Workspaces</a>.</p>\n" } ]
2008/11/04
[ "https://Stackoverflow.com/questions/261738", "https://Stackoverflow.com", "https://Stackoverflow.com/users/32313/" ]
One of my co-workers has resigned and was made to leave the premises before checking in all of his code to TFS. I have access to the physical files. Is there a way for me to access his workspace and check in some of the changes that are still left unchecked in? From tfs I can see which files he has checked out but no way of seeing the exact changes unless very manually.
In TFS 2010, there is a new feature called 'Public Workspaces'. This allows multiple people to **share the same workspace folders** on a computer, but authenticating to TFS using their **own** logon. A TFS administrator can change a workspace to a 'Public Workspace' by running a command like the following: ``` tf workspace /collection:http://yourserver:8080/tfs/yourCollection WorkspaceName;domain\CurrentWorkspaceOwner /permission:Public ``` *(This command can be run on any computer, it doesn't need to be run on the same computer as the workspace you are trying to change)* If there is only one other user that needs to use the workspace, perhaps a simpler method is to just change the owner of the workspace. This can be done by a TFS administrator with the following command: ``` tf workspace /collection:http://yourserver:8080/tfs/yourCollection WorkspaceName;domain\CurrentWorkspaceOwner /newowner:domain\NewWorkspaceOwner ``` Once you have done either of these things, you can logon to that computer as the new owner and use the workspace as if it were your own. You can read more about this feature in this blog post [TFS2010: Public Workspaces](http://blogs.msdn.com/b/granth/archive/2009/11/08/tfs2010-public-workspaces.aspx).
261,752
<p>is it somehow possible to call a rails function or to access a rails object from within jQuery? I'd like to do something like:</p> <pre><code>jQuery(document).ready(function($) { $('#mydiv').html("&lt;%= @object.name %&gt;"); }); </code></pre> <p>OR</p> <pre><code>jQuery(document).ready(function($) { $('#mydiv').html("&lt;%= render :partial =&gt; "contacts" %&gt;"); }); </code></pre> <p>At the moment I'm keeping all my jQuery stuff in my application.js, which is included in my layout. Oh yeah....and I'm not using Rails Edge.</p> <p>Regards,</p> <p>Sebastian</p>
[ { "answer_id": 261913, "author": "changelog", "author_id": 5646, "author_profile": "https://Stackoverflow.com/users/5646", "pm_score": 3, "selected": true, "text": "<p>You'll have to have a method in the controller that will render what you need, if you want to do that. Another way to do it is to use view blocks, like in the end of your layout view</p>\n\n<pre><code>&lt;script type=\"text/javascript\"&gt;\n&lt;%= yield :footerjs %&gt;\n&lt;/script&gt;</code></pre>\n\n<p>and in the view do something like:</p>\n\n<pre><code>&lt;% content_for :footerjs do %&gt;\njQuery(document).ready(function($) {\n$('#mydiv').html('&lt;%= escape_javascript(render :partial => \"contacts\") %&gt;');\n});\n&lt;% end %&gt;</code></pre>\n\n<p>You'll need to make sure that the partial you'll be rendering won't have characters that may cause javascript errors (like finishing the quotes before the end of the string, etc). Also, some browsers don't like multi-line strings, so you'll have to fiddle with that as well.</p>\n" }, { "answer_id": 261987, "author": "Sebastian", "author_id": 29909, "author_profile": "https://Stackoverflow.com/users/29909", "pm_score": 0, "selected": false, "text": "<p>@changelog: thx a lot for your answer. </p>\n\n<p>The problem depicted below the line was solved by enclosing the <code>&lt;%= yield :myjs %&gt;</code> in the appropriate javascript tags as follows:</p>\n\n<pre><code>&lt;script type=\"text/javascript\"&gt;\n&lt;%= yield :myjs %&gt;\n&lt;/script&gt;\n</code></pre>\n\n<p>Thanks again!!</p>\n\n<hr>\n\n<p>I tried to implement it the way you said, but I'm having some difficulties:</p>\n\n<p>I put the following content_for block at the top of my show.html.erb:</p>\n\n<pre><code>&lt;% content_for :myjs do %&gt;\njQuery(document).ready(function($) { alert('hello'); });\n&lt;% end %&gt;\n</code></pre>\n\n<p>In my layout.html I include all javascript as follows (here applications.js implements some general jQuery functions):</p>\n\n<pre><code>&lt;head&gt;\n...\n&lt;%= javascript_include_tag 'jquery', 'application' %&gt;\n&lt;%= javascript_tag \"var AUTH_TOKEN = #{form_authenticity_token.inspect};\" if protect_against_forgery? %&gt;\n&lt;% yield :myjs %&gt;\n&lt;/head&gt;\n&lt;body&gt;\n...\n</code></pre>\n\n<p>The problem is that my javascript doesn't show up in the page's source when I call it. Also the alert function is not called.\nWhen I put in <code>&lt;%= yield :myjs %&gt;</code> instead (with the =) the javascript is rendered at the beginning of my body block, instead of the head, but still the alert function isn't called when I open the page.</p>\n" } ]
2008/11/04
[ "https://Stackoverflow.com/questions/261752", "https://Stackoverflow.com", "https://Stackoverflow.com/users/29909/" ]
is it somehow possible to call a rails function or to access a rails object from within jQuery? I'd like to do something like: ``` jQuery(document).ready(function($) { $('#mydiv').html("<%= @object.name %>"); }); ``` OR ``` jQuery(document).ready(function($) { $('#mydiv').html("<%= render :partial => "contacts" %>"); }); ``` At the moment I'm keeping all my jQuery stuff in my application.js, which is included in my layout. Oh yeah....and I'm not using Rails Edge. Regards, Sebastian
You'll have to have a method in the controller that will render what you need, if you want to do that. Another way to do it is to use view blocks, like in the end of your layout view ``` <script type="text/javascript"> <%= yield :footerjs %> </script> ``` and in the view do something like: ``` <% content_for :footerjs do %> jQuery(document).ready(function($) { $('#mydiv').html('<%= escape_javascript(render :partial => "contacts") %>'); }); <% end %> ``` You'll need to make sure that the partial you'll be rendering won't have characters that may cause javascript errors (like finishing the quotes before the end of the string, etc). Also, some browsers don't like multi-line strings, so you'll have to fiddle with that as well.
261,780
<p>I'm trying to parse dates using the user's date preferences</p> <pre><code>[NSDateFormatter setDefaultFormatterBehavior:NSDateFormatterBehavior10_4]; NSDateFormatter *dateFormatter = [[[NSDateFormatter alloc] init] autorelease]; [dateFormatter setDateStyle:NSDateFormatterShortStyle]; NSDate *date = [ dateFormatter dateFromString:@"7/4/2008" ]; NSLog(@"string from date %@: %@ for locale %@", date, [dateFormatter stringFromDate:date], [[dateFormatter locale] localeIdentifier]); </code></pre> <p>When I set my region (in the International system preferences) to be United States, it prints:</p> <pre><code>2008-08-14 20:20:31.117 Date Difference17226:10b string from date 2008-07-04 00:00:00 -0400: 7/4/08 for locale en_US </code></pre> <p>And when my region is United Kingdom, it prints:</p> <pre><code>2008-08-14 20:19:23.441 Date Difference17199:10b string from date 2008-04-07 00:00:00 -0400: 07/04/2008 for locale en_GB </code></pre> <p>It looks like the NSDateFormatter is insensitive to the change of regions. Notice that the raw printing of the date is properly switching with the region, though.</p> <p>What do I have to do to get the NSDateFormatter to respect the region setting? </p>
[ { "answer_id": 262950, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>This looks correct. In the first output sample, the formatted date string is 7/4/200. In the second, it is 07/04/2008. </p>\n\n<p>What difference were you expecting? </p>\n\n<p>If you did not change your format preferences for the United Kingdom preferred date format, I believe it defaults to MM/DD/YYYY with leading zeros for months and days less than 10.</p>\n" }, { "answer_id": 263027, "author": "Peter Hosey", "author_id": 30461, "author_profile": "https://Stackoverflow.com/users/30461", "pm_score": 2, "selected": false, "text": "<blockquote>\n <p>It looks like the NSDateFormatter is insensitive to the change of regions.</p>\n</blockquote>\n\n<p>No, it is using the locale in both directions.</p>\n\n<p>You can see how the formatter interpreted the date by looking at the date's description (the first <code>%@</code> in your <code>NSLog</code> format).<br>\nWith the region as US, the formatter interpreted the date as 2008-<strong>07-04 (July 4)</strong>.<br>\nWith the region as GB, the formatter interpreted the date as 2008-<strong>04-07 (April 7)</strong>.</p>\n\n<p>Then, you asked the same formatter in the same region to display that date.<br>\nJuly 4 using US format is 07/04/2008 (MM/DD/YYYY).<br>\nApril 7 using GB format is 07/04/2008 (DD/MM/YYYY).</p>\n" } ]
2008/11/04
[ "https://Stackoverflow.com/questions/261780", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14343/" ]
I'm trying to parse dates using the user's date preferences ``` [NSDateFormatter setDefaultFormatterBehavior:NSDateFormatterBehavior10_4]; NSDateFormatter *dateFormatter = [[[NSDateFormatter alloc] init] autorelease]; [dateFormatter setDateStyle:NSDateFormatterShortStyle]; NSDate *date = [ dateFormatter dateFromString:@"7/4/2008" ]; NSLog(@"string from date %@: %@ for locale %@", date, [dateFormatter stringFromDate:date], [[dateFormatter locale] localeIdentifier]); ``` When I set my region (in the International system preferences) to be United States, it prints: ``` 2008-08-14 20:20:31.117 Date Difference17226:10b string from date 2008-07-04 00:00:00 -0400: 7/4/08 for locale en_US ``` And when my region is United Kingdom, it prints: ``` 2008-08-14 20:19:23.441 Date Difference17199:10b string from date 2008-04-07 00:00:00 -0400: 07/04/2008 for locale en_GB ``` It looks like the NSDateFormatter is insensitive to the change of regions. Notice that the raw printing of the date is properly switching with the region, though. What do I have to do to get the NSDateFormatter to respect the region setting?
> > It looks like the NSDateFormatter is insensitive to the change of regions. > > > No, it is using the locale in both directions. You can see how the formatter interpreted the date by looking at the date's description (the first `%@` in your `NSLog` format). With the region as US, the formatter interpreted the date as 2008-**07-04 (July 4)**. With the region as GB, the formatter interpreted the date as 2008-**04-07 (April 7)**. Then, you asked the same formatter in the same region to display that date. July 4 using US format is 07/04/2008 (MM/DD/YYYY). April 7 using GB format is 07/04/2008 (DD/MM/YYYY).
261,783
<p>I am debugging some code and have encountered the following SQL query (simplified version):</p> <pre><code>SELECT ads.*, location.county FROM ads LEFT JOIN location ON location.county = ads.county_id WHERE ads.published = 1 AND ads.type = 13 AND ads.county_id = 2 OR ads.county_id = 5 OR ads.county_id = 7 OR ads.county_id = 9 </code></pre> <p>I'm getting very strange results from the query and I think its because the first OR is negating the AND operators that are found before it.</p> <p>This results in getting results back for ads of all types and not just for the type 13. </p> <p>Each time the query is called there may be a differnt amount of county entities that need to be looked up.</p> <p>Any help on the correct way to go about this would be appreciated. </p>
[ { "answer_id": 261788, "author": "Greg", "author_id": 24181, "author_profile": "https://Stackoverflow.com/users/24181", "pm_score": 8, "selected": true, "text": "<p>Put parentheses around the \"OR\"s:</p>\n\n<pre><code>SELECT ads.*, location.county \nFROM ads\nLEFT JOIN location ON location.county = ads.county_id\nWHERE ads.published = 1 \nAND ads.type = 13\nAND\n(\n ads.county_id = 2\n OR ads.county_id = 5\n OR ads.county_id = 7\n OR ads.county_id = 9\n)\n</code></pre>\n\n<p>Or even better, use IN:</p>\n\n<pre><code>SELECT ads.*, location.county \nFROM ads\nLEFT JOIN location ON location.county = ads.county_id\nWHERE ads.published = 1 \nAND ads.type = 13\nAND ads.county_id IN (2, 5, 7, 9)\n</code></pre>\n" }, { "answer_id": 261791, "author": "Ned Batchelder", "author_id": 14343, "author_profile": "https://Stackoverflow.com/users/14343", "pm_score": 5, "selected": false, "text": "<p>You can try using parentheses around the OR expressions to make sure your query is interpreted correctly, or more concisely, use IN:</p>\n\n<pre><code>SELECT ads.*, location.county \nFROM ads\nLEFT JOIN location ON location.county = ads.county_id\nWHERE ads.published = 1 \nAND ads.type = 13\nAND ads.county_id IN (2,5,7,9)\n</code></pre>\n" }, { "answer_id": 261794, "author": "Ruben", "author_id": 26919, "author_profile": "https://Stackoverflow.com/users/26919", "pm_score": 4, "selected": false, "text": "<p>And even simpler using IN:</p>\n\n<pre><code>SELECT ads.*, location.county \n FROM ads\n LEFT JOIN location ON location.county = ads.county_id\n WHERE ads.published = 1 \n AND ads.type = 13\n AND ads.county_id IN (2,5,7,9)\n</code></pre>\n" } ]
2008/11/04
[ "https://Stackoverflow.com/questions/261783", "https://Stackoverflow.com", "https://Stackoverflow.com/users/319/" ]
I am debugging some code and have encountered the following SQL query (simplified version): ``` SELECT ads.*, location.county FROM ads LEFT JOIN location ON location.county = ads.county_id WHERE ads.published = 1 AND ads.type = 13 AND ads.county_id = 2 OR ads.county_id = 5 OR ads.county_id = 7 OR ads.county_id = 9 ``` I'm getting very strange results from the query and I think its because the first OR is negating the AND operators that are found before it. This results in getting results back for ads of all types and not just for the type 13. Each time the query is called there may be a differnt amount of county entities that need to be looked up. Any help on the correct way to go about this would be appreciated.
Put parentheses around the "OR"s: ``` SELECT ads.*, location.county FROM ads LEFT JOIN location ON location.county = ads.county_id WHERE ads.published = 1 AND ads.type = 13 AND ( ads.county_id = 2 OR ads.county_id = 5 OR ads.county_id = 7 OR ads.county_id = 9 ) ``` Or even better, use IN: ``` SELECT ads.*, location.county FROM ads LEFT JOIN location ON location.county = ads.county_id WHERE ads.published = 1 AND ads.type = 13 AND ads.county_id IN (2, 5, 7, 9) ```
261,801
<p>I have use IlMerge to merge all the dlls of my projects in one exe. I use a targets file which is referenced in the "import" of the main csproj.</p> <p>The ExecCommand in the targets is:</p> <pre><code> &lt;Exec Command="&amp;quot;$(ProgramFiles)\Microsoft\Ilmerge\Ilmerge.exe&amp;quot; /out:@(MainAssembly) &amp;quot;@(IntermediateAssembly)&amp;quot; @(IlmergeAssemblies-&gt;'&amp;quot;%(FullPath)&amp;quot;', ' ')" /&gt; </code></pre> <p>This works. </p> <p>But then I have a Setup Project, when it builds, it ignores the "import" and it doesn't merge the dlls. How can I use the targets file with the Setup Project?</p> <p>I have tried writing this same code for Ilmerge in the Post-build event (in properties of the project) of the main project but it gives me error code 1.</p>
[ { "answer_id": 266642, "author": "Marcus Griep", "author_id": 28645, "author_profile": "https://Stackoverflow.com/users/28645", "pm_score": 2, "selected": false, "text": "<p>I'd recommend that you check out the ILMerge Task in the <a href=\"http://msbuildtasks.tigris.org/\" rel=\"nofollow noreferrer\">MSBuild Community Tasks</a>. Documentation for the ILMerge Task is included in the <a href=\"http://msbuildtasks.tigris.org/servlets/ProjectDocumentList\" rel=\"nofollow noreferrer\">download</a>. It will take away the complexity of specifying the exact command line arguments as you are doing now.</p>\n\n<p>On your specific issue, other than the error code 1, are you getting any other error message as a result? Comment, and I'll edit my response as best I can.</p>\n" }, { "answer_id": 271959, "author": "netadictos", "author_id": 31791, "author_profile": "https://Stackoverflow.com/users/31791", "pm_score": 2, "selected": true, "text": "<p>My solution has been this:\nI put the import in csproj for the Ilmerge targets file which is this:</p>\n\n<pre><code>&lt;Project \n DefaultTargets=\"Build\" \n xmlns=\"http://schemas.microsoft.com/developer/msbuild/2003\"&gt;\n\n &lt;Import Project=\"$(MSBuildBinPath)\\Microsoft.CSharp.targets\" /&gt;\n\n &lt;Target Name=\"AfterBuild\"&gt;\n &lt;CreateItem Include=\"@(ReferencePath)\" Condition=\"'%(CopyLocal)'=='true'\"&gt;\n &lt;Output TaskParameter=\"Include\" ItemName=\"IlmergeAssemblies\"/&gt;\n &lt;/CreateItem&gt;\n\n &lt;Message Text=\"MERGING: @(IlmergeAssemblies-&gt;'%(Filename)')\" Importance=\"High\" /&gt; \n\n &lt;Exec Command=\"&amp;quot;$(ProgramFiles)\\Microsoft\\Ilmerge\\Ilmerge.exe&amp;quot; /out:@(MainAssembly) &amp;quot;@(IntermediateAssembly)&amp;quot; @(IlmergeAssemblies-&gt;'&amp;quot;%(FullPath)&amp;quot;', ' ') /log:ILMerge.log\" /&gt; \n\n &lt;/Target&gt;\n\n &lt;Target Name=\"_CopyFilesMarkedCopyLocal\"/&gt;\n\n&lt;/Project&gt;\n</code></pre>\n\n<p>Then in the setup project i don't include my exe as primary output, i include it as a file, and its localized resources and content.</p>\n\n<p>This works I think, but it is a pity that i couldn't execute the postbuild event of my application (the ilmerge process) before packing it into the setup exe.</p>\n" } ]
2008/11/04
[ "https://Stackoverflow.com/questions/261801", "https://Stackoverflow.com", "https://Stackoverflow.com/users/31791/" ]
I have use IlMerge to merge all the dlls of my projects in one exe. I use a targets file which is referenced in the "import" of the main csproj. The ExecCommand in the targets is: ``` <Exec Command="&quot;$(ProgramFiles)\Microsoft\Ilmerge\Ilmerge.exe&quot; /out:@(MainAssembly) &quot;@(IntermediateAssembly)&quot; @(IlmergeAssemblies->'&quot;%(FullPath)&quot;', ' ')" /> ``` This works. But then I have a Setup Project, when it builds, it ignores the "import" and it doesn't merge the dlls. How can I use the targets file with the Setup Project? I have tried writing this same code for Ilmerge in the Post-build event (in properties of the project) of the main project but it gives me error code 1.
My solution has been this: I put the import in csproj for the Ilmerge targets file which is this: ``` <Project DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> <Import Project="$(MSBuildBinPath)\Microsoft.CSharp.targets" /> <Target Name="AfterBuild"> <CreateItem Include="@(ReferencePath)" Condition="'%(CopyLocal)'=='true'"> <Output TaskParameter="Include" ItemName="IlmergeAssemblies"/> </CreateItem> <Message Text="MERGING: @(IlmergeAssemblies->'%(Filename)')" Importance="High" /> <Exec Command="&quot;$(ProgramFiles)\Microsoft\Ilmerge\Ilmerge.exe&quot; /out:@(MainAssembly) &quot;@(IntermediateAssembly)&quot; @(IlmergeAssemblies->'&quot;%(FullPath)&quot;', ' ') /log:ILMerge.log" /> </Target> <Target Name="_CopyFilesMarkedCopyLocal"/> </Project> ``` Then in the setup project i don't include my exe as primary output, i include it as a file, and its localized resources and content. This works I think, but it is a pity that i couldn't execute the postbuild event of my application (the ilmerge process) before packing it into the setup exe.
261,807
<p>we have a old and dying dedicated server. we want a new one at a new datacenter. we have a bunch of sites using the current server and don't have control of all their DNS. is there an easy way to redirect all the traffic from xx.xx.xx.xx to zz.zz.zz.zz without updating DNS records?</p> <p>Thanks.</p>
[ { "answer_id": 261846, "author": "Corey Trager", "author_id": 9328, "author_profile": "https://Stackoverflow.com/users/9328", "pm_score": 0, "selected": false, "text": "<p>Run software on the old and dying server that would forward the traffic to the new one. In other words, via software like \"iptables\", turn it into a firewall.</p>\n" }, { "answer_id": 261847, "author": "kͩeͣmͮpͥ ͩ", "author_id": 26479, "author_profile": "https://Stackoverflow.com/users/26479", "pm_score": -1, "selected": false, "text": "<p>The short answer is no. Do you think that if it was possible to redirect all traffic from \n<code>208.69.34.231</code> to <code>87.248.113.14</code>, it wouldn't have been done by now?</p>\n\n<p>There are software tools that you can use to relay traffic on certain ports via <code>xx.xx.xx.xx</code> to <code>zz.zz.zz.zz</code> (tunnelling or bridging), but </p>\n\n<ol>\n<li>You'll still have to have a device at <code>xx.xx.xx.xx</code></li>\n<li>The data will have to travel <code>client-&gt;xx.xx.xx.xx.-&gt;zz.zz.zz.zz</code> or <code>zz.zz.zz.zz-&gt;xx.xx.xx.xx-&gt;client</code>, and so it could be slow if the link between xx and zz is slow, or if the device at xx is slow.</li>\n</ol>\n" }, { "answer_id": 261853, "author": "warren", "author_id": 4418, "author_profile": "https://Stackoverflow.com/users/4418", "pm_score": 0, "selected": false, "text": "<p>Another quick route to this would be to:</p>\n\n<ul>\n<li>migrate your data to the new server</li>\n<li>stop the old server</li>\n<li>change the IP address of the new server to the old server</li>\n<li>restart</li>\n</ul>\n\n<p>the whole service shouldn't be offline for more than a couple minutes</p>\n\n<p><strong>edit</strong> updating DNS will certainly be faster, however; I presume you control the authoritativ entries for this server? Change the Time To Live to an absurdly low number (like an hour), update the entry, and let it roll \"naturally\"</p>\n" }, { "answer_id": 261909, "author": "Ian G", "author_id": 31765, "author_profile": "https://Stackoverflow.com/users/31765", "pm_score": 0, "selected": false, "text": "<p>If you were going to keep control of the old IP address you could just use the 404 handler to re-direct pages to the new server, it's ugly, but it should be possible...</p>\n" }, { "answer_id": 261926, "author": "Adam Liss", "author_id": 29157, "author_profile": "https://Stackoverflow.com/users/29157", "pm_score": 3, "selected": true, "text": "<p>Judging from the <code>IIS</code> tag, I'm assuming you're replacing a web server. If that's the case, look into HTTP redirection. One example is here: <a href=\"http://www.somacon.com/p145.php\" rel=\"nofollow noreferrer\">http://www.somacon.com/p145.php</a></p>\n\n<p>This has the advantage of \"telling\" your clients that your page has moved permanently.</p>\n\n<p>If you're not using HTTP, Corey's <code>iptables</code> solution is appropriate. It can silently forward data:</p>\n\n<pre><code>iptables -t nat -I PREROUTING -p tcp -d $OLD_DEST_IP --dport $DEST_PORT -j DNAT --to $NEW_IP\n</code></pre>\n\n<p>Translation: in the <code>nat</code> (Network Address Translation) table, insert a rule in the <code>PREROUTING</code> chain that operates on TCP traffic to the old address:port and DNATs (changes the destination) to the same port at the new address.</p>\n" }, { "answer_id": 262248, "author": "Kyle West", "author_id": 34133, "author_profile": "https://Stackoverflow.com/users/34133", "pm_score": 0, "selected": false, "text": "<p>WOW. What a lot of answers in a short amount of time. This young community is incredible.</p>\n\n<p>Yes, we are replacing web servers, and potentially switching hosting providers (hence the inability to just replace the current server with a new one on the new IP).</p>\n\n<p>We host custom web-applications for a number of clients who can use their own domain names. While we'll instruct them to update their DNS records there is no guarantee of when (or if) they will so we need a temporary solution until we can assure they will.</p>\n\n<p>Does anyone know the performance penalty of using something like IPTABLES, noting the 2 servers will be in physically different locations? </p>\n" }, { "answer_id": 47167298, "author": "124697", "author_id": 521180, "author_profile": "https://Stackoverflow.com/users/521180", "pm_score": 0, "selected": false, "text": "<p>The way I solved this issue is by using a program called ddproxy and forwarded all traffic to port 80 to another IP</p>\n" } ]
2008/11/04
[ "https://Stackoverflow.com/questions/261807", "https://Stackoverflow.com", "https://Stackoverflow.com/users/34133/" ]
we have a old and dying dedicated server. we want a new one at a new datacenter. we have a bunch of sites using the current server and don't have control of all their DNS. is there an easy way to redirect all the traffic from xx.xx.xx.xx to zz.zz.zz.zz without updating DNS records? Thanks.
Judging from the `IIS` tag, I'm assuming you're replacing a web server. If that's the case, look into HTTP redirection. One example is here: <http://www.somacon.com/p145.php> This has the advantage of "telling" your clients that your page has moved permanently. If you're not using HTTP, Corey's `iptables` solution is appropriate. It can silently forward data: ``` iptables -t nat -I PREROUTING -p tcp -d $OLD_DEST_IP --dport $DEST_PORT -j DNAT --to $NEW_IP ``` Translation: in the `nat` (Network Address Translation) table, insert a rule in the `PREROUTING` chain that operates on TCP traffic to the old address:port and DNATs (changes the destination) to the same port at the new address.
261,809
<p>If an interface inherits IEquatable the implementing class can define the behavior of the Equals method. Is it possible to define the behavior of == operations?</p> <pre><code>public interface IFoo : IEquatable {} public class Foo : IFoo { // IEquatable.Equals public bool Equals(IFoo other) { // Compare by value here... } } </code></pre> <p>To check that two IFoo references are equal by comparing their values: </p> <pre><code>IFoo X = new Foo(); IFoo Y = new Foo(); if (X.Equals(Y)) { // Do something } </code></pre> <p>Is it possible to make <code>if (X == Y)</code> use the Equals method on Foo?</p>
[ { "answer_id": 261813, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 4, "selected": true, "text": "<p>No - you can't specify operators in interfaces (mostly because operators are static). The compiler determines which overload of == to call based purely on their static type (i.e. polymorphism isn't involved) and interfaces can't specify the code to say \"return the result of calling X.Equals(Y)\".</p>\n" }, { "answer_id": 261838, "author": "Luc Touraille", "author_id": 20984, "author_profile": "https://Stackoverflow.com/users/20984", "pm_score": 0, "selected": false, "text": "<p>No, because interface can't contain operator functions. A solution would be to make IFoo an abstract class instead of an interface :</p>\n\n<pre><code>abstract class IFoo : IEquatable&lt;IFoo&gt; \n{\n public static bool operator ==(IFoo i1, IFoo i2) { return i1.Equals(i2); }\n public static bool operator !=(IFoo i1, IFoo i2) { return !i1.Equals(i2); }\n public abstract bool Equals(IFoo other);\n}\n\nclass Foo : IFoo\n{\n public override bool Equals(IFoo other)\n {\n // Compare\n }\n}\n</code></pre>\n\n<p>Of course, this makes you lose the flexibility provided by interfaces.</p>\n" } ]
2008/11/04
[ "https://Stackoverflow.com/questions/261809", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11367/" ]
If an interface inherits IEquatable the implementing class can define the behavior of the Equals method. Is it possible to define the behavior of == operations? ``` public interface IFoo : IEquatable {} public class Foo : IFoo { // IEquatable.Equals public bool Equals(IFoo other) { // Compare by value here... } } ``` To check that two IFoo references are equal by comparing their values: ``` IFoo X = new Foo(); IFoo Y = new Foo(); if (X.Equals(Y)) { // Do something } ``` Is it possible to make `if (X == Y)` use the Equals method on Foo?
No - you can't specify operators in interfaces (mostly because operators are static). The compiler determines which overload of == to call based purely on their static type (i.e. polymorphism isn't involved) and interfaces can't specify the code to say "return the result of calling X.Equals(Y)".
261,815
<p>What is the upper limit for an autoincrement primary key in SQL Server? What happens when an SQL Server autoincrement primary key reaches its upper limit?</p>
[ { "answer_id": 261822, "author": "Joel Coehoorn", "author_id": 3043, "author_profile": "https://Stackoverflow.com/users/3043", "pm_score": 2, "selected": false, "text": "<p>It depends on the datatype. If you use bigint, you're unlikely to ever overflow. Even a normal int gives you a couple billion rows. I've never overflowed, so I can't tell you what happens if you do.</p>\n" }, { "answer_id": 261840, "author": "Fred", "author_id": 33630, "author_profile": "https://Stackoverflow.com/users/33630", "pm_score": 0, "selected": false, "text": "<p>Data types descriptions:</p>\n\n<pre><code>BIGINT Integer data from -2^63 through 2^63 - 1\n\nINT Integer data from -2^31 through 2^31 - 1\n\nSMALLINT Integer data from -2^15 through 2^15 - 1\n\nTINYINT Integer data from 0 through 255\n</code></pre>\n\n<p>When you reach the upper limit the autoincrement goes to the lower limit.</p>\n" }, { "answer_id": 261868, "author": "CubanX", "author_id": 27555, "author_profile": "https://Stackoverflow.com/users/27555", "pm_score": 6, "selected": true, "text": "<p>Joel's answer is correct, it is the upper limit of whatever datatype you use.</p>\n\n<p>Here's an example of two of them:</p>\n\n<ul>\n<li>int: 2^31-1 (2,147,483,647) </li>\n<li>bigint: 2^63-1 (9,223,372,036,854,775,807)</li>\n</ul>\n\n<p>I have actually hit the limit at a job I worked at. The actual error is:</p>\n\n<pre>\n Msg 8115, Level 16, State 1, Line 1\n Arithmetic overflow error converting IDENTITY to data type int.\n Arithmetic overflow occurred.\n</pre>\n\n<p>There are a couple fixes to this I can think of off the top of my head. Number 1 is probably very hard and not very likely, number 2 is easy, but will probably cause problems in your code base.</p>\n\n<ol>\n<li>If the identity column doesn't matter to you (it's not a Foreign Key, etc.) then you can just reseed the database and reset the identity column.</li>\n<li>Change your identity column to a bigger number. So for example if you've overflowed an int, change your identity column to a big int. Good luck overflowing that :)</li>\n</ol>\n\n<p>There are probably other fixes, but there is no magic bullet easy one. I just hope this doesn't happen in a table that is the center of a bunch of relationships, because if it does, you're in for a lot of pain. It's not a hard fix, just a tedious and long one.</p>\n" }, { "answer_id": 315469, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>I'll tell you what happens.... my data stopped inserting into that specific table. The database still works but I found data missing and inconsistent. With a little research, I found the error table, then ran a manual insert. The error is the same as above.</p>\n\n<p>Had to change the column to BIGINT. On a 26GB database on a somewhat slow server, took about 30 minutes. On the archive version of the database (150GB or so) it took quite a bit longer. </p>\n\n<p>Fortunately, not too many relationships for this table so the pain was pretty slight.</p>\n" }, { "answer_id": 384945, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<p>DBCC CHECKIDENT (SomeTable, RESEED, 1)</p>\n\n<p>This resets the identity to 1 on table 'SomeTable'</p>\n\n<p>Not sure if this is the best way to do this.</p>\n" } ]
2008/11/04
[ "https://Stackoverflow.com/questions/261815", "https://Stackoverflow.com", "https://Stackoverflow.com/users/407003/" ]
What is the upper limit for an autoincrement primary key in SQL Server? What happens when an SQL Server autoincrement primary key reaches its upper limit?
Joel's answer is correct, it is the upper limit of whatever datatype you use. Here's an example of two of them: * int: 2^31-1 (2,147,483,647) * bigint: 2^63-1 (9,223,372,036,854,775,807) I have actually hit the limit at a job I worked at. The actual error is: ``` Msg 8115, Level 16, State 1, Line 1 Arithmetic overflow error converting IDENTITY to data type int. Arithmetic overflow occurred. ``` There are a couple fixes to this I can think of off the top of my head. Number 1 is probably very hard and not very likely, number 2 is easy, but will probably cause problems in your code base. 1. If the identity column doesn't matter to you (it's not a Foreign Key, etc.) then you can just reseed the database and reset the identity column. 2. Change your identity column to a bigger number. So for example if you've overflowed an int, change your identity column to a big int. Good luck overflowing that :) There are probably other fixes, but there is no magic bullet easy one. I just hope this doesn't happen in a table that is the center of a bunch of relationships, because if it does, you're in for a lot of pain. It's not a hard fix, just a tedious and long one.
261,829
<p>I have three closely related applications that are build from the same source code - let's say APP_A, APP_B, and APP_C. APP_C is a superset of APP_B which in turn is a superset of APP_A.</p> <p>So far I've been using a preprocessor define to specify the application being built, which has worked like this.</p> <pre><code>// File: app_defines.h #define APP_A 0 #define APP_B 1 #define APP_C 2 </code></pre> <p>My IDE build options then specify (for example)</p> <pre><code>#define APPLICATION APP_B </code></pre> <p>... and in source code, I will have things like</p> <pre><code>#include "app_defines.h" #if APPLICATION &gt;= APP_B // extra features for APPB and APP_C #endif </code></pre> <p>However, I shot myself in the foot this morning and wasted far to much time by simply omitting the line to #include "app_defines.h" from one file. Everything compiled fine, but the application crashed with AVs at startup.</p> <p>I'd like to know what a better way of handling this would be. Previously, This would normally one of the few times when I'd consider #define could be used (in C++, anyway), but I still goofed up badly and the compiler didn't protect me. </p>
[ { "answer_id": 261843, "author": "JesperE", "author_id": 13051, "author_profile": "https://Stackoverflow.com/users/13051", "pm_score": 1, "selected": false, "text": "<p>If you're using C++, shouldn't your A, B, and C applications inherit from a common ancestor? That would be the OO way to solve the problem.</p>\n" }, { "answer_id": 261893, "author": "Pieter", "author_id": 5822, "author_profile": "https://Stackoverflow.com/users/5822", "pm_score": 1, "selected": false, "text": "<p>The problem is that using a #if directive with a name that's undefined acts as if it's defined as 0. This could be avoided by always doing an #ifdef first, but that's both cumbersome and error prone.</p>\n\n<p>A slightly better way is to use namespace and namespace aliasing.</p>\n\n<p>E.g.</p>\n\n<pre><code>namespace AppA {\n // application A specific\n}\n\nnamespace AppB {\n // application B specific\n}\n</code></pre>\n\n<p>And use you app_defines.h to do namespace aliasing </p>\n\n<pre><code>#if compiler_option_for_appA\n namespace Application = AppA;\n#elif compiler_option_for_appB\n namespace Application = AppB;\n#endif\n</code></pre>\n\n<p>Or, if more complex combinations, namespace nesting</p>\n\n<pre><code>namespace Application\n{\n #if compiler_option_for_appA\n using namespace AppA;\n #elif compiler_option_for_appB\n using namespace AppB;\n #endif\n}\n</code></pre>\n\n<p>Or any combination of the above.</p>\n\n<p>The advantage is that when you forget the header you'll get unknown namespace errors from your compiler i.s.o. of silently failing because APPLICATION is defaulted to 0.</p>\n\n<p>That being said, I've been in a similar situation, I chose to refactor everything into many libraries, of which the vast majority was shared code, and let the version control system handle what goes where in the different application i.s.o. relying on defines etc. in the code.</p>\n\n<p>It works a bit better in my opionon, but I'm aware that happens to be very application specific, YMMV.</p>\n" }, { "answer_id": 261894, "author": "Jere.Jones", "author_id": 19476, "author_profile": "https://Stackoverflow.com/users/19476", "pm_score": 3, "selected": false, "text": "<p>What you are trying to do seems very similar to \"Product lines\". Carnigie Melon University has an excellent page on the pattern here: <a href=\"http://www.sei.cmu.edu/productlines/\" rel=\"noreferrer\">http://www.sei.cmu.edu/productlines/</a></p>\n\n<p>This is basically a way to build different versions of one piece of software with different capabilities. If you imagine something like Quicken Home/Pro/Business then you are on track.</p>\n\n<p>While that may not be exactly what you attempting, the techniques should be helpful.</p>\n" }, { "answer_id": 261919, "author": "fhe", "author_id": 4445, "author_profile": "https://Stackoverflow.com/users/4445", "pm_score": 0, "selected": false, "text": "<p>You might want to have a look at tools that support the development of product lines and foster explicit variant management in a structured way.</p>\n\n<p>One of these tools is pure::variants from <a href=\"http://www.pure-systems.com/\" rel=\"nofollow noreferrer\">pure-systems</a> which is capable of variability management through feature models and of keeping track of the various places a feature is implemented in source code.</p>\n\n<p>You can select a specific subset of feature from the feature model, constraints between features are being checked, and the concrete variant of your product line, that is, a specific set of source code files and defines is created.</p>\n" }, { "answer_id": 261953, "author": "eli", "author_id": 12893, "author_profile": "https://Stackoverflow.com/users/12893", "pm_score": 1, "selected": false, "text": "<p>Do something like this:</p>\n<pre class=\"lang-text prettyprint-override\"><code>CommonApp ├───── AppExtender ├─ = containment\n ▲ ▲ ▲\n │ │ │ ▲ = ineritance\n AppA AppB AppC │\n</code></pre>\n<p>Put your common code in the class CommonApp and put calls to the interface 'AppExtender' at strategic places. For example the AppExtender interface will have functions like afterStartup, afterConfigurationRead, beforeExit, getWindowTitle ...<br><br></p>\n<p>Then in the main of each application, create the correct extender and pass it to the CommonApp:</p>\n<pre class=\"lang-cpp prettyprint-override\"><code> // main_a.cpp\n \n CommonApp application;\n AppA appA;\n application.setExtender(&amp;appA);\n application.run();\n \n // main_a.cpp\n \n CommonApp application;\n AppB appB;\n application.setExtender(&amp;appB);\n application.run();\n</code></pre>\n" }, { "answer_id": 262031, "author": "plinth", "author_id": 20481, "author_profile": "https://Stackoverflow.com/users/20481", "pm_score": 4, "selected": false, "text": "<p>You don't always have to force inheritance relationships in applications that share a common code base. Really.</p>\n\n<p>There's an old UNIX trick where you tailor the behavior of you application based on argv[0], ie, the application name. If I recall correctly (and it's been 20 years since I looked at it), rsh and rlogin are/were the same command. You simply do runtime configuration based on the value of argv[0].</p>\n\n<p>If you want to stick with build configuration, this is the pattern that is typically used. Your build system/makefile defines a symbol on the command like, APP_CONFIG to be a non-zero value then you have a common include file with the configuration nuts and bolts.</p>\n\n<pre><code>#define APP_A 1\n#define APP_B 2\n\n#ifndef APP_CONFIG\n#error \"APP_CONFIG needs to be set\n#endif\n\n#if APP_CONFIG == APP_A\n#define APP_CONFIG_DEFINED\n// other defines\n#endif\n\n#if APP_CONFIG == APP_B\n#define APP_CONFIG_DEFINED\n// other defines\n#endif\n\n#ifndef APP_CONFIG_DEFINED\n#error \"Undefined configuration\"\n#endif\n</code></pre>\n\n<p>This pattern enforces that the configuration is command line defined and is valid.</p>\n" }, { "answer_id": 263651, "author": "James Antill", "author_id": 10314, "author_profile": "https://Stackoverflow.com/users/10314", "pm_score": 1, "selected": false, "text": "<blockquote>\n <p>However, I shot myself in the foot this morning and wasted far to much time by simply omitting the line to #include \"app_defines.h\" from one file. Everything compiled fine, but the application crashed with AVs at startup.</p>\n</blockquote>\n\n<p>There is a simple fix to this problem, turn on the warnings so that if APP_B isn't defined then your project doesn't compile (or at least produces enough warnings so that you know something is wrong).</p>\n" }, { "answer_id": 263687, "author": "orcmid", "author_id": 33810, "author_profile": "https://Stackoverflow.com/users/33810", "pm_score": 2, "selected": false, "text": "<p>It sounds to me that you might look at modularizing your code into separately-compiled elements, building the variants from a selection of common modules and a variant-specific top-level (main) module. </p>\n\n<p>Then control which ones of these parts go into a build by which header files are used in compiling the top level and which .obj files you include into the linker phase. </p>\n\n<p>You might find this a bit of a struggle at first. In the long run you should have a more reliable and verifiable construction and maintenance process. You should also be able to do better testing without worrying about all the #if variations. </p>\n\n<p>I'm hoping that your application is not terribly large just yet and unraveling a modularization of its functions won't have to deal with a big ball of mud.</p>\n\n<p>At some point you might need run-time checks to verify that the build used consistent components for the application configuration you intended, but that can be figured out later. You can also achieve some compile-time consistency checking, but you'll get most of that with header files and signatures of entry points into the subordinate modules that go into a particular combination.</p>\n\n<p>This is the same game whether you are using C++ classes or operating pretty much at the C/C++ common-language level.</p>\n" }, { "answer_id": 807378, "author": "Hexagon", "author_id": 88451, "author_profile": "https://Stackoverflow.com/users/88451", "pm_score": 0, "selected": false, "text": "<p>To address the specific technical problem of not knowing when a preprocessor define is defined or not, there is a simple but effective trick.</p>\n\n<p>Instead of -</p>\n\n<pre><code>#define APP_A 0\n#define APP_B 1\n#define APP_C 2\n</code></pre>\n\n<p>Use -</p>\n\n<pre><code>#define APP_A() 0\n#define APP_B() 1\n#define APP_C() 2\n</code></pre>\n\n<p>And in the place that queries for the version use -</p>\n\n<pre><code>#if APPLICATION &gt;= APP_B()\n// extra features for APPB and APP_C\n#endif\n</code></pre>\n\n<p>(potentially do something with APPLICATION as well in the same spirit).</p>\n\n<p>Trying to use an undefined preprocessor <strong>function</strong> would produce a warning or an error by most compilers (whereas an undefined preprocessor <strong>define</strong> simply evaluates to 0 silently). If the header isn't included, you would immediately notice - especially if you \"treat warnings as errors\".</p>\n" }, { "answer_id": 807464, "author": "oz10", "author_id": 14069, "author_profile": "https://Stackoverflow.com/users/14069", "pm_score": 0, "selected": false, "text": "<p>Check out <a href=\"http://books.google.com/books?id=aJ1av7UFBPwC&amp;dq=alexandrescu+modern+c%2B%2B+design&amp;printsec=frontcover&amp;source=bn&amp;hl=en&amp;ei=hL_5SbblKJK0Ndf4lcQE&amp;sa=X&amp;oi=book_result&amp;ct=result&amp;resnum=4\" rel=\"nofollow noreferrer\">Alexandrescu's Modern C++ Design</a>. He presents the policy based development using templates. Basically, this approach is an extension of the strategy pattern with the difference being that all choices are made at compile time. I think of Alexandrescu's approach as being similar to using the PIMPL idiom, but implementing with templates.</p>\n\n<p>You would use the pre-processing flags in a common header file to choose which implementation that you wanted to compile, and typedef that to a type used in all the template instantiations elsewhere in your code-base.</p>\n" } ]
2008/11/04
[ "https://Stackoverflow.com/questions/261829", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1737/" ]
I have three closely related applications that are build from the same source code - let's say APP\_A, APP\_B, and APP\_C. APP\_C is a superset of APP\_B which in turn is a superset of APP\_A. So far I've been using a preprocessor define to specify the application being built, which has worked like this. ``` // File: app_defines.h #define APP_A 0 #define APP_B 1 #define APP_C 2 ``` My IDE build options then specify (for example) ``` #define APPLICATION APP_B ``` ... and in source code, I will have things like ``` #include "app_defines.h" #if APPLICATION >= APP_B // extra features for APPB and APP_C #endif ``` However, I shot myself in the foot this morning and wasted far to much time by simply omitting the line to #include "app\_defines.h" from one file. Everything compiled fine, but the application crashed with AVs at startup. I'd like to know what a better way of handling this would be. Previously, This would normally one of the few times when I'd consider #define could be used (in C++, anyway), but I still goofed up badly and the compiler didn't protect me.
You don't always have to force inheritance relationships in applications that share a common code base. Really. There's an old UNIX trick where you tailor the behavior of you application based on argv[0], ie, the application name. If I recall correctly (and it's been 20 years since I looked at it), rsh and rlogin are/were the same command. You simply do runtime configuration based on the value of argv[0]. If you want to stick with build configuration, this is the pattern that is typically used. Your build system/makefile defines a symbol on the command like, APP\_CONFIG to be a non-zero value then you have a common include file with the configuration nuts and bolts. ``` #define APP_A 1 #define APP_B 2 #ifndef APP_CONFIG #error "APP_CONFIG needs to be set #endif #if APP_CONFIG == APP_A #define APP_CONFIG_DEFINED // other defines #endif #if APP_CONFIG == APP_B #define APP_CONFIG_DEFINED // other defines #endif #ifndef APP_CONFIG_DEFINED #error "Undefined configuration" #endif ``` This pattern enforces that the configuration is command line defined and is valid.
261,845
<p>I want to use jQuery with asp.net webfoms. Do I need to get a special toolkit so the .net controls spit out friendly Control ID's?</p> <p>Reason being, I don't want to write javascript referencing my html ID's like control_123_asdfcontrol_234.</p> <p>Has this been addressed in version 3.5? (I remember reading you have to get some special dll that makes ID's friendly).</p>
[ { "answer_id": 261857, "author": "kͩeͣmͮpͥ ͩ", "author_id": 26479, "author_profile": "https://Stackoverflow.com/users/26479", "pm_score": 3, "selected": false, "text": "<p>You can use <code>myControlId = \"&lt;%= myControl.ClientID %&gt;\";</code> to output the (non-friendly) id used to reference it in Javascript.</p>\n" }, { "answer_id": 261915, "author": "Jeff Sheldon", "author_id": 33910, "author_profile": "https://Stackoverflow.com/users/33910", "pm_score": 2, "selected": false, "text": "<p>There are a lot of ways to select elements with jQuery. You could do careful Tag/ClassName selection for one.<br/>I don't know of any way to mess around with the id's themselves until ASP.NET 4.0. Of course you could always give the <a href=\"http://www.asp.net/mvc\" rel=\"nofollow noreferrer\">ASP.NET MVC Framework</a> a try.</p>\n" }, { "answer_id": 261917, "author": "ullmark", "author_id": 23044, "author_profile": "https://Stackoverflow.com/users/23044", "pm_score": 1, "selected": false, "text": "<p>Although I haven't heard of that new \"special dll\" you talk about one simple way would be to use</p>\n\n<pre><code>var myControlId; \n</code></pre>\n\n<p>In your separate js-file and then assign the client id to that var in the aspx/ascx.</p>\n\n<p>I too hate server ID:s... ASP.NET MVC is the solution to all the things that annoys me with asp.net webforms (Viewstate... etc etc).</p>\n" }, { "answer_id": 261989, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>You can attach a unique attribute to your controls (I'm not sure if you can do this without extending the base web controls; a quick search <a href=\"http://www.codeproject.com/KB/webforms/customhtmlattributes.aspx\" rel=\"nofollow noreferrer\">revealed only this</a>) and then use the \"element[attribute:value]\" selector.</p>\n" }, { "answer_id": 262086, "author": "Serhat Ozgel", "author_id": 31505, "author_profile": "https://Stackoverflow.com/users/31505", "pm_score": 0, "selected": false, "text": "<p>You can also override UniqueName and / or ClientID properties of the controls in an extending class and return the actual ID.</p>\n\n<pre><code>MyTextBox : Web.UI.TextBox\n{\n // This modifies the generated 'name' attribute\n override UniqueID { get { return ID; } }\n\n // This modifies the generated 'id' attribute\n override ClientID { get{ return ID; } }\n}\n</code></pre>\n" }, { "answer_id": 342508, "author": "CMPalmer", "author_id": 14894, "author_profile": "https://Stackoverflow.com/users/14894", "pm_score": 4, "selected": false, "text": "<p>The easiest way I've found is just to match on the end of the mangled ID for most controls. The exceptions that Know of are radiobutton lists and checkbox lists - you have to be a little trickier with them.</p>\n\n<p>But if you have this in your .aspx page:</p>\n\n<pre><code>&lt;asp:TextBox ID=\"txtExample\" runat=\"server\" /&gt;\n</code></pre>\n\n<p>Then your jQuery can easily find that control, even if it's mangled by the master page rendering, like this:</p>\n\n<pre><code>$(\"[id$=txtExample]\")\n</code></pre>\n\n<p>The <code>$=</code> operator matches the end of the string and the name mangling is always on the front. Once you've done that, you can get the actual mangled ID like this:</p>\n\n<pre><code>$(\"[id$=txtExample]\").attr(\"id\")\n</code></pre>\n\n<p>and then parse that anyway you see fit. </p>\n\n<p>EDIT:\nThis is an easy way, but it may be more of a performance hit than just giving each control a class the same as its old ID.</p>\n\n<p>See this article that Jeff posted a link to on another jQuery optimization question:</p>\n\n<p><strong><a href=\"http://www.componenthouse.com/article-19\" rel=\"noreferrer\">jQuery: Performance Analysis of Selectors</a></strong></p>\n" }, { "answer_id": 46032389, "author": "Naresh Kumar", "author_id": 8504208, "author_profile": "https://Stackoverflow.com/users/8504208", "pm_score": 0, "selected": false, "text": "<p>Try <code>$get('myId')</code>.\nI think this is the way to select an element in non HTML docs.</p>\n" } ]
2008/11/04
[ "https://Stackoverflow.com/questions/261845", "https://Stackoverflow.com", "https://Stackoverflow.com/users/39677/" ]
I want to use jQuery with asp.net webfoms. Do I need to get a special toolkit so the .net controls spit out friendly Control ID's? Reason being, I don't want to write javascript referencing my html ID's like control\_123\_asdfcontrol\_234. Has this been addressed in version 3.5? (I remember reading you have to get some special dll that makes ID's friendly).
The easiest way I've found is just to match on the end of the mangled ID for most controls. The exceptions that Know of are radiobutton lists and checkbox lists - you have to be a little trickier with them. But if you have this in your .aspx page: ``` <asp:TextBox ID="txtExample" runat="server" /> ``` Then your jQuery can easily find that control, even if it's mangled by the master page rendering, like this: ``` $("[id$=txtExample]") ``` The `$=` operator matches the end of the string and the name mangling is always on the front. Once you've done that, you can get the actual mangled ID like this: ``` $("[id$=txtExample]").attr("id") ``` and then parse that anyway you see fit. EDIT: This is an easy way, but it may be more of a performance hit than just giving each control a class the same as its old ID. See this article that Jeff posted a link to on another jQuery optimization question: **[jQuery: Performance Analysis of Selectors](http://www.componenthouse.com/article-19)**
261,867
<p>I'm unable to make a remote connection to an Oracle XE install (through TOAD / SQL Developer). Here's the deal.</p> <p>I set up a new server (windows 2003). The goal was to make a new image with several applications preinstalled, Oracle XE being one of them. Got Oracle installed no problem, connected locally, remotely and had access to the web interface - the one found at <a href="http://127.0.0.1:8081/apex" rel="noreferrer">http://127.0.0.1:8081/apex</a> (Note: I changed the port of the web interface manually as we are running our Tomcat dev environment on 8080). </p> <p>So, everything is going swimmingly, I create the image, wipe the machine and put the newly created image on there. Everything works except Oracle. After much digging, I update the tnsnames.ora file, add environment variables ORACLE_HOME and ORACLE_SID, so I can connect locally. <b>I still can't connect remotely and have completely lost access to the web interface. I've spent 2 days on google and I'm all out of ideas. Please HELP!</b></p>
[ { "answer_id": 263493, "author": "zendar", "author_id": 25732, "author_profile": "https://Stackoverflow.com/users/25732", "pm_score": 1, "selected": false, "text": "<p>Did you check if you have open port 1521 on firewall?</p>\n" }, { "answer_id": 263516, "author": "Manuel Ferreria", "author_id": 4749, "author_profile": "https://Stackoverflow.com/users/4749", "pm_score": 1, "selected": false, "text": "<p>From the Web Interface, you have to login as a DBA [I think], and there is an option in the administration section where you have to activate \"Enable connections from outside\".</p>\n\n<p>EDIT: Full Path : WebInterface -> Administration -> [drop down menu] Manage HTTP Access -> Available from local server and remote clients.</p>\n" }, { "answer_id": 263673, "author": "Gary Myers", "author_id": 25714, "author_profile": "https://Stackoverflow.com/users/25714", "pm_score": 2, "selected": false, "text": "<p>ManuelF relates to access through the web front end, but isn't relevant to local access through the web front end.</p>\n\n<p>You don't say how hostname/address is being handled, or how you are connecting locally.\nIf you are doing \n<code>SQLPLUS / AS SYSDBA</code> then you are attaching directly.\nIf you are doing <code>SQLPLUS user/pass@XE</code> then you are attaching via the listener. If the former works and the latter doesn't, look for a file called listener.ora and check the hostname in there. If you still have problems, try</p>\n\n<pre><code>sqlplus user/[email protected]:1521/XE\n</code></pre>\n\n<p>If that works, then the problem is the tnsnames.ora.</p>\n\n<p>On the remote access, if your image is installed on 'box a', and you want access from 'box b', can you ping 'box a' from 'box b'. \nThen try, on box_b</p>\n\n<pre><code>sqlplus user/pass@box_a:1521/XE\n</code></pre>\n\n<p>This assumes you have an Oracle client, with sql*plus, on box_b. If that works, you'll need to look at the tnsnames.ora file on box_b.\nIf you don't have an Oracle client on box_b, Oracle's SQL Developer can connect through the JDBC thin driver (which doesn't need any Oracle client), and for that you'll need to specify the host, listener port (generally 1521) and sid (XE for express edition)</p>\n" }, { "answer_id": 19714307, "author": "perlyking", "author_id": 1073262, "author_profile": "https://Stackoverflow.com/users/1073262", "pm_score": 0, "selected": false, "text": "<p>I discovered that remote connections were failing to my Ubuntu box because I'd misconfigured the <code>/etc/hosts</code> file. The machine had a static IP set up in <code>/etc/interfaces</code>, but the entry in hosts had the wrong IP address:</p>\n\n<pre><code>127.0.0.1 localhost\n127.0.1.1 fqdn.domain.com myhost\nsta.tic.ip.address fqdn.domain.com myhost\n</code></pre>\n\n<p>The last line had the wrong IP.</p>\n\n<p>As a result, running <code>lnsrctl status</code> did not list the XE service. Once I corrected the hosts file, I restarted the oracle-xe service and remote connections began to work.</p>\n" }, { "answer_id": 34226827, "author": "Kishore", "author_id": 5669387, "author_profile": "https://Stackoverflow.com/users/5669387", "pm_score": 0, "selected": false, "text": "<p>I have similar issue with windows 8.1 running with firewall. I have installed Oracle XE 11g and installed Oracle Application express 5.0.2. Everything is working as expected in the local host / machine. Only issue was unable to login to oracle application express from the remote machine within LAN.</p>\n\n<p>After some research, resolved the issue by adding TNSLSNR executable to windows fire wall settings as below.</p>\n\n<p>System and Security --> Windows Firewall --> Allowed apps</p>\n" }, { "answer_id": 36012150, "author": "Esmaeil MIRZAEE", "author_id": 4501494, "author_profile": "https://Stackoverflow.com/users/4501494", "pm_score": 0, "selected": false, "text": "<p>make sure remote connection is enabled in your machine.\non the local machine connect to <a href=\"http://127.0.0.1:8080/apex\" rel=\"nofollow\"><code>http://localhost:8080/apex/</code></a> as SYSTEM user, then go to <em>Administration</em> and from right side panel choose <em>Manage HTTP Access</em> then in the following window choose</p>\n\n<blockquote>\n <p>Available from local server and remote clients</p>\n</blockquote>\n\n<p>so press apply changes.</p>\n\n<p>In my machine I have to restart to get result.</p>\n" }, { "answer_id": 52917453, "author": "Johann Horvat", "author_id": 1233925, "author_profile": "https://Stackoverflow.com/users/1233925", "pm_score": 1, "selected": false, "text": "<p>Just login into sqlplus as sysdba or system user and let the following command go:</p>\n\n<pre><code>execute dbms_xdb.setListenerLocalAccess(l_access =&gt; FALSE);\n</code></pre>\n" } ]
2008/11/04
[ "https://Stackoverflow.com/questions/261867", "https://Stackoverflow.com", "https://Stackoverflow.com/users/34142/" ]
I'm unable to make a remote connection to an Oracle XE install (through TOAD / SQL Developer). Here's the deal. I set up a new server (windows 2003). The goal was to make a new image with several applications preinstalled, Oracle XE being one of them. Got Oracle installed no problem, connected locally, remotely and had access to the web interface - the one found at <http://127.0.0.1:8081/apex> (Note: I changed the port of the web interface manually as we are running our Tomcat dev environment on 8080). So, everything is going swimmingly, I create the image, wipe the machine and put the newly created image on there. Everything works except Oracle. After much digging, I update the tnsnames.ora file, add environment variables ORACLE\_HOME and ORACLE\_SID, so I can connect locally. **I still can't connect remotely and have completely lost access to the web interface. I've spent 2 days on google and I'm all out of ideas. Please HELP!**
ManuelF relates to access through the web front end, but isn't relevant to local access through the web front end. You don't say how hostname/address is being handled, or how you are connecting locally. If you are doing `SQLPLUS / AS SYSDBA` then you are attaching directly. If you are doing `SQLPLUS user/pass@XE` then you are attaching via the listener. If the former works and the latter doesn't, look for a file called listener.ora and check the hostname in there. If you still have problems, try ``` sqlplus user/[email protected]:1521/XE ``` If that works, then the problem is the tnsnames.ora. On the remote access, if your image is installed on 'box a', and you want access from 'box b', can you ping 'box a' from 'box b'. Then try, on box\_b ``` sqlplus user/pass@box_a:1521/XE ``` This assumes you have an Oracle client, with sql\*plus, on box\_b. If that works, you'll need to look at the tnsnames.ora file on box\_b. If you don't have an Oracle client on box\_b, Oracle's SQL Developer can connect through the JDBC thin driver (which doesn't need any Oracle client), and for that you'll need to specify the host, listener port (generally 1521) and sid (XE for express edition)
261,873
<p>Here is my problem. I have a website in ASP.NET / C# which receives some data via GET/POST</p> <p>This is "user filled" data, but not through a web page, it's a software that contacts my server.</p> <p>Problem is, this software is sending data encoded in ISO-8859-1 (so Café would be sent as Caf%e9 ) and the rest of my SW/DB is Unicode</p> <p>Also the data gets completely mangled, making recovery of what has been sent impossible :/</p> <p>What would be the best way to deal with this?</p> <p>I tried setting Request.ContentEncoding (before reading), but no avail.</p>
[ { "answer_id": 262065, "author": "tsilb", "author_id": 11112, "author_profile": "https://Stackoverflow.com/users/11112", "pm_score": 1, "selected": false, "text": "<p>%e9 is just é but UrlEncoded. Server.UrlDecode your request string.</p>\n" }, { "answer_id": 264658, "author": "Georg", "author_id": 30776, "author_profile": "https://Stackoverflow.com/users/30776", "pm_score": 1, "selected": false, "text": "<p>Look at </p>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/39d1w2xf.aspx\" rel=\"nofollow noreferrer\">How to: Select an Encoding for ASP.NET Web Page Globalization</a></p>\n\n<p>Short:</p>\n\n<p>In the web.config write </p>\n\n<pre><code>&lt;configuration&gt;\n &lt;system.web&gt;\n &lt;globalization\n fileEncoding=\"utf-8\"\n requestEncoding=\"utf-8\"\n responseEncoding=\"utf-8\"\n culture=\"en-US\"\n uiCulture=\"de-DE\"\n /&gt;\n &lt;/system.web&gt;\n&lt;/configuration&gt;\n</code></pre>\n\n<p>Remove the encoding entries in the aspx headers. </p>\n\n<p>If utf-8 not correct try utf-16</p>\n\n<p>I hope this helps.</p>\n" }, { "answer_id": 267923, "author": "Frank Schwieterman", "author_id": 32203, "author_profile": "https://Stackoverflow.com/users/32203", "pm_score": 0, "selected": false, "text": "<p>If I understand you correctly, you are pulling this information out of an HTTP request. I'm going to assume it is the HTTP request body that is in the encoding.</p>\n\n<p>You can use System.Text.Encoding.GetEncoding(...) to retrieve an Encoding object for ISO-8859-1. Then call GetDecoder() on that encoding object, and use it to interpret the request body. Ideally you'd determine the encoding type you load from Encoding.GetEncoding(...) from header values in the request, so servers with different configurations are supported.</p>\n" }, { "answer_id": 277760, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<p>Original author of the question here.</p>\n\n<p>What helped me was Georg suggestion of setting Web.config variables, I put</p>\n\n<p>requestEncoding=\"iso-8859-1\"</p>\n\n<p>And everything works now, thanks!</p>\n" }, { "answer_id": 3333105, "author": "Dorus", "author_id": 402027, "author_profile": "https://Stackoverflow.com/users/402027", "pm_score": 2, "selected": false, "text": "<p>The only thing that worked here was adding the following code to web.config:</p>\n\n<pre><code>&lt;configuration&gt;\n &lt;system.web&gt;\n &lt;globalization requestEncoding=\"iso-8859-1\"/&gt;\n &lt;/system.web&gt;\n&lt;/configuration&gt;\n</code></pre>\n\n<p>And then use</p>\n\n<pre><code>Request[\"varName\"]\n</code></pre>\n\n<p>Do not use <code>HttpUtility.UrlDecode</code> or <code>HttpUtility.UrlEncode</code>, those 2 only work on the raw query string. Request[] already does the decode for you.</p>\n\n<p>Thanks to JamesP for posting the idea himself.</p>\n" } ]
2008/11/04
[ "https://Stackoverflow.com/questions/261873", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
Here is my problem. I have a website in ASP.NET / C# which receives some data via GET/POST This is "user filled" data, but not through a web page, it's a software that contacts my server. Problem is, this software is sending data encoded in ISO-8859-1 (so Café would be sent as Caf%e9 ) and the rest of my SW/DB is Unicode Also the data gets completely mangled, making recovery of what has been sent impossible :/ What would be the best way to deal with this? I tried setting Request.ContentEncoding (before reading), but no avail.
The only thing that worked here was adding the following code to web.config: ``` <configuration> <system.web> <globalization requestEncoding="iso-8859-1"/> </system.web> </configuration> ``` And then use ``` Request["varName"] ``` Do not use `HttpUtility.UrlDecode` or `HttpUtility.UrlEncode`, those 2 only work on the raw query string. Request[] already does the decode for you. Thanks to JamesP for posting the idea himself.
261,888
<p>In our office, we regularly enjoy some rounds of foosball / table football after work. I have put together a small java program that generates random 2vs2 lineups from the available players and stores the match results in a database afterwards.</p> <p>The current prediction of the outcome uses a simple average of all previous match results from the 4 involved players. This gives a very rough estimation, but I'd like to replace it with something more sophisticated, taking into account things like:</p> <ul> <li>players may be good playing as attacker but bad as defender (or vice versa)</li> <li>players do well against a specific opponent / bad against others</li> <li>some teams work well together, others don't</li> <li>skills change over time</li> </ul> <p>What would be the best algorithm to predict the game outcome as accurately as possible?</p> <p>Someone suggested using a neural network for this, which sounds quite interesting... but I do not have enough knowledge on the topic to say if that could work, and I also suspect it might take too many games to be reasonably trained.</p> <p>EDIT:<br> Had to take a longer break from this due to some project deadlines. To make the question more specific:</p> <p>Given the following mysql table containing all matches played so far:</p> <pre><code>table match_result match_id int pk match_start datetime duration int (match length in seconds) blue_defense int fk to table player blue_attack int fk to table player red_defense int fk to table player red_attack int fk to table player score_blue int score_red int </code></pre> <p>How would you write a function predictResult(blueDef, blueAtk, redDef, redAtk) {...}<br> to estimate the outcome as closely as possible, executing any sql, doing calculations or using external libraries?</p>
[ { "answer_id": 261901, "author": "leppie", "author_id": 15541, "author_profile": "https://Stackoverflow.com/users/15541", "pm_score": 2, "selected": false, "text": "<p>Why use a neuralnet? Use statistics, probably the correlation between each player would be good measure.</p>\n" }, { "answer_id": 261906, "author": "Robert Deml", "author_id": 9516, "author_profile": "https://Stackoverflow.com/users/9516", "pm_score": 1, "selected": false, "text": "<p>Just to start let's gather some information:\nFor a given player we need: </p>\n\n<ol>\n<li>the position they played</li>\n<li>the final score</li>\n</ol>\n\n<p>A good attacker will rack up points.\nA good defender will prevents points from being scored.</p>\n\n<p>The real info will be from a good attacker playing against a good defender.</p>\n" }, { "answer_id": 273766, "author": "Eren Aygunes", "author_id": 27980, "author_profile": "https://Stackoverflow.com/users/27980", "pm_score": 0, "selected": false, "text": "<p>Try applying Naive Bayes classifier.</p>\n\n<blockquote>\n <p>Bayesian learning is a probabilistic\n approach which is based on an\n assumption that the quantities of\n interest are governed by probability\n distributions and that optimal\n decisions can be made by reasoning\n about these probabilities together\n with observed data. [Mitchell, T.\n (1997), Machine Learning]</p>\n</blockquote>\n\n<p>The same exact distribution of the players may result in different match results. If your data has a pattern in it, a pattern based on your variables, Naive Bayes classifier may produce good results.</p>\n\n<p>The algorithm is not very complex. I think, one with some knowledge in probability, can understand &amp; apply it.</p>\n\n<p>In intrusion detection systems, it is being used for determining network anomalies, by looking at various network parameters. Bayesian approach may be very successful in particular types of data and produce high TP &amp; low FP rates. But it may also result in high FP rates, depending on your data. Your data will determine the best approach.</p>\n\n<p>You can use Weka (<a href=\"http://www.cs.waikato.ac.nz/~ml/weka/\" rel=\"nofollow noreferrer\">http://www.cs.waikato.ac.nz/~ml/weka/</a>), a data mining software library, and try different algorithms. It contains the Naive Bayes classifier. \nJust try and see.</p>\n" }, { "answer_id": 486747, "author": "BCS", "author_id": 1343, "author_profile": "https://Stackoverflow.com/users/1343", "pm_score": 0, "selected": false, "text": "<p>One option would be to try and guess the point spread as <a href=\"http://en.wikipedia.org/wiki/Linear_regression\" rel=\"nofollow noreferrer\">some sort of linear model</a>. If you have more games than players you, can do a least squares fit of points per player by building a games matrix (+1 for player on one team, -1 for the other, 0 for spectator) for all the games and a result vector for the spreads.</p>\n" }, { "answer_id": 2505021, "author": "Jeff Moser", "author_id": 1869, "author_profile": "https://Stackoverflow.com/users/1869", "pm_score": 4, "selected": true, "text": "<p>Use the TrueSkill algorithm, it is very good at this. I've implemented it for foosball and chess and it works very well. Coworkers have told me that it's almost <em>too</em> good at this.</p>\n\n<p>For complete details on how it works as well as a link to my implementation, see my \"<a href=\"http://www.moserware.com/2010/03/computing-your-skill.html\" rel=\"noreferrer\">Computing Your Skill</a>\" blog post.</p>\n" } ]
2008/11/04
[ "https://Stackoverflow.com/questions/261888", "https://Stackoverflow.com", "https://Stackoverflow.com/users/33805/" ]
In our office, we regularly enjoy some rounds of foosball / table football after work. I have put together a small java program that generates random 2vs2 lineups from the available players and stores the match results in a database afterwards. The current prediction of the outcome uses a simple average of all previous match results from the 4 involved players. This gives a very rough estimation, but I'd like to replace it with something more sophisticated, taking into account things like: * players may be good playing as attacker but bad as defender (or vice versa) * players do well against a specific opponent / bad against others * some teams work well together, others don't * skills change over time What would be the best algorithm to predict the game outcome as accurately as possible? Someone suggested using a neural network for this, which sounds quite interesting... but I do not have enough knowledge on the topic to say if that could work, and I also suspect it might take too many games to be reasonably trained. EDIT: Had to take a longer break from this due to some project deadlines. To make the question more specific: Given the following mysql table containing all matches played so far: ``` table match_result match_id int pk match_start datetime duration int (match length in seconds) blue_defense int fk to table player blue_attack int fk to table player red_defense int fk to table player red_attack int fk to table player score_blue int score_red int ``` How would you write a function predictResult(blueDef, blueAtk, redDef, redAtk) {...} to estimate the outcome as closely as possible, executing any sql, doing calculations or using external libraries?
Use the TrueSkill algorithm, it is very good at this. I've implemented it for foosball and chess and it works very well. Coworkers have told me that it's almost *too* good at this. For complete details on how it works as well as a link to my implementation, see my "[Computing Your Skill](http://www.moserware.com/2010/03/computing-your-skill.html)" blog post.
261,904
<p>I'm playing about with <a href="http://en.wikipedia.org/wiki/Lighttpd" rel="nofollow noreferrer">lighttpd</a> on a small virtual private server. I two domains pointing to the server. I am using the latest version of lighttpd and mod_evhost on Ubuntu 8.10.</p> <ol> <li><p>I'm trying to set up a rule such that if anyone requests <strong>domain.com</strong> or <strong>www.domain.com</strong> they get served from <em>/webroot/domain.com/www/</em></p></li> <li><p>Similarly, if anyone requests <strong>sub.domain.com</strong> they get served from <em>/webroot/domain.com/sub/</em></p></li> <li><p>If people requests <strong>fake.domain.com</strong> (where <em>/webroot/domain.com/fake/</em> does not exist) I would like them served from <em>/webroot/domain.com/www/</em></p></li> </ol> <p>The third requirement isn't quite so important, I can deal with people requesting subdomains that don't exist being served from the server document root of <em>/webroot/server.com/www/</em> even if they requested <strong>fake.domain.com</strong></p> <p>I've included the relevant parts of my lighttpd.conf file below:</p> <pre><code>server.document-root = "/webroot/server.com/www/" // regex to match sub.domain.com $HTTP["host"] =~ "\b[a-zA-Z]\w*\.\b[a-zA-Z]\w*\.\b[a-zA-Z]\w*" { evhost.path-pattern = "/webroot/%0/%3/" } // regex to match domain.com $HTTP["host"] =~ "\b[a-zA-Z]\w*\.\b[a-zA-Z]\w*" { evhost.path-pattern = "/webroot/%0/www/" } </code></pre> <p>So where am I going wrong? At the moment, all requests to <strong>*.domain.com</strong> and <strong>domain.com</strong> are being served from <em>/webroot/domain.com/www/</em></p> <p>I'd appreciate any help you guys could offer and if I've left anything relevant out please tell me!</p> <p>Cheers, Rob</p>
[ { "answer_id": 261940, "author": "Anders", "author_id": 25515, "author_profile": "https://Stackoverflow.com/users/25515", "pm_score": 1, "selected": false, "text": "<p>For your first one, matching <strong>domain.com</strong> and <strong>www.domain.com</strong>: <code>^\\b([wW]{3}\\.)?[\\w\\d]*\\.com\\b$</code>, and for the second one, I am unsure if regex can determine if a subdomain/page exists, as it is for identifying strings of text of interest. Hopefully that will help you out a bit.</p>\n" }, { "answer_id": 261955, "author": "Tomalak", "author_id": 18771, "author_profile": "https://Stackoverflow.com/users/18771", "pm_score": 4, "selected": true, "text": "<p>Your regexes seem to be a bit overdone.</p>\n\n<p>Here is what I would use:</p>\n\n<pre><code>// regex to match sub.domain.com\n$HTTP[\"host\"] =~ \"^[^.]+\\.[^.]+\\.[^.]+$\" {\n evhost.path-pattern = \"/webroot/%0/%3/\" \n}\n\n// regex to match domain.com \n$HTTP[\"host\"] =~ \"^[^.]+\\.[^.]+$\" {\n evhost.path-pattern = \"/webroot/%0/www/\" \n}\n</code></pre>\n\n<p>where:</p>\n\n<pre><code>[^.]+ matches anything but a dot, 1..n times\n</code></pre>\n\n<p>To match only valid sub domains with fall back to \"www\", you can use this:</p>\n\n<pre><code>// default: route everything to \"www\"\n$HTTP[\"host\"] =~ \"([^.]+\\.)?domain\\.com$\" {\n evhost.path-pattern = \"/webroot/%0/www/\"\n}\n\n// specific regex overwrites \"path-pattern\" for valid sub-domains only\n$HTTP[\"host\"] =~ \"^(valid1|valid2|sub)\\.domain\\.com$\" {\n evhost.path-pattern = \"/webroot/%0/%3/\" \n}\n</code></pre>\n" } ]
2008/11/04
[ "https://Stackoverflow.com/questions/261904", "https://Stackoverflow.com", "https://Stackoverflow.com/users/135/" ]
I'm playing about with [lighttpd](http://en.wikipedia.org/wiki/Lighttpd) on a small virtual private server. I two domains pointing to the server. I am using the latest version of lighttpd and mod\_evhost on Ubuntu 8.10. 1. I'm trying to set up a rule such that if anyone requests **domain.com** or **www.domain.com** they get served from */webroot/domain.com/www/* 2. Similarly, if anyone requests **sub.domain.com** they get served from */webroot/domain.com/sub/* 3. If people requests **fake.domain.com** (where */webroot/domain.com/fake/* does not exist) I would like them served from */webroot/domain.com/www/* The third requirement isn't quite so important, I can deal with people requesting subdomains that don't exist being served from the server document root of */webroot/server.com/www/* even if they requested **fake.domain.com** I've included the relevant parts of my lighttpd.conf file below: ``` server.document-root = "/webroot/server.com/www/" // regex to match sub.domain.com $HTTP["host"] =~ "\b[a-zA-Z]\w*\.\b[a-zA-Z]\w*\.\b[a-zA-Z]\w*" { evhost.path-pattern = "/webroot/%0/%3/" } // regex to match domain.com $HTTP["host"] =~ "\b[a-zA-Z]\w*\.\b[a-zA-Z]\w*" { evhost.path-pattern = "/webroot/%0/www/" } ``` So where am I going wrong? At the moment, all requests to **\*.domain.com** and **domain.com** are being served from */webroot/domain.com/www/* I'd appreciate any help you guys could offer and if I've left anything relevant out please tell me! Cheers, Rob
Your regexes seem to be a bit overdone. Here is what I would use: ``` // regex to match sub.domain.com $HTTP["host"] =~ "^[^.]+\.[^.]+\.[^.]+$" { evhost.path-pattern = "/webroot/%0/%3/" } // regex to match domain.com $HTTP["host"] =~ "^[^.]+\.[^.]+$" { evhost.path-pattern = "/webroot/%0/www/" } ``` where: ``` [^.]+ matches anything but a dot, 1..n times ``` To match only valid sub domains with fall back to "www", you can use this: ``` // default: route everything to "www" $HTTP["host"] =~ "([^.]+\.)?domain\.com$" { evhost.path-pattern = "/webroot/%0/www/" } // specific regex overwrites "path-pattern" for valid sub-domains only $HTTP["host"] =~ "^(valid1|valid2|sub)\.domain\.com$" { evhost.path-pattern = "/webroot/%0/%3/" } ```
261,910
<p>Would you please help me in making a rollover effect using jquery, what i want to do is when someone hover over any of the menu items the text slide down and disappear and a picture slides from the top down to the center (e.g. you could see this effect here <a href="http://www.iviewcom.com/panda" rel="nofollow noreferrer">panda</a> as you can see the picture slide down from the top but the text does not slide down which is not what want).</p> <p>I know it can be easily done using flash but i don't want my menu in flash as that would be a bad practice. </p> <p>can you tell me what do i need to change in my menu HTML and what jquery functions should i use.</p> <p><strong>Thanks So much for your help</strong></p> <p>P.S. this my menu HTML and you can see my menu here </p> <pre><code>&lt;ul class="nav"&gt; &lt;li class="active first"&gt;&lt;a href="#" class="home"&gt;Home&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#" class="news"&gt;News&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#" class="offers"&gt;Special offers&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#" class="private"&gt;Private label&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#" class="locations"&gt;Locations&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#" class="about"&gt;About us&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#" class="jobs"&gt;Jobs&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#" class="contact"&gt;Contact us&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#" class="mm"&gt;Multimedia&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt; </code></pre> <p>MENU: </p> <p><img src="https://i.stack.imgur.com/8ANuL.jpg" alt="alt text"></p>
[ { "answer_id": 262200, "author": "shiftins", "author_id": 8162, "author_profile": "https://Stackoverflow.com/users/8162", "pm_score": 3, "selected": false, "text": "<p>Instead of doing it for you, I'll offer some places to start looking.. </p>\n\n<p>Here is an example that could be easily modified to use 'rollover' instead of 'click': <a href=\"http://css-tricks.com/examples/MenuFader/\" rel=\"noreferrer\">http://css-tricks.com/examples/MenuFader/</a></p>\n\n<p>Details on how the above example was put together (the tutorial):\n<a href=\"http://css-tricks.com/learning-jquery-fading-menu-replacing-content/\" rel=\"noreferrer\">http://css-tricks.com/learning-jquery-fading-menu-replacing-content/</a></p>\n\n<p>I found this tutorial by searching on Google for \"jquery effects examples\":\n<a href=\"http://www.google.com/search?hl=en&amp;q=jquery+effects+examples&amp;btnG=Google+Search&amp;aq=f&amp;oq=\" rel=\"noreferrer\">http://www.google.com/search?hl=en&amp;q=jquery+effects+examples&amp;btnG=Google+Search&amp;aq=f&amp;oq=</a> and clicking on the first and second links.</p>\n\n<p>Good luck with your Jquery project. </p>\n" }, { "answer_id": 444189, "author": "riceboyler", "author_id": 34314, "author_profile": "https://Stackoverflow.com/users/34314", "pm_score": 0, "selected": false, "text": "<p>First things first, you'll really want to give your independent anchor tags ids, as it will make accomplishing what you're wanting much easier.</p>\n\n<p>Look at the slideDown(), and slideToggle() functions, and it would basically require you setting up hidden divs and then on the mouseover event, you would slidetoggle your text out and the hidden image div in, and on mouseout do the opposite.</p>\n\n<p>Good luck, jQuery is a lot of fun to work with. Play with it and see what you can blow up!</p>\n" } ]
2008/11/04
[ "https://Stackoverflow.com/questions/261910", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
Would you please help me in making a rollover effect using jquery, what i want to do is when someone hover over any of the menu items the text slide down and disappear and a picture slides from the top down to the center (e.g. you could see this effect here [panda](http://www.iviewcom.com/panda) as you can see the picture slide down from the top but the text does not slide down which is not what want). I know it can be easily done using flash but i don't want my menu in flash as that would be a bad practice. can you tell me what do i need to change in my menu HTML and what jquery functions should i use. **Thanks So much for your help** P.S. this my menu HTML and you can see my menu here ``` <ul class="nav"> <li class="active first"><a href="#" class="home">Home</a></li> <li><a href="#" class="news">News</a></li> <li><a href="#" class="offers">Special offers</a></li> <li><a href="#" class="private">Private label</a></li> <li><a href="#" class="locations">Locations</a></li> <li><a href="#" class="about">About us</a></li> <li><a href="#" class="jobs">Jobs</a></li> <li><a href="#" class="contact">Contact us</a></li> <li><a href="#" class="mm">Multimedia</a></li> </ul> ``` MENU: ![alt text](https://i.stack.imgur.com/8ANuL.jpg)
Instead of doing it for you, I'll offer some places to start looking.. Here is an example that could be easily modified to use 'rollover' instead of 'click': <http://css-tricks.com/examples/MenuFader/> Details on how the above example was put together (the tutorial): <http://css-tricks.com/learning-jquery-fading-menu-replacing-content/> I found this tutorial by searching on Google for "jquery effects examples": <http://www.google.com/search?hl=en&q=jquery+effects+examples&btnG=Google+Search&aq=f&oq=> and clicking on the first and second links. Good luck with your Jquery project.
261,920
<p>Which method is preferred?</p> <pre><code>Session.Remove("foo"); Session["foo"] = null; </code></pre> <p>Is there a difference?</p>
[ { "answer_id": 261946, "author": "dove", "author_id": 30913, "author_profile": "https://Stackoverflow.com/users/30913", "pm_score": 3, "selected": false, "text": "<p>I would go with Remove but can not honestly say if there is a difference. At a guess there may still be an empty key kept for that null value but not sure. Remove would give me little doubt and if that's what you want to do it <strong>reads better</strong> in code as well.</p>\n" }, { "answer_id": 261980, "author": "splattne", "author_id": 6461, "author_profile": "https://Stackoverflow.com/users/6461", "pm_score": 4, "selected": false, "text": "<p>It has the same effect. I personally think that the <code>Session.Remove</code> method does express the programmer's intent better.</p>\n\n<p>Here some links to the documentation on MSDN:</p>\n\n<ul>\n<li><a href=\"http://msdn.microsoft.com/en-us/library/system.web.sessionstate.httpsessionstate.aspx\" rel=\"noreferrer\">HttpSessionState Class</a></li>\n<li><a href=\"http://msdn.microsoft.com/en-us/library/8dhkksh8.aspx\" rel=\"noreferrer\">HttpSessionState.Item Property (String)</a></li>\n</ul>\n\n<p><em>\"HttpSessionState.Item Property:<br /><br />Property Value\nType: System.Object<br /><br />\nThe session-state value with the specified name, or null reference (Nothing in Visual Basic) if the item does not exist.\"</em></p>\n" }, { "answer_id": 262095, "author": "Buu", "author_id": 17815, "author_profile": "https://Stackoverflow.com/users/17815", "pm_score": 8, "selected": true, "text": "<blockquote>\n <p>Is there a difference?</p>\n</blockquote>\n\n<p>There is.\n<code>Session.Remove(key)</code> deletes the entry (both key &amp; value) from the dictionary while <code>Session[key] = null</code> assigns a value (which happens to be null) to a key. After the former call, the key won't appear in the <code>Session#Keys</code> collection. But after the latter, the key can still be found in the key collection.</p>\n" }, { "answer_id": 262120, "author": "FlySwat", "author_id": 1965, "author_profile": "https://Stackoverflow.com/users/1965", "pm_score": 2, "selected": false, "text": "<p>The biggest difference is how you read from session.</p>\n\n<pre><code>if(Session.ContainsKey[\"foo\"]) { return Session[\"foo\"]; }\n</code></pre>\n\n<p>or</p>\n\n<pre><code>if(Session[\"foo\"] != null) { return Session[\"foo\"]; }\n</code></pre>\n\n<p>If you use the first method, setting the value to null will not work, and you should use remove.</p>\n\n<p>If you use the second method, you can set the value to null.</p>\n" }, { "answer_id": 4133360, "author": "JakubRi", "author_id": 501835, "author_profile": "https://Stackoverflow.com/users/501835", "pm_score": 5, "selected": false, "text": "<p>I know this is old thread but definitely stick with <code>Session[\"key\"] = null</code> - it's much more faster! I've done some tests (on InProc Session State), removing 1000 items in row (elapsed time is for 1000 items totally, so if you want average time for one item, just divide it with 1000):</p>\n\n<p>Removing 1000 existing items:</p>\n\n<pre><code>Session[key] = null; - 0.82380000000000009 ms\nSession.Remove(key); - 59.960100000000004 ms\n</code></pre>\n\n<p>Removing 1000 NOT existing items:</p>\n\n<pre><code>Session[key] = null; - 1.5368000000000002 ms\nSession.Remove(key); - 0.6621 ms\n</code></pre>\n\n<p>Removing 500 existing and 500 not existing items:</p>\n\n<pre><code>Session[key] = null; - 1.0432000000000001 ms\nSession.Remove(key); - 33.9502 ms\n</code></pre>\n\n<p>Here is a piece of code for first test:</p>\n\n<pre><code>Session.Clear();\n\nfor (int i = 0; i &lt; 1000; i++)\n Session[i.ToString()] = new object();\n\nStopwatch sw1 = Stopwatch.StartNew();\nfor (int i = 0; i &lt; 1000; i++)\n Session[i.ToString()] = null;\nsw1.Stop();\n\nSession.Clear();\n\nfor (int i = 0; i &lt; 1000; i++)\n Session[i.ToString()] = new object();\n\nStopwatch sw2 = Stopwatch.StartNew();\nfor (int i = 0; i &lt; 1000; i++)\n Session.Remove(i.ToString());\nsw2.Stop();\n</code></pre>\n" } ]
2008/11/04
[ "https://Stackoverflow.com/questions/261920", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2469/" ]
Which method is preferred? ``` Session.Remove("foo"); Session["foo"] = null; ``` Is there a difference?
> > Is there a difference? > > > There is. `Session.Remove(key)` deletes the entry (both key & value) from the dictionary while `Session[key] = null` assigns a value (which happens to be null) to a key. After the former call, the key won't appear in the `Session#Keys` collection. But after the latter, the key can still be found in the key collection.
261,924
<p>I'll simplify the problem as much as possible:</p> <p>I have an oracle table:</p> <pre><code>row_priority, col1, col2, col3 0, .1, 100, {null} 12, {null}, {null}, 3 24, .2, {null}, {null} </code></pre> <p>Desired result:</p> <pre><code>col1, col2, col3 .2, 100, 3 </code></pre> <p>So according to the priority of the row, it overrides previous row values, if given.</p> <p>I'm attempting to work out a solution using analytical functions over the table, but it just isn't behaving...</p> <p>I try:</p> <pre><code>select last_value(col1 ignore nulls) over () col1, last_value(col2 ignore nulls) over () col2, last_value(col3 ignore nulls) over () col3 from (select * from THE_TABLE order by row_priority) where rownum = 1 </code></pre> <p>or the inverse:</p> <pre><code>select first_value(col1 ignore nulls) over () col1, first_value(col2 ignore nulls) over () col2, first_value(col3 ignore nulls) over () col3 from (select * from THE_TABLE order by row_priority desc) where rownum = 1 </code></pre> <p>And neither seem to ignore nulls. Any hints?</p>
[ { "answer_id": 261941, "author": "Alan", "author_id": 5878, "author_profile": "https://Stackoverflow.com/users/5878", "pm_score": -1, "selected": false, "text": "<p>The COALESCE function may be of help to you here. Perhaps like ...</p>\n\n<pre><code>select first_value(coalesce(col1,0) ignore nulls) over () col1,\n first_value(coalesce(col2,0) ignore nulls) over () col2,\n first_value(coalesce(col3,0) ignore nulls) over () col3\nfrom THE_TABLE\n</code></pre>\n" }, { "answer_id": 261995, "author": "ScottCher", "author_id": 24179, "author_profile": "https://Stackoverflow.com/users/24179", "pm_score": 3, "selected": true, "text": "<p>You need to put rownum = 1 OUTSIDE the analytical query</p>\n\n<pre><code>SELECT *\nFROM ( select last_value(col1 ignore nulls) over () col1,\n last_value(col2 ignore nulls) over () col2,\n last_value(col3 ignore nulls) over () col3\n from (select * from THE_TABLE ORDER BY ROW_PRIORITY)\n )\nWHERE ROWNUM = 1\n</code></pre>\n\n<p>which results in (using your values above):</p>\n\n<pre><code>COL1 COL2 COL3\n------ ------- ----\n0.2 100 3\n</code></pre>\n" }, { "answer_id": 262815, "author": "Dave Costa", "author_id": 6568, "author_profile": "https://Stackoverflow.com/users/6568", "pm_score": -1, "selected": false, "text": "<p>An alternative:</p>\n\n<pre><code>SELECT\n MAX(col1) KEEP (DENSE_RANK LAST ORDER BY row_priority),\n MAX(col2) KEEP (DENSE_RANK LAST ORDER BY row_priority),\n MAX(col3) KEEP (DENSE_RANK LAST ORDER BY row_priority)\nFROM the_table\n</code></pre>\n\n<p>The performance of this may be different from the analytic version; whether it is better or worse depends on your data and environment.</p>\n" } ]
2008/11/04
[ "https://Stackoverflow.com/questions/261924", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18941/" ]
I'll simplify the problem as much as possible: I have an oracle table: ``` row_priority, col1, col2, col3 0, .1, 100, {null} 12, {null}, {null}, 3 24, .2, {null}, {null} ``` Desired result: ``` col1, col2, col3 .2, 100, 3 ``` So according to the priority of the row, it overrides previous row values, if given. I'm attempting to work out a solution using analytical functions over the table, but it just isn't behaving... I try: ``` select last_value(col1 ignore nulls) over () col1, last_value(col2 ignore nulls) over () col2, last_value(col3 ignore nulls) over () col3 from (select * from THE_TABLE order by row_priority) where rownum = 1 ``` or the inverse: ``` select first_value(col1 ignore nulls) over () col1, first_value(col2 ignore nulls) over () col2, first_value(col3 ignore nulls) over () col3 from (select * from THE_TABLE order by row_priority desc) where rownum = 1 ``` And neither seem to ignore nulls. Any hints?
You need to put rownum = 1 OUTSIDE the analytical query ``` SELECT * FROM ( select last_value(col1 ignore nulls) over () col1, last_value(col2 ignore nulls) over () col2, last_value(col3 ignore nulls) over () col3 from (select * from THE_TABLE ORDER BY ROW_PRIORITY) ) WHERE ROWNUM = 1 ``` which results in (using your values above): ``` COL1 COL2 COL3 ------ ------- ---- 0.2 100 3 ```
261,927
<p>I have been running Apache HTTPD in 64bit mode by stripping out the 32bit architecture from the binary (along with the ppc parts). I did this to make it more compatible for python and mysql.</p> <p>However I have another machine that needs it to be run in 32bit mode (it has all four original architectures still in it). Is it possible to make sure that it is running in 32 bit mode and that anything compiled against it uses said mode.</p> <p>Are my options limited to stripping it, or are there start up optiosn that I do not know about.</p>
[ { "answer_id": 263200, "author": "Dave Dribin", "author_id": 26825, "author_profile": "https://Stackoverflow.com/users/26825", "pm_score": 3, "selected": true, "text": "<p>You can use the <a href=\"http://developer.apple.com/documentation/Darwin/Reference/ManPages/man1/arch.1.html\" rel=\"nofollow noreferrer\"><code>arch(1)</code></a> command to change the which architecture is used. This will try Intel 32-bit first and then PPC 32-bit:</p>\n\n<pre><code>% arch -i386 -ppc /usr/sbin/httpd\n</code></pre>\n" }, { "answer_id": 270971, "author": "Rizwan Kassim", "author_id": 35335, "author_profile": "https://Stackoverflow.com/users/35335", "pm_score": 0, "selected": false, "text": "<p>Note that doing so will prevent apache from loading any 64bit shared modules - if you're using EntropyPHP, for instance, this can be a problem.</p>\n" }, { "answer_id": 726389, "author": "Michael Cramer", "author_id": 1496728, "author_profile": "https://Stackoverflow.com/users/1496728", "pm_score": 2, "selected": false, "text": "<p>This method will make a copy of the Apache binary and ensure that apachectl (and hence, the normal OS config) will properly start the 32-bit version:</p>\n\n<p>First, create the 32-bit version of httpd:</p>\n\n<pre><code>sudo lipo -thin i386 /usr/sbin/httpd -output /usr/sbin/httpd.i386\n</code></pre>\n\n<p>Second, edit the system configuration so it uses the new version instead of the default. Change \"/usr/sbin/httpd\" to \"/usr/sbin/httpd.i386\":</p>\n\n<pre><code>sudo vi /System/Library/LaunchDaemons/org.apache.httpd.plist\n</code></pre>\n\n<p>Lastly, restart Apache:</p>\n\n<pre><code>sudo apachectl restart\n</code></pre>\n" } ]
2008/11/04
[ "https://Stackoverflow.com/questions/261927", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3431280/" ]
I have been running Apache HTTPD in 64bit mode by stripping out the 32bit architecture from the binary (along with the ppc parts). I did this to make it more compatible for python and mysql. However I have another machine that needs it to be run in 32bit mode (it has all four original architectures still in it). Is it possible to make sure that it is running in 32 bit mode and that anything compiled against it uses said mode. Are my options limited to stripping it, or are there start up optiosn that I do not know about.
You can use the [`arch(1)`](http://developer.apple.com/documentation/Darwin/Reference/ManPages/man1/arch.1.html) command to change the which architecture is used. This will try Intel 32-bit first and then PPC 32-bit: ``` % arch -i386 -ppc /usr/sbin/httpd ```
261,938
<p>If everything that can be accomplished in <a href="http://en.wikipedia.org/wiki/MXML" rel="nofollow noreferrer">MXML</a> can also be accomplished in ActionScript and many things are easier to accomplish in ActionScript (loops, conditionals, etc) why take the time to learn MXML?</p> <p>The best reasons I have at this point are that the structure of the MXML nicely matches the visual hierarchy of the UI components and that the lines of code to initialize the UI are reduced. On the other hand real-world UIs are often dynamic, implemented as a simple static structure and then filled in dynamically based on runtime conditions (in which case UI updates are in ActionScript anyway). It would also be possible to reduce the <a href="http://en.wikipedia.org/wiki/Source_lines_of_code" rel="nofollow noreferrer">SLOC</a> needed for ActionScript with the creation of a few helper methods.</p>
[ { "answer_id": 261961, "author": "Eric Minkes", "author_id": 1172, "author_profile": "https://Stackoverflow.com/users/1172", "pm_score": 0, "selected": false, "text": "<p>Designing UI elements with mxml and the visual designer is much easier than in code, and less error-prone in my opinion.</p>\n\n<p>Even if the UI changes dynamically, often this means swapping pre-defined UI elements in and out.</p>\n" }, { "answer_id": 261975, "author": "David Arno", "author_id": 7122, "author_profile": "https://Stackoverflow.com/users/7122", "pm_score": 0, "selected": false, "text": "<p>If you use FlexBuilder then MXML is useful for laying out an application as FlexBuilder can read/ write MXML in the design view. Also it is far easier to implement states via MXML.</p>\n\n<p>If you do not use a tool such as FlexBuilder that has a design view, then it may be less useful. Remember though that Flex4 is due to introduce the new Thermo stuff, which includes the ability to create vector graphics using MXML notation, and will allow MXML to be used to skin the Flex components. It'll likely come into its own then. You'll have an advantage at that point if you have already learned your way around MXML.</p>\n" }, { "answer_id": 264212, "author": "fenomas", "author_id": 10651, "author_profile": "https://Stackoverflow.com/users/10651", "pm_score": 0, "selected": false, "text": "<p>Are you saying that you're going to use the Flex framework, but are choosing whether to use MXML or work dynamically in AS? If so, then the chief advantage of MXML is integration with the design interface. If having access to the WYSIWYG interface is not of value to you, then you may find that there's little difference between MXML and pure AS.</p>\n\n<p>If you're asking about using MXML vs. using FLA files, then that's a very different question though - it amounts to \"why should I use the Flex Framework?\"</p>\n" }, { "answer_id": 522572, "author": "Matt Guest", "author_id": 62230, "author_profile": "https://Stackoverflow.com/users/62230", "pm_score": 4, "selected": false, "text": "<p>It depends on your application's needs, but I generally break my design into visual chunks and use custom MXML components to lay out the main areas and components of my application (data panels, dialog boxes, etc) using mxml based custom components. Then I'll augment that with custom actionscript components where I need more visual flexibilty than the built in layout components provide. MXML is handy because it makes it extremely easy to get components on the stage and set their various properties and style settings.</p>\n\n<p>Take this example of two identical login panels:</p>\n\n<p>In MXML:</p>\n\n<pre><code>&lt;mx:Panel xmlns:mx=\"http://www.adobe.com/2006/mxml\" layout=\"absolute\" width=\"290\" height=\"148\" title=\"Login\"&gt;\n &lt;mx:Label text=\"User name:\" width=\"80\" textAlign=\"right\" y=\"8\" x=\"8\"/&gt;\n &lt;mx:Label text=\"Password:\" width=\"80\" textAlign=\"right\" y=\"38\" x=\"8\"/&gt;\n &lt;mx:TextInput id=\"txtUsername\" maxChars=\"20\" y=\"8\" x=\"90\"/&gt;\n &lt;mx:TextInput id=\"txtPassword\" displayAsPassword=\"true\" y=\"38\" x=\"90\" maxChars=\"20\"/&gt;\n &lt;mx:Button x=\"185\" y=\"68\" label=\"Login\" id=\"btnLogin\" click=\"doLogin()\"/&gt;\n&lt;/mx:Panel&gt;\n</code></pre>\n\n<p>And in actionscript:</p>\n\n<pre><code>package\n{\n import flash.events.MouseEvent;\n\n import mx.containers.Panel;\n import mx.controls.Button;\n import mx.controls.Label;\n import mx.controls.TextInput;\n\n public class MyLoginPanel extends Panel\n {\n\n private var _unLabel:Label;\n private var _passLabel:Label;\n private var _txtUsername:TextInput;\n private var _txtPassword:TextInput;\n private var _btnLogin:Button;\n\n public function MyLoginPanel()\n {\n }\n\n override protected function createChildren():void\n {\n super.createChildren();\n\n this.width = 290;\n this.height = 148;\n this.title = \"Login\";\n this.layout = \"absolute\";\n\n _unLabel = new Label();\n _unLabel.text = \"User Name:\";\n _unLabel.width = 80;\n _unLabel.setStyle(\"textAlign\", \"right\");\n _unLabel.move(8, 8);\n this.addChild(_unLabel);\n\n _passLabel = new Label();\n _passLabel.text = \"Password:\";\n _passLabel.width = 80;\n _passLabel.setStyle(\"textAlign\", \"right\");\n _passLabel.move(8, 38);\n this.addChild(_passLabel);\n\n _txtUsername = new TextInput();\n _txtUsername.move(90, 8);\n this.addChild(_txtUsername);\n\n _txtPassword = new TextInput();\n _txtPassword.move(90, 38);\n _txtPassword.displayAsPassword = true;\n this.addChild(_txtPassword);\n\n _btnLogin = new Button();\n _btnLogin.label = \"Login\";\n _btnLogin.move(185, 68);\n _btnLogin.addEventListener(MouseEvent.CLICK, doLogin);\n this.addChild(_btnLogin);\n } \n }\n}\n</code></pre>\n\n<p>Seven lines of code vs 62. That's a pretty simple example, but hopefully you can see how you might benefit by laying out many portions of your application in MXML, whether you're using the design mode in Flex Builder or not.</p>\n\n<p>One thing I do recommend however is keep actionscript out of your mxml files as much as possible. Treat MXML as your view and separate any heavy functionality into other classes. You can then provide public properties in those classes that the controls in your MXML components can bind to. MXML is a layout language and in my experience it pays in the end to use it where it makes sense and drop into actionscript whenever heavier lifting is required.</p>\n" } ]
2008/11/04
[ "https://Stackoverflow.com/questions/261938", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
If everything that can be accomplished in [MXML](http://en.wikipedia.org/wiki/MXML) can also be accomplished in ActionScript and many things are easier to accomplish in ActionScript (loops, conditionals, etc) why take the time to learn MXML? The best reasons I have at this point are that the structure of the MXML nicely matches the visual hierarchy of the UI components and that the lines of code to initialize the UI are reduced. On the other hand real-world UIs are often dynamic, implemented as a simple static structure and then filled in dynamically based on runtime conditions (in which case UI updates are in ActionScript anyway). It would also be possible to reduce the [SLOC](http://en.wikipedia.org/wiki/Source_lines_of_code) needed for ActionScript with the creation of a few helper methods.
It depends on your application's needs, but I generally break my design into visual chunks and use custom MXML components to lay out the main areas and components of my application (data panels, dialog boxes, etc) using mxml based custom components. Then I'll augment that with custom actionscript components where I need more visual flexibilty than the built in layout components provide. MXML is handy because it makes it extremely easy to get components on the stage and set their various properties and style settings. Take this example of two identical login panels: In MXML: ``` <mx:Panel xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute" width="290" height="148" title="Login"> <mx:Label text="User name:" width="80" textAlign="right" y="8" x="8"/> <mx:Label text="Password:" width="80" textAlign="right" y="38" x="8"/> <mx:TextInput id="txtUsername" maxChars="20" y="8" x="90"/> <mx:TextInput id="txtPassword" displayAsPassword="true" y="38" x="90" maxChars="20"/> <mx:Button x="185" y="68" label="Login" id="btnLogin" click="doLogin()"/> </mx:Panel> ``` And in actionscript: ``` package { import flash.events.MouseEvent; import mx.containers.Panel; import mx.controls.Button; import mx.controls.Label; import mx.controls.TextInput; public class MyLoginPanel extends Panel { private var _unLabel:Label; private var _passLabel:Label; private var _txtUsername:TextInput; private var _txtPassword:TextInput; private var _btnLogin:Button; public function MyLoginPanel() { } override protected function createChildren():void { super.createChildren(); this.width = 290; this.height = 148; this.title = "Login"; this.layout = "absolute"; _unLabel = new Label(); _unLabel.text = "User Name:"; _unLabel.width = 80; _unLabel.setStyle("textAlign", "right"); _unLabel.move(8, 8); this.addChild(_unLabel); _passLabel = new Label(); _passLabel.text = "Password:"; _passLabel.width = 80; _passLabel.setStyle("textAlign", "right"); _passLabel.move(8, 38); this.addChild(_passLabel); _txtUsername = new TextInput(); _txtUsername.move(90, 8); this.addChild(_txtUsername); _txtPassword = new TextInput(); _txtPassword.move(90, 38); _txtPassword.displayAsPassword = true; this.addChild(_txtPassword); _btnLogin = new Button(); _btnLogin.label = "Login"; _btnLogin.move(185, 68); _btnLogin.addEventListener(MouseEvent.CLICK, doLogin); this.addChild(_btnLogin); } } } ``` Seven lines of code vs 62. That's a pretty simple example, but hopefully you can see how you might benefit by laying out many portions of your application in MXML, whether you're using the design mode in Flex Builder or not. One thing I do recommend however is keep actionscript out of your mxml files as much as possible. Treat MXML as your view and separate any heavy functionality into other classes. You can then provide public properties in those classes that the controls in your MXML components can bind to. MXML is a layout language and in my experience it pays in the end to use it where it makes sense and drop into actionscript whenever heavier lifting is required.
261,963
<p>I just noticed that you can not use standard math operators on an <code>enum</code> such as <code>++</code> or <code>+=</code>.</p> <p>So what is the best way to iterate through all of the values in a C++ <code>enum</code>?</p>
[ { "answer_id": 261983, "author": "Corey Trager", "author_id": 9328, "author_profile": "https://Stackoverflow.com/users/9328", "pm_score": 3, "selected": false, "text": "<p>You can't with an enum. Maybe an enum isn't the best fit for your situation.</p>\n\n<p>A common convention is to name the last enum value something like MAX and use that to control a loop using an int.</p>\n" }, { "answer_id": 261986, "author": "andreas buykx", "author_id": 19863, "author_profile": "https://Stackoverflow.com/users/19863", "pm_score": 9, "selected": true, "text": "<p>The typical way is as follows:</p>\n\n<pre><code>enum Foo {\n One,\n Two,\n Three,\n Last\n};\n\nfor ( int fooInt = One; fooInt != Last; fooInt++ )\n{\n Foo foo = static_cast&lt;Foo&gt;(fooInt);\n // ...\n}\n</code></pre>\n\n<p>Please note, the enum <code>Last</code> is meant to be skipped by the iteration. Utilizing this \"fake\" <code>Last</code> enum, you don't have to update your terminating condition in the for loop to the last \"real\" enum each time you want to add a new enum.\nIf you want to add more enums later, just add them before Last. The loop in this example will still work. </p>\n\n<p>Of course, this breaks down if the enum values are specified:</p>\n\n<pre><code>enum Foo {\n One = 1,\n Two = 9,\n Three = 4,\n Last\n};\n</code></pre>\n\n<p>This illustrates that an enum is not really meant to iterate through. The typical way to deal with an enum is to use it in a switch statement.</p>\n\n<pre><code>switch ( foo )\n{\n case One:\n // ..\n break;\n case Two: // intentional fall-through\n case Three:\n // ..\n break;\n case Four:\n // ..\n break;\n default:\n assert( ! \"Invalid Foo enum value\" );\n break;\n}\n</code></pre>\n\n<p>If you really want to enumerate, stuff the enum values in a vector and iterate over that. This will properly deal with the specified enum values as well.</p>\n" }, { "answer_id": 261988, "author": "kͩeͣmͮpͥ ͩ", "author_id": 26479, "author_profile": "https://Stackoverflow.com/users/26479", "pm_score": -1, "selected": false, "text": "<p>C++ doesn't have introspection, so you can't determine this kind of thing at run-time.</p>\n" }, { "answer_id": 262030, "author": "João Augusto", "author_id": 6909, "author_profile": "https://Stackoverflow.com/users/6909", "pm_score": 4, "selected": false, "text": "<p>If your enum starts with 0 and the increment is always 1.</p>\n\n<pre><code>enum enumType \n{ \n A = 0,\n B,\n C,\n enumTypeEnd\n};\n\nfor(int i=0; i&lt;enumTypeEnd; i++)\n{\n enumType eCurrent = (enumType) i; \n}\n</code></pre>\n\n<p>If not I guess the only why is to create something like a</p>\n\n<pre><code>vector&lt;enumType&gt; vEnums;\n</code></pre>\n\n<p>add the items, and use normal iterators....</p>\n" }, { "answer_id": 262629, "author": "JohnMcG", "author_id": 1674, "author_profile": "https://Stackoverflow.com/users/1674", "pm_score": 2, "selected": false, "text": "<p>You can also overload the increment/decrement operators for your enumerated type.</p>\n" }, { "answer_id": 8452271, "author": "Mikhail Semenov", "author_id": 653772, "author_profile": "https://Stackoverflow.com/users/653772", "pm_score": 2, "selected": false, "text": "<p>You can try and define the following macro:</p>\n\n<pre><code>#define for_range(_type, _param, _A1, _B1) for (bool _ok = true; _ok;)\\\nfor (_type _start = _A1, _finish = _B1; _ok;)\\\n for (int _step = 2*(((int)_finish)&gt;(int)_start)-1;_ok;)\\\n for (_type _param = _start; _ok ; \\\n (_param != _finish ? \\\n _param = static_cast&lt;_type&gt;(((int)_param)+_step) : _ok = false))\n</code></pre>\n\n<p>Now you can use it:</p>\n\n<pre><code>enum Count { zero, one, two, three }; \n\n for_range (Count, c, zero, three)\n {\n cout &lt;&lt; \"forward: \" &lt;&lt; c &lt;&lt; endl;\n }\n</code></pre>\n\n<p>It can be used to iterate backwards and forwards through unsigned, integers, enums and chars:</p>\n\n<pre><code>for_range (unsigned, i, 10,0)\n{\n cout &lt;&lt; \"backwards i: \" &lt;&lt; i &lt;&lt; endl;\n}\n\n\nfor_range (char, c, 'z','a')\n{\n cout &lt;&lt; c &lt;&lt; endl;\n}\n</code></pre>\n\n<p>Despite its awkward definition it is optimized very well. I looked at disassembler in VC++.\nThe code is extremely efficient. Don't be put off but the three for statements: the compiler will produce only one loop after optimization! You can even define enclosed loops:</p>\n\n<pre><code>unsigned p[4][5];\n\nfor_range (Count, i, zero,three)\n for_range(unsigned int, j, 4, 0)\n { \n p[i][j] = static_cast&lt;unsigned&gt;(i)+j;\n }\n</code></pre>\n\n<p>You obviously cannot iterate through enumerated types with gaps. </p>\n" }, { "answer_id": 17077835, "author": "Riot", "author_id": 1678468, "author_profile": "https://Stackoverflow.com/users/1678468", "pm_score": 3, "selected": false, "text": "<p>Something that hasn't been covered in the other answers = if you're using strongly typed C++11 enums, you cannot use <code>++</code> or <code>+ int</code> on them. In that case, a bit of a messier solution is required:</p>\n\n<pre><code>enum class myenumtype {\n MYENUM_FIRST,\n MYENUM_OTHER,\n MYENUM_LAST\n}\n\nfor(myenumtype myenum = myenumtype::MYENUM_FIRST;\n myenum != myenumtype::MYENUM_LAST;\n myenum = static_cast&lt;myenumtype&gt;(static_cast&lt;int&gt;(myenum) + 1)) {\n\n do_whatever(myenum)\n\n}\n</code></pre>\n" }, { "answer_id": 24982686, "author": "Enzojz", "author_id": 2040143, "author_profile": "https://Stackoverflow.com/users/2040143", "pm_score": 5, "selected": false, "text": "<p>too much complicated these solution, i do like that :</p>\n\n<pre><code>enum NodePosition { Primary = 0, Secondary = 1, Tertiary = 2, Quaternary = 3};\n\nconst NodePosition NodePositionVector[] = { Primary, Secondary, Tertiary, Quaternary };\n\nfor (NodePosition pos : NodePositionVector) {\n...\n}\n</code></pre>\n" }, { "answer_id": 26910769, "author": "zdf", "author_id": 1983409, "author_profile": "https://Stackoverflow.com/users/1983409", "pm_score": 6, "selected": false, "text": "<pre><code>#include &lt;iostream&gt;\n#include &lt;algorithm&gt;\n\nnamespace MyEnum\n{\n enum Type\n {\n a = 100,\n b = 220,\n c = -1\n };\n\n static const Type All[] = { a, b, c };\n}\n\nvoid fun( const MyEnum::Type e )\n{\n std::cout &lt;&lt; e &lt;&lt; std::endl;\n}\n\nint main()\n{\n // all\n for ( const auto e : MyEnum::All )\n fun( e );\n\n // some\n for ( const auto e : { MyEnum::a, MyEnum::b } )\n fun( e );\n\n // all\n std::for_each( std::begin( MyEnum::All ), std::end( MyEnum::All ), fun );\n\n return 0;\n}\n</code></pre>\n" }, { "answer_id": 31836401, "author": "Francesco Chemolli", "author_id": 2938538, "author_profile": "https://Stackoverflow.com/users/2938538", "pm_score": 5, "selected": false, "text": "<p>With c++11, there actually is an alternative: writing a templatized custom iterator.</p>\n<p>let's assume your enum is</p>\n<pre><code>enum class foo {\n one,\n two,\n three\n};\n</code></pre>\n<p>This generic code will do the trick, quite efficiently - place in a generic header, it'll serve you for any enum you may need to iterate over:</p>\n<pre><code>#include &lt;type_traits&gt;\ntemplate &lt; typename C, C beginVal, C endVal&gt;\nclass Iterator {\n typedef typename std::underlying_type&lt;C&gt;::type val_t;\n int val;\npublic:\n Iterator(const C &amp; f) : val(static_cast&lt;val_t&gt;(f)) {}\n Iterator() : val(static_cast&lt;val_t&gt;(beginVal)) {}\n Iterator operator++() {\n ++val;\n return *this;\n }\n C operator*() { return static_cast&lt;C&gt;(val); }\n Iterator begin() { return *this; } //default ctor is good\n Iterator end() {\n static const Iterator endIter=++Iterator(endVal); // cache it\n return endIter;\n }\n bool operator!=(const Iterator&amp; i) { return val != i.val; }\n};\n</code></pre>\n<p>You'll need to specialize it</p>\n<pre><code>typedef Iterator&lt;foo, foo::one, foo::three&gt; fooIterator;\n</code></pre>\n<p>And then you can iterate using range-for</p>\n<pre><code>for (foo i : fooIterator() ) { //notice the parentheses!\n do_stuff(i);\n}\n</code></pre>\n<p>The assumption that you don't have gaps in your enum is still true; there is no assumption on the number of bits actually needed to store the enum value (thanks to std::underlying_type)</p>\n" }, { "answer_id": 35386628, "author": "user2407277", "author_id": 2407277, "author_profile": "https://Stackoverflow.com/users/2407277", "pm_score": 1, "selected": false, "text": "<p>For MS compilers:</p>\n\n<pre><code>#define inc_enum(i) ((decltype(i)) ((int)i + 1))\n\nenum enumtype { one, two, three, count};\nfor(enumtype i = one; i &lt; count; i = inc_enum(i))\n{ \n dostuff(i); \n}\n</code></pre>\n\n<p>Note: this is a lot less code than the simple templatized custom iterator answer.</p>\n\n<p>You can get this to work with GCC by using <code>typeof</code> instead of <code>decltype</code>, but I don't have that compiler handy at the moment to make sure it compiles.</p>\n" }, { "answer_id": 37520025, "author": "Niels Holst", "author_id": 2186676, "author_profile": "https://Stackoverflow.com/users/2186676", "pm_score": 2, "selected": false, "text": "<p>If you do not like to pollute you enum with a final COUNT item (because maybe if you also use the enum in a switch then then the compiler will warn you of a missing case COUNT:), you can do this:</p>\n\n<pre><code>enum Colour {Red, Green, Blue};\nconst Colour LastColour = Blue;\n\nColour co(0);\nwhile (true) {\n // do stuff with co\n // ...\n if (co == LastColour) break;\n co = Colour(co+1);\n}\n</code></pre>\n" }, { "answer_id": 38684696, "author": "kcrossen", "author_id": 1196801, "author_profile": "https://Stackoverflow.com/users/1196801", "pm_score": 0, "selected": false, "text": "<p>If you knew that the enum values were sequential, for example the Qt:Key enum, you could:</p>\n\n<pre><code>Qt::Key shortcut_key = Qt::Key_0;\nfor (int idx = 0; etc...) {\n ....\n if (shortcut_key &lt;= Qt::Key_9) {\n fileMenu-&gt;addAction(\"abc\", this, SLOT(onNewTab()),\n QKeySequence(Qt::CTRL + shortcut_key));\n shortcut_key = (Qt::Key) (shortcut_key + 1);\n }\n}\n</code></pre>\n\n<p>It works as expected.</p>\n" }, { "answer_id": 41718764, "author": "Niki", "author_id": 1894559, "author_profile": "https://Stackoverflow.com/users/1894559", "pm_score": 4, "selected": false, "text": "<p>I often do it like that</p>\n<pre><code> enum EMyEnum\n {\n E_First,\n E_Orange = E_First,\n E_Green,\n E_White,\n E_Blue,\n E_Last\n }\n\n for (EMyEnum i = E_First; i &lt; E_Last; i = EMyEnum(i + 1))\n {}\n</code></pre>\n<p>or if not successive, but with regular step (e.g. bit flags)</p>\n<pre><code> enum EAnimalCaps\n {\n E_None = 0,\n E_First = 0x1,\n E_CanFly = E_First,\n E_CanWalk = 0x2\n E_CanSwim = 0x4,\n E_Last\n }\n \n class MyAnimal\n {\n EAnimalCaps m_Caps;\n }\n\n class Frog\n {\n Frog() : \n m_Caps(EAnimalCaps(E_CanWalk | E_CanSwim))\n {}\n }\n\n for (EAnimalCaps= E_First; i &lt; E_Last; i = EAnimalCaps(i &lt;&lt; 1))\n {}\n</code></pre>\n" }, { "answer_id": 49296191, "author": "mathreadler", "author_id": 5108790, "author_profile": "https://Stackoverflow.com/users/5108790", "pm_score": -1, "selected": false, "text": "<p>Just make an array of ints and loop over the array, but make the last element say -1 and use it for exit condition.</p>\n\n<p>If enum is:</p>\n\n<pre><code>enum MyEnumType{Hay=12,Grass=42,Beer=39};\n</code></pre>\n\n<p>then create array:</p>\n\n<pre><code>int Array[] = {Hay,Grass,Beer,-1};\n\nfor (int h = 0; Array[h] != -1; h++){\n doStuff( (MyEnumType) Array[h] );\n}\n</code></pre>\n\n<p>This does not break down no matter the ints in the representation as long as -1 check does not collide with one of the elements of course.</p>\n" }, { "answer_id": 53214460, "author": "Ethan Bradford", "author_id": 5277967, "author_profile": "https://Stackoverflow.com/users/5277967", "pm_score": 2, "selected": false, "text": "<p>Here's another solution which only works for contiguous enums. It gives the expected iteration, except for ugliness in the increment, which is where it belongs, since that's what's broken in C++.</p>\n\n<pre><code>enum Bar {\n One = 1,\n Two,\n Three,\n End_Bar // Marker for end of enum; \n};\n\nfor (Bar foo = One; foo &lt; End_Bar; foo = Bar(foo + 1))\n{\n // ...\n}\n</code></pre>\n" }, { "answer_id": 56332539, "author": "Eponymous", "author_id": 309334, "author_profile": "https://Stackoverflow.com/users/309334", "pm_score": 3, "selected": false, "text": "<pre class=\"lang-cpp prettyprint-override\"><code>enum class A {\n a0=0, a3=3, a4=4\n};\nconstexpr std::array&lt;A, 3&gt; ALL_A {A::a0, A::a3, A::a4}; // constexpr is important here\n\nfor(A a: ALL_A) {\n if(a==A::a0 || a==A::a4) std::cout &lt;&lt; static_cast&lt;int&gt;(a);\n}\n</code></pre>\n\n<p>A <code>constexpr std::array</code> can iterate even non-sequential enums without the array being instantiated by the compiler. This depends on things like the compiler's optimization heuristics and whether you take the array's address. </p>\n\n<p>In my experiments, I found that <code>g++</code> 9.1 with <code>-O3</code> will optimize away the above array if there are 2 non-sequential values or quite a few sequential values (I tested up to 6). But it only does this if you have an <code>if</code> statement. (I tried a statement that compared an integer value greater than all the elements in a sequential array and it inlined the iteration despite none being excluded, but when I left out the if statement, the values were put in memory.) It also inlined 5 values from a non-sequential enum in [one case|<a href=\"https://godbolt.org/z/XuGtoc]\" rel=\"noreferrer\">https://godbolt.org/z/XuGtoc]</a>. I suspect this odd behavior is due to deep heuristics having to do with caches and branch prediction.</p>\n\n<p>Here is a <a href=\"https://godbolt.org/z/vaD3py\" rel=\"noreferrer\">link to a simple test iteration on godbolt</a> that demonstrates the array does not always get instantiated.</p>\n\n<p>The price of this technique is writing the enum elements twice and keeping the two lists in sync.</p>\n" }, { "answer_id": 57023705, "author": "marski", "author_id": 10450868, "author_profile": "https://Stackoverflow.com/users/10450868", "pm_score": 3, "selected": false, "text": "<p>Assuming that enum is numbered sequentially is error prone. Moreover, you may want to iterate over selected enumerators only. If that subset is small, looping over it explicitly might be an elegant choice:</p>\n\n<pre><code>enum Item { Man, Wolf, Goat, Cabbage }; // or enum class\n\nfor (auto item : {Wolf, Goat, Cabbage}) { // or Item::Wolf, ...\n // ...\n}\n</code></pre>\n" }, { "answer_id": 57068588, "author": "Justin Moloney", "author_id": 11795459, "author_profile": "https://Stackoverflow.com/users/11795459", "pm_score": 0, "selected": false, "text": "<pre><code>typedef enum{\n first = 2,\n second = 6,\n third = 17\n}MyEnum;\n\nstatic const int enumItems[] = {\n first,\n second,\n third\n}\n\nstatic const int EnumLength = sizeof(enumItems) / sizeof(int);\n\nfor(int i = 0; i &lt; EnumLength; i++){\n //Do something with enumItems[i]\n}\n</code></pre>\n" }, { "answer_id": 58983366, "author": "LAL", "author_id": 2432790, "author_profile": "https://Stackoverflow.com/users/2432790", "pm_score": 1, "selected": false, "text": "<p>In Bjarne Stroustrup's C++ programming language book, you can read that he's proposing to overload the <code>operator++</code> for your specific <code>enum</code>. <code>enum</code> are user-defined types and overloading operator exists in the language for these specific situations. </p>\n\n<p>You'll be able to code the following: </p>\n\n<pre><code>#include &lt;iostream&gt;\nenum class Colors{red, green, blue};\nColors&amp; operator++(Colors &amp;c, int)\n{\n switch(c)\n {\n case Colors::red:\n return c=Colors::green;\n case Colors::green:\n return c=Colors::blue;\n case Colors::blue:\n return c=Colors::red; // managing overflow\n default:\n throw std::exception(); // or do anything else to manage the error...\n }\n}\n\nint main()\n{\n Colors c = Colors::red;\n // casting in int just for convenience of output. \n std::cout &lt;&lt; (int)c++ &lt;&lt; std::endl;\n std::cout &lt;&lt; (int)c++ &lt;&lt; std::endl;\n std::cout &lt;&lt; (int)c++ &lt;&lt; std::endl;\n std::cout &lt;&lt; (int)c++ &lt;&lt; std::endl;\n std::cout &lt;&lt; (int)c++ &lt;&lt; std::endl;\n return 0;\n}\n</code></pre>\n\n<p>test code: <a href=\"http://cpp.sh/357gb\" rel=\"nofollow noreferrer\">http://cpp.sh/357gb</a></p>\n\n<p>Mind that I'm using <code>enum class</code>. Code works fine with <code>enum</code> also. But I prefer <code>enum class</code> since they are strong typed and can prevent us to make mistake at compile time. </p>\n" }, { "answer_id": 63000998, "author": "Ben", "author_id": 874660, "author_profile": "https://Stackoverflow.com/users/874660", "pm_score": 0, "selected": false, "text": "<p>Extending @Eponymous's answer: It's great, but doesn't provide a general syntax. Here's what I came up with:</p>\n<pre><code>// Common/EnumTools.h\n#pragma once\n\n#include &lt;array&gt;\n\nnamespace Common {\n\n// Here we forward-declare metafunction for mapping enums to their values.\n// Since C++&lt;23 doesn't have reflection, you have to populate it yourself :-(\n// Usage: After declaring enum class E, add this overload in the namespace of E:\n// inline constexpr auto allValuesArray(const E&amp;, Commob::EnumAllValuesTag) { return std::array{E::foo, E::bar}; }\n// Then `AllValues&lt;NS::E&gt;` will call `allValuesArray(NS::E{}, EnumAllValuesTag)` which will resolve\n// by ADL.\n// Just be sure to keep it sync'd with your enum!\n\n// Here's what you want to use in, e.g., loops: &quot;for (auto val : Common::AllValues&lt;MyEnum&gt;) {&quot;\n\nstruct EnumAllValuesTag {}; // So your allValuesArray function is clearly associated with this header.\n\ntemplate &lt;typename Enum&gt;\nstatic inline constexpr auto AllValues = allValuesArray(Enum{}, EnumAllValuesTag{});\n// ^ Just &quot;constexpr auto&quot; or &quot;constexpr std::array&lt;Enum, allValuesArray(Enum{}, EnumAllValuesTag{}).size()&gt;&quot; didn't work on all compilers I'm using, but this did.\n\n} // namespace Common\n</code></pre>\n<p>then in your namespace:</p>\n<pre><code>#include &quot;Common/EnumTools.h&quot;\n\nnamespace MyNamespace {\n\nenum class MyEnum {\n foo,\n bar = 4,\n baz = 42,\n};\n\n// Making this not have to be in the `Common` namespace took some thinking,\n// but is a critical feature since otherwise there's no hope in keeping it sync'd with the enum.\ninline constexpr auto allValuesArray(const MyEnum&amp;, Common::EnumAllValuesTag) {\n return std::array{ MyEnum::foo, MyEnum::bar, MyEnum::baz };\n}\n\n} // namespace MyNamespace\n</code></pre>\n<p>then wherever you need to use it:</p>\n<pre><code>for (const auto&amp; e : Common::AllValues&lt;MyNamespace::MyEnum&gt;) { ... }\n</code></pre>\n<p>so even if you've typedef'd:</p>\n<pre><code>namespace YourNS {\nusing E = MyNamespace::MyEnum;\n} // namespace YourNS\n\nfor (const auto&amp; e : Common::AllValues&lt;YourNS::E&gt;) { ... }\n</code></pre>\n<p>I can't think of anything much better, short of the actual language feature everyone looking at this page want.</p>\n<p>Future work:</p>\n<ol>\n<li>You should be able to add a <code>constexpr</code> function (and so a metafunction) that filters <code>Common::AllValues&lt;E&gt;</code> to provide a <code>Common::AllDistinctValues&lt;E&gt;</code> for the case of enums with repeated numerical values like <code>enum { foo = 0, bar = 0 };</code>.</li>\n<li>I bet there's a way to use the compiler's <code>switch</code>-covers-all-<code>enum</code>-values to write <code>allValuesArray</code> such that it errors if the enum has added a value.</li>\n</ol>\n" }, { "answer_id": 64147276, "author": "Scott M", "author_id": 4492824, "author_profile": "https://Stackoverflow.com/users/4492824", "pm_score": 1, "selected": false, "text": "<p>Upsides: enums can have any values you like in any order you like and it's still easy to iterate over them.\nNames and values are defined once, in the first #define.</p>\n<p>Downsides: if you use this at work, you need a whole paragraph to explain it to your coworkers. And, it's annoying to have to declare memory to give your loop something to iterate over, but I don't know of a workaround that doesn't confine you to enums with adjacent values (and if the enum will always have adjacent values, the enum might not be buying you all that much anyway.)</p>\n<pre><code>//create a, b, c, d as 0, 5, 6, 7\n#define LIST x(a) x(b,=5) x(c) x(d)\n#define x(n, ...) n __VA_ARGS__,\nenum MyEnum {LIST}; //define the enum\n#undef x //needed\n#define x(n,...) n ,\nMyEnum myWalkableEnum[] {LIST}; //define an iterable list of enum values\n#undef x //neatness\n\nint main()\n{\n std::cout &lt;&lt; d;\n for (auto z : myWalkableEnum)\n std::cout &lt;&lt; z;\n}\n//outputs 70567\n</code></pre>\n<p>The trick of declaring a list with an undefined macro wrapper, and then defining the wrapper differently in various situations, has a lot of applications other than this one.</p>\n" }, { "answer_id": 65834483, "author": "SylvainD", "author_id": 1104488, "author_profile": "https://Stackoverflow.com/users/1104488", "pm_score": -1, "selected": false, "text": "<p>Most solution are based on loops over the (MIN, MAX) range but overlook the fact that might be holes in the enum.</p>\n<p>My suggestions is:</p>\n<pre><code> for (int i = MYTYPE_MIN; i &lt;= MYTYPE_MAX; i++) {\n if (MYTYPE_IsValid(i)) {\n MYTYPE value = (MYTYPE)i;\n // DoStuff(value)\n } \n } \n \n</code></pre>\n" }, { "answer_id": 67659256, "author": "Aryaman Gupta", "author_id": 6381133, "author_profile": "https://Stackoverflow.com/users/6381133", "pm_score": 2, "selected": false, "text": "<p>There is already discussion about std::initializer_list (C++11) in the comments.\nI am mentioning example to iterate over the enum.</p>\n<p>or std::initializer_list and a simpler syntax:</p>\n<pre><code>enum E {\n E1 = 4,\n E2 = 8,\n // ..\n En\n};\n\nconstexpr std::initializer_list&lt;E&gt; all_E = {E1, E2, /*..*/ En};\n</code></pre>\n<p><strong>and then</strong></p>\n<pre><code>for (auto e : all_E) {\n // Do job with e\n}\n</code></pre>\n<p>Reference <a href=\"https://riptutorial.com/cplusplus/example/13085/iteration-over-an-enum#:%7E:text=C%2B%2B%20Iteration%20over%20an%20enum&amp;text=There%20is%20no%20built%2Din%20to%20iterate%20over%20enumeration.\" rel=\"nofollow noreferrer\">Link</a></p>\n" }, { "answer_id": 69774217, "author": "Gabriel Staples", "author_id": 4561887, "author_profile": "https://Stackoverflow.com/users/4561887", "pm_score": 2, "selected": false, "text": "<p>Here are some very readable and easy-to-understand approaches, for both <em>weakly-typed</em> C and C++ regular <code>enum</code>s, <em>and</em> <em>strongly-typed</em> C++ <code>enum class</code>es.</p>\n<p>I recommend compiling all examples below with <code>-Wall -Wextra -Werror</code>. This gives you the added safety that if you forget to cover any enum value in the <code>switch</code> case your compiler will <em>throw a compile-time error</em>! This forces you to keep your enum definition and switch cases in-sync, which is an extra safety measure for your code. This tip works so long as you:</p>\n<ol>\n<li>Cover <em>all</em> enum values in your <code>switch</code> case, and</li>\n<li>Do NOT have a <code>default</code> switch case.</li>\n<li>Build with the <code>-Wall -Wextra -Werror</code> flags.</li>\n</ol>\n<p>I recommend you follow all 3 of those points, as it is a good practice and creates better code.</p>\n<h2>1. For a standard, <em>weakly-typed</em> C or C++ <code>enum</code>:</h2>\n<p><strong>C definition (this is also valid C++):</strong></p>\n<pre class=\"lang-c prettyprint-override\"><code>typedef enum my_error_type_e \n{\n MY_ERROR_TYPE_SOMETHING_1 = 0,\n MY_ERROR_TYPE_SOMETHING_2,\n MY_ERROR_TYPE_SOMETHING_3,\n MY_ERROR_TYPE_SOMETHING_4,\n MY_ERROR_TYPE_SOMETHING_5,\n /// Not a valid value; this is the number of members in this enum\n MY_ERROR_TYPE_count,\n // helpers for iterating over the enum\n MY_ERROR_TYPE_begin = 0,\n MY_ERROR_TYPE_end = MY_ERROR_TYPE_count,\n} my_error_type_t;\n</code></pre>\n<p><strong>C++ definition:</strong></p>\n<pre class=\"lang-cpp prettyprint-override\"><code>enum my_error_type_t \n{\n MY_ERROR_TYPE_SOMETHING_1 = 0,\n MY_ERROR_TYPE_SOMETHING_2,\n MY_ERROR_TYPE_SOMETHING_3,\n MY_ERROR_TYPE_SOMETHING_4,\n MY_ERROR_TYPE_SOMETHING_5,\n /// Not a valid value; this is the number of members in this enum\n MY_ERROR_TYPE_count,\n // helpers for iterating over the enum\n MY_ERROR_TYPE_begin = 0,\n MY_ERROR_TYPE_end = MY_ERROR_TYPE_count,\n};\n</code></pre>\n<p><strong>C or C++ iteration over this <em>weakly-typed</em> enum:</strong></p>\n<p>Note: incrementing an enum by doing <code>my_error_type++</code> is <em>not</em> allowed--not even on C-style enums, so we must do this instead: <code>my_error_type = (my_error_type_t)(my_error_type + 1)</code>. Notice that <code>my_error_type + 1</code> <em>is</em> allowed, however, since this weak enum is automatically implicitly cast to an <code>int</code> here to make this addition possible withOUT having to manually cast it to an int like this: <code>my_error_type = (my_error_type_t)((int)my_error_type + 1)</code>.</p>\n<pre class=\"lang-cpp prettyprint-override\"><code>for (my_error_type_t my_error_type = MY_ERROR_TYPE_begin; \n my_error_type &lt; MY_ERROR_TYPE_end;\n my_error_type = (my_error_type_t)(my_error_type + 1)) \n{\n switch (my_error_type) \n {\n case MY_ERROR_TYPE_SOMETHING_1:\n break;\n case MY_ERROR_TYPE_SOMETHING_2:\n break;\n case MY_ERROR_TYPE_SOMETHING_3:\n break;\n case MY_ERROR_TYPE_SOMETHING_4:\n break;\n case MY_ERROR_TYPE_SOMETHING_5:\n break;\n case MY_ERROR_TYPE_count:\n // This case will never be reached.\n break;\n }\n}\n</code></pre>\n<h2>2. For a <em>scoped</em>, <em>strongly-typed</em> C++ <code>enum class</code>:</h2>\n<p><strong>C++ definition:</strong></p>\n<pre class=\"lang-cpp prettyprint-override\"><code>enum class my_error_type_t\n{\n SOMETHING_1 = 0,\n SOMETHING_2,\n SOMETHING_3,\n SOMETHING_4,\n SOMETHING_5,\n /// Not a valid value; this is the number of members in this enum\n count,\n // helpers for iterating over the enum\n begin = 0,\n end = count,\n};\n</code></pre>\n<p><strong>C++ iteration over this <em>strongly-typed</em> enum:</strong></p>\n<p>Notice the extra <code>(size_t)</code> cast (or <code>(int)</code> would be acceptable too) required to forcefully increment the <code>enum class</code> variable! I also chose to use the C++-style <code>static_cast&lt;my_error_type_t&gt;</code> cast here, but a C-style <code>(my_error_type_t)</code> cast, as done above, would have been fine as well.</p>\n<pre class=\"lang-cpp prettyprint-override\"><code>for (my_error_type_t my_error_type = my_error_type_t::begin; \n my_error_type &lt; my_error_type_t::end;\n my_error_type = static_cast&lt;my_error_type_t&gt;((size_t)my_error_type + 1)) \n{\n switch (my_error_type) \n {\n case my_error_type_t::SOMETHING_1:\n break;\n case my_error_type_t::SOMETHING_2:\n break;\n case my_error_type_t::SOMETHING_3:\n break;\n case my_error_type_t::SOMETHING_4:\n break;\n case my_error_type_t::SOMETHING_5:\n break;\n case my_error_type_t::count:\n // This case will never be reached.\n break;\n }\n}\n</code></pre>\n<p>Also notice the scoping. In the C++ <em>strongly-typed</em> <code>enum class</code> I used <code>my_error_type_t::</code> to access each scoped <code>enum class</code> member. But, in the C-style <em>weakly-typed</em> regular <code>enum</code>, very similar scoping can be achieved, as I demonstrated, simply be prefixing each <code>enum</code> member name with <code>MY_ERROR_TYPE_</code>. So, the fact that the C++ <em>strongly-typed</em> <code>enum class</code> adds scoping doesn't really add much value--it's really just a personal preference in that regard. And the fact that the C++ <em>strongly-typed</em> <code>enum class</code> has extra type-safety also has pros and cons. It may help you in some cases but it definitely makes incrementing the enum and iterating over it a pain-in-the-butt, which, honestly, means it is doing its job. By making it <em>harder</em> to increment the scoped <code>enum class</code> variable as though it was an integer, the C++ <em>strongly-typed</em> <code>enum class</code> is doing <em>exactly what it was designed to do</em>. Whether or not you <em>want</em> that behavior is up to you. Personally, I frequently do <em>not</em> want that behavior, and so it is not uncommon for me to prefer to use C-style enums even in C++.</p>\n<h2>See also:</h2>\n<ol>\n<li>[my answer] <a href=\"https://stackoverflow.com/a/70889843/4561887\">Is there a way to initialize a vector by index in c++11?</a></li>\n<li>[my Q&amp;A] <a href=\"https://stackoverflow.com/questions/69762598/what-are-commonly-used-ways-to-iterate-over-an-enum-class-in-c/69762682#69762682\">What are commonly-used ways to iterate over an enum class in C++?</a></li>\n<li>My answer on some of the differences between <code>enum class</code>es (<em>strongly-typed</em> enums) and regular <code>enum</code>s (<em>weakly-typed</em> enums) in C++: <a href=\"https://stackoverflow.com/questions/8357240/how-to-automatically-convert-strongly-typed-enum-into-int/65014885#65014885\">How to automatically convert strongly typed enum into int?</a></li>\n<li><a href=\"https://github.com/ElectricRCAircraftGuy/eRCaGuy_hello_world#additional-c-and-c-build-notes-ex-wgcc-or-clang-compilers\" rel=\"nofollow noreferrer\">Some of my personal notes on the <code>-Wall -Wextra -Werror</code> and other build options</a>, from my <a href=\"https://github.com/ElectricRCAircraftGuy/eRCaGuy_hello_world\" rel=\"nofollow noreferrer\">eRCaGuy_hello_world</a> repo.</li>\n</ol>\n" }, { "answer_id": 70449757, "author": "jaques-sam", "author_id": 2522849, "author_profile": "https://Stackoverflow.com/users/2522849", "pm_score": 0, "selected": false, "text": "<p>Using a lambda, I found this the best (modern) way of looping over enums.\nThis highly improves the abstraction.\nCan even make it a template, so it's applicable to any enum.\nThis code neither gives you issues with clang(-tidy).</p>\n<pre class=\"lang-cpp prettyprint-override\"><code>#include &lt;functional&gt;\n\n/// @brief Loop over all enum values where the last enum value is the invalid one\nvoid forEachAction(std::function&lt;void(Enum)&gt; &amp;&amp;doThis) {\n for (int value = 0; value = static_cast&lt;int&gt;(Enum::LastValue); ++value ) {\n doThis(static_cast&lt;Enum&gt;(value ));\n }\n}\n\n...\n\nforEachAction([this](Enum value) {\n ... // what you want to execute for every enum\n});\n</code></pre>\n" }, { "answer_id": 70492798, "author": "nathanfranke", "author_id": 7260220, "author_profile": "https://Stackoverflow.com/users/7260220", "pm_score": 2, "selected": false, "text": "<p>Casting the variable to an <code>int&amp;</code> lets you increment while keeping the type readable.</p>\n<pre class=\"lang-cpp prettyprint-override\"><code>#include &lt;iostream&gt;\n\nenum MyEnum\n{\n ONE,\n TWO,\n THREE,\n FOUR,\n};\n\nint main()\n{\n for (MyEnum v = MyEnum::ONE; v &lt;= MyEnum::FOUR; ++(int&amp;)v)\n {\n std::cout&lt;&lt;v&lt;&lt;std::endl;\n }\n\n return 0;\n}\n</code></pre>\n<pre><code>0\n1\n2\n3\n</code></pre>\n" }, { "answer_id": 72368235, "author": "void", "author_id": 6919603, "author_profile": "https://Stackoverflow.com/users/6919603", "pm_score": 1, "selected": false, "text": "<p>(Taking Marski's answer as a big hint...)</p>\n<p>Since the body of an enum definition is the same as an initialiser list it is possible to do this without repeating the item list if we use a simple macro to write out the values:</p>\n<pre><code>#define ITEM_LIST_MACRO Wolf, Goat, Cabbage\n\nenum Item { ITEM_LIST_MACRO }; // Define the enum\n\n// Now iterate through it\nfor (auto item : { ITEM_LIST_MACRO }) {\n}\n</code></pre>\n<p>Pros: Simple, no repetition, and no need to maintain annoying first/last sentinel values. (Indeed I think this might be the only solution suggested so far that does not require the user to remember to update an 'end' marker when a new item is added to the list.)</p>\n<p>Cons: Doesn't work with scoped enums (enum class) because the initialiser list would need the scope (Item::Wolf etc). Also doesn't work if you want to specify the values of the enum members rather than having them defaulted.</p>\n" } ]
2008/11/04
[ "https://Stackoverflow.com/questions/261963", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1366/" ]
I just noticed that you can not use standard math operators on an `enum` such as `++` or `+=`. So what is the best way to iterate through all of the values in a C++ `enum`?
The typical way is as follows: ``` enum Foo { One, Two, Three, Last }; for ( int fooInt = One; fooInt != Last; fooInt++ ) { Foo foo = static_cast<Foo>(fooInt); // ... } ``` Please note, the enum `Last` is meant to be skipped by the iteration. Utilizing this "fake" `Last` enum, you don't have to update your terminating condition in the for loop to the last "real" enum each time you want to add a new enum. If you want to add more enums later, just add them before Last. The loop in this example will still work. Of course, this breaks down if the enum values are specified: ``` enum Foo { One = 1, Two = 9, Three = 4, Last }; ``` This illustrates that an enum is not really meant to iterate through. The typical way to deal with an enum is to use it in a switch statement. ``` switch ( foo ) { case One: // .. break; case Two: // intentional fall-through case Three: // .. break; case Four: // .. break; default: assert( ! "Invalid Foo enum value" ); break; } ``` If you really want to enumerate, stuff the enum values in a vector and iterate over that. This will properly deal with the specified enum values as well.
261,978
<p>I have the following JavaScript code to pop up a window in Internet Explorer. The code is executed from a page within a Microsoft CRM modal dialog box. (RequestID is a string that is always the same in the test system - at the moment it contains "abcdefg" - without the quotes).</p> <pre><code>var cancelUrl = "CancelRequest.aspx?RequestID=" + RequestID; alert("About to open a window.\n\n" + cancelUrl); window.open(cancelUrl); alert("Window opened"); </code></pre> <p>I expect to see a message telling me that I am about to open a window. I then expect to see a window open and get another message about the window having been opened. I don't really care about the order of the last two events; the alerts are there so I know the code has been executed.</p> <p>I have two PCs and a virtual PC. All running IE7. On the Windows 2003 VPC, the messages and pop-up appear every time without fail.</p> <p>On the Vista PC and WinXP PC, the messages appear but the pop-up only appears intermittently. (I think this may be the case on the Vista PC too).</p> <p>All three have identical settings in IE. All have the IE pop-up blocker disabled and have no other pop-up blockers installed.</p> <p>Can anyone shed any light on this?</p>
[ { "answer_id": 262005, "author": "zendar", "author_id": 25732, "author_profile": "https://Stackoverflow.com/users/25732", "pm_score": 0, "selected": false, "text": "<p>This code is simple. Use debugger and see what is going on.</p>\n\n<p>Check that site with FireFox or Chrome, they have JS debuggers.</p>\n\n<p><strong>Edit:</strong></p>\n\n<p>Add try/catch block around <code>window.open()</code> and see if there is some exception there.</p>\n\n<p><strong>Edit 2:</strong></p>\n\n<p>I see now that you are sending characters as RequestId. You should check if that URL can handle that kind of value. Since name is <code>RequestId</code> I'd say that there is big chance that there should be numeric only parameter. If that is correct, then it can happen that server side crashes when you try to open window and then nothing happens. Reason more to set try/catch block and test.</p>\n" }, { "answer_id": 262411, "author": "Jack", "author_id": 24998, "author_profile": "https://Stackoverflow.com/users/24998", "pm_score": 0, "selected": false, "text": "<p>You might want to try Firebug lite, which will work for IE.</p>\n\n<p><a href=\"http://getfirebug.com/lite.html\" rel=\"nofollow noreferrer\">http://getfirebug.com/lite.html</a></p>\n\n<p>The try/catch other people have mentioned is also a good idea. I think.</p>\n\n<p>Additionally, is there any chance that the pop-up is trying to use a window that is already open but minimized. So it doesn't appear to be working but it's really just reloading the minimized window?</p>\n" }, { "answer_id": 272736, "author": "scunliffe", "author_id": 6144, "author_profile": "https://Stackoverflow.com/users/6144", "pm_score": 3, "selected": true, "text": "<p>Ah, I think I got it... missed it in the description...</p>\n\n<p>You are <strong>trying to open a non-modal</strong> window <strong>from a modal dialog</strong> in <strong>IE</strong>.</p>\n\n<p>This AFAIK, should not work.</p>\n\n<p>Try opening another modal window instead.</p>\n\n<p>Effectively you are saying...</p>\n\n<p>on window A, open up modal window B, now open up non-modal window C, which isn't really valid.</p>\n" } ]
2008/11/04
[ "https://Stackoverflow.com/questions/261978", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21862/" ]
I have the following JavaScript code to pop up a window in Internet Explorer. The code is executed from a page within a Microsoft CRM modal dialog box. (RequestID is a string that is always the same in the test system - at the moment it contains "abcdefg" - without the quotes). ``` var cancelUrl = "CancelRequest.aspx?RequestID=" + RequestID; alert("About to open a window.\n\n" + cancelUrl); window.open(cancelUrl); alert("Window opened"); ``` I expect to see a message telling me that I am about to open a window. I then expect to see a window open and get another message about the window having been opened. I don't really care about the order of the last two events; the alerts are there so I know the code has been executed. I have two PCs and a virtual PC. All running IE7. On the Windows 2003 VPC, the messages and pop-up appear every time without fail. On the Vista PC and WinXP PC, the messages appear but the pop-up only appears intermittently. (I think this may be the case on the Vista PC too). All three have identical settings in IE. All have the IE pop-up blocker disabled and have no other pop-up blockers installed. Can anyone shed any light on this?
Ah, I think I got it... missed it in the description... You are **trying to open a non-modal** window **from a modal dialog** in **IE**. This AFAIK, should not work. Try opening another modal window instead. Effectively you are saying... on window A, open up modal window B, now open up non-modal window C, which isn't really valid.
261,985
<p>I have the following </p> <pre><code>var id='123'; newDiv.innerHTML = "&lt;a href=\"#\" onclick=\" TestFunction('"+id+"', false);\"&gt;&lt;/a&gt;"; </code></pre> <p>Which renders <code>&lt;a href="#" onclick="return Testfunction('123',false);"&gt;&lt;/a&gt;</code> in my HTML.</p> <p>The problem I have is that I wish to take the call to the method TestFunction, and use as a string parameter in my function StepTwo(string, boolean), which would ideally end up in live HTML as shown...</p> <pre><code>&lt;a href="#" onclick="StepTwo("TestFunction('123',false)",true)"&gt;&lt;/a&gt; </code></pre> <p>notice how the TestFunction is a string here (it is executed within StepTwo using eval).</p> <p>I have tried to format my JS as by :</p> <pre><code>newDiv.innerHTML = "&lt;a href=\"#\" onclick=\"StepTwo(\"TestFunction('"+id+"', false);\",true)\"&gt;&lt;/a&gt;"; </code></pre> <p>but while this appears to me correct in my IDE, in the rendered HTML, it as garbelled beyond belief.</p> <p>Would appreciate if anyone could point me in the right direction. Thanks!</p>
[ { "answer_id": 261999, "author": "Greg", "author_id": 24181, "author_profile": "https://Stackoverflow.com/users/24181", "pm_score": 2, "selected": false, "text": "<p>You should be using <code>&amp;quot;</code> not <code>\"</code> or <code>\\\"</code> inside an HTML string quoted with double-quotes.</p>\n\n<p><code>NewDiv.innerHTML = \"&lt;a href=\\\"#\\\" onclick=\\\"StepTwo(&amp;quot;TestFunction('\"+id+\"', false);&amp;quot;,true)\\\"&gt;&lt;/a&gt;\";</code></p>\n\n<p>There's probably a better way to do this - any time you find yourself using <code>eval()</code> you should stand back and look for a different solution.</p>\n" }, { "answer_id": 262001, "author": "knabar", "author_id": 34171, "author_profile": "https://Stackoverflow.com/users/34171", "pm_score": 3, "selected": true, "text": "<p>Try using &amp;quot; instead of \\\"</p>\n\n<p>newDiv.innerHTML = &quot;&lt;a href=&amp;quot;#&amp;quot;...</p>\n" }, { "answer_id": 262002, "author": "kͩeͣmͮpͥ ͩ", "author_id": 26479, "author_profile": "https://Stackoverflow.com/users/26479", "pm_score": 0, "selected": false, "text": "<p>You could create the a element and attach to the click event using DOM Methods.</p>\n\n<p>A Javascript Framework (like the ubiquitous jQuery) would make this a lot easier.</p>\n" }, { "answer_id": 262008, "author": "Corey Trager", "author_id": 9328, "author_profile": "https://Stackoverflow.com/users/9328", "pm_score": 0, "selected": false, "text": "<ol>\n<li><p>You need to alternate your \" and '. </p></li>\n<li><p>Maybe you don't need quotes around the 123, because of Javascripts flexible typing. Pass it without quotes but treat it as a string within TestFunction.</p></li>\n</ol>\n" }, { "answer_id": 262010, "author": "Gareth", "author_id": 31582, "author_profile": "https://Stackoverflow.com/users/31582", "pm_score": 0, "selected": false, "text": "<p>Your biggest problem is using eval, it leads to so many potential problems that it's nearly always better to find an alternative solution.</p>\n\n<p>Your immediate problem is that what you really have is</p>\n\n<pre><code>&lt;a href=\"#\" onclick=\"StepTwo(\"&gt;&lt;/a&gt;\n</code></pre>\n\n<p>as the next <code>\"</code> after the start of the onclick attribute, closes it. Use &amp;quot; as others have suggested. And don't use eval.</p>\n" }, { "answer_id": 262033, "author": "Kent Fredric", "author_id": 15614, "author_profile": "https://Stackoverflow.com/users/15614", "pm_score": 3, "selected": false, "text": "<p>One of the biggest capital failures on the internet is creating html in javascript by gluing strings together. </p>\n\n<pre><code>var mya = document.createElement(\"a\");\nmya.href=\"#\"; \nmya.onclick = function(){ \n StepTwo(function(){ \n TestFunction('123', false ); \n }, true ); \n};\nnewDiv.innerHTML = \"\"; \nnewDiv.appendChild(mya);\n</code></pre>\n\n<p>This Eliminates the need for any fancy escaping stuff. </p>\n\n<p>( I probably should do 'onclick' differently, but this should work, I'm trying hard not to just use jQuery code to do everything ) </p>\n\n<p>Heres how I would do it in jQuery: </p>\n\n<pre><code>jQuery(function($){ \n\n var container = $(\"#container\"); \n var link = document.createElement(\"a\"); /* faster than $(\"&lt;a&gt;&lt;/a&gt;\"); */\n $(link).attr(\"href\", \"Something ( or # )\" ); \n $(link).click( function(){ \n var doStepTwo = function()\n { \n TestFunction('123', true ); \n };\n StepTwo( doStepTwo, false ); /* StepTwo -&gt; doStepTwo -&gt; TestFunction() */\n });\n container.append(link); \n}); \n</code></pre>\n\n<h3>There is no good excuse for gluing strings together in Javascript</h3>\n\n<p>All it does is <strong>ADD</strong> overhead of html parsing back into dom structures, and <strong>ADD</strong> potential for XSS based broken HTML. Even <em>beloved google</em> get this wrong in some of their advertising scripts and have caused <em>epic failures</em> in many cases I have seen ( and they don't want to know about it ) </p>\n\n<p><strong>I don't understand Javascript</strong> is the only excuse, and it's <strong>NOT</strong> a good one. </p>\n" }, { "answer_id": 262046, "author": "Mauricio", "author_id": 33913, "author_profile": "https://Stackoverflow.com/users/33913", "pm_score": 0, "selected": false, "text": "<p>The best way is to create the element with <code>document.createElement</code>, but if you're not willing to, I guess you could do <code>&lt;a href=\"#\" onclick=\"StepTwo('TestFunction(\\'123\\',false)',true)\"&gt;&lt;/a&gt;</code> or use <code>&amp;quot;</code>.</p>\n\n<p>In your code:</p>\n\n<pre><code>newDiv.innerHTML = \"&lt;a href=\\\"#\\\" onclick=\\\"StepTwo('TestFunction(\\'\"+id+\"\\', false);\\',true)\\\"&gt;&lt;/a&gt;\";\n</code></pre>\n\n<p>If it doesn't work, try changing \"<code>\\'</code>\" to \"<code>\\\\'</code>\".</p>\n\n<p>Remember that the \" character is used to open and close the attribute on HTML tags. If you use it in the attribute's value, the browser will understand it as the close char.</p>\n\n<p>Example:\n<code>&lt;input type=\"text\" value=\"foo\"bar\"&gt;</code> will end up being <code>&lt;input type=\"text\" value=\"foo\"&gt;</code>.</p>\n" }, { "answer_id": 262055, "author": "RekrowYnapmoc", "author_id": 28871, "author_profile": "https://Stackoverflow.com/users/28871", "pm_score": 0, "selected": false, "text": "<p>Hey guys, thanks for all the answers. I find that the quot; seems to work best.</p>\n\n<p>I'll give you guys some votes up once I get more reputation!</p>\n\n<p>In regards to eval(), what you see in the question is a very small snapshot of the application being developed. I understand the woes of eval, however, this is one of those one in a million situations where it's the correct choice for the situation at hand.</p>\n\n<p>It would be understood better if you could see what these functions do (have given them very generic names for stackoverflow).</p>\n\n<p>Thanks again!</p>\n" }, { "answer_id": 262092, "author": "Gene", "author_id": 22673, "author_profile": "https://Stackoverflow.com/users/22673", "pm_score": 1, "selected": false, "text": "<p>You claim that eval is the right thing to do here. I'm not so sure.</p>\n\n<p>Have you considered this approach:</p>\n\n<pre><code>&lt;a href=\"#\" onclick=\"StepTwo(TestFunction,['123',false],true)\"&gt;&lt;/a&gt;\n</code></pre>\n\n<p>and in your StepTwo function</p>\n\n<pre><code>function StepTwo(func,args,flag){\n //do what ever you do with the flag\n //instead of eval use the function.apply to call the function.\n func.apply(args);\n}\n</code></pre>\n" }, { "answer_id": 262151, "author": "ngn", "author_id": 23109, "author_profile": "https://Stackoverflow.com/users/23109", "pm_score": 0, "selected": false, "text": "<pre><code>&lt;a href=\"#\" onclick=\"StepTwo('TestFunction(\\'123\\', false)', true)\"&gt;...&lt;/a&gt;\n</code></pre>\n" }, { "answer_id": 38287467, "author": "Hedzer", "author_id": 3457733, "author_profile": "https://Stackoverflow.com/users/3457733", "pm_score": 0, "selected": false, "text": "<p>I know this is hella' old now, but if anyone has issues with escaped strings when using eval (and you absolutely have to use eval), I've got a way to avoid problems.</p>\n\n<pre><code>var html = '&lt;a href=\"#\\\" onclick=\" TestFunction(\\''+id+'\\', false);\"&gt;&lt;/a&gt;';\neval('(function(div, html){div.innerHTML = html;})')(newDiv, html);\n</code></pre>\n\n<p>So, what's going on here? </p>\n\n<ol>\n<li><code>eval</code> creates a function that contains two parameters, <code>div</code> and <code>html</code> and returns it.</li>\n<li>The function is immediately run with the parameters to the right of the eval function. This is basically like an IIFE.</li>\n</ol>\n\n<p>In this case</p>\n\n<pre><code>var myNewMethod = eval('(function(div, html){div.innerHTML = html;})');\n</code></pre>\n\n<p>is basically the same as:</p>\n\n<pre><code>var myNewMethod = function(div, html){div.innerHTML = html;}\n</code></pre>\n\n<p>and then we're just doing this:</p>\n\n<pre><code>myNewMethod(newDiv, html); //where html had the string containing markup\n</code></pre>\n\n<p>I would suggest not using eval. If it can't be avoided, or if you control all the inputs and there's no risk of injection then this will help in cases where string escapes are an issue.</p>\n\n<p>I also tend to use <code>Function</code>, but it isn't any more secure.\nHere's the snippet I use:</p>\n\n<pre><code> var feval = function(code) {\n return (new Function(code))();\n}\n</code></pre>\n" } ]
2008/11/04
[ "https://Stackoverflow.com/questions/261985", "https://Stackoverflow.com", "https://Stackoverflow.com/users/28871/" ]
I have the following ``` var id='123'; newDiv.innerHTML = "<a href=\"#\" onclick=\" TestFunction('"+id+"', false);\"></a>"; ``` Which renders `<a href="#" onclick="return Testfunction('123',false);"></a>` in my HTML. The problem I have is that I wish to take the call to the method TestFunction, and use as a string parameter in my function StepTwo(string, boolean), which would ideally end up in live HTML as shown... ``` <a href="#" onclick="StepTwo("TestFunction('123',false)",true)"></a> ``` notice how the TestFunction is a string here (it is executed within StepTwo using eval). I have tried to format my JS as by : ``` newDiv.innerHTML = "<a href=\"#\" onclick=\"StepTwo(\"TestFunction('"+id+"', false);\",true)\"></a>"; ``` but while this appears to me correct in my IDE, in the rendered HTML, it as garbelled beyond belief. Would appreciate if anyone could point me in the right direction. Thanks!
Try using &quot; instead of \" newDiv.innerHTML = "<a href=&quot;#&quot;...
261,998
<p>I have a list of elements (the <em>X</em> in the following examples) displayed either in a row or in a column of an HTML table.</p> <p>In HTML code point of view, I have either (horizontal display):</p> <pre><code>&lt;table id="myTable"&gt; &lt;tr&gt; &lt;td&gt;A&lt;/td&gt; &lt;td&gt;B&lt;/td&gt; &lt;td&gt;C&lt;/td&gt; ... &lt;/tr&gt; &lt;/table&gt; </code></pre> <p>or (vertical display):</p> <pre><code>&lt;table id="myTable"&gt; &lt;tr&gt; &lt;td&gt;A&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;B&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;C&lt;/td&gt; &lt;/tr&gt; ... &lt;/table&gt; </code></pre> <p>This HTML code is generated by a JSF component (called <code>&lt;h:selectManyCheckboxes/&gt;</code>), and thus, I have no control on this HTML code.</p> <p>However, I want to display my list of elements in 2 columns. In others words, the HTML code of my table will be something like that:</p> <pre><code>&lt;table id="myTable"&gt; &lt;tr&gt; &lt;td&gt;A&lt;/td&gt; &lt;td&gt;B&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;C&lt;/td&gt; &lt;td&gt;D&lt;/td&gt; &lt;/tr&gt; ... &lt;/table&gt; </code></pre> <p>How can I do that using jQuery?</p> <p>Thanks in advance for your help.</p> <p>ps: If you need to know, the X are in fact an input and a label, i.e.:</p> <pre><code>&lt;td&gt;&lt;input .../&gt;&lt;label .../&gt;&lt;/td&gt; </code></pre>
[ { "answer_id": 262083, "author": "Prestaul", "author_id": 5628, "author_profile": "https://Stackoverflow.com/users/5628", "pm_score": 1, "selected": false, "text": "<p>Assuming you are starting with one cell in each row and that each cell has one label and one input then I think that you want something like this:</p>\n\n<pre><code>$('#myTable tr').each(function() {\n $('&lt;td/&gt;').append( \n $(this).find('td input') \n ).appendTo(this);\n });\n</code></pre>\n" }, { "answer_id": 262093, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>Interesting exercise. This does what you ask, however it might not be exactly what you want. But it tells you how it can be done. You can </p>\n\n<p>tweak it to where it works the way you expect.</p>\n\n<pre><code>&lt;!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\"&gt;\n&lt;html xmlns=\"http://www.w3.org/1999/xhtml\" &gt;\n&lt;head&gt;\n &lt;title&gt;Example of restructuring tables&lt;/title&gt;\n &lt;script src=\"Scripts/jquery-1.2.6.commented.js\"&gt;&lt;/script&gt;\n&lt;/head&gt;\n&lt;!--&lt;body&gt;&lt;table id=\"Table1\"&gt;\n &lt;tr&gt;\n &lt;td&gt;1&lt;/td&gt;\n &lt;td&gt;2&lt;/td&gt;\n &lt;td&gt;3&lt;/td&gt;\n &lt;td&gt;4&lt;/td&gt;\n &lt;/tr&gt;\n&lt;/table&gt;--&gt;\n&lt;table id=\"myTable\"&gt;\n &lt;tr&gt;\n &lt;td&gt;1&lt;/td&gt;\n &lt;/tr&gt;\n &lt;tr&gt;\n &lt;td&gt;2&lt;/td&gt;\n &lt;/tr&gt;\n &lt;tr&gt;\n &lt;td&gt;3&lt;/td&gt;\n &lt;/tr&gt;\n &lt;tr&gt;\n &lt;td&gt;4&lt;/td&gt;\n &lt;/tr&gt;\n&lt;/table&gt;\n&lt;script type=\"text/javascript\"&gt;\n $(document).ready(function() {\n debugger;\n var tds = $(\"#myTable tr td\"); // gets all td elements in the table with id myTable\n var col1 = $(\"&lt;tr&gt;&lt;/tr&gt;\"); // holds our first row's columns\n var col2 = $(\"&lt;tr&gt;&lt;/tr&gt;\"); // holds our second row's columns\n var halfway = Math.ceil(tds.length / 2);\n // add the first half of our td's to the first row, the second half to the second\n for (var i = 0; i &lt; tds.length; i++) {\n if (i &lt; halfway)\n col1.append(tds[i]);\n else\n col2.append(tds[i]);\n }\n // clear out the clutter from the table\n $(\"#myTable\").children().remove();\n // add our two rows\n $(\"#myTable\").append(col1);\n $(\"#myTable\").append(col2);\n });\n&lt;/script&gt;\n&lt;/body&gt;\n&lt;/html&gt;\n</code></pre>\n\n<hr>\n\n<p>See, your example of how you wanted it to end up put everything in two rows, yet your question said \"two columns\". I did two rows just because it was easier. You just need to modify the for loop so that its more along this line</p>\n" }, { "answer_id": 262624, "author": "Prestaul", "author_id": 5628, "author_profile": "https://Stackoverflow.com/users/5628", "pm_score": 3, "selected": true, "text": "<p>Given the additional information you've provided, I think that this is what you want. It traverses the table moving the cells from every second row into the previous row...</p>\n\n<pre><code>var idx = 1;\nvar row, next;\nwhile((row = $('#myTable tr:nth-child(' + idx++ + ')')).length) {\n if((next = $('#myTable tr:nth-child(' + idx + ')')).length) {\n row.append(next.find('td'));\n next.remove();\n }\n}\n</code></pre>\n" } ]
2008/11/04
[ "https://Stackoverflow.com/questions/261998", "https://Stackoverflow.com", "https://Stackoverflow.com/users/26457/" ]
I have a list of elements (the *X* in the following examples) displayed either in a row or in a column of an HTML table. In HTML code point of view, I have either (horizontal display): ``` <table id="myTable"> <tr> <td>A</td> <td>B</td> <td>C</td> ... </tr> </table> ``` or (vertical display): ``` <table id="myTable"> <tr> <td>A</td> </tr> <tr> <td>B</td> </tr> <tr> <td>C</td> </tr> ... </table> ``` This HTML code is generated by a JSF component (called `<h:selectManyCheckboxes/>`), and thus, I have no control on this HTML code. However, I want to display my list of elements in 2 columns. In others words, the HTML code of my table will be something like that: ``` <table id="myTable"> <tr> <td>A</td> <td>B</td> </tr> <tr> <td>C</td> <td>D</td> </tr> ... </table> ``` How can I do that using jQuery? Thanks in advance for your help. ps: If you need to know, the X are in fact an input and a label, i.e.: ``` <td><input .../><label .../></td> ```
Given the additional information you've provided, I think that this is what you want. It traverses the table moving the cells from every second row into the previous row... ``` var idx = 1; var row, next; while((row = $('#myTable tr:nth-child(' + idx++ + ')')).length) { if((next = $('#myTable tr:nth-child(' + idx + ')')).length) { row.append(next.find('td')); next.remove(); } } ```
262,012
<p>I'm just starting to pick up ASP.Net MVC and find myself writing a lot of &lt;%= %> in the views. Intellisense does supply the closing %>, but I find that typing the introductory &lt;%= to be burdensome (they are tough for me to type :-)).</p> <p>I've dabbled around a bit with Rails and the NetBeans IDE where I was able to type:</p> <pre><code>r&lt;tab&gt; - which would expand to &lt;% %&gt; </code></pre> <p>and</p> <pre><code>re&lt;tab&gt; - which would expand to &lt;%= %&gt; </code></pre> <p>Can something similar be done in the Visual Studio 2008 IDE?</p>
[ { "answer_id": 262074, "author": "Tom Ritter", "author_id": 8435, "author_profile": "https://Stackoverflow.com/users/8435", "pm_score": 0, "selected": false, "text": "<p>I believe <a href=\"http://www.dotnetjunkies.ddj.com/Article/C95AC204-DE44-4D4A-A2B7-1EB1BE14A8A1.dcik\" rel=\"nofollow noreferrer\">Code Snippets</a> would fit the bill.</p>\n" }, { "answer_id": 262262, "author": "plinth", "author_id": 20481, "author_profile": "https://Stackoverflow.com/users/20481", "pm_score": 0, "selected": false, "text": "<p>I've found it straight forward to write a macro and then bind it to a keyboard command.</p>\n\n<p>I use Tools->Macros->Macro Explorer to see what's there and you can create a new module and add in a macro to inject your code. Then you bind it to a key with Tools->Customize->Keyboard...</p>\n\n<p>Since it's not too different from what you're doing, here is a macro to inject a source command with the date and username - VBScript - I didn't look to hard for other alternatives.</p>\n\n<pre><code>Imports System\nImports EnvDTE\nImports EnvDTE80\nImports EnvDTE90\nImports System.Diagnostics\n\nPublic Module Module1\n\n Private Function GetUserName() As String\n GetUserName = System.Environment.UserName\n End Function\n\n Sub InjectChangeComment()\n ActiveDocument().Selection().Text = \"// \" + System.DateTime.Now.ToString(\"MM-dd-yy\") + \" \" + GetUserName() + vbTab + vbTab + vbTab\n End Sub\n\nEnd Module\n</code></pre>\n" }, { "answer_id": 262452, "author": "Chris Bowen - MSFT", "author_id": 33173, "author_profile": "https://Stackoverflow.com/users/33173", "pm_score": 2, "selected": false, "text": "<p>Based on a comment, I double-checked the snippets answer below and it unfortunately doesn't run in HTML view. The other way to do this is via a recorded macro:</p>\n\n<ul>\n<li>In your web project, start recording: <kbd>CTRL</kbd>+<kbd>SHIFT</kbd>+<kbd>R</kbd></li>\n<li>Type <code>&lt;%= %&gt;</code> then return the caret to between the spaces after the \"=\"</li>\n<li>Stop recording: <kbd>CTRL</kbd>+<kbd>SHIFT</kbd>+<kbd>R</kbd></li>\n<li>Insert the macro via <kbd>CTRL</kbd>+<kbd>SHIFT</kbd>+<kbd>P</kbd></li>\n</ul>\n\n<p>That <em>could</em> be enough, but it would be better to have it across all projects, plus we'd like a better keystroke than <kbd>CTRL</kbd>+<kbd>SHIFT</kbd>+<kbd>P</kbd>:</p>\n\n<ul>\n<li>Save the Macro: Tools->Macros->Save Temporary Macro, giving it a name</li>\n<li>Bind it to a keystroke combination:\n\n<ul>\n<li>Tools->Options, and choose the Keyboard node</li>\n<li>Search for the name you chose</li>\n<li>Enter a key combination (e.g. <kbd>ALT</kbd>+<kbd>A</kbd>) and click OK</li>\n</ul></li>\n</ul>\n\n<p>Now you can press the key shortcut (e.g. <kbd>ALT</kbd>+<kbd>A</kbd>) in HTML view, it will insert &lt;%= %>, and position the caret in the tags, ready for input.</p>\n\n<hr>\n\n<p>[Old Answer: doesn't work in HTML view, unfortunately.]</p>\n\n<p>For a Code Snippet, create an XML snippet file (e.g. \"asp.snippet\") with the name, shortcut and expansion, then use Tools -> Code Snippet Manager to add the folder where your snippet is stored.</p>\n\n<p>Here's the XML for snippet that (via \"asp[tab][tab]\"), expands \"&lt;%= [code] %>\"</p>\n\n<pre><code>&lt;?xml version=\"1.0\" encoding=\"utf-8\"?&gt;\n&lt;CodeSnippet Format=\"1.0.0\" xmlns=\"http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet\"&gt;\n &lt;Header&gt;\n &lt;Title&gt;ASP Server Tags&lt;/Title&gt;\n &lt;Author&gt;Chris Bowen&lt;/Author&gt;\n &lt;Shortcut&gt;asp&lt;/Shortcut&gt;\n &lt;Description&gt;ASP.NET server escape characters, including equals&lt;/Description&gt;\n &lt;SnippetTypes&gt;\n &lt;SnippetType&gt;SurroundsWith&lt;/SnippetType&gt;\n &lt;SnippetType&gt;Expansion&lt;/SnippetType&gt;\n &lt;/SnippetTypes&gt;\n &lt;/Header&gt;\n &lt;Snippet&gt;\n &lt;Declarations&gt;\n &lt;Literal&gt;\n &lt;ID&gt;code&lt;/ID&gt;\n &lt;Default&gt;Code&lt;/Default&gt;\n &lt;/Literal&gt;\n &lt;/Declarations&gt;\n &lt;Code Language=\"csharp\"&gt;\n &lt;![CDATA[&lt;%= $code$ $selected$%&gt;$end$]]&gt;\n &lt;/Code&gt;\n &lt;/Snippet&gt;\n&lt;/CodeSnippet&gt;\n</code></pre>\n\n<p>More details are <a href=\"http://msdn.microsoft.com/en-us/library/ms165392.aspx\" rel=\"nofollow noreferrer\">here on MSDN</a>.</p>\n\n<p>BTW, VS has a snippet to create snippets. Just open a new XML file, then right click and choose Insert Snippet -> \"Snippet\".</p>\n" }, { "answer_id": 262453, "author": "Brian Schmitt", "author_id": 30492, "author_profile": "https://Stackoverflow.com/users/30492", "pm_score": 3, "selected": true, "text": "<p>This macro function should do it:</p>\n\n<p>The main code will do one of two things, if nothing is selected it will just insert the &lt;%= %> code construct, if you have something currently selected in the editor, it will wrap that code with the construct E.G. &lt;%= selected code here %></p>\n\n<pre><code>Public Sub WrapMVC()\n Try\n DTE.UndoContext.Open(\"Wrap MVC\")\n Dim OutText As String = \"\"\n Dim OutFormat As String = \"&lt;%={0} %&gt;\"\n DTE.ActiveDocument.Selection.Text = String.Format(OutFormat, ActiveWindowSelection)\n Finally\n DTE.UndoContext.Close()\n End Try\nEnd Sub\n</code></pre>\n\n<p><strong>Helper Routines:</strong></p>\n\n<pre><code>Friend Function ActiveWindowSelection() As String\n If DTE.ActiveWindow.ObjectKind = EnvDTE.Constants.vsWindowKindOutput Then\n Return OutputWindowSelection()\n End If\n If DTE.ActiveWindow.ObjectKind = \"{57312C73-6202-49E9-B1E1-40EA1A6DC1F6}\" Then\n Return HTMLEditorSelection()\n End If\n Return SelectionText(DTE.ActiveWindow.Selection)\nEnd Function\n\nPrivate Function HTMLEditorSelection() As String\n Dim hw As EnvDTE.HTMLWindow = ActiveDocument.ActiveWindow.Object\n Dim tw As TextWindow = hw.CurrentTabObject\n Return SelectionText(tw.Selection)\nEnd Function\n\nPrivate Function OutputWindowSelection() As String\n Dim w As Window = DTE.Windows.Item(EnvDTE.Constants.vsWindowKindOutput)\n Dim ow As OutputWindow = w.Object\n Dim owp As OutputWindowPane = ow.OutputWindowPanes.Item(ow.ActivePane.Name)\n Return SelectionText(owp.TextDocument.Selection)\nEnd Function\n\nPrivate Function SelectionText(ByVal sel As EnvDTE.TextSelection) As String\n If sel Is Nothing Then\n Return \"\"\n End If\n If sel.Text.Length &lt;= 2 Then\n SelectWord(sel)\n End If\n If sel.Text.Length &lt;= 2 Then\n Return \"\"\n End If\n Return sel.Text\nEnd Function\n\nPrivate Sub SelectWord(ByVal sel As EnvDTE.TextSelection)\n Dim leftPos As Integer\n Dim line As Integer\n Dim pt As EnvDTE.EditPoint = sel.ActivePoint.CreateEditPoint()\n\n sel.WordLeft(True, 1)\n line = sel.TextRanges.Item(1).StartPoint.Line\n leftPos = sel.TextRanges.Item(1).StartPoint.LineCharOffset\n pt.MoveToLineAndOffset(line, leftPos)\n sel.MoveToPoint(pt)\n sel.WordRight(True, 1)\nEnd Sub\n</code></pre>\n" }, { "answer_id": 263855, "author": "Haacked", "author_id": 598, "author_profile": "https://Stackoverflow.com/users/598", "pm_score": 0, "selected": false, "text": "<p>Code Snippets in the HTML view do not work. It's slated for the next version of Visual Studio. I'd look at a Macro approach for now, or see if other tools allow for snippets in the HTML editor.</p>\n" }, { "answer_id": 271799, "author": "anonym0use", "author_id": 35441, "author_profile": "https://Stackoverflow.com/users/35441", "pm_score": 0, "selected": false, "text": "<p>One good tool which will allow you to do this is Resharper. You can create your own templates that will do what you require but also have surround with tags too. There are a whole host of features and is well worth it for the price.</p>\n" } ]
2008/11/04
[ "https://Stackoverflow.com/questions/262012", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7961/" ]
I'm just starting to pick up ASP.Net MVC and find myself writing a lot of <%= %> in the views. Intellisense does supply the closing %>, but I find that typing the introductory <%= to be burdensome (they are tough for me to type :-)). I've dabbled around a bit with Rails and the NetBeans IDE where I was able to type: ``` r<tab> - which would expand to <% %> ``` and ``` re<tab> - which would expand to <%= %> ``` Can something similar be done in the Visual Studio 2008 IDE?
This macro function should do it: The main code will do one of two things, if nothing is selected it will just insert the <%= %> code construct, if you have something currently selected in the editor, it will wrap that code with the construct E.G. <%= selected code here %> ``` Public Sub WrapMVC() Try DTE.UndoContext.Open("Wrap MVC") Dim OutText As String = "" Dim OutFormat As String = "<%={0} %>" DTE.ActiveDocument.Selection.Text = String.Format(OutFormat, ActiveWindowSelection) Finally DTE.UndoContext.Close() End Try End Sub ``` **Helper Routines:** ``` Friend Function ActiveWindowSelection() As String If DTE.ActiveWindow.ObjectKind = EnvDTE.Constants.vsWindowKindOutput Then Return OutputWindowSelection() End If If DTE.ActiveWindow.ObjectKind = "{57312C73-6202-49E9-B1E1-40EA1A6DC1F6}" Then Return HTMLEditorSelection() End If Return SelectionText(DTE.ActiveWindow.Selection) End Function Private Function HTMLEditorSelection() As String Dim hw As EnvDTE.HTMLWindow = ActiveDocument.ActiveWindow.Object Dim tw As TextWindow = hw.CurrentTabObject Return SelectionText(tw.Selection) End Function Private Function OutputWindowSelection() As String Dim w As Window = DTE.Windows.Item(EnvDTE.Constants.vsWindowKindOutput) Dim ow As OutputWindow = w.Object Dim owp As OutputWindowPane = ow.OutputWindowPanes.Item(ow.ActivePane.Name) Return SelectionText(owp.TextDocument.Selection) End Function Private Function SelectionText(ByVal sel As EnvDTE.TextSelection) As String If sel Is Nothing Then Return "" End If If sel.Text.Length <= 2 Then SelectWord(sel) End If If sel.Text.Length <= 2 Then Return "" End If Return sel.Text End Function Private Sub SelectWord(ByVal sel As EnvDTE.TextSelection) Dim leftPos As Integer Dim line As Integer Dim pt As EnvDTE.EditPoint = sel.ActivePoint.CreateEditPoint() sel.WordLeft(True, 1) line = sel.TextRanges.Item(1).StartPoint.Line leftPos = sel.TextRanges.Item(1).StartPoint.LineCharOffset pt.MoveToLineAndOffset(line, leftPos) sel.MoveToPoint(pt) sel.WordRight(True, 1) End Sub ```
262,015
<p>I need to modify a (xml-)file from Apache Ant. "loadfile" task allows to load the file's content in a property. But how to store the property's value back to a file after its (property) modification?</p> <p>Of course I could write custom task to perform this operation but I would like to know if there's some existing implementation.</p>
[ { "answer_id": 262064, "author": "sblundy", "author_id": 4893, "author_profile": "https://Stackoverflow.com/users/4893", "pm_score": 5, "selected": true, "text": "<p>You can use the <a href=\"http://ant.apache.org/manual/Tasks/echo.html\" rel=\"noreferrer\">echo</a> task.</p>\n\n<pre><code>&lt;echo file=\"${fileName}\" message=\"${xmlProperty}\"/&gt;\n</code></pre>\n\n<p>The <a href=\"http://ant.apache.org/manual/Tasks/echoxml.html\" rel=\"noreferrer\">echoxml</a> task might be of interest to you as well.</p>\n" }, { "answer_id": 9478786, "author": "Jarekczek", "author_id": 772981, "author_profile": "https://Stackoverflow.com/users/772981", "pm_score": 3, "selected": false, "text": "<p>Use <a href=\"http://ant.apache.org/manual/Tasks/propertyfile.html\" rel=\"noreferrer\">propertyfile</a> task. An example taken from ant manual:</p>\n\n<pre><code>&lt;propertyfile file=\"my.properties\"&gt;\n &lt;entry key=\"abc\" value=\"${abc}\"/&gt;\n&lt;/propertyfile&gt;\n</code></pre>\n\n<p>This may be better than <code>echo</code> as it updates the properties file with a given value, while <code>echo</code> appends to or overwrites the whole file.</p>\n" } ]
2008/11/04
[ "https://Stackoverflow.com/questions/262015", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15647/" ]
I need to modify a (xml-)file from Apache Ant. "loadfile" task allows to load the file's content in a property. But how to store the property's value back to a file after its (property) modification? Of course I could write custom task to perform this operation but I would like to know if there's some existing implementation.
You can use the [echo](http://ant.apache.org/manual/Tasks/echo.html) task. ``` <echo file="${fileName}" message="${xmlProperty}"/> ``` The [echoxml](http://ant.apache.org/manual/Tasks/echoxml.html) task might be of interest to you as well.
262,043
<p>I am trying to do something like this:</p> <pre><code>while @nrOfAuthlevels &gt;= @myAuthLevel begin set @myAuthLevel = @myAuthLevel + 1 SELECT Role.name, Role.authorityLevel FROM [dbo].[Role] ORDER BY Role.authorityLevel end </code></pre> <p>The result of this stored procedure shall be a table with all Role.authorityLevel below my own. But this generates several tables.</p>
[ { "answer_id": 262057, "author": "Biri", "author_id": 968, "author_profile": "https://Stackoverflow.com/users/968", "pm_score": 1, "selected": false, "text": "<p>Create a temp table before the loop and don't select data, but insert data to this temp table:</p>\n\n<pre><code>create table #tmp (\n Name type,\n authorityLevel type\n)\n\nwhile @nrOfAuthlevels &gt;= @myAuthLevel\nbegin\n set @myAuthLevel = @myAuthLevel + 1 \n insert into #tmp values(\n SELECT Role.name, Role.authorityLevel\n FROM [dbo].[Role]\n where ...\n )\nend\n</code></pre>\n" }, { "answer_id": 262058, "author": "Stephen Wrighton", "author_id": 7516, "author_profile": "https://Stackoverflow.com/users/7516", "pm_score": 3, "selected": false, "text": "<p>If you want to keep that current structure, then you would need to insert into a temporary table for every step through the while loop, and outside of that return from the TEMP table.</p>\n\n<p>That said, why not just use a <strong>WHERE</strong> clause to get the expected return results:</p>\n\n<pre><code>SELECT Role.Name, Role.AuthorityLevel\n FROM dbo.Role\n WHERE Role.AuthorityLevel &lt; @MyAuthLevel\n ORDER BY Role.AuthorityLevel\n</code></pre>\n" } ]
2008/11/04
[ "https://Stackoverflow.com/questions/262043", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I am trying to do something like this: ``` while @nrOfAuthlevels >= @myAuthLevel begin set @myAuthLevel = @myAuthLevel + 1 SELECT Role.name, Role.authorityLevel FROM [dbo].[Role] ORDER BY Role.authorityLevel end ``` The result of this stored procedure shall be a table with all Role.authorityLevel below my own. But this generates several tables.
If you want to keep that current structure, then you would need to insert into a temporary table for every step through the while loop, and outside of that return from the TEMP table. That said, why not just use a **WHERE** clause to get the expected return results: ``` SELECT Role.Name, Role.AuthorityLevel FROM dbo.Role WHERE Role.AuthorityLevel < @MyAuthLevel ORDER BY Role.AuthorityLevel ```
262,075
<p>The following doesn't work, but something like this is what I'm looking for.</p> <pre><code>select * from Products where Description like (@SearchedDescription + %) </code></pre> <p>SSRS uses the @ operator in-front of a parameter to simulate an 'in', and I'm not finding a way to match up a string to a list of strings.</p>
[ { "answer_id": 278959, "author": "Pulsehead", "author_id": 2156, "author_profile": "https://Stackoverflow.com/users/2156", "pm_score": 0, "selected": false, "text": "<p>Have you tried to do:</p>\n\n<p><code>select * from Products where Description like (@SearchedDescription + '%')</code>\n(Putting single quotes around the % sign?)</p>\n" }, { "answer_id": 296817, "author": "Registered User", "author_id": 38332, "author_profile": "https://Stackoverflow.com/users/38332", "pm_score": 3, "selected": true, "text": "<p>There are a few options on how to use a LIKE operator with a parameter. </p>\n\n<p>OPTION 1</p>\n\n<p>If you add the % to the parameter value, then you can customize how the LIKE filter will be processed. For instance, your query could be:</p>\n\n<pre><code> SELECT name\n FROM master.dbo.sysobjects\n WHERE name LIKE @ReportParameter1\n</code></pre>\n\n<p>For the data set to use the LIKE statement properly, then you could use a parameter value like sysa%. When I tested a sample report in SSRS 2008 using this code, I returned the following four tables:</p>\n\n<pre><code> sysallocunits\n sysaudacts\n sysasymkeys\n sysaltfiles\n</code></pre>\n\n<p>OPTION 2</p>\n\n<p>Another way to do this that doesn't require the user to add any '%' symbol is to generate a variable that has the code and exceute the variable.</p>\n\n<pre><code> DECLARE @DynamicSQL NVARCHAR(MAX) \n\n SET @DynamicSQL = \n 'SELECT name, id, xtype\n FROM dbo.sysobjects\n WHERE name LIKE ''' + @ReportParameter1 + '%''\n '\n\n EXEC (@DynamicSQL)\n</code></pre>\n\n<p>This will give you finer controller over how the LIKE statement will be used. If you don't want users to inject any additional operators, then you can always add code to strip out non alpha-numeric characters before merging it into the final query.</p>\n\n<p>OPTION 3</p>\n\n<p>You can create a stored procedure that controls this functionality. I generally prefer to use stored procedures as data sources for SSRS and never allow dynamically generated SQL, but that's just a preference of mine. This helps with discoverability when performing dependency analysis checks and also allows you to ensure optimal query performance.</p>\n\n<p>OPTION 4</p>\n\n<p>Create a .NET code assembly that helps dynamically generate the SQL code. I think this is overkill and a poor choice at best, but it could work conceivably.</p>\n" }, { "answer_id": 859043, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>Dano, which version of SSRS are you using? If it's RS2000, the multi-parameter list is\nnot officially supported, but there is a workaround....</p>\n" }, { "answer_id": 1686379, "author": "Pradeep sharma", "author_id": 204632, "author_profile": "https://Stackoverflow.com/users/204632", "pm_score": 0, "selected": false, "text": "<p>put like this:</p>\n\n<pre><code>select * \nfrom tsStudent \nwhere studentName like @SName+'%'\n</code></pre>\n" }, { "answer_id": 52488317, "author": "Jeff Breadner", "author_id": 4187907, "author_profile": "https://Stackoverflow.com/users/4187907", "pm_score": 0, "selected": false, "text": "<p>I know this is super old, but this came up in my search to solve the same problem, and I wound up using a solution not described here. I'm adding a new potential solution to help whomever else might follow.</p>\n\n<p>As written, this solution only works in SQL Server 2016 and later, but can be adapted for older versions by writing a custom <a href=\"https://learn.microsoft.com/en-us/sql/t-sql/functions/string-split-transact-sql?view=sql-server-2017\" rel=\"nofollow noreferrer\">string_split</a> UDF, and by using a subquery instead of a CTE.</p>\n\n<p>First, map your @SearchedDescription into your Dataset as a single string using JOIN:</p>\n\n<p><code>=JOIN(@SearchedDedscription, \",\")</code></p>\n\n<p>Then use STRING_SPLIT to map your \"A,B,C,D\" kind of string into a tabular structure.</p>\n\n<pre><code>;with\nSearchTerms as (\n select distinct\n Value\n from \n string_split(@SearchedDescription, ',')\n)\nselect distinct\n *\nfrom\n Products\n inner join SearchTerms on\n Products.Description like SearchTerms.Value + '%'\n</code></pre>\n\n<p>If someone adds the same search term multiple times, this would duplicate rows in the result set. Similarly, a single product could match multiple search terms. I've added <code>distinct</code> to both the SearchTerms CTE and the main query to try to suppress this inappropriate row duplication. </p>\n\n<p>If your query is more complex (including results from other joins) then this could become an increasingly big problem. Just be aware of it, it's the main drawback of this method.</p>\n" } ]
2008/11/04
[ "https://Stackoverflow.com/questions/262075", "https://Stackoverflow.com", "https://Stackoverflow.com/users/26938/" ]
The following doesn't work, but something like this is what I'm looking for. ``` select * from Products where Description like (@SearchedDescription + %) ``` SSRS uses the @ operator in-front of a parameter to simulate an 'in', and I'm not finding a way to match up a string to a list of strings.
There are a few options on how to use a LIKE operator with a parameter. OPTION 1 If you add the % to the parameter value, then you can customize how the LIKE filter will be processed. For instance, your query could be: ``` SELECT name FROM master.dbo.sysobjects WHERE name LIKE @ReportParameter1 ``` For the data set to use the LIKE statement properly, then you could use a parameter value like sysa%. When I tested a sample report in SSRS 2008 using this code, I returned the following four tables: ``` sysallocunits sysaudacts sysasymkeys sysaltfiles ``` OPTION 2 Another way to do this that doesn't require the user to add any '%' symbol is to generate a variable that has the code and exceute the variable. ``` DECLARE @DynamicSQL NVARCHAR(MAX) SET @DynamicSQL = 'SELECT name, id, xtype FROM dbo.sysobjects WHERE name LIKE ''' + @ReportParameter1 + '%'' ' EXEC (@DynamicSQL) ``` This will give you finer controller over how the LIKE statement will be used. If you don't want users to inject any additional operators, then you can always add code to strip out non alpha-numeric characters before merging it into the final query. OPTION 3 You can create a stored procedure that controls this functionality. I generally prefer to use stored procedures as data sources for SSRS and never allow dynamically generated SQL, but that's just a preference of mine. This helps with discoverability when performing dependency analysis checks and also allows you to ensure optimal query performance. OPTION 4 Create a .NET code assembly that helps dynamically generate the SQL code. I think this is overkill and a poor choice at best, but it could work conceivably.
262,106
<p>What happen when SQL Server 2005 happen to reach the maximum for an IDENTITY column? Does it start from the beginning and start refilling the gap? </p> <p>What is the behavior of SQL Server 2005 when it happen?</p>
[ { "answer_id": 262123, "author": "xsl", "author_id": 11387, "author_profile": "https://Stackoverflow.com/users/11387", "pm_score": 5, "selected": true, "text": "<p><strong>You will get an overflow error when the maximum value is reached</strong>. If you use the bigint datatype with a maximum value of <code>9,223,372,036,854,775,807</code> this will most likely never be the case. </p>\n\n<p>The error message you will get, will look like this:</p>\n\n<pre><code>Msg 220, Level 16, State 2, Line 10\nArithmetic overflow error for data type tinyint, value = 256.\n</code></pre>\n\n<p><a href=\"http://forums.microsoft.com/msdn/ShowPost.aspx?PostID=4038424&amp;SiteID=1&amp;pageid=0\" rel=\"noreferrer\">(Source)</a></p>\n\n<p>As far as I know MS SQL provides no functionality to fill the identity gaps, so you will either have to do this by yourself or change the datatype of the identity column.</p>\n\n<p>In addition to this you can set the start value to the smallest negative number, to get an even bigger range of values to use.</p>\n\n<p><a href=\"http://mssqlserver.wordpress.com/2006/12/01/what-happens-when-my-integer-identity-runs-out-of-scope/\" rel=\"noreferrer\">Here is a good blog post about this topic</a>.</p>\n" }, { "answer_id": 262128, "author": "tvanfosson", "author_id": 12950, "author_profile": "https://Stackoverflow.com/users/12950", "pm_score": 1, "selected": false, "text": "<p>It will not fill in the gaps. Instead inserts will fail until you change the definition of the column to either drop the identity and find some other way of filling in the gaps or increase the size (go from int to bigint) or change the type of the data (from int to decimal) so that more identity values are available.</p>\n" }, { "answer_id": 262142, "author": "BradC", "author_id": 21398, "author_profile": "https://Stackoverflow.com/users/21398", "pm_score": 0, "selected": false, "text": "<p>If the identity column is an Integer, then your max is 2,147,483,647. You will get an overflow error if you exceed it. </p>\n\n<p>If you think this is a risk, just use the BIGINT datatype, which gives you up to 9,223,372,036,854,775,807. Can't imagine a database table with that many rows.</p>\n\n<p>Further discussion <a href=\"http://forums.microsoft.com/msdn/ShowPost.aspx?PostID=4038424&amp;SiteID=1&amp;pageid=0\" rel=\"nofollow noreferrer\">here</a>. (Same link as xsl mentioned).</p>\n" }, { "answer_id": 262202, "author": "Kevin", "author_id": 19038, "author_profile": "https://Stackoverflow.com/users/19038", "pm_score": 1, "selected": false, "text": "<p>You will be unable to insert new rows and will receive the error message listed above until you fix the problem. You can do this a number of ways. If you still have data and are using all the id's below the max, you will have to change the datatype. If the data is getting purged on a regular basis and you have a large gap that is not going to be used, you can reseed the identity number to the lowest number in that gap. For example,at a previous job,we were logging transactions. We had maybe 40-50 million per month, but we were purging everything older than 6 months, so every few years, the identity would get close to 2 Billion, but we would have nothing with an id below 1.5 billion, so we would reseed back to 0. Again it's possible that neither of these will work for you and you will have to find a different solution.</p>\n" }, { "answer_id": 262397, "author": "Logicalmind", "author_id": 26977, "author_profile": "https://Stackoverflow.com/users/26977", "pm_score": 0, "selected": false, "text": "<p>In the event that you do hit the maximum number for you identity column, you can move the data from that table into a secondary table with a bigger identity column type and specify the starting value for that new identity value to be the maximum of the previous type. The new identity values will continue from that point.</p>\n" }, { "answer_id": 1312293, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>If you delete \"old values\" from time to time you just need to reset the seed using\nDBCC CHECKIDENT ('MyTable', RESEED, 0);</p>\n" } ]
2008/11/04
[ "https://Stackoverflow.com/questions/262106", "https://Stackoverflow.com", "https://Stackoverflow.com/users/24975/" ]
What happen when SQL Server 2005 happen to reach the maximum for an IDENTITY column? Does it start from the beginning and start refilling the gap? What is the behavior of SQL Server 2005 when it happen?
**You will get an overflow error when the maximum value is reached**. If you use the bigint datatype with a maximum value of `9,223,372,036,854,775,807` this will most likely never be the case. The error message you will get, will look like this: ``` Msg 220, Level 16, State 2, Line 10 Arithmetic overflow error for data type tinyint, value = 256. ``` [(Source)](http://forums.microsoft.com/msdn/ShowPost.aspx?PostID=4038424&SiteID=1&pageid=0) As far as I know MS SQL provides no functionality to fill the identity gaps, so you will either have to do this by yourself or change the datatype of the identity column. In addition to this you can set the start value to the smallest negative number, to get an even bigger range of values to use. [Here is a good blog post about this topic](http://mssqlserver.wordpress.com/2006/12/01/what-happens-when-my-integer-identity-runs-out-of-scope/).
262,108
<p>I am creating an application which displays some messages and its directions in the DataGridView. I would like to replace some columns content with pictures. For example I would like to replace number 0 which represents the incoming call with a green arrow (some .jpg image).</p> <p>Does anyone know how this could be achieved?</p> <p>Thanks!</p>
[ { "answer_id": 262149, "author": "Gavin Miller", "author_id": 33226, "author_profile": "https://Stackoverflow.com/users/33226", "pm_score": 0, "selected": false, "text": "<p>GridViews have the ability to use an image field as opposed to a data bound field. This sounds like it would do the trick.</p>\n" }, { "answer_id": 262175, "author": "Quibblesome", "author_id": 1143, "author_profile": "https://Stackoverflow.com/users/1143", "pm_score": 0, "selected": false, "text": "<p>Look at creating a custom datagridviewCell datagridviewColumn and/or dataGridViewEditingControl.</p>\n" }, { "answer_id": 813815, "author": "JJO", "author_id": 99141, "author_profile": "https://Stackoverflow.com/users/99141", "pm_score": 2, "selected": true, "text": "<p>We stored the images in the resource file as BMP files. Then, we handle the CellFormatting event in the DataGridView like this:</p>\n\n<pre><code> private void messageInfoDataGridView_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)\n {\n // Is this the correct column? (It's actually a DataGridViewImageColumn)\n if (messageInfoDataGridView.Columns[e.ColumnIndex] == messageSeverityDataGridViewTextBoxColumn)\n {\n // Get the row we're formatting\n DataGridViewRow row = messageInfoDataGridView.Rows[e.RowIndex];\n // Get the enum from the row.\n MessageSeverity severity = ((MessageInfo)row.DataBoundItem).MessageSeverity;\n Bitmap cellValueImage;\n // Map the enumerated type to an image...\n // SeverityImageMap is a Dictionary&lt;MessageSeverity,Bitmap&gt;.\n if (ReferenceTables.SeverityImageMap.ContainsKey(severity))\n cellValueImage = ReferenceTables.SeverityImageMap[severity];\n else\n cellValueImage = Resources.NoAction;\n\n // Set the event args.\n e.Value = cellValueImage;\n e.FormattingApplied = true;\n }\n }\n</code></pre>\n" } ]
2008/11/04
[ "https://Stackoverflow.com/questions/262108", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22996/" ]
I am creating an application which displays some messages and its directions in the DataGridView. I would like to replace some columns content with pictures. For example I would like to replace number 0 which represents the incoming call with a green arrow (some .jpg image). Does anyone know how this could be achieved? Thanks!
We stored the images in the resource file as BMP files. Then, we handle the CellFormatting event in the DataGridView like this: ``` private void messageInfoDataGridView_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e) { // Is this the correct column? (It's actually a DataGridViewImageColumn) if (messageInfoDataGridView.Columns[e.ColumnIndex] == messageSeverityDataGridViewTextBoxColumn) { // Get the row we're formatting DataGridViewRow row = messageInfoDataGridView.Rows[e.RowIndex]; // Get the enum from the row. MessageSeverity severity = ((MessageInfo)row.DataBoundItem).MessageSeverity; Bitmap cellValueImage; // Map the enumerated type to an image... // SeverityImageMap is a Dictionary<MessageSeverity,Bitmap>. if (ReferenceTables.SeverityImageMap.ContainsKey(severity)) cellValueImage = ReferenceTables.SeverityImageMap[severity]; else cellValueImage = Resources.NoAction; // Set the event args. e.Value = cellValueImage; e.FormattingApplied = true; } } ```
262,110
<p>Ok, the more I use LINQ, the more I like it! I recently found myself working in some legacy code at work. It is your classic DataSet and DataTable rich application. Well, when adding a bit of functionality I found myself <em>really</em> wanting to just query the rows of a DataTable for the results I was looking for.</p> <p>Let me repeat that... instead of looping and adding to a temp collection, I just wanted to ask the Rows collection for what I needed. No looping, no temp variables, just give me what I want.</p> <pre><code>var customerOrderIds = table.Rows.Cast&lt;DataRow&gt;() .Where(x =&gt; (string)x["CUSTOMER_ID"] == customerId) .Select(x =&gt; (string)x["CUSTOMER_ORDER_ID"]) .Distinct(); </code></pre> <p><strong>My question is whether or not this is a good thing, or am getting carried away with LINQ?</strong> It does seem to me that this declarative style of pulling a subset of data out of a collection is a good thing and more readable in the end. But then again, maybe I'm just smitten :)</p>
[ { "answer_id": 262124, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 3, "selected": false, "text": "<p>Seems good to me - although I'd try to use a strongly typed data set which makes the LINQ queries look even more pleasant.</p>\n\n<p>But yes, LINQ is a very good thing - and LINQ to Objects (and the surrounding technologies for XML and DataSets) is fabulously predictable compared to the out-of-process LINQ providers. (It's less <em>sexy</em> than LINQ to SQL, but more widely applicable IMO.)</p>\n" }, { "answer_id": 262126, "author": "Mitchel Sellers", "author_id": 13279, "author_profile": "https://Stackoverflow.com/users/13279", "pm_score": 0, "selected": false, "text": "<p>Personally since the data table doesn't have the ability to do a select distinct on its own, I'll say that it isn't all that bad.</p>\n\n<p>I would potentially ask though if there was any way to eventually get to using objects rather than data tables, as I think it would be easier for future developers to understand.</p>\n" }, { "answer_id": 262127, "author": "Chad Moran", "author_id": 25416, "author_profile": "https://Stackoverflow.com/users/25416", "pm_score": 0, "selected": false, "text": "<p>You're not getting carried away at all. There are actual works published on LINQ to DataSets. Having such clear, declarative object queries makes for much easier code maintainability. But you have to remember at the time you're filtering the data all of it has already been pulled back. You may want to consider adding the filtering to the SQL for the DataSet query.</p>\n" }, { "answer_id": 262167, "author": "Marc Gravell", "author_id": 23354, "author_profile": "https://Stackoverflow.com/users/23354", "pm_score": 5, "selected": true, "text": "<p>One other observation; if you aren't using typed datasets, you might also want to know about the <code>Field&lt;&gt;</code> extension method:</p>\n\n<pre><code> var customerOrderIds = table.Rows.Cast&lt;DataRow&gt;()\n .Where(x =&gt; x.Field&lt;string&gt;(\"CUSTOMER_ID\") == customerId)\n .Select(x =&gt; x.Field&lt;string&gt;(\"CUSTOMER_ORDER_ID\"))\n .Distinct();\n</code></pre>\n\n<p>Or using the query syntax:</p>\n\n<pre><code> var customerOrderIds = (\n from row in table.Rows.Cast&lt;DataRow&gt;()\n where row.Field&lt;string&gt;(\"CUSTOMER_ID\") == customerId\n select row.Field&lt;string&gt;(\"CUSTOMER_ORDER_ID\")\n ).Distinct();\n</code></pre>\n\n<p>I'm not saying it is better or worse - just another viable option.</p>\n\n<p>(Actually, I don't use <code>DataTable</code> very much, so YMMV)</p>\n" }, { "answer_id": 262190, "author": "Timothy Khouri", "author_id": 11917, "author_profile": "https://Stackoverflow.com/users/11917", "pm_score": 0, "selected": false, "text": "<p>LINQ is simply writing the \"looping/temp variable\" code for you. LINQ helps you to write code faster (and more readable).</p>\n\n<p>You're code is good.</p>\n" }, { "answer_id": 262821, "author": "Amy B", "author_id": 8155, "author_profile": "https://Stackoverflow.com/users/8155", "pm_score": 2, "selected": false, "text": "<p>The query looks fine.</p>\n\n<p>I'd like to point out two small things.</p>\n\n<blockquote>\n <p>No looping</p>\n</blockquote>\n\n<p>System.Linq.Enumerable methods operate against the IEnumerable(T) contract, which almost always means looping - O(N) solutions. Two implications of this: </p>\n\n<ul>\n<li>Prefer Any() over Count() > 0 . Any() is O(1). Count() is O(N).</li>\n<li>Join... all joins are nested loop O(M*N).</li>\n</ul>\n\n<blockquote>\n <p>.Cast</p>\n</blockquote>\n\n<p>.Cast works great for DataTable.Rows (all those objects -are- rows, so cast always succeeds). For heterogeneous collections, be aware of .OfType() - which filters out any items that cannot be casted.</p>\n\n<p>Lastly, be aware that queries are not executed until they are enumerated! You can force enumeration by foreach, ToList, ToArray, First, Single, and many more.</p>\n" }, { "answer_id": 1245464, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>A join (using the join keyword, but not the from keyword) uses a Dictionary for the matches and is thus <code>O(M+N)</code>.</p>\n\n<p>So is a group by, but not the following:</p>\n\n<pre><code>from x in Xs\nfrom y in Ys\n .Where(o =&gt; o == x)\nselect new\n{\n x,\n y\n}\n</code></pre>\n\n<p>which is <code>O(M*N)</code>.</p>\n" } ]
2008/11/04
[ "https://Stackoverflow.com/questions/262110", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2595/" ]
Ok, the more I use LINQ, the more I like it! I recently found myself working in some legacy code at work. It is your classic DataSet and DataTable rich application. Well, when adding a bit of functionality I found myself *really* wanting to just query the rows of a DataTable for the results I was looking for. Let me repeat that... instead of looping and adding to a temp collection, I just wanted to ask the Rows collection for what I needed. No looping, no temp variables, just give me what I want. ``` var customerOrderIds = table.Rows.Cast<DataRow>() .Where(x => (string)x["CUSTOMER_ID"] == customerId) .Select(x => (string)x["CUSTOMER_ORDER_ID"]) .Distinct(); ``` **My question is whether or not this is a good thing, or am getting carried away with LINQ?** It does seem to me that this declarative style of pulling a subset of data out of a collection is a good thing and more readable in the end. But then again, maybe I'm just smitten :)
One other observation; if you aren't using typed datasets, you might also want to know about the `Field<>` extension method: ``` var customerOrderIds = table.Rows.Cast<DataRow>() .Where(x => x.Field<string>("CUSTOMER_ID") == customerId) .Select(x => x.Field<string>("CUSTOMER_ORDER_ID")) .Distinct(); ``` Or using the query syntax: ``` var customerOrderIds = ( from row in table.Rows.Cast<DataRow>() where row.Field<string>("CUSTOMER_ID") == customerId select row.Field<string>("CUSTOMER_ORDER_ID") ).Distinct(); ``` I'm not saying it is better or worse - just another viable option. (Actually, I don't use `DataTable` very much, so YMMV)
262,116
<p>The build machine at work has many projects, but we are only experiencing a problem with one. </p> <p>Two projects are very similar, one builds in debug mode, the other in release mode. They both clear out the projects directory, and then does a full Get from source safe. The debug build gets the source fine and fairly quickly, but the release build takes ages to get the source (It pauses for a long time on the CheckingModifications part, whereas the debug build does not pause for nearly as long). The sourcecontrol blocks are identical (included from a single file), and are as follows:</p> <pre><code>&lt;sourcecontrol type="vss" autoGetSource="true" applyLabel="false"&gt; &lt;executable&gt;C:\Program Files\Microsoft Visual Studio\VSS\win32\SS.EXE&lt;/executable&gt; &lt;project&gt;$/Projects&lt;/project&gt; &lt;username&gt;####&lt;/username&gt; &lt;password&gt;####&lt;/password&gt; &lt;ssdir&gt;\\####\SourceCode\VSS&lt;/ssdir&gt; &lt;workingDirectory&gt;D:\Projects\&lt;/workingDirectory&gt; &lt;culture&gt;en-GB&lt;/culture&gt; &lt;cleanCopy&gt;True&lt;/cleanCopy&gt; &lt;/sourcecontrol&gt; </code></pre> <p>Any one have any ideas on why the release builds source control block is slower?</p>
[ { "answer_id": 1730490, "author": "Pedro", "author_id": 13188, "author_profile": "https://Stackoverflow.com/users/13188", "pm_score": 0, "selected": false, "text": "<p>Are the Debug and Release builds running at the same time? If so, I could see one waiting for the other to finish.</p>\n" }, { "answer_id": 1742403, "author": "Pondidum", "author_id": 1500, "author_profile": "https://Stackoverflow.com/users/1500", "pm_score": 3, "selected": true, "text": "<p>In the end we have switched from SourceSafe to SourceGear Vault (mainly for branching features, but speed and reliability were also large factors).</p>\n\n<p>We have also moved our build machine from an old pc to a server which has a 1Gb/s connection to the source server, rather than 100Mb/s, which has helped considerably.</p>\n\n<p>In the end when I was installing and testing Vault on the same machine (well, a clone) as the old build machine, it was cutting the source get operation from around 10 mins to 5. Once it was installed on the build server source get time is now around 1min.</p>\n\n<p>My advice to anyone is just to switch from SourceSafe to anything else...you wont regret it.</p>\n" } ]
2008/11/04
[ "https://Stackoverflow.com/questions/262116", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1500/" ]
The build machine at work has many projects, but we are only experiencing a problem with one. Two projects are very similar, one builds in debug mode, the other in release mode. They both clear out the projects directory, and then does a full Get from source safe. The debug build gets the source fine and fairly quickly, but the release build takes ages to get the source (It pauses for a long time on the CheckingModifications part, whereas the debug build does not pause for nearly as long). The sourcecontrol blocks are identical (included from a single file), and are as follows: ``` <sourcecontrol type="vss" autoGetSource="true" applyLabel="false"> <executable>C:\Program Files\Microsoft Visual Studio\VSS\win32\SS.EXE</executable> <project>$/Projects</project> <username>####</username> <password>####</password> <ssdir>\\####\SourceCode\VSS</ssdir> <workingDirectory>D:\Projects\</workingDirectory> <culture>en-GB</culture> <cleanCopy>True</cleanCopy> </sourcecontrol> ``` Any one have any ideas on why the release builds source control block is slower?
In the end we have switched from SourceSafe to SourceGear Vault (mainly for branching features, but speed and reliability were also large factors). We have also moved our build machine from an old pc to a server which has a 1Gb/s connection to the source server, rather than 100Mb/s, which has helped considerably. In the end when I was installing and testing Vault on the same machine (well, a clone) as the old build machine, it was cutting the source get operation from around 10 mins to 5. Once it was installed on the build server source get time is now around 1min. My advice to anyone is just to switch from SourceSafe to anything else...you wont regret it.
262,141
<p>I have a image button. I wanted to add a text "Search" on it. I am not able to add it because the "imagebutton" property in VS 2008 does not have text control in it. Can anyone tell me how to add text to a image button?? </p> <pre><code> &lt;asp:ImageButton ID="Searchbutton" runat="server" AlternateText="Search" CssClass="bluebutton" ImageUrl="../Graphics/bluebutton.gif" Width="110px" onclick="Searchbutton_Click"/&gt; </code></pre>
[ { "answer_id": 262171, "author": "leppie", "author_id": 15541, "author_profile": "https://Stackoverflow.com/users/15541", "pm_score": 5, "selected": true, "text": "<pre><code>&lt;button runat=\"server\" \n style=\"background-image:url('/Content/Img/stackoverflow-logo-250.png')\" &gt;\n your text here&lt;br/&gt;and some more&lt;br/&gt;&lt;br/&gt; and some more ....\n &lt;/button&gt;\n</code></pre>\n" }, { "answer_id": 262173, "author": "Marek Blotny", "author_id": 33744, "author_profile": "https://Stackoverflow.com/users/33744", "pm_score": 3, "selected": false, "text": "<p>You can't do that with <code>ImageButton</code>. </p>\n\n<p>However, you can use a simple <code>Button</code>, set the text, and add a background image (bluebutton.gif) using CSS to achieve the desired effect.</p>\n" }, { "answer_id": 262191, "author": "Arief", "author_id": 34096, "author_profile": "https://Stackoverflow.com/users/34096", "pm_score": 0, "selected": false, "text": "<p>I don't think you can write text to an ImageButton control of ASP.NET. You can generate image on the fly if that's what you need, and write the text from your code behind, but it will be too complicated, use normal button with CSS instead, unless your image cannot be generated by CSS.</p>\n" }, { "answer_id": 1658527, "author": "Khanzor", "author_id": 68268, "author_profile": "https://Stackoverflow.com/users/68268", "pm_score": 0, "selected": false, "text": "<p>You can also do this using an asp:Label, like this:</p>\n\n<pre><code>&lt;style type=\"text/css\"&gt;\n .faux-button\n {\n cursor:pointer;\n }\n&lt;/style&gt;\n\n&lt;div class=\"faux-button\"&gt;\n &lt;asp:ImageButton ID=\"ibtnAddUser\" \n runat=\"server\" \n ImageUrl=\"~/Images/add.gif\" \n AlternateText=\"Add a user image\" /&gt;\n &lt;asp:Label ID=\"lblAddUser\" \n runat=\"server\" \n Text=\"Add User\" \n AssociatedControlID=\"imgClick\" /&gt;\n&lt;/div&gt;\n</code></pre>\n" }, { "answer_id": 4429329, "author": "Iman", "author_id": 184572, "author_profile": "https://Stackoverflow.com/users/184572", "pm_score": 3, "selected": false, "text": "<p>This tip from <a href=\"http://forums.asp.net/t/1024015.aspx\" rel=\"noreferrer\">dotnetslave.com</a> worked for me:</p>\n\n<pre><code>&lt;asp:LinkButton \n CssClass=\"lnkSubmit\" \n ID=\"lnkButton\" \n runat=\"server\"&gt;SUBMIT&lt;/asp:LinkButton&gt;\n\na.lnkSubmit:active\n{ \n margin:0px 0px 0px 0px;\n background:url(../../images/li_bg1.jpg) left center no-repeat;\n padding: 0em 1.2em;\n font: 8pt \"tahoma\";\n color: #336699;\n text-decoration: none;\n font-weight: normal;\n letter-spacing: 0px;\n</code></pre>\n\n<p>}</p>\n" }, { "answer_id": 5323678, "author": "PraveenPandey", "author_id": 662248, "author_profile": "https://Stackoverflow.com/users/662248", "pm_score": 1, "selected": false, "text": "<p>It is not possible to add text inside of an image button. I have also faced the same problem. My solution was to use a link button instead of an image button. Just adding the image in the style tag should work. </p>\n" }, { "answer_id": 9173554, "author": "Etherman", "author_id": 1075062, "author_profile": "https://Stackoverflow.com/users/1075062", "pm_score": 0, "selected": false, "text": "<p>I realise this is an old post, but I have recently solved this same problem for myself.</p>\n\n<p>I created an ImgButton server control to render this:</p>\n\n<pre><code>&lt;button&gt; &lt;img src=\"button_icon.png\" /&gt; Caption Text &lt;/button&gt;\n</code></pre>\n\n<p>Using CSS to style a background image has some drawbacks, mainly:</p>\n\n<ul>\n<li>The text tends to overlap the image unless you get clever with left-aligned image and right-aligned text (which is then inconvenient if you throw a RTL language into the mix)</li>\n<li>The image is a background image, and does not appear to be \"on the button\" when we click the button it does not get \"pushed down\" the same as the text</li>\n</ul>\n\n<p>I'll try to insert the code here, but also have the full source code and examples here:\n<a href=\"http://www.allottware.co.za/Blog/archive/2012/02/07/button-img-button-with-image-and-text-button.aspx\" rel=\"nofollow\">Button with Img tag and Caption Text</a></p>\n\n<p>ImgButton.cs:</p>\n\n<pre><code>[DefaultProperty(\"Text\")]\n[DefaultEvent(\"Click\")]\n[ToolboxData(\"&lt;{0}:ImgButton runat=server&gt;&lt;/{0}:ImgButton&gt;\")]\npublic class ImgButton : WebControl, IPostBackEventHandler\n{\n #region Public Properties\n\n public enum ImgButtonStyle\n {\n Button,\n Anchor\n }\n\n [Bindable(true)]\n [Category(\"Appearance\")]\n [DefaultValue(\"\")]\n [Localizable(true)]\n public string Text\n {\n get\n {\n String s = (String)ViewState[\"Text\"];\n return ((s == null) ? String.Empty : s);\n }\n\n set\n {\n ViewState[\"Text\"] = value;\n }\n }\n [EditorAttribute(typeof(System.Web.UI.Design.ImageUrlEditor), typeof(UITypeEditor))]\n public string ImgSrc { get; set; }\n public string CommandName { get; set; }\n public string CommandArgument { get; set; }\n [EditorAttribute(typeof(System.Web.UI.Design.UrlEditor), typeof(UITypeEditor))]\n public string NavigateUrl { get; set; }\n public string OnClientClick { get; set; }\n public ImgButtonStyle RenderStyle { get; set; }\n [DefaultValue(true)]\n public bool UseSubmitBehavior { get; set; }\n [DefaultValue(true)]\n public bool CausesValidation { get; set; }\n public string ValidationGroup { get; set; }\n [DefaultValue(0)]\n public int Tag { get; set; }\n\n #endregion\n\n #region Constructor\n\n public ImgButton()\n {\n Text = \"Text\";\n ImgSrc = \"~/Masters/_default/img/action-help.png\";\n UseSubmitBehavior = true;\n CausesValidation = true;\n }\n\n #endregion\n\n #region Events\n\n // Defines the Click event.\n public event EventHandler Click;\n public event CommandEventHandler Command;\n\n protected virtual void OnClick(EventArgs e)\n {\n if (Click != null)\n {\n Click(this, e);\n }\n }\n\n protected virtual void OnCommand(CommandEventArgs e)\n {\n if (Command != null)\n {\n Command(this, e);\n }\n RaiseBubbleEvent(this, e);\n }\n\n public void RaisePostBackEvent(string eventArgument)\n {\n if (CausesValidation)\n {\n Page.Validate(ValidationGroup);\n if (!Page.IsValid) return;\n }\n OnClick(EventArgs.Empty);\n if (!String.IsNullOrEmpty(CommandName))\n OnCommand(new CommandEventArgs(CommandName, CommandArgument));\n }\n\n #endregion\n\n #region Rendering\n\n // Do not wrap in &lt;span&gt; tag\n public override void RenderBeginTag(HtmlTextWriter writer)\n {\n writer.Write(\"\");\n }\n\n protected override void RenderContents(HtmlTextWriter output)\n {\n string click;\n string disabled = (Enabled ? \"\" : \"disabled \");\n string type = (String.IsNullOrEmpty(NavigateUrl) &amp;&amp; UseSubmitBehavior ? \"submit\" : \"button\");\n string imgsrc = ResolveUrl(ImgSrc ?? \"\");\n\n if (String.IsNullOrEmpty(NavigateUrl))\n click = Page.ClientScript.GetPostBackEventReference(this, \"\");\n else\n if (NavigateUrl != null)\n click = String.Format(\"location.href='{0}'\", ResolveUrl(NavigateUrl));\n else\n click = OnClientClick;\n\n switch (RenderStyle)\n {\n case ImgButtonStyle.Button:\n if (String.IsNullOrEmpty(NavigateUrl) &amp;&amp; UseSubmitBehavior)\n {\n output.Write(String.Format(\n \"&lt;button id=\\\"{0}\\\" {1}class=\\\"{2}\\\" type=\\\"{3}\\\" name=\\\"{4}\\\" title=\\\"{5}\\\"&gt;&lt;img src=\\\"{6}\\\" alt=\\\"{5}\\\"/&gt;{7}&lt;/button&gt;\",\n ClientID,\n disabled,\n CssClass,\n type,\n UniqueID,\n ToolTip,\n imgsrc,\n Text\n ));\n }\n else\n {\n output.Write(String.Format(\n \"&lt;button id=\\\"{0}\\\" {1}class=\\\"{2}\\\" type=\\\"{3}\\\" name=\\\"{4}\\\" onclick=\\\"javascript:{5}\\\" title=\\\"{6}\\\"&gt;&lt;img src=\\\"{7}\\\" alt=\\\"{6}\\\"/&gt;{8}&lt;/button&gt;\",\n ClientID,\n disabled,\n CssClass,\n type,\n UniqueID,\n click,\n ToolTip,\n imgsrc,\n Text\n ));\n }\n break;\n\n case ImgButtonStyle.Anchor:\n output.Write(String.Format(\n \"&lt;a id=\\\"{0}\\\" {1}class=\\\"{2}\\\" onclick=\\\"javascript:{3}\\\" title=\\\"{4}\\\"&gt;&lt;img src=\\\"{5}\\\" alt=\\\"{4}\\\"/&gt;{6}&lt;/a&gt;\",\n ID,\n disabled,\n CssClass,\n click,\n ToolTip,\n imgsrc,\n Text\n ));\n break;\n }\n }\n\n public override void RenderEndTag(HtmlTextWriter writer)\n {\n writer.Write(\"\");\n }\n\n #endregion\n}\n</code></pre>\n\n<p>Here is the CSS I use on my buttons (where I put \"icon\" in the CssClass property of the button):</p>\n\n<pre><code>button.icon\n{\n cursor: pointer;\n}\n\nbutton.icon img\n{\n margin: 0px;\n padding: 0px 5px 0px 5px;\n vertical-align: middle;\n}\n</code></pre>\n" }, { "answer_id": 45662886, "author": "megabc123", "author_id": 8458805, "author_profile": "https://Stackoverflow.com/users/8458805", "pm_score": 0, "selected": false, "text": "<p>If you use a Link button, you can add a bootstrap button and then add text via the CSS \"after\" property.</p>\n\n<p><strong>LinkButton:</strong></p>\n\n<pre><code>&lt;asp:LinkButton id=\"download\" CssClass=\"btn btn-primary\" Text=\"Download\" OnCommand=\"OnButtonClick\" CommandName=\"Download\" runat=\"server\"&gt;\n &lt;span aria-hidden=\"true\" class=\"glyphicon glyphicon-download-alt\"&gt;&lt;/span&gt;&lt;/asp:LinkButton&gt;\n</code></pre>\n\n<p><strong>CSS:</strong></p>\n\n<pre><code>#MainContent_download:after{ \ncontent: \"Download\"; \npadding-left: 5px;\n</code></pre>\n\n<p>}</p>\n" }, { "answer_id": 56633676, "author": "nes", "author_id": 4638823, "author_profile": "https://Stackoverflow.com/users/4638823", "pm_score": 0, "selected": false, "text": "<p>I prefer the below solution:</p>\n\n<pre><code> &lt;div style=\"padding: 5px; float: left;overflow: auto;height: auto;\"&gt;\n &lt;asp:ImageButton ID=\"ImageButton2\" ImageUrl=\"./icons/search24.png\" ToolTip=\"Search\" runat=\"server\" /&gt;\n &lt;p&gt;&lt;asp:Label ID=\"Label7\" runat=\"server\" Text=\"Search\"&gt;&lt;/asp:Label&gt;&lt;/p&gt;\n &lt;/div&gt;\n</code></pre>\n\n<p>You can change the <code>style</code> to make it center aligned, etc.</p>\n" } ]
2008/11/04
[ "https://Stackoverflow.com/questions/262141", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I have a image button. I wanted to add a text "Search" on it. I am not able to add it because the "imagebutton" property in VS 2008 does not have text control in it. Can anyone tell me how to add text to a image button?? ``` <asp:ImageButton ID="Searchbutton" runat="server" AlternateText="Search" CssClass="bluebutton" ImageUrl="../Graphics/bluebutton.gif" Width="110px" onclick="Searchbutton_Click"/> ```
``` <button runat="server" style="background-image:url('/Content/Img/stackoverflow-logo-250.png')" > your text here<br/>and some more<br/><br/> and some more .... </button> ```
262,143
<p>I have a html string held in memory after transforming to my desired template with XSLT. What is the best mechanism to the send this to the client printer? </p> <p>In previous projects I have shamelessly cheated and created a print preview screen, which was essentially an ASPX page with white background that I then printed using <code>Window.print()</code>.</p> <p>Cheers</p>
[ { "answer_id": 262164, "author": "Joel Coehoorn", "author_id": 3043, "author_profile": "https://Stackoverflow.com/users/3043", "pm_score": 1, "selected": false, "text": "<p>Look at CSS media selectors. You can use them to create a single page the looks how you want on the screen and also prints nicely when the user chooses print in the browser.</p>\n" }, { "answer_id": 262199, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": true, "text": "<p>I don't think a 'print preview' is cheating at all. Since your string is most likely on the server (ie created in ASP.NET code-behind), you must output it to the client somehow and call window.print() to print. There's no way for a webserver to access a client's printers. However you may be able to streamline things using a few tips:</p>\n\n<p>-use @media tags in CSS to provide a printable style for your page. In many cases, you can use this to hide any navigation, etc. and not have a need for a 'print preview'. I usually add something like the following to my .css file:</p>\n\n<pre><code>.showwhenprinting {position:absolute; display:none;}\n@media print\n{\n .hidewhenprinting {position:absolute; display:none;}\n .showwhenprinting {position:relative; display:block;}\n}\n</code></pre>\n\n<p>This will let you hide blocks when printing in most browsers. For example:</p>\n\n<pre><code>&lt;div class=\"someclass hidewhenprinting\"&gt;Navigation Menu&lt;/div&gt;\n&lt;div class=\"someclass showwhenprinting\"&gt;Printed Page Title&lt;/div&gt;\n</code></pre>\n\n<p>The other benefit of this approach is that it allows users to simply click 'print' as they normally would in the browser. The drawbacks are that some older browsers do not support it, and in some cases it does not give you enough control over the layout (for example if you want page headers/footers).</p>\n\n<p>-if the above doesn't give you the output you need (for example, you don't want the page URL, etc. on the printed result), the other option would be to use a printer-friendly format such as PDF. To do this, use Reporting Services or a similar tool for generating your PDF.</p>\n\n<p>-A final option I wouldn't really recommend is to add a hidden iframe to the page, populate it with your \"printable\" HTML, and call print() in it. This may work, but would require some javascript to pull off, so you would need to take care to make it cross-browser. This would have the same drawbacks of option #1, but be more difficult to get right.</p>\n" } ]
2008/11/04
[ "https://Stackoverflow.com/questions/262143", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11802/" ]
I have a html string held in memory after transforming to my desired template with XSLT. What is the best mechanism to the send this to the client printer? In previous projects I have shamelessly cheated and created a print preview screen, which was essentially an ASPX page with white background that I then printed using `Window.print()`. Cheers
I don't think a 'print preview' is cheating at all. Since your string is most likely on the server (ie created in ASP.NET code-behind), you must output it to the client somehow and call window.print() to print. There's no way for a webserver to access a client's printers. However you may be able to streamline things using a few tips: -use @media tags in CSS to provide a printable style for your page. In many cases, you can use this to hide any navigation, etc. and not have a need for a 'print preview'. I usually add something like the following to my .css file: ``` .showwhenprinting {position:absolute; display:none;} @media print { .hidewhenprinting {position:absolute; display:none;} .showwhenprinting {position:relative; display:block;} } ``` This will let you hide blocks when printing in most browsers. For example: ``` <div class="someclass hidewhenprinting">Navigation Menu</div> <div class="someclass showwhenprinting">Printed Page Title</div> ``` The other benefit of this approach is that it allows users to simply click 'print' as they normally would in the browser. The drawbacks are that some older browsers do not support it, and in some cases it does not give you enough control over the layout (for example if you want page headers/footers). -if the above doesn't give you the output you need (for example, you don't want the page URL, etc. on the printed result), the other option would be to use a printer-friendly format such as PDF. To do this, use Reporting Services or a similar tool for generating your PDF. -A final option I wouldn't really recommend is to add a hidden iframe to the page, populate it with your "printable" HTML, and call print() in it. This may work, but would require some javascript to pull off, so you would need to take care to make it cross-browser. This would have the same drawbacks of option #1, but be more difficult to get right.
262,150
<p>I have a page where my combo box has hundreds of elements which makes it very hard to pick the one item I want. Is there a good Javascript replacement that would do better than</p> <pre><code>&lt;select id="field-component" name="field_component"&gt; &lt;option selected="selected"&gt;1&lt;/option&gt;&lt;option&gt;2&lt;/option&gt;... &lt;/select&gt; </code></pre> <p>Is there something with "Intellisense"-like auto-complete?</p>
[ { "answer_id": 262187, "author": "VonC", "author_id": 6309, "author_profile": "https://Stackoverflow.com/users/6309", "pm_score": 3, "selected": true, "text": "<p><img src=\"https://i.stack.imgur.com/TouKN.gif\" alt=\"http://www.dhtmlx.com/images/logo_combo.gif\"><br>\nYou have <a href=\"http://www.dhtmlx.com/docs/products/dhtmlxCombo/index.shtml\" rel=\"nofollow noreferrer\">dhtmlCombo</a>, using ajax to retrieve data when you are filling the input field.</p>\n\n<p>dhtmlxCombo is a cross-browser JavaScript combobox with autocomplete feature. </p>\n\n<p>It extends basic selectbox functionality to meet the requirements of the most up-to-date web applications. </p>\n\n<p>dhtmlxCombo can be converted from existing HTML SELECT or populated with JavaScript. Supporting AJAX, it can also <strong>get list values from the server datasource dynamically</strong>. </p>\n" }, { "answer_id": 262213, "author": "Diodeus - James MacFarlane", "author_id": 12579, "author_profile": "https://Stackoverflow.com/users/12579", "pm_score": 0, "selected": false, "text": "<p>The <a href=\"http://github.com/madrobby/scriptaculous/wikis/ajax-autocompleter\" rel=\"nofollow noreferrer\">autocompleter</a> using <a href=\"http://prototypejs.org\" rel=\"nofollow noreferrer\">Prototype</a> and <a href=\"http://script.aculo.us/\" rel=\"nofollow noreferrer\">Scriptaculous</a> works well in this situation.</p>\n" }, { "answer_id": 262221, "author": "Christian C. Salvadó", "author_id": 5445, "author_profile": "https://Stackoverflow.com/users/5445", "pm_score": 2, "selected": false, "text": "<p>Check the <a href=\"http://plugins.jquery.com/project/jq-autocomplete\" rel=\"nofollow noreferrer\">jQuery Autocomplete</a> plugin, it's easy to use, you only have to generate a JSON response server side.</p>\n\n<p>See <a href=\"http://jquery.bassistance.de/autocomplete/demo/\" rel=\"nofollow noreferrer\">this demos</a>.</p>\n" }, { "answer_id": 263654, "author": "Kornel", "author_id": 27009, "author_profile": "https://Stackoverflow.com/users/27009", "pm_score": 3, "selected": false, "text": "<p>In HTML 5 there's standard combo box. </p>\n\n<p>Currently only Opera supports it, but if you happen to be time traveller or writing Opera-only application, it's a nice solution :)</p>\n\n<pre><code>&lt;input type=text list=listid&gt;\n&lt;datalist id=listid&gt;\n &lt;select&gt;&lt;option&gt;1&lt;option&gt;2&lt;/select&gt;\n&lt;/datalist&gt;\n</code></pre>\n" }, { "answer_id": 264259, "author": "Jared Farrish", "author_id": 451969, "author_profile": "https://Stackoverflow.com/users/451969", "pm_score": 0, "selected": false, "text": "<p>Just a note: If the select box is current focused, you can type on your keyboard and it will take you to the selection beginning with that text, so typing \"k-e-n\" into a US State dropdown would auto-select the \"Kentucky\" option.</p>\n" }, { "answer_id": 14446321, "author": "zoonman", "author_id": 669493, "author_profile": "https://Stackoverflow.com/users/669493", "pm_score": 0, "selected": false, "text": "<p>You can try this combobox realization <a href=\"http://www.zoonman.com/projects/combobox/\" rel=\"nofollow\">http://www.zoonman.com/projects/combobox/</a></p>\n\n<ul>\n<li>Pure JavaScript. Editable. Supports IE6.</li>\n<li>Nonstandard HTML layout.</li>\n</ul>\n" }, { "answer_id": 18116080, "author": "David Schwartz", "author_id": 399124, "author_profile": "https://Stackoverflow.com/users/399124", "pm_score": 0, "selected": false, "text": "<p>I think Twitter's free <code>typeahead.js</code> library is the best autocomplete library available today. Check it out at <a href=\"http://twitter.github.io/typeahead.js/\" rel=\"nofollow\">http://twitter.github.io/typeahead.js/</a></p>\n" } ]
2008/11/04
[ "https://Stackoverflow.com/questions/262150", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6583/" ]
I have a page where my combo box has hundreds of elements which makes it very hard to pick the one item I want. Is there a good Javascript replacement that would do better than ``` <select id="field-component" name="field_component"> <option selected="selected">1</option><option>2</option>... </select> ``` Is there something with "Intellisense"-like auto-complete?
![http://www.dhtmlx.com/images/logo_combo.gif](https://i.stack.imgur.com/TouKN.gif) You have [dhtmlCombo](http://www.dhtmlx.com/docs/products/dhtmlxCombo/index.shtml), using ajax to retrieve data when you are filling the input field. dhtmlxCombo is a cross-browser JavaScript combobox with autocomplete feature. It extends basic selectbox functionality to meet the requirements of the most up-to-date web applications. dhtmlxCombo can be converted from existing HTML SELECT or populated with JavaScript. Supporting AJAX, it can also **get list values from the server datasource dynamically**.
262,156
<p>I try to get rounded corners on a UIImage, what I read so far, the easiest way is to use a mask images. For this I used code from TheElements iPhone Example and some image resize code I found. My problem is that resizedImage is always nil and I don't find the error...</p> <pre><code>- (UIImage *)imageByScalingProportionallyToSize:(CGSize)targetSize { CGSize imageSize = [self size]; float width = imageSize.width; float height = imageSize.height; // scaleFactor will be the fraction that we'll // use to adjust the size. For example, if we shrink // an image by half, scaleFactor will be 0.5. the // scaledWidth and scaledHeight will be the original, // multiplied by the scaleFactor. // // IMPORTANT: the "targetHeight" is the size of the space // we're drawing into. The "scaledHeight" is the height that // the image actually is drawn at, once we take into // account the ideal of maintaining proportions float scaleFactor = 0.0; float scaledWidth = targetSize.width; float scaledHeight = targetSize.height; CGPoint thumbnailPoint = CGPointMake(0,0); // since not all images are square, we want to scale // proportionately. To do this, we find the longest // edge and use that as a guide. if ( CGSizeEqualToSize(imageSize, targetSize) == NO ) { // use the longeset edge as a guide. if the // image is wider than tall, we'll figure out // the scale factor by dividing it by the // intended width. Otherwise, we'll use the // height. float widthFactor = targetSize.width / width; float heightFactor = targetSize.height / height; if ( widthFactor &lt; heightFactor ) scaleFactor = widthFactor; else scaleFactor = heightFactor; // ex: 500 * 0.5 = 250 (newWidth) scaledWidth = width * scaleFactor; scaledHeight = height * scaleFactor; // center the thumbnail in the frame. if // wider than tall, we need to adjust the // vertical drawing point (y axis) if ( widthFactor &lt; heightFactor ) thumbnailPoint.y = (targetSize.height - scaledHeight) * 0.5; else if ( widthFactor &gt; heightFactor ) thumbnailPoint.x = (targetSize.width - scaledWidth) * 0.5; } CGContextRef mainViewContentContext; CGColorSpaceRef colorSpace; colorSpace = CGColorSpaceCreateDeviceRGB(); // create a bitmap graphics context the size of the image mainViewContentContext = CGBitmapContextCreate (NULL, targetSize.width, targetSize.height, 8, 0, colorSpace, kCGImageAlphaPremultipliedLast); // free the rgb colorspace CGColorSpaceRelease(colorSpace); if (mainViewContentContext==NULL) return NULL; //CGContextSetFillColorWithColor(mainViewContentContext, [[UIColor whiteColor] CGColor]); //CGContextFillRect(mainViewContentContext, CGRectMake(0, 0, targetSize.width, targetSize.height)); CGContextDrawImage(mainViewContentContext, CGRectMake(thumbnailPoint.x, thumbnailPoint.y, scaledWidth, scaledHeight), self.CGImage); // Create CGImageRef of the main view bitmap content, and then // release that bitmap context CGImageRef mainViewContentBitmapContext = CGBitmapContextCreateImage(mainViewContentContext); CGContextRelease(mainViewContentContext); CGImageRef maskImage = [[UIImage imageNamed:@"Mask.png"] CGImage]; CGImageRef resizedImage = CGImageCreateWithMask(mainViewContentBitmapContext, maskImage); CGImageRelease(mainViewContentBitmapContext); // convert the finished resized image to a UIImage UIImage *theImage = [UIImage imageWithCGImage:resizedImage]; // image is retained by the property setting above, so we can // release the original CGImageRelease(resizedImage); // return the image return theImage; } </code></pre>
[ { "answer_id": 262545, "author": "Lounges", "author_id": 8918, "author_profile": "https://Stackoverflow.com/users/8918", "pm_score": 0, "selected": false, "text": "<p><a href=\"https://stackoverflow.com/questions/205431/rounded-corners-on-uiimage#205643\">See here...</a>\nIMO unless you absolutely need to do it in code, just overlay an image on top.</p>\n\n<p>Something along the lines of...</p>\n\n<pre><code>- (void)drawRect:(CGRect)rect \n{\n // Drawing code\n [backgroundImage drawInRect:rect];\n [buttonOverlay drawInRect:rect]; \n}\n</code></pre>\n" }, { "answer_id": 262566, "author": "wisequark", "author_id": 33159, "author_profile": "https://Stackoverflow.com/users/33159", "pm_score": 3, "selected": false, "text": "<p>You aren't actually doing anything other than scaling there. What you need to do is to \"mask\" the corners of the image by clipping it with a CGPath. For instance - </p>\n\n<pre><code> - (void)drawRect:(CGRect)rect {\n CGContextRef context = UIGraphicsGetCurrentContext();\n CGContextBeginTransparencyLayerWithRect(context, self.frame, NULL);\n CGContextSetRGBFillColor(context, 1.0, 1.0, 1.0, 1.0); \n CGFloat roundRadius = (radius) ? radius : 12.0;\n CGFloat minx = CGRectGetMinX(self.frame), midx = CGRectGetMidX(self.frame), maxx = CGRectGetMaxX(self.frame);\n CGFloat miny = CGRectGetMinY(self.frame), midy = CGRectGetMidY(self.frame), maxy = CGRectGetMaxY(self.frame);\n\n // draw the arcs, handle paths\n CGContextMoveToPoint(context, minx, midy);\n CGContextAddArcToPoint(context, minx, miny, midx, miny, roundRadius);\n CGContextAddArcToPoint(context, maxx, miny, maxx, midy, roundRadius);\n CGContextAddArcToPoint(context, maxx, maxy, midx, maxy, roundRadius);\n CGContextAddArcToPoint(context, minx, maxy, minx, midy, roundRadius);\n CGContextClosePath(context);\n CGContextDrawPath(context, kCGPathFill);\n CGContextEndTransparencyLayer(context);\n}\n</code></pre>\n\n<p>I suggest checking out the Quartz 2D programming guide or some other samples.</p>\n" }, { "answer_id": 698800, "author": "catlan", "author_id": 23028, "author_profile": "https://Stackoverflow.com/users/23028", "pm_score": 5, "selected": true, "text": "<p>The problem was the use of CGImageCreateWithMask which returned an all black image. The solution I found was to use CGContextClipToMask instead:</p>\n\n<pre><code>CGContextRef mainViewContentContext;\nCGColorSpaceRef colorSpace;\n\ncolorSpace = CGColorSpaceCreateDeviceRGB();\n\n// create a bitmap graphics context the size of the image\nmainViewContentContext = CGBitmapContextCreate (NULL, targetSize.width, targetSize.height, 8, 0, colorSpace, kCGImageAlphaPremultipliedLast);\n\n// free the rgb colorspace\nCGColorSpaceRelease(colorSpace); \n\nif (mainViewContentContext==NULL)\n return NULL;\n\nCGImageRef maskImage = [[UIImage imageNamed:@\"mask.png\"] CGImage];\nCGContextClipToMask(mainViewContentContext, CGRectMake(0, 0, targetSize.width, targetSize.height), maskImage);\nCGContextDrawImage(mainViewContentContext, CGRectMake(thumbnailPoint.x, thumbnailPoint.y, scaledWidth, scaledHeight), self.CGImage);\n\n\n// Create CGImageRef of the main view bitmap content, and then\n// release that bitmap context\nCGImageRef mainViewContentBitmapContext = CGBitmapContextCreateImage(mainViewContentContext);\nCGContextRelease(mainViewContentContext);\n\n// convert the finished resized image to a UIImage \nUIImage *theImage = [UIImage imageWithCGImage:mainViewContentBitmapContext];\n// image is retained by the property setting above, so we can \n// release the original\nCGImageRelease(mainViewContentBitmapContext);\n\n// return the image\nreturn theImage;\n</code></pre>\n" }, { "answer_id": 1572549, "author": "sang", "author_id": 152673, "author_profile": "https://Stackoverflow.com/users/152673", "pm_score": 1, "selected": false, "text": "<p>The reason it worked with clipping, not with masking, seems to be the color space. </p>\n\n<p>Apple Documentation's below.</p>\n\n<p>mask\nA mask. If the mask is an image, it must be in the DeviceGray color space, must not have an alpha component, and may not itself be masked by an image mask or a masking color. If the mask is not the same size as the image specified by the image parameter, then Quartz scales the mask to fit the image.</p>\n" }, { "answer_id": 1834558, "author": "jessecurry", "author_id": 151792, "author_profile": "https://Stackoverflow.com/users/151792", "pm_score": 8, "selected": false, "text": "<p>If you are using a UIImageView to display the image you can simply do the following:</p>\n\n<pre><code>imageView.layer.cornerRadius = 5.0;\nimageView.layer.masksToBounds = YES;\n</code></pre>\n\n<p>And to add a border:</p>\n\n<pre><code>imageView.layer.borderColor = [UIColor lightGrayColor].CGColor;\nimageView.layer.borderWidth = 1.0;\n</code></pre>\n\n<p>I believe that you'll have to import <code>&lt;QuartzCore/QuartzCore.h&gt;</code> and link against it for the above code to work.</p>\n" }, { "answer_id": 8206424, "author": "epatel", "author_id": 842, "author_profile": "https://Stackoverflow.com/users/842", "pm_score": 7, "selected": false, "text": "<p>How about these lines...</p>\n\n<pre><code>// Get your image somehow\nUIImage *image = [UIImage imageNamed:@\"image.jpg\"];\n\n// Begin a new image that will be the new image with the rounded corners \n// (here with the size of an UIImageView)\nUIGraphicsBeginImageContextWithOptions(imageView.bounds.size, NO, 1.0);\n\n// Add a clip before drawing anything, in the shape of an rounded rect\n[[UIBezierPath bezierPathWithRoundedRect:imageView.bounds \n cornerRadius:10.0] addClip];\n// Draw your image\n[image drawInRect:imageView.bounds];\n\n// Get the image, here setting the UIImageView image\nimageView.image = UIGraphicsGetImageFromCurrentImageContext();\n\n// Lets forget about that we were drawing\nUIGraphicsEndImageContext();\n</code></pre>\n" }, { "answer_id": 10619379, "author": "Voda Ion", "author_id": 1233416, "author_profile": "https://Stackoverflow.com/users/1233416", "pm_score": 2, "selected": false, "text": "<pre><code>static void addRoundedRectToPath(CGContextRef context, CGRect rect, float ovalWidth, float ovalHeight)\n{\n float fw, fh;\n if (ovalWidth == 0 || ovalHeight == 0) {\n CGContextAddRect(context, rect);\n return;\n }\n CGContextSaveGState(context);\n CGContextTranslateCTM (context, CGRectGetMinX(rect), CGRectGetMinY(rect));\n CGContextScaleCTM (context, ovalWidth, ovalHeight);\n fw = CGRectGetWidth (rect) / ovalWidth;\n fh = CGRectGetHeight (rect) / ovalHeight;\n CGContextMoveToPoint(context, fw, fh/2);\n CGContextAddArcToPoint(context, fw, fh, fw/2, fh, 1);\n CGContextAddArcToPoint(context, 0, fh, 0, fh/2, 1);\n CGContextAddArcToPoint(context, 0, 0, fw/2, 0, 1);\n CGContextAddArcToPoint(context, fw, 0, fw, fh/2, 1);\n CGContextClosePath(context);\n CGContextRestoreGState(context);\n}\n\n+ (UIImage *)imageWithRoundCorner:(UIImage*)img andCornerSize:(CGSize)size\n{\n UIImage * newImage = nil;\n\n if( nil != img)\n {\n @autoreleasepool {\n int w = img.size.width;\n int h = img.size.height;\n\n CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();\n CGContextRef context = CGBitmapContextCreate(NULL, w, h, 8, 4 * w, colorSpace, kCGImageAlphaPremultipliedFirst);\n\n CGContextBeginPath(context);\n CGRect rect = CGRectMake(0, 0, img.size.width, img.size.height);\n addRoundedRectToPath(context, rect, size.width, size.height);\n CGContextClosePath(context);\n CGContextClip(context);\n\n CGContextDrawImage(context, CGRectMake(0, 0, w, h), img.CGImage);\n\n CGImageRef imageMasked = CGBitmapContextCreateImage(context);\n CGContextRelease(context);\n CGColorSpaceRelease(colorSpace);\n [img release];\n\n newImage = [[UIImage imageWithCGImage:imageMasked] retain];\n CGImageRelease(imageMasked);\n\n }\n }\n\n return newImage;\n}\n</code></pre>\n" }, { "answer_id": 13836510, "author": "Augustine P A", "author_id": 889289, "author_profile": "https://Stackoverflow.com/users/889289", "pm_score": 1, "selected": false, "text": "<p>Hi guys try this code,</p>\n\n<pre><code>+ (UIImage *)roundedRectImageFromImage:(UIImage *)image withRadious:(CGFloat)radious {\n\nif(radious == 0.0f)\n return image;\n\nif( image != nil) {\n\n CGFloat imageWidth = image.size.width;\n CGFloat imageHeight = image.size.height;\n\n CGRect rect = CGRectMake(0.0f, 0.0f, imageWidth, imageHeight);\n UIWindow *window = [[[UIApplication sharedApplication] windows] objectAtIndex:0];\n const CGFloat scale = window.screen.scale;\n UIGraphicsBeginImageContextWithOptions(rect.size, NO, scale);\n\n CGContextRef context = UIGraphicsGetCurrentContext();\n\n CGContextBeginPath(context);\n CGContextSaveGState(context);\n CGContextTranslateCTM (context, CGRectGetMinX(rect), CGRectGetMinY(rect));\n CGContextScaleCTM (context, radious, radious);\n\n CGFloat rectWidth = CGRectGetWidth (rect)/radious;\n CGFloat rectHeight = CGRectGetHeight (rect)/radious;\n\n CGContextMoveToPoint(context, rectWidth, rectHeight/2.0f);\n CGContextAddArcToPoint(context, rectWidth, rectHeight, rectWidth/2.0f, rectHeight, radious);\n CGContextAddArcToPoint(context, 0.0f, rectHeight, 0.0f, rectHeight/2.0f, radious);\n CGContextAddArcToPoint(context, 0.0f, 0.0f, rectWidth/2.0f, 0.0f, radious);\n CGContextAddArcToPoint(context, rectWidth, 0.0f, rectWidth, rectHeight/2.0f, radious);\n CGContextRestoreGState(context);\n CGContextClosePath(context);\n CGContextClip(context);\n\n [image drawInRect:CGRectMake(0.0f, 0.0f, imageWidth, imageHeight)];\n\n UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();\n UIGraphicsEndImageContext();\n\n return newImage;\n}\n\nreturn nil;\n}\n</code></pre>\n\n<p>Cheers !!!</p>\n" }, { "answer_id": 32303467, "author": "Besi", "author_id": 784318, "author_profile": "https://Stackoverflow.com/users/784318", "pm_score": 5, "selected": false, "text": "<p>I created an <code>UIImage</code>-extension in swift, based on @epatel's great answer:</p>\n<pre><code>extension UIImage{\n var roundedImage: UIImage {\n let rect = CGRect(origin:CGPoint(x: 0, y: 0), size: self.size)\n UIGraphicsBeginImageContextWithOptions(self.size, false, 1)\n defer { \n // End context after returning to avoid memory leak\n UIGraphicsEndImageContext() \n }\n \n UIBezierPath(\n roundedRect: rect,\n cornerRadius: self.size.height\n ).addClip()\n self.drawInRect(rect)\n return UIGraphicsGetImageFromCurrentImageContext()\n }\n}\n</code></pre>\n<p>Tested in a storyboard:</p>\n<p><a href=\"https://i.stack.imgur.com/6Ij3P.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/6Ij3P.png\" alt=\"storyboard\" /></a></p>\n" }, { "answer_id": 32308205, "author": "user3182143", "author_id": 3182143, "author_profile": "https://Stackoverflow.com/users/3182143", "pm_score": 0, "selected": false, "text": "<p>For Creating a Round Corner image we can use quartzcore.</p>\n\n<p>First How to add QuartzCore framework?</p>\n\n<pre><code>Click project -Targets\n -&gt;project\n -&gt;BuildPhase\n -&gt;Link Binary with Libraries\n -&gt;Then click + symbol finally select from list and add it\n</code></pre>\n\n<p>or else</p>\n\n<pre><code>Click project -Targets\n -&gt;Targets\n -&gt;general\n -&gt;Linked Frameworks and Libraries\n -&gt;Then click + symbol finally select from list and add the QuartzCore framework\n</code></pre>\n\n<p>Now import </p>\n\n<pre><code>#import &lt;QuartzCore/QuartzCore.h&gt; \n</code></pre>\n\n<p>in your ViewController</p>\n\n<p>Then in viewDidLoad method</p>\n\n<pre><code>self.yourImageView.layer.cornerRadius = 5.0;\nself.yourImageView.layer.borderWidth = 1.0f;\nself.yourImageView.layer.borderColor = [UIColor blackColor].CGColor;\nself.yourImageView.layer.masksToBounds = YES;\n</code></pre>\n" }, { "answer_id": 42454084, "author": "bartosss", "author_id": 4867143, "author_profile": "https://Stackoverflow.com/users/4867143", "pm_score": 1, "selected": false, "text": "<p>It's very easy to create a rounded image when you make use of the image dimension.</p>\n\n<pre><code>cell.messageImage.layer.cornerRadius = image.size.width / 2\ncell.messageImage.layer.masksToBounds = true\n</code></pre>\n" }, { "answer_id": 45053455, "author": "Idan", "author_id": 1071887, "author_profile": "https://Stackoverflow.com/users/1071887", "pm_score": 1, "selected": false, "text": "<p>Found out the best and simple way of doing it is as follows (no answer did that):</p>\n\n<pre><code>UIImageView *imageView;\n\nimageView.layer.cornerRadius = imageView.frame.size.width/2.0f;\nimageView.layer.masksToBounds = TRUE;\n</code></pre>\n\n<p>Pretty simple and done this right.</p>\n" }, { "answer_id": 47518249, "author": "Donsb", "author_id": 9016470, "author_profile": "https://Stackoverflow.com/users/9016470", "pm_score": 0, "selected": false, "text": "<p>I was struggling to round the corners of a UIImage box in my storyboard. I had a IBOutlet for my UIImage called image. After reading a bunch of posts on here, I simply added 3 lines and that worked perfectly. </p>\n\n<pre><code>import UIKit\n</code></pre>\n\n<p>Then in viewDidLoad:</p>\n\n<pre><code>image.layer.cornerRadius = 20.0\n\nimage.layer.masksToBounds = true\n</code></pre>\n\n<p>This is for iOS 11.1 in Xcode 9.</p>\n" }, { "answer_id": 51657994, "author": "samwize", "author_id": 242682, "author_profile": "https://Stackoverflow.com/users/242682", "pm_score": 4, "selected": false, "text": "<p>Extending <a href=\"https://stackoverflow.com/a/32303467/242682\">Besi's excellent answer</a>, with correct scale, in <strong>Swift 4</strong>:</p>\n\n<pre><code>extension UIImage {\n\n public func rounded(radius: CGFloat) -&gt; UIImage {\n let rect = CGRect(origin: .zero, size: size)\n UIGraphicsBeginImageContextWithOptions(size, false, 0)\n UIBezierPath(roundedRect: rect, cornerRadius: radius).addClip()\n draw(in: rect)\n return UIGraphicsGetImageFromCurrentImageContext()!\n }\n\n}\n</code></pre>\n" }, { "answer_id": 52293534, "author": "scrat84", "author_id": 526410, "author_profile": "https://Stackoverflow.com/users/526410", "pm_score": 2, "selected": false, "text": "<p>I think this could be very related:\nIn iOS 11 there is a very elgant way of rounding each single corner of a (Image)View.</p>\n\n<pre><code>let imageView = UIImageView(image: UIImage(named: \"myImage\")) \nimageView.layer.maskedCorners = [.layerMinXMinYCorner, .layerMaxXMinYCorner]\nimageView.layer.cornerRadius = 10.0\n</code></pre>\n" }, { "answer_id": 62862742, "author": "maks_b", "author_id": 13243912, "author_profile": "https://Stackoverflow.com/users/13243912", "pm_score": 1, "selected": false, "text": "<p>I liked the answer of @samwize, however it caused me nasty memory leaks when used with collectionView.\nTo fix it I found that <code>UIGraphicsEndImageContext()</code> was missing</p>\n<pre class=\"lang-swift prettyprint-override\"><code>extension UIImage {\n /**\n Rounds corners of UIImage\n - Parameter proportion: Proportion to minimum paramter (width or height)\n in order to have the same look of corner radius independetly\n from aspect ratio and actual size\n */\n func roundCorners(proportion: CGFloat) -&gt; UIImage {\n let minValue = min(self.size.width, self.size.height)\n let radius = minValue/proportion\n \n let rect = CGRect(origin: CGPoint(x: 0, y: 0), size: self.size)\n UIGraphicsBeginImageContextWithOptions(self.size, false, 1)\n UIBezierPath(roundedRect: rect, cornerRadius: radius).addClip()\n self.draw(in: rect)\n let image = UIGraphicsGetImageFromCurrentImageContext() ?? self\n UIGraphicsEndImageContext()\n return image\n }\n}\n</code></pre>\n<p>Feel free to just pass the radius instead of proportion. <code>proportion</code> is used because I have collectionView scroll and images have different sizes, therefore when using constant <strong>radius</strong> it actually looks different in terms of proprtions (example: two images, one is 1000x1000 and another 2000x2000, <strong>corner radius</strong> of 30 will look different on each one of them)</p>\n<p>So if you do <code>image.roundCorners(proportion: 20)</code> all the pictures look like the have the same corner radius.</p>\n<p>This answer is also an updated version.</p>\n" } ]
2008/11/04
[ "https://Stackoverflow.com/questions/262156", "https://Stackoverflow.com", "https://Stackoverflow.com/users/23028/" ]
I try to get rounded corners on a UIImage, what I read so far, the easiest way is to use a mask images. For this I used code from TheElements iPhone Example and some image resize code I found. My problem is that resizedImage is always nil and I don't find the error... ``` - (UIImage *)imageByScalingProportionallyToSize:(CGSize)targetSize { CGSize imageSize = [self size]; float width = imageSize.width; float height = imageSize.height; // scaleFactor will be the fraction that we'll // use to adjust the size. For example, if we shrink // an image by half, scaleFactor will be 0.5. the // scaledWidth and scaledHeight will be the original, // multiplied by the scaleFactor. // // IMPORTANT: the "targetHeight" is the size of the space // we're drawing into. The "scaledHeight" is the height that // the image actually is drawn at, once we take into // account the ideal of maintaining proportions float scaleFactor = 0.0; float scaledWidth = targetSize.width; float scaledHeight = targetSize.height; CGPoint thumbnailPoint = CGPointMake(0,0); // since not all images are square, we want to scale // proportionately. To do this, we find the longest // edge and use that as a guide. if ( CGSizeEqualToSize(imageSize, targetSize) == NO ) { // use the longeset edge as a guide. if the // image is wider than tall, we'll figure out // the scale factor by dividing it by the // intended width. Otherwise, we'll use the // height. float widthFactor = targetSize.width / width; float heightFactor = targetSize.height / height; if ( widthFactor < heightFactor ) scaleFactor = widthFactor; else scaleFactor = heightFactor; // ex: 500 * 0.5 = 250 (newWidth) scaledWidth = width * scaleFactor; scaledHeight = height * scaleFactor; // center the thumbnail in the frame. if // wider than tall, we need to adjust the // vertical drawing point (y axis) if ( widthFactor < heightFactor ) thumbnailPoint.y = (targetSize.height - scaledHeight) * 0.5; else if ( widthFactor > heightFactor ) thumbnailPoint.x = (targetSize.width - scaledWidth) * 0.5; } CGContextRef mainViewContentContext; CGColorSpaceRef colorSpace; colorSpace = CGColorSpaceCreateDeviceRGB(); // create a bitmap graphics context the size of the image mainViewContentContext = CGBitmapContextCreate (NULL, targetSize.width, targetSize.height, 8, 0, colorSpace, kCGImageAlphaPremultipliedLast); // free the rgb colorspace CGColorSpaceRelease(colorSpace); if (mainViewContentContext==NULL) return NULL; //CGContextSetFillColorWithColor(mainViewContentContext, [[UIColor whiteColor] CGColor]); //CGContextFillRect(mainViewContentContext, CGRectMake(0, 0, targetSize.width, targetSize.height)); CGContextDrawImage(mainViewContentContext, CGRectMake(thumbnailPoint.x, thumbnailPoint.y, scaledWidth, scaledHeight), self.CGImage); // Create CGImageRef of the main view bitmap content, and then // release that bitmap context CGImageRef mainViewContentBitmapContext = CGBitmapContextCreateImage(mainViewContentContext); CGContextRelease(mainViewContentContext); CGImageRef maskImage = [[UIImage imageNamed:@"Mask.png"] CGImage]; CGImageRef resizedImage = CGImageCreateWithMask(mainViewContentBitmapContext, maskImage); CGImageRelease(mainViewContentBitmapContext); // convert the finished resized image to a UIImage UIImage *theImage = [UIImage imageWithCGImage:resizedImage]; // image is retained by the property setting above, so we can // release the original CGImageRelease(resizedImage); // return the image return theImage; } ```
The problem was the use of CGImageCreateWithMask which returned an all black image. The solution I found was to use CGContextClipToMask instead: ``` CGContextRef mainViewContentContext; CGColorSpaceRef colorSpace; colorSpace = CGColorSpaceCreateDeviceRGB(); // create a bitmap graphics context the size of the image mainViewContentContext = CGBitmapContextCreate (NULL, targetSize.width, targetSize.height, 8, 0, colorSpace, kCGImageAlphaPremultipliedLast); // free the rgb colorspace CGColorSpaceRelease(colorSpace); if (mainViewContentContext==NULL) return NULL; CGImageRef maskImage = [[UIImage imageNamed:@"mask.png"] CGImage]; CGContextClipToMask(mainViewContentContext, CGRectMake(0, 0, targetSize.width, targetSize.height), maskImage); CGContextDrawImage(mainViewContentContext, CGRectMake(thumbnailPoint.x, thumbnailPoint.y, scaledWidth, scaledHeight), self.CGImage); // Create CGImageRef of the main view bitmap content, and then // release that bitmap context CGImageRef mainViewContentBitmapContext = CGBitmapContextCreateImage(mainViewContentContext); CGContextRelease(mainViewContentContext); // convert the finished resized image to a UIImage UIImage *theImage = [UIImage imageWithCGImage:mainViewContentBitmapContext]; // image is retained by the property setting above, so we can // release the original CGImageRelease(mainViewContentBitmapContext); // return the image return theImage; ```
262,158
<p>The simple HTML below displays differently in Firefox and WebKit-based browsers (I checked in Safari, Chrome and iPhone).</p> <p>In Firefox both border and text have the same color (<code>#880000</code>), but in Safari the text gets a bit lighter (as if it had some transparency applied to it).</p> <p>Can I somehow fix this (remove this transparency in Safari)?</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;html xmlns="http://www.w3.org/1999/xhtml"&gt; &lt;head&gt; &lt;title&gt;&lt;/title&gt; &lt;style type="text/css"&gt; input:disabled{ border:solid 1px #880000; background-color:#ffffff; color:#880000; } &lt;/style&gt; &lt;/head&gt; &lt;body&gt; &lt;form action=""&gt; &lt;input type="text" value="disabled input box" disabled="disabled"/&gt; &lt;/form&gt; &lt;/body&gt; &lt;/html&gt;</code></pre> </div> </div> </p>
[ { "answer_id": 262478, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>Can you use a button instead of an input?</p>\n\n<pre><code>&lt;html xmlns=\"http://www.w3.org/1999/xhtml\"&gt;\n&lt;head&gt;\n &lt;title&gt;&lt;/title&gt;\n &lt;style type=\"text/css\"&gt;\n button:disabled{\n border:solid 1px #880000;\n background-color:#ffffff;\n color:#880000;\n }\n &lt;/style&gt;\n&lt;/head&gt;\n&lt;body&gt;\n &lt;form action=\"\"&gt;\n &lt;button type=\"button\" disabled=\"disabled\"&gt;disabled input box&lt;/button&gt;\n &lt;/form&gt;\n&lt;/body&gt;\n&lt;/html&gt;\n</code></pre>\n" }, { "answer_id": 263865, "author": "Steve Perks", "author_id": 16124, "author_profile": "https://Stackoverflow.com/users/16124", "pm_score": 3, "selected": false, "text": "<p>it's an interesting question and I've tried plenty of overrides to see if I can get it going, but nothing's working. Modern browsers actually use their own style sheets to tell elements how to display, so maybe if you can sniff out Chrome's stylesheet you can see what styles they're forcing on to it. I'll be very interested in the result and if you don't have one I'll spend a little time myself looking for it later when I have some time to waste.</p>\n\n<p>FYI,</p>\n\n<pre><code>opacity: 1!important;\n</code></pre>\n\n<p>doesn't override it, so I'm not sure it's opacity.</p>\n" }, { "answer_id": 263939, "author": "Kornel", "author_id": 27009, "author_profile": "https://Stackoverflow.com/users/27009", "pm_score": 3, "selected": false, "text": "<p>You could change color to <code>#440000</code> just for Safari, but IMHO the best solution would be <strong>not to</strong> change looks of button <em>at all</em>. This way, in every browser on every platform, it will look just like users expect it to.</p>\n" }, { "answer_id": 265706, "author": "Serxipc", "author_id": 34009, "author_profile": "https://Stackoverflow.com/users/34009", "pm_score": 2, "selected": false, "text": "<p>You can use the readonly attribute instead of the disabled attribute, but then you will need to add a class because there isn't a pseudo-class input:readonly.</p>\n\n<pre><code>&lt;html xmlns=\"http://www.w3.org/1999/xhtml\"&gt;\n&lt;head&gt;\n&lt;title&gt;&lt;/title&gt;\n&lt;style type=\"text/css\"&gt;\nbutton.readonly{\n border:solid 1px #880000;\n background-color:#ffffff;\n color:#880000;\n}\n&lt;/style&gt;\n&lt;/head&gt;\n&lt;body&gt;\n&lt;form action=\"\"&gt;\n &lt;button type=\"button\" readonly=\"readonly\" class=\"readonly\"&gt;disabled input box&lt;/button&gt;\n&lt;/form&gt;\n&lt;/body&gt;\n&lt;/html&gt;\n</code></pre>\n\n<p>Beware that a disabled input and readonly input aren't the same.\nA readonly input can have focus, and will send values on submit. Look at <a href=\"http://www.w3.org/TR/html401/interact/forms.html#h-17.12\" rel=\"nofollow noreferrer\">w3.org</a></p>\n" }, { "answer_id": 2951396, "author": "conceptDawg", "author_id": 34901, "author_profile": "https://Stackoverflow.com/users/34901", "pm_score": 2, "selected": false, "text": "<p>This question is very old but I thought that I would post an updated webkit solution.\nJust use the following CSS:</p>\n\n<pre><code>input::-webkit-input-placeholder {\n color: #880000;\n}\n</code></pre>\n" }, { "answer_id": 4648315, "author": "Kemo", "author_id": 570015, "author_profile": "https://Stackoverflow.com/users/570015", "pm_score": 9, "selected": true, "text": "<pre><code>-webkit-text-fill-color: #880000;\nopacity: 1; /* required on iOS */\n</code></pre>\n" }, { "answer_id": 23511280, "author": "lijinma", "author_id": 1702174, "author_profile": "https://Stackoverflow.com/users/1702174", "pm_score": 6, "selected": false, "text": "<p>Phone and Tablet webkit browsers (Safari and Chrome) and desktop IE have a number of default changes to disabled form elements that you'll need to override if you want to style disabled inputs.</p>\n\n<pre><code>-webkit-text-fill-color:#880000; /* Override iOS / Android font color change */\n-webkit-opacity:1; /* Override iOS opacity change affecting text &amp; background color */\ncolor:#880000; /* Override IE font color change */\n</code></pre>\n" }, { "answer_id": 45209441, "author": "vanduc1102", "author_id": 1681903, "author_profile": "https://Stackoverflow.com/users/1681903", "pm_score": 3, "selected": false, "text": "<p>for @ryan</p>\n\n<p>I wanted my disabled input box to look like a normal one. This is the only thing that would work in Safari Mobile.</p>\n\n<pre><code>-webkit-text-fill-color: rgba(0, 0, 0, 1);\n-webkit-opacity: 1;\nbackground: white;\n</code></pre>\n" }, { "answer_id": 55253186, "author": "Freez", "author_id": 4332533, "author_profile": "https://Stackoverflow.com/users/4332533", "pm_score": 2, "selected": false, "text": "<p>If you want to fix the problem for all the disabled inputs, you can define <code>-webkit-text-fill-color</code> to <code>currentcolor</code>, so the <code>color</code> property of the input will be used.</p>\n\n<pre class=\"lang-css prettyprint-override\"><code>input[disabled] {\n -webkit-text-fill-color: currentcolor;\n}\n</code></pre>\n\n<p>See that fiddle on Safari\n<a href=\"https://jsfiddle.net/u549yk87/3/\" rel=\"nofollow noreferrer\">https://jsfiddle.net/u549yk87/3/</a></p>\n" }, { "answer_id": 55876580, "author": "paulcol.", "author_id": 1101480, "author_profile": "https://Stackoverflow.com/users/1101480", "pm_score": 4, "selected": false, "text": "<p><strong>UPDATED 2021:</strong></p>\n<p>Combining ideas from this page into a &quot;set and forget&quot; reset that makes all disabled text the same as normal text.</p>\n<pre><code>input:disabled, textarea:disabled, input:disabled::placeholder, textarea:disabled::placeholder {\n -webkit-text-fill-color: currentcolor; /* 1. sets text fill to current `color` for safari */\n opacity: 1; /* 2. correct opacity on iOS */\n}\n</code></pre>\n" } ]
2008/11/04
[ "https://Stackoverflow.com/questions/262158", "https://Stackoverflow.com", "https://Stackoverflow.com/users/34187/" ]
The simple HTML below displays differently in Firefox and WebKit-based browsers (I checked in Safari, Chrome and iPhone). In Firefox both border and text have the same color (`#880000`), but in Safari the text gets a bit lighter (as if it had some transparency applied to it). Can I somehow fix this (remove this transparency in Safari)? ```html <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title></title> <style type="text/css"> input:disabled{ border:solid 1px #880000; background-color:#ffffff; color:#880000; } </style> </head> <body> <form action=""> <input type="text" value="disabled input box" disabled="disabled"/> </form> </body> </html> ```
``` -webkit-text-fill-color: #880000; opacity: 1; /* required on iOS */ ```
262,160
<p>I've got menu items that look like this</p> <pre><code>&lt;ul&gt; &lt;li&gt;Item1&lt;span class="context-trigger"&gt;&lt;/span&gt;&lt;/li&gt; &lt;li&gt;Item2&lt;span class="context-trigger"&gt;&lt;/span&gt;&lt;/li&gt; &lt;li&gt;Item3&lt;span class="context-trigger"&gt;&lt;/span&gt;&lt;/li&gt; &lt;/ul&gt; </code></pre> <p>with CSS that turns the above into a horizontal menu, and JS that turns the [spans] into buttons that bring up contextual menus. Vaguely like this:</p> <pre> Item1^ Item2^ Item3^ </pre> <p>If the menu gets too wide for the browser width, it wraps, which is what I want. The problem is that sometimes it's putting in line-breaks before the [spans]. I only want it to break between [li]s. Any ideas?</p>
[ { "answer_id": 262193, "author": "Huibert Gill", "author_id": 1254442, "author_profile": "https://Stackoverflow.com/users/1254442", "pm_score": 5, "selected": true, "text": "<p>try using </p>\n\n<pre><code>white-space: nowrap;\n</code></pre>\n\n<p>in the css definition of your context-trigger class.</p>\n\n<p>Edit: I think patmortech is correct though, putting nowrap on the span does not work, because there is no \"white space\" content. It might also be that sticking the style on the LI element does not work either, because the browser might breakup the parts because the span is a nested element in li. You might reconsider your code, drop the SPAN element and use css on the LI elements.</p>\n" }, { "answer_id": 262209, "author": "patmortech", "author_id": 19090, "author_profile": "https://Stackoverflow.com/users/19090", "pm_score": 2, "selected": false, "text": "<p>You need to put the following to keep your list item from wrapping (putting it in the context-trigger class would just keep the span contents from wrapping):</p>\n\n<pre><code>li { white-space:nowrap; }\n</code></pre>\n" }, { "answer_id": 262235, "author": "Chris Marasti-Georg", "author_id": 96, "author_profile": "https://Stackoverflow.com/users/96", "pm_score": 0, "selected": false, "text": "<p>If you float the <code>&lt;li&gt;</code> elements, you should get the effect you want.</p>\n" } ]
2008/11/04
[ "https://Stackoverflow.com/questions/262160", "https://Stackoverflow.com", "https://Stackoverflow.com/users/24197/" ]
I've got menu items that look like this ``` <ul> <li>Item1<span class="context-trigger"></span></li> <li>Item2<span class="context-trigger"></span></li> <li>Item3<span class="context-trigger"></span></li> </ul> ``` with CSS that turns the above into a horizontal menu, and JS that turns the [spans] into buttons that bring up contextual menus. Vaguely like this: ``` Item1^ Item2^ Item3^ ``` If the menu gets too wide for the browser width, it wraps, which is what I want. The problem is that sometimes it's putting in line-breaks before the [spans]. I only want it to break between [li]s. Any ideas?
try using ``` white-space: nowrap; ``` in the css definition of your context-trigger class. Edit: I think patmortech is correct though, putting nowrap on the span does not work, because there is no "white space" content. It might also be that sticking the style on the LI element does not work either, because the browser might breakup the parts because the span is a nested element in li. You might reconsider your code, drop the SPAN element and use css on the LI elements.
262,192
<p>In our project we have a large number (hundreds) of FLA files created by the artists in CS3, from which we compile SWFs to use in our Flex/AS3 application.</p> <p>As part of a streamlined build/deploy system, it would be really handy to be able to automate publishing all these FLAs, and ideally deploying the SWFs too. I found some ways to do the batch publishing from CS3 using JSFL, but was surprised to discover CS3 doesn't apparently have any command-line functionality for this?</p> <p>This is on a Linux system for what it's worth, I don't have experience with JSFL to know if you can run scripts from the command line somehow?</p> <p><strong>note</strong>: I should have said "Linux is preferred"... I don't use Linux but our server/build PC is Linux... I didn't realise CS3 was not compatible so I guess we can do this part on Windows.</p>
[ { "answer_id": 262228, "author": "AlexGvozden", "author_id": 34217, "author_profile": "https://Stackoverflow.com/users/34217", "pm_score": 2, "selected": false, "text": "<p>How you are running Flash CS3 on Linux ? \nyou cannot run JSFL from command line but compiling a FLA file should be possible</p>\n\n<p>some old example \n<a href=\"http://www.mikechambers.com/blog/2003/11/01/flashcommand-flash-2004-command-line-compiler/\" rel=\"nofollow noreferrer\">http://www.mikechambers.com/blog/2003/11/01/flashcommand-flash-2004-command-line-compiler/</a></p>\n\n<p>newer stuff from Mike Chambers \n<a href=\"http://code.google.com/p/flashcommand/\" rel=\"nofollow noreferrer\">http://code.google.com/p/flashcommand/</a> for OSX</p>\n\n<p>so it's definitely possible seems only through semi automated IDE publishing, </p>\n\n<p>too bad Flex compiler is not capable of such a thing, together with ANT tasks it's a killer...\nwith FDT editor things are pretty cool and automated </p>\n" }, { "answer_id": 488306, "author": "D. Starr", "author_id": 1144394, "author_profile": "https://Stackoverflow.com/users/1144394", "pm_score": 3, "selected": false, "text": "<p>Execute your JSFL scripts from the command line just like this:</p>\n\n<p>on Windows: <code>\"c:\\program files\\macromedia\\flash 8\\flash.exe\" myscript.jsfl</code></p>\n\n<p>on Mac: <code>open myscript.jsfl</code></p>\n\n<p>I believe older versions of Flash ran on Wine no problem but not as sure about CS3.</p>\n\n<p>To iterate over a batch of local files, try something like this (in JSFL):</p>\n\n<pre><code>var importFolder = fl.browseForFolderURL('Select a folder with existing FLA files');\nvar importFolderContents = FLfile.listFolder(importFolder);\nfor (i = 0; i &lt;importFolderContents.length; i++) {\n file = importFolderContents[i];\n fl.openDocument(file); // and so on\n}\n</code></pre>\n\n<p>And some other methods you'll probably want to investigate are..</p>\n\n<p><a href=\"http://livedocs.adobe.com/flash/8/main/00004635.html\" rel=\"noreferrer\">fl.getDocumentDOM()</a>\n<a href=\"http://livedocs.adobe.com/flash/9.0/main/00003933.html\" rel=\"noreferrer\">document.exportSWF()</a>\n<a href=\"http://livedocs.adobe.com/flash/9.0/main/00003968.html\" rel=\"noreferrer\">document.publish()</a>\n<a href=\"http://livedocs.adobe.com/flash/9.0/main/00004130.html\" rel=\"noreferrer\">fl.closeDocument()</a></p>\n" }, { "answer_id": 23528544, "author": "Triynko", "author_id": 88409, "author_profile": "https://Stackoverflow.com/users/88409", "pm_score": 0, "selected": false, "text": "<p>Yes, absolutely. In fact, I've built an end-to-end solution which, at the click of a single button, will update class files with a version time stamp, open Flash if it's not already open, open individual files for publication, signal the automation program via inter-process-communication when each file has completed publishing so you don't run into any timing issues, and deploy specific files to the web upon completion (after automatically backing them up and timestamping the filenames), and the whole process completes in under 10 seconds.</p>\n\n<p>See my Q&amp;A here: <a href=\"https://stackoverflow.com/q/23525495/88409\">Automating publishing of FLA files; calling Process.Start multiple times</a></p>\n" }, { "answer_id": 39378135, "author": "Alexei Skachykhin", "author_id": 3491120, "author_profile": "https://Stackoverflow.com/users/3491120", "pm_score": 1, "selected": false, "text": "<p>Like it was already stated, it is possible to do with JSFL scripts, although you still need to have command line tool that communicates with Adobe Flash Professional to log the process into stdout and supply exit code based on compilation result. </p>\n\n<p>I ended up writing this tool myself <a href=\"https://www.npmjs.com/package/flc\" rel=\"nofollow\">https://www.npmjs.com/package/flc</a>. It is basically a command line interface that abstracts Adobe Flash Professional away. Tested against Flash Pro 2014 and 2015.</p>\n" } ]
2008/11/04
[ "https://Stackoverflow.com/questions/262192", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13220/" ]
In our project we have a large number (hundreds) of FLA files created by the artists in CS3, from which we compile SWFs to use in our Flex/AS3 application. As part of a streamlined build/deploy system, it would be really handy to be able to automate publishing all these FLAs, and ideally deploying the SWFs too. I found some ways to do the batch publishing from CS3 using JSFL, but was surprised to discover CS3 doesn't apparently have any command-line functionality for this? This is on a Linux system for what it's worth, I don't have experience with JSFL to know if you can run scripts from the command line somehow? **note**: I should have said "Linux is preferred"... I don't use Linux but our server/build PC is Linux... I didn't realise CS3 was not compatible so I guess we can do this part on Windows.
Execute your JSFL scripts from the command line just like this: on Windows: `"c:\program files\macromedia\flash 8\flash.exe" myscript.jsfl` on Mac: `open myscript.jsfl` I believe older versions of Flash ran on Wine no problem but not as sure about CS3. To iterate over a batch of local files, try something like this (in JSFL): ``` var importFolder = fl.browseForFolderURL('Select a folder with existing FLA files'); var importFolderContents = FLfile.listFolder(importFolder); for (i = 0; i <importFolderContents.length; i++) { file = importFolderContents[i]; fl.openDocument(file); // and so on } ``` And some other methods you'll probably want to investigate are.. [fl.getDocumentDOM()](http://livedocs.adobe.com/flash/8/main/00004635.html) [document.exportSWF()](http://livedocs.adobe.com/flash/9.0/main/00003933.html) [document.publish()](http://livedocs.adobe.com/flash/9.0/main/00003968.html) [fl.closeDocument()](http://livedocs.adobe.com/flash/9.0/main/00004130.html)
262,201
<p>How can I write a C++ function returning true if a real number is exactly representable with a double?</p> <pre><code>bool isRepresentable( const char* realNumber ) { bool answer = false; // what goes here? return answer; } </code></pre> <p>Simple tests:</p> <pre><code>assert( true==isRepresentable( "0.5" ) ); assert( false==isRepresentable( "0.1" ) ); </code></pre>
[ { "answer_id": 262229, "author": "Treb", "author_id": 22114, "author_profile": "https://Stackoverflow.com/users/22114", "pm_score": -1, "selected": false, "text": "<p>Convert the string into a float with a larger scope than a double. Cast that to a double and see if they match.</p>\n" }, { "answer_id": 262236, "author": "Richard Poole", "author_id": 26003, "author_profile": "https://Stackoverflow.com/users/26003", "pm_score": 0, "selected": false, "text": "<p>This should do the trick:</p>\n\n<pre><code>bool isRepresentable(const char *realNumber)\n{\n double value = strtod(realNumber, NULL);\n\n char test[20];\n sprintf(test, \"%f\", value);\n\n return strcmp(realNumber, test) == 0;\n}\n</code></pre>\n\n<p>Probably best to use the 'safe' version of sprintf to prevent a potential buffer overrun (is it even possible in this case?)</p>\n" }, { "answer_id": 262240, "author": "Trap", "author_id": 7839, "author_profile": "https://Stackoverflow.com/users/7839", "pm_score": 0, "selected": false, "text": "<p>I'd convert the string to its numeric bit representation, (a bit array or a long), then convert the string to a double and see if they match.</p>\n" }, { "answer_id": 262269, "author": "schnaader", "author_id": 34065, "author_profile": "https://Stackoverflow.com/users/34065", "pm_score": 1, "selected": false, "text": "<p>Here is my version. sprintf converts 0.5 to 0.50000, zeros at the end have to be removed.</p>\n\n<p>EDIT: Has to be rewritten to handle numbers without decimal point that end with 0 correctly (like 12300).</p>\n\n<pre>\nbool isRepresentable( const char* realNumber )\n{\n bool answer = false;\n\n double dVar = atof(realNumber);\n char check[20];\n sprintf(check, \"%f\", dVar);\n\n // Remove zeros at end - TODO: Only do if decimal point in string\n for (int i = strlen(check) - 1; i >= 0; i--) {\n if (check[i] != '0') break;\n check[i] = 0;\n }\n\n answer = (strcmp(realNumber, check) == 0);\n\n return answer;\n}\n</pre>\n" }, { "answer_id": 262314, "author": "Mike G.", "author_id": 18901, "author_profile": "https://Stackoverflow.com/users/18901", "pm_score": 3, "selected": false, "text": "<p>Holy homework, batman! :)</p>\n\n<p>What makes this interesting is that you can't simply do an (atof|strtod|sscanf) -> sprintf loop and check whether you got the original string back. sprintf on many platforms detects the \"as close as you can get to 0.1\" double and prints it as 0.1, for example, even though 0.1 isn't precisely representable.</p>\n\n<pre><code>#include &lt;stdio.h&gt;\n\nint main() {\n printf(\"%llx = %f\\n\",0.1,0.1);\n}\n</code></pre>\n\n<p>prints:\n3fb999999999999a = 0.100000</p>\n\n<p>on my system.</p>\n\n<p>The real answer probably would require parsing out the double to convert it to an exact fractional representation (0.1 = 1/10) and then making sure that the atof conversion times the denominator equals the numerator.</p>\n\n<p>I think.</p>\n" }, { "answer_id": 262809, "author": "Alexei", "author_id": 34317, "author_profile": "https://Stackoverflow.com/users/34317", "pm_score": 4, "selected": true, "text": "<p>Parse the number into the form a + N / (10^k), where a and N are integers, and k is the number of decimal places you have. </p>\n\n<p>Example: 12.0345 -> 12 + 345 / 10^4, a = 12, N = 345, k = 4</p>\n\n<p>Now, 10^k = (2 * 5) ^ k = 2^k * 5^k</p>\n\n<p>You can represent your number as exact binary fraction if and only if you get rid of the 5^k term in the denominator. </p>\n\n<p>The result would check (N mod 5^k) == 0</p>\n" } ]
2008/11/04
[ "https://Stackoverflow.com/questions/262201", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15485/" ]
How can I write a C++ function returning true if a real number is exactly representable with a double? ``` bool isRepresentable( const char* realNumber ) { bool answer = false; // what goes here? return answer; } ``` Simple tests: ``` assert( true==isRepresentable( "0.5" ) ); assert( false==isRepresentable( "0.1" ) ); ```
Parse the number into the form a + N / (10^k), where a and N are integers, and k is the number of decimal places you have. Example: 12.0345 -> 12 + 345 / 10^4, a = 12, N = 345, k = 4 Now, 10^k = (2 \* 5) ^ k = 2^k \* 5^k You can represent your number as exact binary fraction if and only if you get rid of the 5^k term in the denominator. The result would check (N mod 5^k) == 0
262,219
<p>I'm trying to get CellID using AT commands, but I dont get any response from the modem, mine code looks like below, I send AT+CCED command, but never get any response.</p> <pre><code>HANDLE hCom; char * xpos; char rsltstr[5]; DWORD returnValue; DWORD LAC; DWORD CellId; int bufpos; DCB dcb; COMMTIMEOUTS to; DWORD nWritten; DWORD event; DWORD nRead; char outbuf[20], buf[256]; hCom = CreateFile(L"\\\.\\COM9:",GENERIC_READ|GENERIC_WRITE,0,0,OPEN_EXISTING,0,0); if (hCom==NULL || hCom==INVALID_HANDLE_VALUE) { TCHAR szBuf[80]; DWORD dw = GetLastError(); // get the most uptodate cells _stprintf(szBuf, TEXT("CreateFile failed with error %d."), dw); MessageBox(0, szBuf, TEXT("Error"), MB_OK); hCom= NULL; return -1; } if (!GetCommState(hCom, &amp;dcb)) { return -2; } dcb.BaudRate= CBR_115200; dcb.ByteSize= 8; dcb.fParity= false; dcb.StopBits= ONESTOPBIT; if (!SetCommState(hCom, &amp;dcb)) { return -3; } if (!EscapeCommFunction(hCom, SETDTR)) { return -4; } if (!GetCommTimeouts(hCom, &amp;to)) { return -6; } to.ReadIntervalTimeout= 0; to.ReadTotalTimeoutConstant= 200; to.ReadTotalTimeoutMultiplier= 0; to.WriteTotalTimeoutConstant= 20000; to.WriteTotalTimeoutMultiplier= 0; if (!SetCommTimeouts(hCom, &amp;to)) { return -7; } if (!SetCommMask(hCom, EV_RXCHAR)) { return -8; } bufpos = 0; strcpy(outbuf,"AT+CCED=0,5\r"); if (!WriteFile(hCom, outbuf, strlen(outbuf), &amp;nWritten, NULL)) { return -10; } if (nWritten != strlen(outbuf)) { return -11; } if (!WaitCommEvent(hCom, &amp;event, NULL)) { return -12; } while(1) { if (!ReadFile(hCom, buf+bufpos, 256 - bufpos, &amp;nRead, NULL)) { return -13; } if (nRead == 0) // &lt;---- it alweys break here break; bufpos += nRead; if (bufpos &gt;= 256) break; } </code></pre>
[ { "answer_id": 274176, "author": "Shane Powell", "author_id": 23235, "author_profile": "https://Stackoverflow.com/users/23235", "pm_score": 1, "selected": false, "text": "<p>I don't know anything about using the AT commands to get the cell id but you can use the RIL interface to get the cell id. It may be simpler than using the AT commands (unless you are trying to get it remotely?)</p>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/ms890075.aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/ms890075.aspx</a></p>\n\n<p>You use the RIL_GetCellTowerInfo function to get the current cell tower id.</p>\n" }, { "answer_id": 283997, "author": "michael", "author_id": 31207, "author_profile": "https://Stackoverflow.com/users/31207", "pm_score": 1, "selected": false, "text": "<p>my problem is that on some devicec RIL iterface methods returns E_NOTIMPL and nothing works, so I tought that I could directly tolk with mobile modem with AT commands.</p>\n\n<p>Does anyone have solution to such a problem, I'm fighting with it for over a week now.</p>\n" }, { "answer_id": 309475, "author": "atzz", "author_id": 23252, "author_profile": "https://Stackoverflow.com/users/23252", "pm_score": 2, "selected": false, "text": "<p>First of all, try <strong>L\"COM9:\"</strong> for the first parameter of CreateFile.</p>\n\n<p>Check out this page: <a href=\"http://msdn.microsoft.com/en-us/library/aa930218.aspx\" rel=\"nofollow noreferrer\">Device File Names</a></p>\n" }, { "answer_id": 1757630, "author": "Boogaloo", "author_id": 195628, "author_profile": "https://Stackoverflow.com/users/195628", "pm_score": 1, "selected": false, "text": "<p>Apparently I am not allowed to comment.. so:\n@Sebastian: I run Ril_GetCellTowerInfo on 2 models of HTC Diamond + an HTC Touch Pro + an ATT Fuze. It works on all 4 phones. I'd be happy to share some working code (in VB.NET) if you need more help.</p>\n" } ]
2008/11/04
[ "https://Stackoverflow.com/questions/262219", "https://Stackoverflow.com", "https://Stackoverflow.com/users/31207/" ]
I'm trying to get CellID using AT commands, but I dont get any response from the modem, mine code looks like below, I send AT+CCED command, but never get any response. ``` HANDLE hCom; char * xpos; char rsltstr[5]; DWORD returnValue; DWORD LAC; DWORD CellId; int bufpos; DCB dcb; COMMTIMEOUTS to; DWORD nWritten; DWORD event; DWORD nRead; char outbuf[20], buf[256]; hCom = CreateFile(L"\\\.\\COM9:",GENERIC_READ|GENERIC_WRITE,0,0,OPEN_EXISTING,0,0); if (hCom==NULL || hCom==INVALID_HANDLE_VALUE) { TCHAR szBuf[80]; DWORD dw = GetLastError(); // get the most uptodate cells _stprintf(szBuf, TEXT("CreateFile failed with error %d."), dw); MessageBox(0, szBuf, TEXT("Error"), MB_OK); hCom= NULL; return -1; } if (!GetCommState(hCom, &dcb)) { return -2; } dcb.BaudRate= CBR_115200; dcb.ByteSize= 8; dcb.fParity= false; dcb.StopBits= ONESTOPBIT; if (!SetCommState(hCom, &dcb)) { return -3; } if (!EscapeCommFunction(hCom, SETDTR)) { return -4; } if (!GetCommTimeouts(hCom, &to)) { return -6; } to.ReadIntervalTimeout= 0; to.ReadTotalTimeoutConstant= 200; to.ReadTotalTimeoutMultiplier= 0; to.WriteTotalTimeoutConstant= 20000; to.WriteTotalTimeoutMultiplier= 0; if (!SetCommTimeouts(hCom, &to)) { return -7; } if (!SetCommMask(hCom, EV_RXCHAR)) { return -8; } bufpos = 0; strcpy(outbuf,"AT+CCED=0,5\r"); if (!WriteFile(hCom, outbuf, strlen(outbuf), &nWritten, NULL)) { return -10; } if (nWritten != strlen(outbuf)) { return -11; } if (!WaitCommEvent(hCom, &event, NULL)) { return -12; } while(1) { if (!ReadFile(hCom, buf+bufpos, 256 - bufpos, &nRead, NULL)) { return -13; } if (nRead == 0) // <---- it alweys break here break; bufpos += nRead; if (bufpos >= 256) break; } ```
First of all, try **L"COM9:"** for the first parameter of CreateFile. Check out this page: [Device File Names](http://msdn.microsoft.com/en-us/library/aa930218.aspx)
262,247
<p>Let's say there is a report to compare charges with adjustments that outputs to excel, such that each row has the following fields:</p> <ul> <li>Account Number</li> <li>charge date</li> <li>Original item number</li> <li>Adjusted Item number</li> <li>Original Qty</li> <li>Adjusted Qty</li> <li>Original amount</li> <li>Adjusted amount</li> <li>Original Post date</li> <li>Adjusted Post date</li> </ul> <p>I need to help a user create a view in Excel that helps them spot changes in each record. She wants it to show each record in two rows like this:</p> <pre> Account | Date | O. Item | O. Qty | O. Amount | O. Post | | A. Item | A. Qty | A. Amount | A. Post </pre> <p>Is there anything built into Excel to allow you to group records like this? VBA is not an option in this case. </p> <p>It's okay if the cells under account and date duplicate those values, if that makes it easier. Bonus points if you can get some kind of alternating row effect that helps delimit each record (that part I can do on my own in vba later if I have to).</p>
[ { "answer_id": 262332, "author": "Tomalak", "author_id": 18771, "author_profile": "https://Stackoverflow.com/users/18771", "pm_score": 3, "selected": true, "text": "<p>It is a little tricky, but doable. I'm looking into this currently, stand by.</p>\n\n<p>Okay, the idea is this.</p>\n\n<p>You have the following layout:</p>\n\n<pre>\n/| A | B | C | D | F |\n-+---------+---------+---------+---------+---------+\n1| Acc No. | Data1 | Data1' | Data2 | Data2' |\n2| 1 | 10 | 11 | a | b |\n3| 2 | 100 | 108 | a | a |\n4| 3 | 50 | 55 | f | g |\n</pre>\n\n<p>Make a second Sheet:</p>\n\n<pre>\n/| A | B | C | D |\n-+-----+-----+-----------------------------+-----------------------------+\n1| A/O | Ref | Data1 | Data2 |\n2| A | 2 | =INDIRECT(\"Sheet1!B\" & $B2) | =INDIRECT(\"Sheet1!D\" & $B2) |\n3| O | 2 | =INDIRECT(\"Sheet1!C\" & $B3) | =INDIRECT(\"Sheet1!E\" & $B3) |\n4| A | 3 | =INDIRECT(\"Sheet1!B\" & $B4) | =INDIRECT(\"Sheet1!D\" & $B4) |\n5| O | 3 | =INDIRECT(\"Sheet1!C\" & $B5) | =INDIRECT(\"Sheet1!E\" & $B5) |\n</pre>\n\n<p>Columns \"A/0\" and \"Ref\" are manual, in my current model. Probably there is a way to automate them but I wanted to keep it simple. Filling down to cover an arbitrarily long input table in Sheet1 would work.</p>\n" }, { "answer_id": 262347, "author": "GvS", "author_id": 11492, "author_profile": "https://Stackoverflow.com/users/11492", "pm_score": 0, "selected": false, "text": "<p>I think it is only possible with programming (hey, this is a programming-related site). </p>\n\n<p>When VBA is not an option, is it allowed to use VB.Net or C#?</p>\n" }, { "answer_id": 262357, "author": "Alexandre Brisebois", "author_id": 18619, "author_profile": "https://Stackoverflow.com/users/18619", "pm_score": 0, "selected": false, "text": "<p>I've done exactly this in VBA a few years ago and it worked great, i guess you could do the samething using C# with Interops?</p>\n\n<p>I could tell what was added, removed and changed. It create a report in the end which was easy to sort out and filter.</p>\n\n<p>Is there a reason why VBA is not an option? \nAnd what other options are available?</p>\n\n<p>you could also cross reference the data using Excel functions, but this <strong>can</strong> be quite complicated for someone who is not an excel power user. <a href=\"http://www.contextures.com/tiptech.html\" rel=\"nofollow noreferrer\">general help in excel formulas</a></p>\n\n<p><strong>Edit:</strong> you will need functions like Find Index Offset VLookup Match, this can all be done by combining them. the only drawback is that there is a limit to the formula length. When this limit is reached split the logic in multiple columns or rows.</p>\n\n<p><strong>Edit:</strong> you could intergrate the VBA in a single workbook, and have the template saved. each time they wish to compare they use this template to execute the comparisson. this way no deployment is required. they simply need to copy the file and use it.</p>\n\n<p><strong>Edit:</strong> The solution proposed by Tomalak may not work since when records are added or removed, we have no control on where these records will be positioned. you will need to find the row with a key match and work from there.</p>\n" }, { "answer_id": 262365, "author": "grammar31", "author_id": 12815, "author_profile": "https://Stackoverflow.com/users/12815", "pm_score": 1, "selected": false, "text": "<p>A simple workaround might be to use <a href=\"http://www.cpearson.com/excel/cformatting.htm\" rel=\"nofollow noreferrer\">Conditional Formatting</a> (directions are for Office 2007):</p>\n\n<ol>\n<li>Highlight the \"Adjusted\" column (suppose, it's Column D and the Original was column C)</li>\n<li>Click \"Conditional Formatting\"</li>\n<li>Click \"New Rule...\"</li>\n<li>Click the last item \"Usa a formula to determine which cells to format\"</li>\n<li>Enter C1 &lt;> D1</li>\n<li>Pick a formatting style.</li>\n</ol>\n\n<p>Apply the rule, and all the entries that don't match will be highlighted in the style you selected.</p>\n" }, { "answer_id": 262446, "author": "BradC", "author_id": 21398, "author_profile": "https://Stackoverflow.com/users/21398", "pm_score": 1, "selected": false, "text": "<p>I also did this with Indirect. My formulas on the second sheet look something like:</p>\n\n<p>=INDIRECT(\"source!A\" &amp; INT(ROW()/2)+1)</p>\n\n<p>You will hard-code the letter to indicate the column source, and then the calculation will automatically choose from the correct row. Should copy down as far as you need.</p>\n" }, { "answer_id": 263682, "author": "dbb", "author_id": 25675, "author_profile": "https://Stackoverflow.com/users/25675", "pm_score": 0, "selected": false, "text": "<p>Conditional formatting can do both jobs, because you can have up to 3 conditions per cell</p>\n\n<ol>\n<li><p>you can (say) use red bold text to highlight any cells which are different, using a validation formula like this</p>\n\n<p>eg =(DataA!C8 &lt;> DataB!C8)</p></li>\n<li><p>you can shade alternate rows using a formula like this (as used in cell C8)</p>\n\n<p>eg =(MOD(CELL(\"Row\",C8),2)=0)</p></li>\n</ol>\n\n<p>which will shade even rows. To shade odd rows instead, of course, use =1 at the end of the formula instead of =0</p>\n" } ]
2008/11/04
[ "https://Stackoverflow.com/questions/262247", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3043/" ]
Let's say there is a report to compare charges with adjustments that outputs to excel, such that each row has the following fields: * Account Number * charge date * Original item number * Adjusted Item number * Original Qty * Adjusted Qty * Original amount * Adjusted amount * Original Post date * Adjusted Post date I need to help a user create a view in Excel that helps them spot changes in each record. She wants it to show each record in two rows like this: ``` Account | Date | O. Item | O. Qty | O. Amount | O. Post | | A. Item | A. Qty | A. Amount | A. Post ``` Is there anything built into Excel to allow you to group records like this? VBA is not an option in this case. It's okay if the cells under account and date duplicate those values, if that makes it easier. Bonus points if you can get some kind of alternating row effect that helps delimit each record (that part I can do on my own in vba later if I have to).
It is a little tricky, but doable. I'm looking into this currently, stand by. Okay, the idea is this. You have the following layout: ``` /| A | B | C | D | F | -+---------+---------+---------+---------+---------+ 1| Acc No. | Data1 | Data1' | Data2 | Data2' | 2| 1 | 10 | 11 | a | b | 3| 2 | 100 | 108 | a | a | 4| 3 | 50 | 55 | f | g | ``` Make a second Sheet: ``` /| A | B | C | D | -+-----+-----+-----------------------------+-----------------------------+ 1| A/O | Ref | Data1 | Data2 | 2| A | 2 | =INDIRECT("Sheet1!B" & $B2) | =INDIRECT("Sheet1!D" & $B2) | 3| O | 2 | =INDIRECT("Sheet1!C" & $B3) | =INDIRECT("Sheet1!E" & $B3) | 4| A | 3 | =INDIRECT("Sheet1!B" & $B4) | =INDIRECT("Sheet1!D" & $B4) | 5| O | 3 | =INDIRECT("Sheet1!C" & $B5) | =INDIRECT("Sheet1!E" & $B5) | ``` Columns "A/0" and "Ref" are manual, in my current model. Probably there is a way to automate them but I wanted to keep it simple. Filling down to cover an arbitrarily long input table in Sheet1 would work.
262,249
<p>I have a debug app I've been writing which receives data from a C-based process via UDP. One of the strings sent to me contains a <code>°</code> character - <a href="http://en.wikipedia.org/wiki/Degree_symbol" rel="nofollow noreferrer">Unicode U+00B0</a> (which incidentally breaks the StackOverflow search function!). When my wxPython application tries to append that string to a text box I get a <code>UnicodeDecodeError</code>.</p> <p>My first attempt to fix the issue simply caught that error (because the app apparently does send <em>some</em> bad messages. The problem is that the app also uses the character to report various temperatures around the unit and that's something we really need to log. Changing the source app is out of my control, so how can I detect and decode those symbols into something the <code>wxTextCtrl</code> can display?</p>
[ { "answer_id": 262433, "author": "pdc", "author_id": 8925, "author_profile": "https://Stackoverflow.com/users/8925", "pm_score": 1, "selected": false, "text": "<p>I can't say mych about wxPython itself, but I am guessing that it is trying to convert the text to Unicode before displaying it, If you have a string like <code>'123\\xB0'</code> and try to convert it to Unicode with teh default encoding (ASCII) then it will throw <code>UnicodeDecodeError</code>. You can probably fix this by replacing </p>\n\n<pre><code>s = message.get_string()\n</code></pre>\n\n<p>with </p>\n\n<pre><code>s = message.get_string().decode('ISO8859-1')\n</code></pre>\n\n<p>(where I am assuming a function <code>get_string()</code> that gets the message as a string). The difference here is that by handong the conversion to Unicode yourself you get to specify the encoding.</p>\n" }, { "answer_id": 263330, "author": "Toni Ruža", "author_id": 6267, "author_profile": "https://Stackoverflow.com/users/6267", "pm_score": 3, "selected": true, "text": "<p>pdc got it right, the following works fine (but fails without the <code>decode</code>):</p>\n\n<pre><code>#!/usr/bin/env python\n# -*- coding: utf-8 -*-\nimport wx\n\napp = wx.PySimpleApp()\napp.TopWindow = wx.Frame(None)\nfield = wx.TextCtrl(app.TopWindow)\nfield.Value += '°'.decode('ISO8859-1')\napp.TopWindow.Show()\napp.MainLoop()\n</code></pre>\n" }, { "answer_id": 13496753, "author": "Jason Viers", "author_id": 480667, "author_profile": "https://Stackoverflow.com/users/480667", "pm_score": 0, "selected": false, "text": "<p>Things may have been different back when this was asked, but my thoughts for anyone who stumbles on this:</p>\n\n<p>The issue is wxPython is trying to convert TO unicode, and lacking charset information it tries to use ASCII, which is invalid. If you know your data is utf-8, tell it so and it'll just work.</p>\n\n<pre><code>#!/usr/bin/env python\n# -*- coding: utf-8 -*-\nimport wx\n\napp = wx.PySimpleApp()\napp.TopWindow = wx.Frame(None)\nfield = wx.TextCtrl(app.TopWindow)\n\nstring_data = '°'\nprint type(string_data)\n# this would error, as it tries to convert to unicode from ascii\n# field.Value += string_data\n\nunicode_data = unicode(string_data, 'utf-8')\nprint type(unicode_data)\nfield.Value += unicode_data\napp.TopWindow.Show()\napp.MainLoop()\n</code></pre>\n" } ]
2008/11/04
[ "https://Stackoverflow.com/questions/262249", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15369/" ]
I have a debug app I've been writing which receives data from a C-based process via UDP. One of the strings sent to me contains a `°` character - [Unicode U+00B0](http://en.wikipedia.org/wiki/Degree_symbol) (which incidentally breaks the StackOverflow search function!). When my wxPython application tries to append that string to a text box I get a `UnicodeDecodeError`. My first attempt to fix the issue simply caught that error (because the app apparently does send *some* bad messages. The problem is that the app also uses the character to report various temperatures around the unit and that's something we really need to log. Changing the source app is out of my control, so how can I detect and decode those symbols into something the `wxTextCtrl` can display?
pdc got it right, the following works fine (but fails without the `decode`): ``` #!/usr/bin/env python # -*- coding: utf-8 -*- import wx app = wx.PySimpleApp() app.TopWindow = wx.Frame(None) field = wx.TextCtrl(app.TopWindow) field.Value += '°'.decode('ISO8859-1') app.TopWindow.Show() app.MainLoop() ```
262,254
<p>How can I use CRTP in C++ to avoid the overhead of virtual member functions?</p>
[ { "answer_id": 262270, "author": "Roger Lipscombe", "author_id": 8446, "author_profile": "https://Stackoverflow.com/users/8446", "pm_score": 1, "selected": false, "text": "<p>I had to look up <a href=\"http://en.wikipedia.org/wiki/Curiously_Recurring_Template_Pattern\" rel=\"nofollow noreferrer\">CRTP</a>. Having done that, however, I found some stuff about <a href=\"http://en.wikipedia.org/wiki/Template_metaprogramming#Static_polymorphism\" rel=\"nofollow noreferrer\">Static Polymorphism</a>. I suspect that this is the answer to your question.</p>\n\n<p>It turns out that <a href=\"http://en.wikipedia.org/wiki/Active_Template_Library\" rel=\"nofollow noreferrer\">ATL</a> uses this pattern quite extensively.</p>\n" }, { "answer_id": 262276, "author": "user23167", "author_id": 23167, "author_profile": "https://Stackoverflow.com/users/23167", "pm_score": -1, "selected": false, "text": "<p><a href=\"http://en.wikipedia.org/wiki/Curiously_Recurring_Template_Pattern\" rel=\"nofollow noreferrer\">This</a> Wikipedia answer has all you need. Namely:</p>\n\n<pre><code>template &lt;class Derived&gt; struct Base\n{\n void interface()\n {\n // ...\n static_cast&lt;Derived*&gt;(this)-&gt;implementation();\n // ...\n }\n\n static void static_func()\n {\n // ...\n Derived::static_sub_func();\n // ...\n }\n};\n\nstruct Derived : Base&lt;Derived&gt;\n{\n void implementation();\n static void static_sub_func();\n};\n</code></pre>\n\n<p>Although I don't know how much this actually buys you. The overhead of a virtual function call is (compiler dependent, of course):</p>\n\n<ul>\n<li>Memory: One function pointer per virtual function</li>\n<li>Runtime: One function pointer call</li>\n</ul>\n\n<p>While the overhead of CRTP static polymorphism is:</p>\n\n<ul>\n<li>Memory: Duplication of Base per template instantiation</li>\n<li>Runtime: One function pointer call + whatever static_cast is doing</li>\n</ul>\n" }, { "answer_id": 262692, "author": "fizzer", "author_id": 18167, "author_profile": "https://Stackoverflow.com/users/18167", "pm_score": 4, "selected": false, "text": "<p>I've been looking for decent discussions of CRTP myself. Todd Veldhuizen's <a href=\"http://www.cs.indiana.edu/cgi-bin/techreports/TRNNN.cgi?trnum=TR542\" rel=\"noreferrer\">Techniques for Scientific C++</a> is a great resource for this (1.3) and many other advanced techniques like expression templates.</p>\n\n<p>Also, I found that you could read most of Coplien's original C++ Gems article at Google books. Maybe that's still the case.</p>\n" }, { "answer_id": 262984, "author": "Dean Michael", "author_id": 11274, "author_profile": "https://Stackoverflow.com/users/11274", "pm_score": 7, "selected": false, "text": "<p>There are two ways.</p>\n\n<p>The first one is by specifying the interface statically for the structure of types:</p>\n\n<pre><code>template &lt;class Derived&gt;\nstruct base {\n void foo() {\n static_cast&lt;Derived *&gt;(this)-&gt;foo();\n };\n};\n\nstruct my_type : base&lt;my_type&gt; {\n void foo(); // required to compile.\n};\n\nstruct your_type : base&lt;your_type&gt; {\n void foo(); // required to compile.\n};\n</code></pre>\n\n<p>The second one is by avoiding the use of the reference-to-base or pointer-to-base idiom and do the wiring at compile-time. Using the above definition, you can have template functions that look like these:</p>\n\n<pre><code>template &lt;class T&gt; // T is deduced at compile-time\nvoid bar(base&lt;T&gt; &amp; obj) {\n obj.foo(); // will do static dispatch\n}\n\nstruct not_derived_from_base { }; // notice, not derived from base\n\n// ...\nmy_type my_instance;\nyour_type your_instance;\nnot_derived_from_base invalid_instance;\nbar(my_instance); // will call my_instance.foo()\nbar(your_instance); // will call your_instance.foo()\nbar(invalid_instance); // compile error, cannot deduce correct overload\n</code></pre>\n\n<p>So combining the structure/interface definition and the compile-time type deduction in your functions allows you to do static dispatch instead of dynamic dispatch. This is the essence of static polymorphism.</p>\n" }, { "answer_id": 65961084, "author": "jisrael18", "author_id": 15013600, "author_profile": "https://Stackoverflow.com/users/15013600", "pm_score": 1, "selected": false, "text": "<p><strong>CRTP/SFINAE Static Dispatching with Strict Signature Checking</strong></p>\n<p>This solution for static dispatching uses CRTP and SFINAE, which is not new.\nWhat is unique about this solution is that it also enforces strict signature\nchecking, which allows us to statically dispatch overloaded methods in the same\nway dynamic dispatching works for virtual functions.</p>\n<p>To begin, let's first look at the limitations of a traditional solution using\nSFINAE. The following was taken from Ben Deane's CppCon 2016 Lightning Talk\n“A Static Alternative to Virtual Functions, Using Expression SFINAE.&quot;</p>\n<pre class=\"lang-cpp prettyprint-override\"><code>#define SFINAE_DETECT(name, expr) \\\n template &lt;typename T&gt; \\\n using name##_t = decltype(expr); \\\n template &lt;typename T, typename = void&gt; \\\n struct has_##name : public std::false_type {}; \\\n template &lt;typename T&gt; \\\n struct has_##name&lt;T, void_t&lt;name##_t&lt;T&gt;&gt;&gt; : public std::true_type {};\n\n// detect CommonPrefix(string)\nSFINAE_DETECT(common_prefix,\n declval&lt;T&gt;().CommonPrefix(std::string()))\n</code></pre>\n<p>Using the above code, the template instantiation <code>has_complete&lt;DerivedClass&gt;</code>\nwill, in general, do what you would expect. If <code>DerivedClass</code> has a method named\n<code>Complete</code> that accepts a <code>std::string</code>, the resulting type will be\n<code>std::true_type</code>.</p>\n<p>What happens when you want to overload a function?</p>\n<pre class=\"lang-cpp prettyprint-override\"><code>template &lt;class Derived&gt;\nstruct Base {\n std::string foo(bool);\n std::string foo(int);\n ...\n};\n\nstruct Derived : public Base&lt;Derived&gt;\n{\n std::string foo(int);\n};\n</code></pre>\n<p>In this case, <code>Derived</code> does, in fact, have a method named <code>foo</code> that accepts a\n<code>bool</code> because <code>bool</code> is implicitly convertible to <code>int</code>. Therefore,\neven if we only set up dispatching for the signature that accepts a bool, <code>has_foo&lt;Derived&gt;</code> would resolve to <code>std::true_type</code>, and the call would be\ndispatched to <code>Derived::foo(int)</code>. Is this what we want? Probably not, because\nthis is not the way that virtual functions work. A function can only override a\nvirtual function if the two signatures match exactly. I propose that we make a\nstatic dispatch mechanism that behaves in the same way.</p>\n<pre class=\"lang-cpp prettyprint-override\"><code>template &lt;template &lt;class...&gt; class Op, class... Types&gt;\nstruct dispatcher;\n\ntemplate &lt;template &lt;class...&gt; class Op, class T&gt;\nstruct dispatcher&lt;Op, T&gt; : std::experimental::detected_t&lt;Op, T&gt; {};\n\ntemplate &lt;template &lt;class...&gt; class Op, class T, class... Types&gt;\nstruct dispatcher&lt;Op, T, Types...&gt;\n : std::experimental::detected_or_t&lt;\n typename dispatcher&lt;Op, Types...&gt;::type, Op, T&gt; {};\n\ntemplate &lt;template &lt;class...&gt; class Op, class... Types&gt;\nusing dispatcher_t = typename dispatcher&lt;Op, Types...&gt;::type;\n</code></pre>\n<p>That's nice, but that alone doesn't enforce signature checks. To perform strict\nsignature checking, we have to properly define the template template parameter\n<code>Op</code>. To do this, we will make use of a <code>std::integral_constant</code> of a member\nfunction pointer. Here's what that looks like:</p>\n<pre class=\"lang-cpp prettyprint-override\"><code>template &lt;class T&gt;\nusing foo_op_b = std::integral_constant&lt;std::string(T::*)(bool), &amp;T::foo&gt;;\n\ntemplate &lt;class T&gt;\nusing foo_op_i = std::integral_constant&lt;std::string(T::*)(int), &amp;T::foo&gt;\n</code></pre>\n<p>Defining our <code>Op</code>s in this way allows us to dispatch only to methods with an\nexact signature match.</p>\n<pre class=\"lang-cpp prettyprint-override\"><code>// Resolves to std::integral_constant&lt;std::string(T::*)(bool), &amp;Derived::foo&gt;\nusing foo_bool_ic = dispatcher_t&lt;foo_op_b, Derived, Defaults&gt;;\n\n// Resolves to std::integral_constant&lt;std::string(T::*)(int), &amp;Defaults::foo&gt;\nusing foo_int_ic = dispatcher_t&lt;foo_op_i, Derived, Defaults&gt;;\n</code></pre>\n<p>Now let's put it all together.</p>\n<pre class=\"lang-cpp prettyprint-override\"><code>#include &lt;iostream&gt;\n#include &lt;experimental/type_traits&gt;\n#include &lt;string&gt;\n\ntemplate &lt;template &lt;class...&gt; class Op, class... Types&gt;\nstruct dispatcher;\n\ntemplate &lt;template &lt;class...&gt; class Op, class T&gt;\nstruct dispatcher&lt;Op, T&gt; : std::experimental::detected_t&lt;Op, T&gt; {};\n\ntemplate &lt;template &lt;class...&gt; class Op, class T, class... Types&gt;\nstruct dispatcher&lt;Op, T, Types...&gt;\n : std::experimental::detected_or_t&lt;\n typename dispatcher&lt;Op, Types...&gt;::type, Op, T&gt; {};\n\ntemplate &lt;template &lt;class...&gt; class Op, class... Types&gt;\nusing dispatcher_t = typename dispatcher&lt;Op, Types...&gt;::type;\n\n\n// Used to deduce class type from a member function pointer\ntemplate &lt;class R, class T, class... Args&gt;\nauto method_cls(R(T::*)(Args...)) -&gt; T;\n\n\nstruct Defaults {\n std::string foo(bool value) { return value ? &quot;true&quot; : &quot;false&quot;; }\n std::string foo(int value) { return value ? &quot;true&quot; : &quot;false&quot;; }\n\n // Ensure that the class is polymorphic so we can use dynamic_cast\n virtual ~Defaults() {};\n};\n\ntemplate &lt;class Derived&gt;\nstruct Base : Defaults {\n template &lt;class T&gt;\n using foo_op_b = std::integral_constant&lt;std::string(T::*)(bool), &amp;T::foo&gt;;\n\n template &lt;class T&gt;\n using foo_op_i = std::integral_constant&lt;std::string(T::*)(int), &amp;T::foo&gt;;\n\n std::string foo(bool value) {\n auto method = dispatcher_t&lt;foo_op_b, Derived, Defaults&gt;::value;\n auto *target = dynamic_cast&lt;decltype(method_cls(method)) *&gt;(this);\n return (target-&gt;*method)(value);\n }\n\n std::string foo(int value) {\n auto method = dispatcher_t&lt;foo_op_i, Derived, Defaults&gt;::value;\n auto *target = dynamic_cast&lt;decltype(method_cls(method)) *&gt;(this);\n return (target-&gt;*method)(value);\n }\n};\n\nstruct Derived : Base&lt;Derived&gt; {\n std::string foo(bool value) { return value ? &quot;TRUE&quot; : &quot;FALSE&quot;; }\n};\n\nint main() {\n Derived d;\n std::cout &lt;&lt; dynamic_cast&lt;Base&lt;Derived&gt; *&gt;(&amp;d)-&gt;foo(true) &lt;&lt; std::endl; // TRUE\n std::cout &lt;&lt; dynamic_cast&lt;Base&lt;Derived&gt; *&gt;(&amp;d)-&gt;foo(1) &lt;&lt; std::endl; // true\n}\n</code></pre>\n<p>Writing a macro that creates a dispatcher for a non-overloaded member function\nwould be simple enough, but making one that supports overloaded functions would\nbe a bit more challenging. If anybody cares to contribute that, I'd welcome the\naddition.</p>\n" } ]
2008/11/04
[ "https://Stackoverflow.com/questions/262254", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
How can I use CRTP in C++ to avoid the overhead of virtual member functions?
There are two ways. The first one is by specifying the interface statically for the structure of types: ``` template <class Derived> struct base { void foo() { static_cast<Derived *>(this)->foo(); }; }; struct my_type : base<my_type> { void foo(); // required to compile. }; struct your_type : base<your_type> { void foo(); // required to compile. }; ``` The second one is by avoiding the use of the reference-to-base or pointer-to-base idiom and do the wiring at compile-time. Using the above definition, you can have template functions that look like these: ``` template <class T> // T is deduced at compile-time void bar(base<T> & obj) { obj.foo(); // will do static dispatch } struct not_derived_from_base { }; // notice, not derived from base // ... my_type my_instance; your_type your_instance; not_derived_from_base invalid_instance; bar(my_instance); // will call my_instance.foo() bar(your_instance); // will call your_instance.foo() bar(invalid_instance); // compile error, cannot deduce correct overload ``` So combining the structure/interface definition and the compile-time type deduction in your functions allows you to do static dispatch instead of dynamic dispatch. This is the essence of static polymorphism.
262,267
<p>How do I create a toolbar for Excel using an XLA document?</p>
[ { "answer_id": 262304, "author": "Onorio Catenacci", "author_id": 2820, "author_profile": "https://Stackoverflow.com/users/2820", "pm_score": 1, "selected": false, "text": "<p>Not sure if this is what you're looking for but I thought this might help you out:</p>\n\n<p><a href=\"http://www.contextures.com/xlToolbar02.html\" rel=\"nofollow noreferrer\">Excel -- Macro Toolbar</a></p>\n\n<p>Since you don't specify a version of Excel I'm not sure if this will work for you or not but perhaps it will furnish you with a good starting point.</p>\n" }, { "answer_id": 262319, "author": "BradC", "author_id": 21398, "author_profile": "https://Stackoverflow.com/users/21398", "pm_score": 3, "selected": true, "text": "<p>To make a toolbar, in the onload event, you are going to do something like:</p>\n\n<pre><code>Dim myBar As CommandBar, myButt As CommandBarControl \n\n'Delete the toolbar if it already exists'\nOn Error Resume Next \nCommandBars(\"My Toolbar\").Delete \nOn Error Goto 0\n\nSet myBar = CommandBars.Add(Name:=\"My Toolbar\", _\n Position:=msoBarFloating, Temporary:=True) \nmyBar.Visible = True \n\n ' Create a button with text on the bar and set some properties.'\nSet myButt = ComBar.Controls.Add(Type:=msoControlButton) \nWith myButt\n .Caption = \"Macro1\" \n .Style = msoButtonCaption \n .TooltipText = \"Run Macro1\" \n .OnAction = \"Macro1\" \nEnd With \n\n ' Create a button with an image on the bar and set some properties.'\nSet myButt = ComBar.Controls.Add(Type:=msoControlButton) \nWith myButt \n 'the faceId line will let you choose an icon'\n ' If you choose to use the faceId then the caption is not displayed'\n .FaceId = 1000 \n .Caption = \"Icon Button\" \n .TooltipText = \"Run Macro2\" \n .OnAction = \"Macro2\" \nEnd With \n</code></pre>\n\n<p>The polite thing to do is delete the toolbar on exit, also.</p>\n" } ]
2008/11/04
[ "https://Stackoverflow.com/questions/262267", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16794/" ]
How do I create a toolbar for Excel using an XLA document?
To make a toolbar, in the onload event, you are going to do something like: ``` Dim myBar As CommandBar, myButt As CommandBarControl 'Delete the toolbar if it already exists' On Error Resume Next CommandBars("My Toolbar").Delete On Error Goto 0 Set myBar = CommandBars.Add(Name:="My Toolbar", _ Position:=msoBarFloating, Temporary:=True) myBar.Visible = True ' Create a button with text on the bar and set some properties.' Set myButt = ComBar.Controls.Add(Type:=msoControlButton) With myButt .Caption = "Macro1" .Style = msoButtonCaption .TooltipText = "Run Macro1" .OnAction = "Macro1" End With ' Create a button with an image on the bar and set some properties.' Set myButt = ComBar.Controls.Add(Type:=msoControlButton) With myButt 'the faceId line will let you choose an icon' ' If you choose to use the faceId then the caption is not displayed' .FaceId = 1000 .Caption = "Icon Button" .TooltipText = "Run Macro2" .OnAction = "Macro2" End With ``` The polite thing to do is delete the toolbar on exit, also.
262,280
<p>When I get a reference to a <code>System.Diagnostics.Process</code>, how can I know if a process is currently running?</p>
[ { "answer_id": 262291, "author": "Patrick Desjardins", "author_id": 13913, "author_profile": "https://Stackoverflow.com/users/13913", "pm_score": 9, "selected": true, "text": "<p>This is a way to do it with the name:</p>\n\n<pre><code>Process[] pname = Process.GetProcessesByName(\"notepad\");\nif (pname.Length == 0)\n MessageBox.Show(\"nothing\");\nelse\n MessageBox.Show(\"run\");\n</code></pre>\n\n<p>You can loop all process to get the ID for later manipulation:</p>\n\n<pre><code>Process[] processlist = Process.GetProcesses();\nforeach(Process theprocess in processlist){\n Console.WriteLine(\"Process: {0} ID: {1}\", theprocess.ProcessName, theprocess.Id);\n}\n</code></pre>\n" }, { "answer_id": 262350, "author": "Jeff Kotula", "author_id": 1382162, "author_profile": "https://Stackoverflow.com/users/1382162", "pm_score": 1, "selected": false, "text": "<p><code>Process.GetProcesses()</code> is the way to go. But you may need to use one or more different criteria to find your process, depending on how it is running (i.e. as a service or a normal app, whether or not it has a titlebar).</p>\n" }, { "answer_id": 262391, "author": "JaredPar", "author_id": 23283, "author_profile": "https://Stackoverflow.com/users/23283", "pm_score": 2, "selected": false, "text": "<p>It depends on how reliable you want this function to be. If you want to know if the particular process instance you have is still running and available with 100% accuracy then you are out of luck. The reason being that from the managed process object there are only 2 ways to identify the process.</p>\n\n<p>The first is the Process Id. Unfortunately, process ids are not unique and can be recycled. Searching the process list for a matching Id will only tell you that there is a process with the same id running, but it's not necessarily your process.</p>\n\n<p>The second item is the Process Handle. It has the same problem though as the Id and it's more awkward to work with.</p>\n\n<p>If you're looking for medium level reliability then checking the current process list for a process of the same ID is sufficient. </p>\n" }, { "answer_id": 262406, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>Maybe (probably) I am reading the question wrongly, but are you looking for the HasExited property that will tell you that the process represented by your Process object has exited (either normally or not).</p>\n\n<p>If the process you have a reference to has a UI you can use the Responding property to determine if the UI is currently responding to user input or not.</p>\n\n<p>You can also set EnableRaisingEvents and handle the Exited event (which is sent asychronously) or call WaitForExit() if you want to block.</p>\n" }, { "answer_id": 262487, "author": "Coincoin", "author_id": 42, "author_profile": "https://Stackoverflow.com/users/42", "pm_score": 4, "selected": false, "text": "<p>Synchronous solution :</p>\n\n<pre><code>void DisplayProcessStatus(Process process)\n{\n process.Refresh(); // Important\n\n\n if(process.HasExited)\n {\n Console.WriteLine(\"Exited.\");\n }\n else\n {\n Console.WriteLine(\"Running.\");\n } \n}\n</code></pre>\n\n<p>Asynchronous solution:</p>\n\n<pre><code>void RegisterProcessExit(Process process)\n{\n // NOTE there will be a race condition with the caller here\n // how to fix it is left as an exercise\n process.Exited += process_Exited;\n}\n\nstatic void process_Exited(object sender, EventArgs e)\n{\n Console.WriteLine(\"Process has exited.\");\n}\n</code></pre>\n" }, { "answer_id": 268394, "author": "reshefm", "author_id": 30717, "author_profile": "https://Stackoverflow.com/users/30717", "pm_score": 5, "selected": false, "text": "<p>This is the simplest way I found after using reflector.\nI created an extension method for that:</p>\n\n<pre><code>public static class ProcessExtensions\n{\n public static bool IsRunning(this Process process)\n {\n if (process == null) \n throw new ArgumentNullException(\"process\");\n\n try\n {\n Process.GetProcessById(process.Id);\n }\n catch (ArgumentException)\n {\n return false;\n }\n return true;\n }\n}\n</code></pre>\n\n<p>The <code>Process.GetProcessById(processId)</code> method calls the <code>ProcessManager.IsProcessRunning(processId)</code> method and throws <code>ArgumentException</code> in case the process does not exist. For some reason the <code>ProcessManager</code> class is internal...</p>\n" }, { "answer_id": 7541479, "author": "George Birbilis", "author_id": 903783, "author_profile": "https://Stackoverflow.com/users/903783", "pm_score": 0, "selected": false, "text": "<p>You can instantiate a Process instance once for the process you want and keep on tracking the process using that .NET Process object (it will keep on tracking till you call Close on that .NET object explicitly, even if the process it was tracking has died [this is to be able to give you time of process close, aka ExitTime etc.])</p>\n\n<p>Quoting <a href=\"http://msdn.microsoft.com/en-us/library/fb4aw7b8.aspx\" rel=\"nofollow\">http://msdn.microsoft.com/en-us/library/fb4aw7b8.aspx</a>:</p>\n\n<blockquote>\n <p>When an associated process exits (that is, when it is shut down by the\n operation system through a normal or abnormal termination), the system\n stores administrative information about the process and returns to the\n component that had called WaitForExit. The Process component can then\n access the information, which includes the ExitTime, by using the\n Handle to the exited process. </p>\n \n <p>Because the associated process has exited, the Handle property of the\n component no longer points to an existing process resource. Instead,\n the handle can be used only to access the operating system’s\n information about the process resource. The system is aware of handles\n to exited processes that have not been released by Process components,\n so it keeps the ExitTime and Handle information in memory until the\n Process component specifically frees the resources. For this reason,\n any time you call Start for a Process instance, call Close when the\n associated process has terminated and you no longer need any\n administrative information about it. Close frees the memory allocated\n to the exited process.</p>\n</blockquote>\n" }, { "answer_id": 13918804, "author": "Jack Griffin", "author_id": 1362643, "author_profile": "https://Stackoverflow.com/users/1362643", "pm_score": 0, "selected": false, "text": "<p>I tried Coincoin's solution :<br>\nBefore processing some file, I copy it as a temporary file and open it.<br>\nWhen I'm done, I close the application if it is still open and delete\nthe temporary file :<br>\nI just use a Process variable and check it afterwards :</p>\n\n<pre><code>private Process openApplication; \nprivate void btnOpenFile_Click(object sender, EventArgs e) { \n ...\n // copy current file to fileCache \n ... \n // open fileCache with proper application\n openApplication = System.Diagnostics.Process.Start( fileCache ); \n}\n</code></pre>\n\n<p>Later I close the application : </p>\n\n<pre><code> ... \nopenApplication.Refresh(); \n\n// close application if it is still open \nif ( !openApplication.HasExited() ) {\n openApplication.Kill(); \n}\n\n// delete temporary file \nSystem.IO.File.Delete( fileCache );\n</code></pre>\n\n<p>It works ( so far )</p>\n" }, { "answer_id": 17603535, "author": "berkay", "author_id": 2465932, "author_profile": "https://Stackoverflow.com/users/2465932", "pm_score": 0, "selected": false, "text": "<pre><code>string process = &quot;notepad&quot;;\nif (Process.GetProcessesByName(process).Length &gt; 0)\n{\n MessageBox.Show(&quot;Working&quot;);\n}\nelse\n{\n MessageBox.Show(&quot;Not Working&quot;);\n}\n</code></pre>\n<p>also you can use a timer for checking the process every time</p>\n" }, { "answer_id": 21482938, "author": "Aelphaeis", "author_id": 2656813, "author_profile": "https://Stackoverflow.com/users/2656813", "pm_score": 4, "selected": false, "text": "<p>reshefm had a pretty nice answer; however, it does not account for a situation in which the process was never started to begin with.</p>\n\n<p>Here is a a modified version of what he posted.</p>\n\n<pre><code> public static bool IsRunning(this Process process)\n {\n try {Process.GetProcessById(process.Id);}\n catch (InvalidOperationException) { return false; }\n catch (ArgumentException){return false;}\n return true;\n }\n</code></pre>\n\n<p>I removed his ArgumentNullException because its actually suppose to be a null reference exception and it gets thrown by the system anyway and I also accounted for the situation in which the process was never started to begin with or the close() method was used to close the process.</p>\n" }, { "answer_id": 38234565, "author": "guneysus", "author_id": 1766716, "author_profile": "https://Stackoverflow.com/users/1766716", "pm_score": 4, "selected": false, "text": "<p>This should be a one-liner:</p>\n\n<pre><code>public static class ProcessHelpers {\n public static bool IsRunning (string name) =&gt; Process.GetProcessesByName(name).Length &gt; 0;\n}\n</code></pre>\n" }, { "answer_id": 45581057, "author": "Hao Nguyen", "author_id": 2883813, "author_profile": "https://Stackoverflow.com/users/2883813", "pm_score": 0, "selected": false, "text": "<p>Despite of supported API from .Net frameworks regarding checking existing process by process ID, those functions are very slow. It costs a huge amount of CPU cycles to run Process.GetProcesses() or Process.GetProcessById/Name().</p>\n\n<p>A much quicker method to check a running process by ID is to use native API <a href=\"https://msdn.microsoft.com/en-us/library/windows/desktop/ms684320(v=vs.85).aspx\" rel=\"nofollow noreferrer\">OpenProcess()</a>. If return handle is 0, the process doesn't exist. If handle is different than 0, the process is running. There's no guarantee this method would work 100% at all time due to permission.</p>\n" }, { "answer_id": 55721450, "author": "Latency", "author_id": 878539, "author_profile": "https://Stackoverflow.com/users/878539", "pm_score": 0, "selected": false, "text": "<p>There are many problems associated with this, as other have seemed to partially address:</p>\n\n<ul>\n<li>Any instance members are not guaranteed to be thread safe. Meaning there are race conditions that may occur with the lifetime of the snapshot while trying to evaluate the properties of the object.</li>\n<li>The process handle will throw Win32Exception for ACCESS DENIED where permissions for evaluating this and other such properties aren't allowed.</li>\n<li>For ISN'T RUNNING status, an ArgumentException will also be raised when trying to evaluate some of its properties.</li>\n</ul>\n\n<p>Whether the properties others have mentioned are internal or not, you can still obtain information from them via reflection if permission allows.</p>\n\n<pre><code>var x = obj.GetType().GetProperty(\"Name\", BindingFlags.NonPublic | BindingFlags.Instance);\n</code></pre>\n\n<p>You could pinvoke Win32 code for <a href=\"https://learn.microsoft.com/en-us/windows/desktop/ToolHelp/taking-a-snapshot-and-viewing-processes\" rel=\"nofollow noreferrer\">Snapshot</a> or you can use <a href=\"https://stackoverflow.com/questions/15269677/how-to-get-all-the-users-processes-in-wmi\">WMI</a> which is slower.</p>\n\n<pre><code>HANDLE CreateToolhelp32Snapshot(\n DWORD dwFlags,\n DWORD th32ProcessID\n);\n</code></pre>\n\n<p>Another option would be to <a href=\"https://learn.microsoft.com/en-us/windows/desktop/api/processthreadsapi/nf-processthreadsapi-openprocess\" rel=\"nofollow noreferrer\">OpenProcess</a> / CloseProcess, but you will still run into the same issues with exceptions being thrown same as before.</p>\n\n<p>For WMI - OnNewEvent.Properties[\"?\"]:</p>\n\n<ul>\n<li>\"ParentProcessID\"</li>\n<li>\"ProcessID\"</li>\n<li>\"ProcessName\"</li>\n<li>\"SECURITY_DESCRIPTOR\"</li>\n<li>\"SessionID\"</li>\n<li>\"Sid\"</li>\n<li>\"TIME_CREATED\"</li>\n</ul>\n" } ]
2008/11/04
[ "https://Stackoverflow.com/questions/262280", "https://Stackoverflow.com", "https://Stackoverflow.com/users/30717/" ]
When I get a reference to a `System.Diagnostics.Process`, how can I know if a process is currently running?
This is a way to do it with the name: ``` Process[] pname = Process.GetProcessesByName("notepad"); if (pname.Length == 0) MessageBox.Show("nothing"); else MessageBox.Show("run"); ``` You can loop all process to get the ID for later manipulation: ``` Process[] processlist = Process.GetProcesses(); foreach(Process theprocess in processlist){ Console.WriteLine("Process: {0} ID: {1}", theprocess.ProcessName, theprocess.Id); } ```
262,325
<p>I've been tasked with deploying an application built by a third party on an Oracle Application Server, version 10.1.3.0. I've deployed it on Oracle Application Server version 10.1.2.0 without much difficulty. I'm getting the following error:</p> <pre><code>javax.naming.NamingException: Lookup error: javax.naming.AuthenticationException: No such domain/application: "etrace"; nested exception is: javax.naming.AuthenticationException: No such domain/application: "etrace" [Root exception is javax.naming.AuthenticationException: No such domain/application: "etrace"] at com.evermind.server.rmi.RMIClientContext.lookup(RMIClientContext.java:64) at javax.naming.InitialContext.lookup(InitialContext.java:351) </code></pre> <p>Before that the application code instantiates and initializes an InitialContext Object and performs the lookup method call. The value it passes is just a String with the value of the fully qualified name of the class being requested (com.ntc.tracing.app.security.EtraceAuthenticatorService). Looking at the InitialContext object, I know it has the following parameters set in the environments hashtable:</p> <pre><code>java.naming.factory.initial: com.evermind.server.rmi.RMIInitialContextFactory java.naming.provider.url: ormi://ntcdevr310g22:12401/etrace java.naming.factory.url.pkgs: oracle.oc4j.naming.url java.naming.security.principal: admin java.naming.security.credentials: admin1 </code></pre> <p>The provider url, principal and credentials are set by me (via command line).</p> <p>I'm confused as to what the error even means. If I give it a "bad" provider url or no principal and pass, I'll get a different error (NullPointerException). That tells me it's hitting the naming provider, but it's not saying it can't find the class.</p> <p>Any suggestions would be greatly appreciated. Right now I'm stumped.</p>
[ { "answer_id": 262296, "author": "Lou Franco", "author_id": 3937, "author_profile": "https://Stackoverflow.com/users/3937", "pm_score": 3, "selected": true, "text": "<p>Fiddler can do constrained bandwidth and latency simulations.</p>\n" }, { "answer_id": 262385, "author": "mipadi", "author_id": 28804, "author_profile": "https://Stackoverflow.com/users/28804", "pm_score": 2, "selected": false, "text": "<p>You could check out <a href=\"http://www.isi.edu/nsnam/ns/\" rel=\"nofollow noreferrer\">ns-2</a> or <a href=\"http://www.nsnam.org/\" rel=\"nofollow noreferrer\">ns-3</a>. ns-2 is a well-tested network simulator. ns-3 is the \"replacement\" by the same group of people.</p>\n" }, { "answer_id": 265294, "author": "Ido Schacham", "author_id": 32088, "author_profile": "https://Stackoverflow.com/users/32088", "pm_score": 1, "selected": false, "text": "<p><a href=\"http://snad.ncsl.nist.gov/nistnet/\" rel=\"nofollow noreferrer\">NIST Net</a> can do some crazy network emulation.</p>\n" }, { "answer_id": 275344, "author": "Krunch", "author_id": 35831, "author_profile": "https://Stackoverflow.com/users/35831", "pm_score": 1, "selected": false, "text": "<p>It depends on what exactly you want to simulate. honeyd let you create detailed virtual network topologies including assymetric routes, packet loss, various TCP personality for each virtual host and let you back these virtual hosts or ports with a real system or process.</p>\n\n<p><a href=\"http://www.honeyd.org/\" rel=\"nofollow noreferrer\">http://www.honeyd.org/</a></p>\n" }, { "answer_id": 401220, "author": "rupello", "author_id": 635, "author_profile": "https://Stackoverflow.com/users/635", "pm_score": 1, "selected": false, "text": "<p><a href=\"https://stackoverflow.com/questions/155329/bandwidth-and-traffic-simulator-for-web-apps#401200\">Here is a list</a> of free and commercial traffic shaping applications that I compiled in answer to a similar question</p>\n" }, { "answer_id": 25390372, "author": "Valentinos Ioannou", "author_id": 2658039, "author_profile": "https://Stackoverflow.com/users/2658039", "pm_score": 1, "selected": false, "text": "<p>OMNeT++ you can simulate any type of network you want .Also create your protocols for commuincation!\n<a href=\"http://www.omnetpp.org/\" rel=\"nofollow\">http://www.omnetpp.org/</a></p>\n\n<p>And it's free</p>\n" } ]
2008/11/04
[ "https://Stackoverflow.com/questions/262325", "https://Stackoverflow.com", "https://Stackoverflow.com/users/25532/" ]
I've been tasked with deploying an application built by a third party on an Oracle Application Server, version 10.1.3.0. I've deployed it on Oracle Application Server version 10.1.2.0 without much difficulty. I'm getting the following error: ``` javax.naming.NamingException: Lookup error: javax.naming.AuthenticationException: No such domain/application: "etrace"; nested exception is: javax.naming.AuthenticationException: No such domain/application: "etrace" [Root exception is javax.naming.AuthenticationException: No such domain/application: "etrace"] at com.evermind.server.rmi.RMIClientContext.lookup(RMIClientContext.java:64) at javax.naming.InitialContext.lookup(InitialContext.java:351) ``` Before that the application code instantiates and initializes an InitialContext Object and performs the lookup method call. The value it passes is just a String with the value of the fully qualified name of the class being requested (com.ntc.tracing.app.security.EtraceAuthenticatorService). Looking at the InitialContext object, I know it has the following parameters set in the environments hashtable: ``` java.naming.factory.initial: com.evermind.server.rmi.RMIInitialContextFactory java.naming.provider.url: ormi://ntcdevr310g22:12401/etrace java.naming.factory.url.pkgs: oracle.oc4j.naming.url java.naming.security.principal: admin java.naming.security.credentials: admin1 ``` The provider url, principal and credentials are set by me (via command line). I'm confused as to what the error even means. If I give it a "bad" provider url or no principal and pass, I'll get a different error (NullPointerException). That tells me it's hitting the naming provider, but it's not saying it can't find the class. Any suggestions would be greatly appreciated. Right now I'm stumped.
Fiddler can do constrained bandwidth and latency simulations.
262,330
<p>Is there a common or established algorithm for peer-nodes in a network to decide on a unique "network-channel" (or any other form of semi-secret identifier)?</p> <p>The environment I'm working in is SecondLife. I am trying to figure out how to get many identical peer scripted objects to agree on a "channel" number which allows them to form a network, without interfering with other existing networks of the same kind of objects.</p> <p>All objects get instantiated at roughly the same time, and have access to the (common) system time.</p> <p>Approaches I've thought of:</p> <ol> <li><p>Time-of-instantiation based. Channel is derived (by md5) from the unix time. Problem is the "<strong>roughly</strong> the same time" part. They may get instantiated right on the cusp of a new second.</p></li> <li><p>Random wait. Make objects wait a random amount, and announce a (randomly generated) channel number decided upon by the first one to wake. Problem is, the system has a low time granularity, and more than one object can wake before the announcement was processed.</p></li> <li><p>Combine 1 and 2. Announce a high-res timestamp after waiting a random amount, and derive channel from the lowest announced timestamp.</p></li> </ol> <p>This has to be something smarter people than me have thought about. Any better way of doing this?</p>
[ { "answer_id": 671632, "author": "Domchi", "author_id": 29192, "author_profile": "https://Stackoverflow.com/users/29192", "pm_score": 1, "selected": false, "text": "<p>How would a new object know which network to join (new or existing)? Depending on what exactly you need, there are number of approaches.</p>\n\n<h2>First method</h2>\n\n<p>You can use less precise timer than every second, for example something like this:</p>\n\n<pre><code>integer time = llGetUnixTime();\ninteger channel = time - (time % 1000);\n</code></pre>\n\n<p>All the objects rezzed at nearly the same time are likely to have same channel according to the above code, although you'd probably want to make sure that time % 1000 is not near 0 or 1000 and perhaps use time % 10000 in that case.</p>\n\n<h2>Second method</h2>\n\n<p>Other than that, you can create some sort of discovery protocol. For example:</p>\n\n<ol>\n<li>newly rezzed object says hello on hard-coded control channel</li>\n<li>main server for each network in area responds with channel number of its network</li>\n<li>object chooses network he wants to join</li>\n<li>if nobody responds, object becomes server for its own network, by incrementing control channel by some number (for example +1)</li>\n<li>if object wants to create its own network anyway, it increments highest channel in use by +1 and creates its own channel/network</li>\n</ol>\n\n<h2>Combination</h2>\n\n<p>Of course, you can combine both methods - use llGetUnixTime() to derive channel, say hello, and if server responds become node, otherwise become server. Also, you can check appropriate higher and lower channel to avoid having two networks because of time rollover differences in rezzing of objects.</p>\n" }, { "answer_id": 1029730, "author": "btubbs", "author_id": 120871, "author_profile": "https://Stackoverflow.com/users/120871", "pm_score": 0, "selected": false, "text": "<p>Are your objects being rezzed by another object? If so, then the easy solution is to provide the channel number in the integer parameter of llRezObject. The rezzed (child) objects can then just use the param from their on_rez events as the channel.</p>\n\n<p>For example, the rezzer parent would do something like this:</p>\n\n<pre><code>integer networkchannel = 3495293;\nllRezObject(\"myobject\", rezpos, rezvel, rezrot, networkchannel);\n</code></pre>\n\n<p>and the rezzed child objects would do something like this:</p>\n\n<pre><code>on_rez(integer networkchannel)\n{\n llListen(networkchannel, \"\", NULL_KEY, \"\");\n}\n</code></pre>\n" } ]
2008/11/04
[ "https://Stackoverflow.com/questions/262330", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
Is there a common or established algorithm for peer-nodes in a network to decide on a unique "network-channel" (or any other form of semi-secret identifier)? The environment I'm working in is SecondLife. I am trying to figure out how to get many identical peer scripted objects to agree on a "channel" number which allows them to form a network, without interfering with other existing networks of the same kind of objects. All objects get instantiated at roughly the same time, and have access to the (common) system time. Approaches I've thought of: 1. Time-of-instantiation based. Channel is derived (by md5) from the unix time. Problem is the "**roughly** the same time" part. They may get instantiated right on the cusp of a new second. 2. Random wait. Make objects wait a random amount, and announce a (randomly generated) channel number decided upon by the first one to wake. Problem is, the system has a low time granularity, and more than one object can wake before the announcement was processed. 3. Combine 1 and 2. Announce a high-res timestamp after waiting a random amount, and derive channel from the lowest announced timestamp. This has to be something smarter people than me have thought about. Any better way of doing this?
How would a new object know which network to join (new or existing)? Depending on what exactly you need, there are number of approaches. First method ------------ You can use less precise timer than every second, for example something like this: ``` integer time = llGetUnixTime(); integer channel = time - (time % 1000); ``` All the objects rezzed at nearly the same time are likely to have same channel according to the above code, although you'd probably want to make sure that time % 1000 is not near 0 or 1000 and perhaps use time % 10000 in that case. Second method ------------- Other than that, you can create some sort of discovery protocol. For example: 1. newly rezzed object says hello on hard-coded control channel 2. main server for each network in area responds with channel number of its network 3. object chooses network he wants to join 4. if nobody responds, object becomes server for its own network, by incrementing control channel by some number (for example +1) 5. if object wants to create its own network anyway, it increments highest channel in use by +1 and creates its own channel/network Combination ----------- Of course, you can combine both methods - use llGetUnixTime() to derive channel, say hello, and if server responds become node, otherwise become server. Also, you can check appropriate higher and lower channel to avoid having two networks because of time rollover differences in rezzing of objects.
262,338
<p>In oracle, I want to create a delete sproc that returns an integer based on the outcome of the deletion.</p> <p>this is what i have so far.</p> <pre><code>create or replace PROCEDURE Testing ( iKey IN VARCHAR2 ) AS BEGIN delete from MyTable WHERE TheKey = iKey; END Testing; </code></pre> <p>i've tried putting a RETURNS INTEGER in but the sproc won't compile.</p>
[ { "answer_id": 262370, "author": "Justin Cave", "author_id": 10397, "author_profile": "https://Stackoverflow.com/users/10397", "pm_score": 4, "selected": false, "text": "<p>A procedure does not return a value. A function returns a value, but you shouldn't be doing DML in a function (otherwise you cannot do things like reference the function in a SQL statement, you confuse permission grants since normally DBAs want to be able to grant read-only users access to all the functions so that users are doing computations consistently, etc.).</p>\n\n<p>You can add an OUT parameter to the procedure to return the status. If \"success\" means that one or more rows were updated, you can use SQL%ROWCOUNT to get a count of the number of rows modified by the prior SQL statement and use that to populate the return parameter, i.e.</p>\n\n<pre><code>CREATE OR REPLACE PROCEDURE test_proc (\n p_iKey IN VARCHAR2,\n p_retVal OUT INTEGER\n)\nAS\nBEGIN\n DELETE FROM myTable\n WHERE theKey = p_iKey;\n\n IF( SQL%ROWCOUNT &gt;= 1 )\n THEN\n p_retVal := 1;\n ELSE\n p_retVal := 0;\n END IF;\nEND test_proc;\n</code></pre>\n\n<p>Of course, from a general code clarity standpoint, I'm dubious about OUT parameters that appear to be trying to return a status code. You are generally much better served by assuming success and throwing exceptions in the event of an error.</p>\n" }, { "answer_id": 262384, "author": "Jacob Schoen", "author_id": 3340, "author_profile": "https://Stackoverflow.com/users/3340", "pm_score": 0, "selected": false, "text": "<p>You are probably looking for a function instead. </p>\n\n<pre><code>FUNCTION TESTING (iKEY IN VARCHAR2) RETURN NUMBER\nIS\n v_count NUMBER;\n yourNumber NUMBER;\nBEGIN\n\n SELECT COUNT(*) INTO v_count\n FROM MyTable\n WHERE TheKey = iKey;\n\n IF v_count &gt; 0\n THEN\n DELETE FROM MyTable \n WHERE TheKey = iKey;\n\n SELECT COUNT(*) INTO v_count\n FROM MyTable\n WHERE TheKey = iKey;\n\n IF (v_count = 0)\n THEN\n yourNumber := 1; --means successful deletion\n END IF;\n ELSE\n yourNumber := 0; --means no items to delete\n END IF;\n return yourNumber;\n\n EXCEPTION\n WHEN OTHERS THEN\n RETURN -1; --means error was encountered\nEND TESTING;\n</code></pre>\n\n<p>Note: Where I work we generally put functions inside a sql package.</p>\n" }, { "answer_id": 262514, "author": "stjohnroe", "author_id": 2985, "author_profile": "https://Stackoverflow.com/users/2985", "pm_score": 3, "selected": true, "text": "<p>Use a function and the implicit SQL cursor to determine the number of rows deleted</p>\n\n<pre><code>create or replace\nFUNCTION Testing\n( \niKey IN VARCHAR2\n) RETURN INTEGER\n AS \n\nBEGIN\n delete from MyTable WHERE \n TheKey = iKey;\n\n RETURN SQL%ROWCOUNT;\n\nEND Testing;\n</code></pre>\n\n<p>That should work</p>\n" }, { "answer_id": 270520, "author": "user34850", "author_id": 34850, "author_profile": "https://Stackoverflow.com/users/34850", "pm_score": 3, "selected": false, "text": "<p>You can use a stored procedure to return results.</p>\n\n<pre><code>CREATE OR REPLACE PROCEDURE testing (iKey IN VARCHAR2, oRes OUT NUMBER)\nAS\nBEGIN\n DELETE FROM MyTable\n WHERE TheKey = iKey;\n\n oRes := SQL%ROWCOUNT;\nEND;\n</code></pre>\n\n<p>To call the procedure use something like:</p>\n\n<pre><code>DECLARE\n pRes NUMBER;\nBEGIN\n testing ('myspecialkey', pRes);\n DBMS_OUTPUT.put_line (pRes);\nEND;\n</code></pre>\n" }, { "answer_id": 20140863, "author": "PG08 de Spurs", "author_id": 3021003, "author_profile": "https://Stackoverflow.com/users/3021003", "pm_score": 0, "selected": false, "text": "<p>The <code>SQL%ROWCOUNT</code> will only return a value immediately after a DML its value will reset if another DML is executed.</p>\n\n<p>To get around the problem as I was executing deletes in a loop I issued the following command after the dml:</p>\n\n<pre><code>row_count := row_count + SQL%ROWCOUNT;\n</code></pre>\n\n<p>Please make sure you declare and initialize <code>row_count := 0;</code> </p>\n" } ]
2008/11/04
[ "https://Stackoverflow.com/questions/262338", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21180/" ]
In oracle, I want to create a delete sproc that returns an integer based on the outcome of the deletion. this is what i have so far. ``` create or replace PROCEDURE Testing ( iKey IN VARCHAR2 ) AS BEGIN delete from MyTable WHERE TheKey = iKey; END Testing; ``` i've tried putting a RETURNS INTEGER in but the sproc won't compile.
Use a function and the implicit SQL cursor to determine the number of rows deleted ``` create or replace FUNCTION Testing ( iKey IN VARCHAR2 ) RETURN INTEGER AS BEGIN delete from MyTable WHERE TheKey = iKey; RETURN SQL%ROWCOUNT; END Testing; ``` That should work
262,339
<p>I'd like to use the ADO.NET Entity Framework for data access, extend its objects for my business logic, and bind those objects to controls in my UI.</p> <p>As explained in <a href="https://stackoverflow.com/questions/260233/how-do-i-extend-adonet-entity-framework-objects-with-partial-classes">the answers to another question</a>, I cannot extend ADO.NET Entity Framework objects with partial classes and use my custom methods in LINQ queries.</p> <p><a href="http://img221.imageshack.us/img221/7329/clientsq0.gif" rel="nofollow noreferrer">ADO.NET Entity Framework partial class http://img221.imageshack.us/img221/7329/clientsq0.gif</a></p> <p>I don't want methods showing up in the Intellisense that are going to create run-time errors! How should I architect my application to avoid this problem?</p> <p><a href="http://img83.imageshack.us/img83/1580/iswashingtongn0.gif" rel="nofollow noreferrer">VB.NET LINQ with custom method http://img83.imageshack.us/img83/1580/iswashingtongn0.gif</a></p> <p>Do I need a data access Client class and also a business logic Client class? It seems like that will get confusing.</p>
[ { "answer_id": 262375, "author": "CubanX", "author_id": 27555, "author_profile": "https://Stackoverflow.com/users/27555", "pm_score": 2, "selected": false, "text": "<p>You can architect your solution using (Plain Old C# Objects) POCO's and Managers.</p>\n\n<p>That way you separate the business logic from the value objects.</p>\n\n<p>To make it \"look pretty\", you can mark your methods with the (this) modifier on the parameters so you can then use those methods as extension methods.</p>\n\n<p>An example could make this pretty clear:</p>\n\n<h2>Location Value Object:</h2>\n\n<pre><code>public class Location\n{\n public string City { get; set; }\n public string State { get; set; }\n}\n</code></pre>\n\n<h2>Location Manager:</h2>\n\n<pre><code>public static class LocationManager\n{\n public static bool IsWashington(this Location location)\n {\n return location.State == \"WA\";\n }\n}\n</code></pre>\n\n<p>Now, the extension methods will show up differently than the standard properties/methods on the object.</p>\n\n<p>The \"IsWashington\" method can be called 2 ways</p>\n\n<pre><code>Location location = new Location { State = \"WA\" };\nLocationManager.IsWashington(location);\n</code></pre>\n\n<h2>OR</h2>\n\n<pre><code>Location location = new Location { State = \"WA\" };\nlocation.IsWashington();\n</code></pre>\n\n<p>Now you have separation of your business logic and value objects, yet you still can have \"pretty\" method calls.</p>\n\n<p>If you feel your fellow devs (or you :) ) will abuse the extension method part, then just don't use it.</p>\n" }, { "answer_id": 278157, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<p>I also use entity framework and tried first to extend the classed but I soon found that was not a good solution so I ended up making new classes (in a new class library) which I prefixed with a B. I did not extend the entity classes. </p>\n\n<p>If I have a class named NewsPost the business class is named BNewsPost and all business logic connected to that class is collected here. For join the returning elements of used to place the logic.</p>\n\n<p>Not a very exiting solution but it did the trick.</p>\n\n<p>regards</p>\n" } ]
2008/11/04
[ "https://Stackoverflow.com/questions/262339", "https://Stackoverflow.com", "https://Stackoverflow.com/users/83/" ]
I'd like to use the ADO.NET Entity Framework for data access, extend its objects for my business logic, and bind those objects to controls in my UI. As explained in [the answers to another question](https://stackoverflow.com/questions/260233/how-do-i-extend-adonet-entity-framework-objects-with-partial-classes), I cannot extend ADO.NET Entity Framework objects with partial classes and use my custom methods in LINQ queries. [ADO.NET Entity Framework partial class http://img221.imageshack.us/img221/7329/clientsq0.gif](http://img221.imageshack.us/img221/7329/clientsq0.gif) I don't want methods showing up in the Intellisense that are going to create run-time errors! How should I architect my application to avoid this problem? [VB.NET LINQ with custom method http://img83.imageshack.us/img83/1580/iswashingtongn0.gif](http://img83.imageshack.us/img83/1580/iswashingtongn0.gif) Do I need a data access Client class and also a business logic Client class? It seems like that will get confusing.
You can architect your solution using (Plain Old C# Objects) POCO's and Managers. That way you separate the business logic from the value objects. To make it "look pretty", you can mark your methods with the (this) modifier on the parameters so you can then use those methods as extension methods. An example could make this pretty clear: Location Value Object: ---------------------- ``` public class Location { public string City { get; set; } public string State { get; set; } } ``` Location Manager: ----------------- ``` public static class LocationManager { public static bool IsWashington(this Location location) { return location.State == "WA"; } } ``` Now, the extension methods will show up differently than the standard properties/methods on the object. The "IsWashington" method can be called 2 ways ``` Location location = new Location { State = "WA" }; LocationManager.IsWashington(location); ``` OR -- ``` Location location = new Location { State = "WA" }; location.IsWashington(); ``` Now you have separation of your business logic and value objects, yet you still can have "pretty" method calls. If you feel your fellow devs (or you :) ) will abuse the extension method part, then just don't use it.
262,341
<p>I have a requirement to allow a user of this ASP.NET web application to upload a specifically formatted Excel spreadsheet, fill arrays with data from the spreadsheet, and bind the arrays to a Oracle stored procedure for validation and insertion into the database. I must be able to read the data from the Excel spreadsheet without being able to save it to the web server's hard disk. This is the part I cannot figure out how to do. Here's a simple code example.</p> <pre><code>&lt;%--ASP.NET Declarative--%&gt; &lt;asp:FileUpload ID="FileUpload1" runat="server" /&gt; &lt;asp:Button ID="Button1" runat="server" Text="Send File" OnClick="Button1_Click" /&gt; // C# Code-Behind protected void Button1_Click(object sender, EventArgs e) { var postedFile = FileUpload1.PostedFile; // ... Read file in memory and put in format to send to stored procedure ... } </code></pre> <p>Can anyone help me with this? I appreciate anyone's consideration.</p> <p>thx,<br /> gabe</p>
[ { "answer_id": 262353, "author": "Christian C. Salvadó", "author_id": 5445, "author_profile": "https://Stackoverflow.com/users/5445", "pm_score": 2, "selected": false, "text": "<p>Use the FileUpload1.<a href=\"http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.fileupload.filecontent.aspx\" rel=\"nofollow noreferrer\">FileContent</a> Stream. I guess your Excel library can handle streams directly. </p>\n" }, { "answer_id": 262494, "author": "TcKs", "author_id": 20382, "author_profile": "https://Stackoverflow.com/users/20382", "pm_score": 1, "selected": false, "text": "<p>The COM libraries of Excel does not support loading file from another source than file.\nBut there exists a lot of third-party components, which allows you read/write excel files.</p>\n\n<p>Othervise you can see a documentation for th XLS file format at <a href=\"http://msdn.microsoft.com/en-us/library/cc313154.aspx\" rel=\"nofollow noreferrer\">[MS-XLS]: Excel Binary File Format (.xls) Structure Specification</a>.</p>\n\n<p>Or you can use a same way of office files processing like in Sharepoint Server. See <a href=\"http://msdn.microsoft.com/en-us/library/microsoft.office.excel.server.webservices.aspx\" rel=\"nofollow noreferrer\">Microsoft.Office.Excel.Server.WebServices Namespace</a>.</p>\n" }, { "answer_id": 262646, "author": "hearn", "author_id": 30096, "author_profile": "https://Stackoverflow.com/users/30096", "pm_score": 0, "selected": false, "text": "<p>This is something I've been playing with recently.</p>\n\n<p>Check this post: <a href=\"https://stackoverflow.com/questions/156500/write-an-excel-workbook-to-a-memory-stream-net\">Write an excel workbook to a memory stream .NET</a></p>\n\n<p>It points to a great library by Carlos Aguilar Mares, which lets you work with Excel workbooks as XML.</p>\n\n<p><a href=\"http://www.carlosag.net/Tools/ExcelXmlWriter/\" rel=\"nofollow noreferrer\">ExcelXMLWriter</a></p>\n\n<p>You dont need Excel installed on the server (which is kinda breaking the MS licensing anyway as you are accessing this over the web). </p>\n\n<p>You can load the Excel workbook as a stream using <code>Workbook.Load(stream)</code></p>\n" }, { "answer_id": 262847, "author": "Ricardo Villamil", "author_id": 19314, "author_profile": "https://Stackoverflow.com/users/19314", "pm_score": -1, "selected": false, "text": "<p>Could you have your users upload a CSV file instead? Dealing with a plain text file would be much easier. I had a similar issue before and I asked the users and they were OK, saved me tons of work.</p>\n\n<p>Good luck.</p>\n" }, { "answer_id": 263895, "author": "Christoph", "author_id": 34464, "author_profile": "https://Stackoverflow.com/users/34464", "pm_score": 1, "selected": false, "text": "<p>maybe have look on csvreader, it reads csv, xls and xlsx:</p>\n\n<p><a href=\"http://www.csvreader.com\" rel=\"nofollow noreferrer\">http://www.csvreader.com</a></p>\n" }, { "answer_id": 269515, "author": "gabe", "author_id": 34315, "author_profile": "https://Stackoverflow.com/users/34315", "pm_score": 3, "selected": false, "text": "<p>I found a great lightweight open source API on Codeplex for doing this called ExcelDataReader. </p>\n\n<p>It can transform an input stream of an excel file into a <code>System.Data.DataSet</code> object (probably parsing using BIFF specs). </p>\n\n<p>Here's the link:</p>\n\n<blockquote>\n <p><a href=\"http://www.codeplex.com/ExcelDataReader\" rel=\"noreferrer\">http://www.codeplex.com/ExcelDataReader</a> </p>\n</blockquote>\n\n<p>Here's a code sample:</p>\n\n<pre><code>&lt;%--ASP.NET Declarative--%&gt;\n&lt;asp:FileUpload ID=\"FileUpload1\" runat=\"server\" /&gt;\n&lt;asp:Button ID=\"Button1\" runat=\"server\" Text=\"Send File\" OnClick=\"Button1_Click\" /&gt;\n&lt;asp:GridView ID=\"GridView1\" runat=\"server\" /&gt;\n\n// C# Code-Behind\nprotected void Button1_Click(object sender, EventArgs e) {\n // the ExcelDataReader takes a System.IO.Stream object\n var excelReader = new ExcelDataReader(FileUpload1.FileContent);\n FileUpload1.FileContent.Close();\n\n DataSet wb = excelReader.WorkbookData;\n // get the first worksheet of the workbook\n DataTable dt = excelReader.WorkbookData.Tables[0];\n\n GridView1.DataSource = dt.AsDataView();\n GridView1.DataBind();\n}\n</code></pre>\n" } ]
2008/11/04
[ "https://Stackoverflow.com/questions/262341", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I have a requirement to allow a user of this ASP.NET web application to upload a specifically formatted Excel spreadsheet, fill arrays with data from the spreadsheet, and bind the arrays to a Oracle stored procedure for validation and insertion into the database. I must be able to read the data from the Excel spreadsheet without being able to save it to the web server's hard disk. This is the part I cannot figure out how to do. Here's a simple code example. ``` <%--ASP.NET Declarative--%> <asp:FileUpload ID="FileUpload1" runat="server" /> <asp:Button ID="Button1" runat="server" Text="Send File" OnClick="Button1_Click" /> // C# Code-Behind protected void Button1_Click(object sender, EventArgs e) { var postedFile = FileUpload1.PostedFile; // ... Read file in memory and put in format to send to stored procedure ... } ``` Can anyone help me with this? I appreciate anyone's consideration. thx, gabe
I found a great lightweight open source API on Codeplex for doing this called ExcelDataReader. It can transform an input stream of an excel file into a `System.Data.DataSet` object (probably parsing using BIFF specs). Here's the link: > > <http://www.codeplex.com/ExcelDataReader> > > > Here's a code sample: ``` <%--ASP.NET Declarative--%> <asp:FileUpload ID="FileUpload1" runat="server" /> <asp:Button ID="Button1" runat="server" Text="Send File" OnClick="Button1_Click" /> <asp:GridView ID="GridView1" runat="server" /> // C# Code-Behind protected void Button1_Click(object sender, EventArgs e) { // the ExcelDataReader takes a System.IO.Stream object var excelReader = new ExcelDataReader(FileUpload1.FileContent); FileUpload1.FileContent.Close(); DataSet wb = excelReader.WorkbookData; // get the first worksheet of the workbook DataTable dt = excelReader.WorkbookData.Tables[0]; GridView1.DataSource = dt.AsDataView(); GridView1.DataBind(); } ```
262,351
<p>I have several identical elements with different attributes that I'm accessing with SimpleXML:</p> <pre><code>&lt;data&gt; &lt;seg id="A1"/&gt; &lt;seg id="A5"/&gt; &lt;seg id="A12"/&gt; &lt;seg id="A29"/&gt; &lt;seg id="A30"/&gt; &lt;/data&gt; </code></pre> <p>I need to remove a specific <strong>seg</strong> element, with an id of "A12", how can I do this? I've tried looping through the <strong>seg</strong> elements and <em>unset</em>ting the specific one, but this doesn't work, the elements remain.</p> <pre><code>foreach($doc-&gt;seg as $seg) { if($seg['id'] == 'A12') { unset($seg); } } </code></pre>
[ { "answer_id": 262556, "author": "Stefan Gehrig", "author_id": 11354, "author_profile": "https://Stackoverflow.com/users/11354", "pm_score": 7, "selected": true, "text": "<p>While <a href=\"http://de.php.net/manual/en/book.simplexml.php\" rel=\"noreferrer\">SimpleXML</a> provides <a href=\"https://stackoverflow.com/a/16062633/367456\">a way to remove</a> XML nodes, its modification capabilities are somewhat limited. One other solution is to resort to using the <a href=\"http://de.php.net/manual/en/book.dom.php\" rel=\"noreferrer\">DOM</a> extension. <a href=\"http://de.php.net/manual/en/function.dom-import-simplexml.php\" rel=\"noreferrer\">dom_import_simplexml()</a> will help you with converting your <code>SimpleXMLElement</code> into a <code>DOMElement</code>.</p>\n\n<p>Just some example code (tested with PHP 5.2.5):</p>\n\n<pre><code>$data='&lt;data&gt;\n &lt;seg id=\"A1\"/&gt;\n &lt;seg id=\"A5\"/&gt;\n &lt;seg id=\"A12\"/&gt;\n &lt;seg id=\"A29\"/&gt;\n &lt;seg id=\"A30\"/&gt;\n&lt;/data&gt;';\n$doc=new SimpleXMLElement($data);\nforeach($doc-&gt;seg as $seg)\n{\n if($seg['id'] == 'A12') {\n $dom=dom_import_simplexml($seg);\n $dom-&gt;parentNode-&gt;removeChild($dom);\n }\n}\necho $doc-&gt;asXml();\n</code></pre>\n\n<p>outputs</p>\n\n<pre><code>&lt;?xml version=\"1.0\"?&gt;\n&lt;data&gt;&lt;seg id=\"A1\"/&gt;&lt;seg id=\"A5\"/&gt;&lt;seg id=\"A29\"/&gt;&lt;seg id=\"A30\"/&gt;&lt;/data&gt;\n</code></pre>\n\n<p>By the way: selecting specific nodes is much more simple when you use XPath (<a href=\"http://de.php.net/manual/en/function.simplexml-element-xpath.php\" rel=\"noreferrer\">SimpleXMLElement->xpath</a>): </p>\n\n<pre><code>$segs=$doc-&gt;xpath('//seq[@id=\"A12\"]');\nif (count($segs)&gt;=1) {\n $seg=$segs[0];\n}\n// same deletion procedure as above\n</code></pre>\n" }, { "answer_id": 345872, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<p>There is a way to remove a child element via SimpleXml. The code looks for a \n element, and does nothing. Otherwise it adds the element to a string. It then writes out the string to a file. Also note that the code saves a backup before overwriting the original file.</p>\n\n<pre><code>$username = $_GET['delete_account'];\necho \"DELETING: \".$username;\n$xml = simplexml_load_file(\"users.xml\");\n\n$str = \"&lt;?xml version=\\\"1.0\\\"?&gt;\n&lt;users&gt;\";\nforeach($xml-&gt;children() as $child){\n if($child-&gt;getName() == \"user\") {\n if($username == $child['name']) {\n continue;\n } else {\n $str = $str.$child-&gt;asXML();\n }\n }\n}\n$str = $str.\"\n&lt;/users&gt;\";\necho $str;\n\n$xml-&gt;asXML(\"users_backup.xml\");\n$myFile = \"users.xml\";\n$fh = fopen($myFile, 'w') or die(\"can't open file\");\nfwrite($fh, $str);\nfclose($fh);\n</code></pre>\n" }, { "answer_id": 394722, "author": "datasn.io", "author_id": 49318, "author_profile": "https://Stackoverflow.com/users/49318", "pm_score": 5, "selected": false, "text": "<p>Just unset the node:</p>\n\n<pre><code>$str = &lt;&lt;&lt;STR\n&lt;a&gt;\n &lt;b&gt;\n &lt;c&gt;\n &lt;/c&gt;\n &lt;/b&gt;\n&lt;/a&gt;\nSTR;\n\n$xml = simplexml_load_string($str);\nunset($xml –&gt; a –&gt; b –&gt; c); // this would remove node c\necho $xml –&gt; asXML(); // xml document string without node c\n</code></pre>\n\n<p>This code was taken from <a href=\"http://www.kavoir.com/2008/12/how-to-delete-remove-nodes-in-simplexml.html\" rel=\"noreferrer\">How to delete / remove nodes in SimpleXML</a>.</p>\n" }, { "answer_id": 1312071, "author": "Urszula Karzelek", "author_id": 63852, "author_profile": "https://Stackoverflow.com/users/63852", "pm_score": 0, "selected": false, "text": "<p>Idea about helper functions is from one of the comments for DOM on <a href=\"http://pl.php.net/manual/pl/domnode.removechild.php\" rel=\"nofollow noreferrer\">php.net</a> and idea about using unset is from <a href=\"http://www.kavoir.com/2008/12/how-to-delete-remove-nodes-in-simplexml.html\" rel=\"nofollow noreferrer\">kavoir.com</a>. For me this solution finally worked: </p>\n\n<pre><code>function Myunset($node)\n{\n unsetChildren($node);\n $parent = $node-&gt;parentNode;\n unset($node);\n}\n\nfunction unsetChildren($node)\n{\n while (isset($node-&gt;firstChild))\n {\n unsetChildren($node-&gt;firstChild);\n unset($node-&gt;firstChild);\n }\n}\n</code></pre>\n\n<p>using it:\n$xml is SimpleXmlElement</p>\n\n<pre><code>Myunset($xml-&gt;channel-&gt;item[$i]);\n</code></pre>\n\n<p>The result is stored in $xml, so don’t worry about assigning it to any variable.</p>\n" }, { "answer_id": 1550728, "author": "Ilari Kajaste", "author_id": 115807, "author_profile": "https://Stackoverflow.com/users/115807", "pm_score": 0, "selected": false, "text": "<p>Even though SimpleXML doesn't have a detailed way to remove elements, you <em>can</em> remove elements from SimpleXML by using PHP's <code>unset()</code>. The key to doing this is managing to target the desired element. At least one way to do the targeting is using the order of the elements. First find out the order number of the element you want to remove (for example with a loop), then remove the element:</p>\n\n<pre><code>$target = false;\n$i = 0;\nforeach ($xml-&gt;seg as $s) {\n if ($s['id']=='A12') { $target = $i; break; }\n $i++;\n}\nif ($target !== false) {\n unset($xml-&gt;seg[$target]);\n}\n</code></pre>\n\n<p>You can even remove multiple elements with this, by storing the order number of target items in an array. Just remember to do the removal in a reverse order (<code>array_reverse($targets)</code>), because removing an item naturally reduces the order number of the items that come after it.</p>\n\n<p>Admittedly, it's a bit of a hackaround, but it seems to work fine.</p>\n" }, { "answer_id": 1737879, "author": "Josh Davis", "author_id": 74311, "author_profile": "https://Stackoverflow.com/users/74311", "pm_score": 2, "selected": false, "text": "<p>For future reference, deleting nodes with SimpleXML can be a pain sometimes, especially if you don't know the exact structure of the document. That's why I have written <a href=\"http://code.google.com/p/simpledom/\" rel=\"nofollow noreferrer\">SimpleDOM</a>, a class that extends SimpleXMLElement to add a few convenience methods.</p>\n\n<p>For instance, deleteNodes() will delete all nodes matching a XPath expression. And if you want to delete all nodes with the attribute \"id\" equal to \"A5\", all you have to do is:</p>\n\n<pre><code>// don't forget to include SimpleDOM.php\ninclude 'SimpleDOM.php';\n\n// use simpledom_load_string() instead of simplexml_load_string()\n$data = simpledom_load_string(\n '&lt;data&gt;\n &lt;seg id=\"A1\"/&gt;\n &lt;seg id=\"A5\"/&gt;\n &lt;seg id=\"A12\"/&gt;\n &lt;seg id=\"A29\"/&gt;\n &lt;seg id=\"A30\"/&gt;\n &lt;/data&gt;'\n);\n\n// and there the magic happens\n$data-&gt;deleteNodes('//seg[@id=\"A5\"]');\n</code></pre>\n" }, { "answer_id": 1795569, "author": "Witman", "author_id": 218120, "author_profile": "https://Stackoverflow.com/users/218120", "pm_score": 3, "selected": false, "text": "<p>I believe Stefan's answer is right on. If you want to remove only one node (rather than all matching nodes), here is another example:</p>\n\n<pre><code>//Load XML from file (or it could come from a POST, etc.)\n$xml = simplexml_load_file('fileName.xml');\n\n//Use XPath to find target node for removal\n$target = $xml-&gt;xpath(\"//seg[@id=$uniqueIdToDelete]\");\n\n//If target does not exist (already deleted by someone/thing else), halt\nif(!$target)\nreturn; //Returns null\n\n//Import simpleXml reference into Dom &amp; do removal (removal occurs in simpleXML object)\n$domRef = dom_import_simplexml($target[0]); //Select position 0 in XPath array\n$domRef-&gt;parentNode-&gt;removeChild($domRef);\n\n//Format XML to save indented tree rather than one line and save\n$dom = new DOMDocument('1.0');\n$dom-&gt;preserveWhiteSpace = false;\n$dom-&gt;formatOutput = true;\n$dom-&gt;loadXML($xml-&gt;asXML());\n$dom-&gt;save('fileName.xml');\n</code></pre>\n\n<p>Note that sections Load XML... (first) and Format XML... (last) could be replaced with different code depending on where your XML data comes from and what you want to do with the output; it is the sections in between that find a node and remove it. </p>\n\n<p>In addition, the if statement is only there to ensure that the target node exists before trying to move it. You could choose different ways to handle or ignore this case.</p>\n" }, { "answer_id": 2437056, "author": "posthy", "author_id": 292772, "author_profile": "https://Stackoverflow.com/users/292772", "pm_score": -1, "selected": false, "text": "<p>Your initial approach was right, but you forgot one little thing about foreach. It doesn't work on the original array/object, but creates a copy of each element as it iterates, so you did unset the copy. Use reference like this:</p>\n\n<pre><code>foreach($doc-&gt;seg as &amp;$seg) \n{\n if($seg['id'] == 'A12')\n {\n unset($seg);\n }\n}\n</code></pre>\n" }, { "answer_id": 2461606, "author": "joan16v", "author_id": 295590, "author_profile": "https://Stackoverflow.com/users/295590", "pm_score": 1, "selected": false, "text": "<p>A new idea: <code>simple_xml</code> works as a array.</p>\n\n<p>We can search for the indexes of the \"array\" we want to delete, and then, use the <code>unset()</code> function to delete this array indexes. My example:</p>\n\n<pre><code>$pos=$this-&gt;xml-&gt;getXMLUser();\n$i=0; $array_pos=array();\nforeach($this-&gt;xml-&gt;doc-&gt;users-&gt;usr[$pos]-&gt;u_cfg_root-&gt;profiles-&gt;profile as $profile) {\n if($profile-&gt;p_timestamp=='0') { $array_pos[]=$i; }\n $i++;\n}\n//print_r($array_pos);\nfor($i=0;$i&lt;count($array_pos);$i++) {\n unset($this-&gt;xml-&gt;doc-&gt;users-&gt;usr[$pos]-&gt;u_cfg_root-&gt;profiles-&gt;profile[$array_pos[$i]]);\n}\n</code></pre>\n" }, { "answer_id": 3577996, "author": "sunnyface45", "author_id": 432165, "author_profile": "https://Stackoverflow.com/users/432165", "pm_score": 3, "selected": false, "text": "<p>This work for me:</p>\n\n<pre><code>$data = '&lt;data&gt;\n&lt;seg id=\"A1\"/&gt;\n&lt;seg id=\"A5\"/&gt;\n&lt;seg id=\"A12\"/&gt;\n&lt;seg id=\"A29\"/&gt;\n&lt;seg id=\"A30\"/&gt;&lt;/data&gt;';\n\n$doc = new SimpleXMLElement($data);\n\n$segarr = $doc-&gt;seg;\n\n$count = count($segarr);\n\n$j = 0;\n\nfor ($i = 0; $i &lt; $count; $i++) {\n\n if ($segarr[$j]['id'] == 'A12') {\n unset($segarr[$j]);\n $j = $j - 1;\n }\n $j = $j + 1;\n}\n\necho $doc-&gt;asXml();\n</code></pre>\n" }, { "answer_id": 3687592, "author": "Michał Tatarynowicz", "author_id": 49564, "author_profile": "https://Stackoverflow.com/users/49564", "pm_score": 2, "selected": false, "text": "<p>If you extend the base SimpleXMLElement class, you can use this method:</p>\n\n<pre><code>class MyXML extends SimpleXMLElement {\n\n public function find($xpath) {\n $tmp = $this-&gt;xpath($xpath);\n return isset($tmp[0])? $tmp[0]: null;\n }\n\n public function remove() {\n $dom = dom_import_simplexml($this);\n return $dom-&gt;parentNode-&gt;removeChild($dom);\n }\n\n}\n\n// Example: removing the &lt;bar&gt; element with id = 1\n$foo = new MyXML('&lt;foo&gt;&lt;bar id=\"1\"/&gt;&lt;bar id=\"2\"/&gt;&lt;/foo&gt;');\n$foo-&gt;find('//bar[@id=\"1\"]')-&gt;remove();\nprint $foo-&gt;asXML(); // &lt;foo&gt;&lt;bar id=\"2\"/&gt;&lt;/foo&gt;\n</code></pre>\n" }, { "answer_id": 16062633, "author": "hakre", "author_id": 367456, "author_profile": "https://Stackoverflow.com/users/367456", "pm_score": 6, "selected": false, "text": "<p>Contrary to popular belief in the existing answers, each Simplexml element node can be removed from the document just by itself and <code>unset()</code>. The point in case is just that you need to understand how SimpleXML actually works.</p>\n\n<p>First locate the element you want to remove:</p>\n\n<pre><code>list($element) = $doc-&gt;xpath('/*/seg[@id=\"A12\"]');\n</code></pre>\n\n<p>Then remove the element represented in <code>$element</code> you unset its <em>self-reference</em>:</p>\n\n<pre><code>unset($element[0]);\n</code></pre>\n\n<p>This works because the first element of any element is the element itself in Simplexml (self-reference). This has to do with its magic nature, numeric indices are representing the elements in any list (e.g. parent->children), and even the single child is such a list.</p>\n\n<p>Non-numeric string indices represent attributes (in array-access) or child-element(s) (in property-access).</p>\n\n<p>Therefore numeric indecies in property-access like:</p>\n\n<pre><code>unset($element-&gt;{0});\n</code></pre>\n\n<p>work as well.</p>\n\n<p>Naturally with that xpath example, it is rather straight forward (in PHP 5.4):</p>\n\n<pre><code>unset($doc-&gt;xpath('/*/seg[@id=\"A12\"]')[0][0]);\n</code></pre>\n\n<p>The full example code (<a href=\"http://eval.in/16674\" rel=\"noreferrer\">Demo</a>):</p>\n\n<pre><code>&lt;?php\n/**\n * Remove a child with a specific attribute, in SimpleXML for PHP\n * @link http://stackoverflow.com/a/16062633/367456\n */\n\n$data=&lt;&lt;&lt;DATA\n&lt;data&gt;\n &lt;seg id=\"A1\"/&gt;\n &lt;seg id=\"A5\"/&gt;\n &lt;seg id=\"A12\"/&gt;\n &lt;seg id=\"A29\"/&gt;\n &lt;seg id=\"A30\"/&gt;\n&lt;/data&gt;\nDATA;\n\n\n$doc = new SimpleXMLElement($data);\n\nunset($doc-&gt;xpath('seg[@id=\"A12\"]')[0]-&gt;{0});\n\n$doc-&gt;asXml('php://output');\n</code></pre>\n\n<p>Output:</p>\n\n<pre><code>&lt;?xml version=\"1.0\"?&gt;\n&lt;data&gt;\n &lt;seg id=\"A1\"/&gt;\n &lt;seg id=\"A5\"/&gt;\n\n &lt;seg id=\"A29\"/&gt;\n &lt;seg id=\"A30\"/&gt;\n&lt;/data&gt;\n</code></pre>\n" }, { "answer_id": 16691801, "author": "Ben Yitzhaki", "author_id": 1138430, "author_profile": "https://Stackoverflow.com/users/1138430", "pm_score": 0, "selected": false, "text": "<p>I was also strugling with this issue and the answer is way easier than those provided over here.\nyou can just look for it using xpath and unset it it the following method:</p>\n\n<pre><code>unset($XML-&gt;xpath(\"NODESNAME[@id='test']\")[0]-&gt;{0});\n</code></pre>\n\n<p>this code will look for a node named \"NODESNAME\" with the id attribute \"test\" and remove the first occurence.</p>\n\n<p>remember to save the xml using $XML->saveXML(...);</p>\n" }, { "answer_id": 17426636, "author": "WoodrowShigeru", "author_id": 2126442, "author_profile": "https://Stackoverflow.com/users/2126442", "pm_score": 0, "selected": false, "text": "<p>Since I encountered the same fatal error as Gerry and I'm not familiar with DOM, I decided to do it like this:</p>\n\n<pre><code>$item = $xml-&gt;xpath(\"//seg[@id='A12']\");\n$page = $xml-&gt;xpath(\"/data\");\n$id = \"A12\";\n\nif ( count($item) &amp;&amp; count($page) ) {\n $item = $item[0];\n $page = $page[0];\n\n // find the numerical index within -&gt;children().\n $ch = $page-&gt;children();\n $ch_as_array = (array) $ch;\n\n if ( count($ch_as_array) &amp;&amp; isset($ch_as_array['seg']) ) {\n $ch_as_array = $ch_as_array['seg'];\n $index_in_array = array_search($item, $ch_as_array);\n if ( ($index_in_array !== false)\n &amp;&amp; ($index_in_array !== null)\n &amp;&amp; isset($ch[$index_in_array])\n &amp;&amp; ($ch[$index_in_array]['id'] == $id) ) {\n\n // delete it!\n unset($ch[$index_in_array]);\n\n echo \"&lt;pre&gt;\"; var_dump($xml); echo \"&lt;/pre&gt;\";\n }\n } // end of ( if xml object successfully converted to array )\n} // end of ( valid item AND section )\n</code></pre>\n" }, { "answer_id": 34970296, "author": "Daniele Orlando", "author_id": 1750243, "author_profile": "https://Stackoverflow.com/users/1750243", "pm_score": 0, "selected": false, "text": "<p>With <a href=\"https://github.com/servo-php/fluidxml\" rel=\"nofollow\"><strong>FluidXML</strong></a> you can use XPath to select the elements to remove.</p>\n\n<pre><code>$doc = fluidify($doc);\n\n$doc-&gt;remove('//*[@id=\"A12\"]');\n</code></pre>\n\n<p><a href=\"https://github.com/servo-php/fluidxml\" rel=\"nofollow\">https://github.com/servo-php/fluidxml</a></p>\n\n<hr>\n\n<p>The XPath <code>//*[@id=\"A12\"]</code> means:</p>\n\n<ul>\n<li>in any point of the document (<code>//</code>)</li>\n<li>every node (<code>*</code>)</li>\n<li>with the attribute <code>id</code> equal to <code>A12</code> (<code>[@id=\"A12\"]</code>).</li>\n</ul>\n" }, { "answer_id": 35887177, "author": "Columbus", "author_id": 1213292, "author_profile": "https://Stackoverflow.com/users/1213292", "pm_score": 0, "selected": false, "text": "<p>If you want to cut list of similar (not unique) child elements, for example items of RSS feed, you could use this code:</p>\n\n<pre><code>for ( $i = 9999; $i &gt; 10; $i--) {\n unset($xml-&gt;xpath('/rss/channel/item['. $i .']')[0]-&gt;{0});\n}\n</code></pre>\n\n<p>It will cut tail of RSS to 10 elements. I tried to remove with</p>\n\n<pre><code>for ( $i = 10; $i &lt; 9999; $i ++ ) {\n unset($xml-&gt;xpath('/rss/channel/item[' . $i . ']')[0]-&gt;{0});\n}\n</code></pre>\n\n<p>But it works somehow randomly and cuts only some of the elements.</p>\n" }, { "answer_id": 39202726, "author": "Krzysztof Przygoda", "author_id": 2254935, "author_profile": "https://Stackoverflow.com/users/2254935", "pm_score": 2, "selected": false, "text": "<p>To remove/keep nodes with certain attribute value or falling into array of attribute values you can extend <code>SimpleXMLElement</code> class like this (most recent version in my <a href=\"https://gist.github.com/KrzysztofPrzygoda/e53223e4450ed35effb75f54826cc434\" rel=\"nofollow noreferrer\">GitHub Gist</a>):</p>\n\n<pre><code>class SimpleXMLElementExtended extends SimpleXMLElement\n{ \n /**\n * Removes or keeps nodes with given attributes\n *\n * @param string $attributeName\n * @param array $attributeValues\n * @param bool $keep TRUE keeps nodes and removes the rest, FALSE removes nodes and keeps the rest \n * @return integer Number o affected nodes\n *\n * @example: $xml-&gt;o-&gt;filterAttribute('id', $products_ids); // Keeps only nodes with id attr in $products_ids\n * @see: http://stackoverflow.com/questions/17185959/simplexml-remove-nodes\n */\n public function filterAttribute($attributeName = '', $attributeValues = array(), $keepNodes = TRUE)\n { \n $nodesToRemove = array();\n\n foreach($this as $node)\n {\n $attributeValue = (string)$node[$attributeName];\n\n if ($keepNodes)\n {\n if (!in_array($attributeValue, $attributeValues)) $nodesToRemove[] = $node;\n }\n else\n { \n if (in_array($attributeValue, $attributeValues)) $nodesToRemove[] = $node;\n }\n }\n\n $result = count($nodesToRemove);\n\n foreach ($nodesToRemove as $node) {\n unset($node[0]);\n }\n\n return $result;\n }\n}\n</code></pre>\n\n<p>Then having your <code>$doc</code> XML you can remove your <code>&lt;seg id=\"A12\"/&gt;</code> node calling:</p>\n\n<pre><code>$data='&lt;data&gt;\n &lt;seg id=\"A1\"/&gt;\n &lt;seg id=\"A5\"/&gt;\n &lt;seg id=\"A12\"/&gt;\n &lt;seg id=\"A29\"/&gt;\n &lt;seg id=\"A30\"/&gt;\n&lt;/data&gt;';\n\n$doc=new SimpleXMLElementExtended($data);\n$doc-&gt;seg-&gt;filterAttribute('id', ['A12'], FALSE);\n</code></pre>\n\n<p>or remove multiple <code>&lt;seg /&gt;</code> nodes:</p>\n\n<pre><code>$doc-&gt;seg-&gt;filterAttribute('id', ['A1', 'A12', 'A29'], FALSE);\n</code></pre>\n\n<p>For keeping only <code>&lt;seg id=\"A5\"/&gt;</code> and <code>&lt;seg id=\"A30\"/&gt;</code> nodes and removing the rest:</p>\n\n<pre><code>$doc-&gt;seg-&gt;filterAttribute('id', ['A5', 'A30'], TRUE);\n</code></pre>\n" }, { "answer_id": 69392700, "author": "Lev Zadumkin", "author_id": 8972280, "author_profile": "https://Stackoverflow.com/users/8972280", "pm_score": 0, "selected": false, "text": "<p>I had a similar task - remove child elements, that are already present with the specified attribute. In other words, remove duplicates in xml. I have the following xml structure:</p>\n<pre><code>&lt;rups&gt;\n &lt;rup id=&quot;1&quot;&gt;\n &lt;profiles&gt; ... &lt;/profiles&gt;\n &lt;sections&gt;\n &lt;section id=&quot;1.1&quot; num=&quot;Б1.В&quot; parent_id=&quot;&quot;/&gt;\n &lt;section id=&quot;1.1.1&quot; num=&quot;Б1.В.1&quot; parent_id=&quot;1.1&quot;/&gt;\n ...\n &lt;section id=&quot;1.1&quot; num=&quot;Б1.В&quot; parent_id=&quot;&quot;/&gt;\n &lt;section id=&quot;1.1.2&quot; num=&quot;Б1.В.2&quot; parent_id=&quot;1.1&quot;/&gt;\n ...\n &lt;/sections&gt;\n &lt;/rup&gt;\n &lt;rup id=&quot;2&quot;&gt;\n ...\n &lt;/rup&gt;\n ...\n &lt;/rups&gt;\n</code></pre>\n<p>For example, <code>rups/rup[@id='1']/sections/section[@id='1.1']</code> elements are duplicated and I only need to leave the first one.\nI'm using a reference to array of elements, loop-for and unset():</p>\n<pre><code>$xml = simplexml_load_file('rup.xml');\nforeach ($xml-&gt;rup as $rup) {\n $r_s = [];\n $bads_r_s = 0;\n $sections = &amp;$rup-&gt;sections-&gt;section;\n for ($i = count($sections)-1; $i &gt;= 0; --$i) {\n if (in_array((string)$sections[$i]['id'], $r_s)) {\n $bads_r_s++;\n unset($sections[$i]);\n continue;\n }\n $r_s[] = (string)$sections[$i]['id'];\n }\n}\n$xml-&gt;saveXML('rup_checked.xml');\n</code></pre>\n" } ]
2008/11/04
[ "https://Stackoverflow.com/questions/262351", "https://Stackoverflow.com", "https://Stackoverflow.com/users/33739/" ]
I have several identical elements with different attributes that I'm accessing with SimpleXML: ``` <data> <seg id="A1"/> <seg id="A5"/> <seg id="A12"/> <seg id="A29"/> <seg id="A30"/> </data> ``` I need to remove a specific **seg** element, with an id of "A12", how can I do this? I've tried looping through the **seg** elements and *unset*ting the specific one, but this doesn't work, the elements remain. ``` foreach($doc->seg as $seg) { if($seg['id'] == 'A12') { unset($seg); } } ```
While [SimpleXML](http://de.php.net/manual/en/book.simplexml.php) provides [a way to remove](https://stackoverflow.com/a/16062633/367456) XML nodes, its modification capabilities are somewhat limited. One other solution is to resort to using the [DOM](http://de.php.net/manual/en/book.dom.php) extension. [dom\_import\_simplexml()](http://de.php.net/manual/en/function.dom-import-simplexml.php) will help you with converting your `SimpleXMLElement` into a `DOMElement`. Just some example code (tested with PHP 5.2.5): ``` $data='<data> <seg id="A1"/> <seg id="A5"/> <seg id="A12"/> <seg id="A29"/> <seg id="A30"/> </data>'; $doc=new SimpleXMLElement($data); foreach($doc->seg as $seg) { if($seg['id'] == 'A12') { $dom=dom_import_simplexml($seg); $dom->parentNode->removeChild($dom); } } echo $doc->asXml(); ``` outputs ``` <?xml version="1.0"?> <data><seg id="A1"/><seg id="A5"/><seg id="A29"/><seg id="A30"/></data> ``` By the way: selecting specific nodes is much more simple when you use XPath ([SimpleXMLElement->xpath](http://de.php.net/manual/en/function.simplexml-element-xpath.php)): ``` $segs=$doc->xpath('//seq[@id="A12"]'); if (count($segs)>=1) { $seg=$segs[0]; } // same deletion procedure as above ```
262,361
<p>I've been trying to design a database schema for a side project but I havent been able to produce anything that I'm comfortable with. I'm using ASP.Net with LINQ for my data access:</p> <p>I'm going to allow users to specify up to 10 "items" each with 2 numeric properties, and 1 referential property, the item name.</p> <p>If I were to put this entry into 1 row, it would easily equal out to some 30+ columns (minimum), e.g. item_1_name (ref) item_1_weight item_1_volume item_2_name... etc...</p> <p>And I can't simply turn these columns into referential tables as each property can essentially range from 1 to 400+.</p> <p>I also figured that if a user only decides to put 1 item into their entry, the method of which I create the object for that data will be static as with LINQ I'd have to check whether the properties and whatnot are NULL and work accordingly. Also, if I ever wanted to increase the number of items allowed in an entry, it'd be a headache to work with.</p> <p>The other option I've thought of is simply creating a row for each item and tying it with an entry id. So I'd essentially never have null entries, but my table would grow astronomically deep but not very wide, as there would only be some 5 odd columns.</p> <p>Is there something I'm overlooking in my design/is there a much better and efficient way of doing this?</p> <p>EDIT: When I say that it will grow astronomically, I mean it in this sense: A user can create an entry, and each entry will most likely have a group of items. So say they make 1 entry a day to the site, they could have 3 groups of items, with the max number of items (10), which would equate to 30 items for that sole entry. Make an entry everyday for a week at that rate and you could have 210 rows for that single user.</p>
[ { "answer_id": 262403, "author": "Manu", "author_id": 2133, "author_profile": "https://Stackoverflow.com/users/2133", "pm_score": 0, "selected": false, "text": "<p>use a single item table: </p>\n\n<p>userId, itemIndex, isReference, numericValue, referenceValue</p>\n\n<p>this way the value for item_3_name for user 999 translates to</p>\n\n<p>999,3,true,null,value</p>\n\n<p>You will have to enforce certain constraints yourself, s.a. the maximal number of items per user, etc.</p>\n" }, { "answer_id": 262412, "author": "Bill Karwin", "author_id": 20860, "author_profile": "https://Stackoverflow.com/users/20860", "pm_score": 3, "selected": true, "text": "<p>I'd recommend the latter design you mention, create one dependent table with five columns:</p>\n\n<pre><code>CREATE TABLE Items (\n user_id INTEGER NOT NULL,\n item_id INTEGER NOT NULL DEFAULT 1,\n numeric_property1 INTEGER,\n numeric_property2 INTEGER,\n referential_property INTEGER,\n PRIMARY KEY (user_id, item_id),\n FOREIGN KEY (user_id) REFERENCES Users(user_id)\n ON DELETE CASCADE,\n FOREIGN KEY (item_id) REFERENCES num_items(item_id),\n FOREIGN KEY (referential_property) REFERENCES some_other_table(some_column)\n);\n</code></pre>\n\n<p>I show a table <code>num_items</code> above, which contains the numbers 1 through 10 if you want to restrict users to 10 items at most:</p>\n\n<pre><code>CREATE TABLE num_items (item_id INTEGER NOT NULL );\nINSERT INTO num_items (item_id) \n VALUES (1), (2), (3), (4), (5), (6), (7), (8), (9), (10);\n</code></pre>\n\n<p>Advantages of this design is that it's easy to <code>COUNT()</code> how many items a given user has, it's easy to compute things like <code>MIN()</code> and <code>MAX()</code> for a given property, you can enforce a foreign key for the referential property, etc.</p>\n\n<p>Some databases have a feature to declare the second part of a compound primary key (<code>item_id</code> in this case) as auto-incrementing, so if you specify the value for <code>entity_id</code> but omit <code>item_id</code> it automatically gets the next unused value (but does not fill gaps if you delete one). You don't state which brand of database you're using so I'll leave it to you to figure out this feature.</p>\n\n<p><strong>edit:</strong> As Tony Andrews says in his answer, the number of rows is not a problem. You don't state which brand of database you're intending to use, but unless you choose an especially feeble product like MS Access, you can rely on the database to process millions of rows easily. If you choose indexes well, and write queries that use those indexes, efficiency shouldn't be a problem.</p>\n" }, { "answer_id": 262414, "author": "Tony Andrews", "author_id": 18747, "author_profile": "https://Stackoverflow.com/users/18747", "pm_score": 0, "selected": false, "text": "<p>Proper database design would be to store each user/item in a separate row. This will be much easier to work with, and removes the arbitrary restriction of 10 items. I wouldn't say it will grow \"astronomically deep\", there will be around 10 x (no. of users) rows.</p>\n" } ]
2008/11/04
[ "https://Stackoverflow.com/questions/262361", "https://Stackoverflow.com", "https://Stackoverflow.com/users/30816/" ]
I've been trying to design a database schema for a side project but I havent been able to produce anything that I'm comfortable with. I'm using ASP.Net with LINQ for my data access: I'm going to allow users to specify up to 10 "items" each with 2 numeric properties, and 1 referential property, the item name. If I were to put this entry into 1 row, it would easily equal out to some 30+ columns (minimum), e.g. item\_1\_name (ref) item\_1\_weight item\_1\_volume item\_2\_name... etc... And I can't simply turn these columns into referential tables as each property can essentially range from 1 to 400+. I also figured that if a user only decides to put 1 item into their entry, the method of which I create the object for that data will be static as with LINQ I'd have to check whether the properties and whatnot are NULL and work accordingly. Also, if I ever wanted to increase the number of items allowed in an entry, it'd be a headache to work with. The other option I've thought of is simply creating a row for each item and tying it with an entry id. So I'd essentially never have null entries, but my table would grow astronomically deep but not very wide, as there would only be some 5 odd columns. Is there something I'm overlooking in my design/is there a much better and efficient way of doing this? EDIT: When I say that it will grow astronomically, I mean it in this sense: A user can create an entry, and each entry will most likely have a group of items. So say they make 1 entry a day to the site, they could have 3 groups of items, with the max number of items (10), which would equate to 30 items for that sole entry. Make an entry everyday for a week at that rate and you could have 210 rows for that single user.
I'd recommend the latter design you mention, create one dependent table with five columns: ``` CREATE TABLE Items ( user_id INTEGER NOT NULL, item_id INTEGER NOT NULL DEFAULT 1, numeric_property1 INTEGER, numeric_property2 INTEGER, referential_property INTEGER, PRIMARY KEY (user_id, item_id), FOREIGN KEY (user_id) REFERENCES Users(user_id) ON DELETE CASCADE, FOREIGN KEY (item_id) REFERENCES num_items(item_id), FOREIGN KEY (referential_property) REFERENCES some_other_table(some_column) ); ``` I show a table `num_items` above, which contains the numbers 1 through 10 if you want to restrict users to 10 items at most: ``` CREATE TABLE num_items (item_id INTEGER NOT NULL ); INSERT INTO num_items (item_id) VALUES (1), (2), (3), (4), (5), (6), (7), (8), (9), (10); ``` Advantages of this design is that it's easy to `COUNT()` how many items a given user has, it's easy to compute things like `MIN()` and `MAX()` for a given property, you can enforce a foreign key for the referential property, etc. Some databases have a feature to declare the second part of a compound primary key (`item_id` in this case) as auto-incrementing, so if you specify the value for `entity_id` but omit `item_id` it automatically gets the next unused value (but does not fill gaps if you delete one). You don't state which brand of database you're using so I'll leave it to you to figure out this feature. **edit:** As Tony Andrews says in his answer, the number of rows is not a problem. You don't state which brand of database you're intending to use, but unless you choose an especially feeble product like MS Access, you can rely on the database to process millions of rows easily. If you choose indexes well, and write queries that use those indexes, efficiency shouldn't be a problem.
262,362
<p>On Ubuntu Linux with Gnome, running my Swing application by double clicking on the jar file in Gnomes file browser leads to errors because required libraries that are dynamically loaded via the Java Plugin Framework (residing in subdirectories) are not found.</p> <p>The base libraries for the framework itself are resolved correctly, as stated in my executable jar's manifest file. However, once the framework launches, no plugins (not even the one specifying my platform) are found.</p> <p>Launching the application from the terminal via</p> <pre> java -jar myjar.jar </pre> <p>works like a charm, ad does running the application by double-clicking a shell-script.</p> <p>However, I'd like to avoid a terminal window. (I'm a Windows person, maybe it won't annoy linux people as it does annoy those on windows.)</p> <p>The problem is reproducible across several Linux systems. Is there something I need to do so Java resolves the libraries correctly?</p>
[ { "answer_id": 262395, "author": "Steve B.", "author_id": 19479, "author_profile": "https://Stackoverflow.com/users/19479", "pm_score": 0, "selected": false, "text": "<p>Java loads jars in order in its classpath, i.e. jar1:jar2:jar3... Most java applications ship with some sort of script which sets all of this up by specifying a classpath and a list of jars that the application will need. </p>\n\n<p>What you want to do is probably not terribly advisable, as it means globally specifying a collection of jars that you want to load with every java application, and you're liable to create conflicts with whatever libraries ship with the application. </p>\n\n<p>This isn't really a problem, the easiest solution is probably to throw together a little shell script launcher. </p>\n" }, { "answer_id": 262436, "author": "David M. Karr", "author_id": 10508, "author_profile": "https://Stackoverflow.com/users/10508", "pm_score": 2, "selected": false, "text": "<p>I believe if you add to the jar a META-INF/MANIFEST.MF file containing a \"Classpath:\" attribute, with a value specifying the relative paths to the jars you need (I'm not sure whether they are space or comma separated), that might work.</p>\n" }, { "answer_id": 262507, "author": "el_eduardo", "author_id": 13469, "author_profile": "https://Stackoverflow.com/users/13469", "pm_score": 0, "selected": false, "text": "<p>Either you can write a shell script to launch and that is what you invoke or create a launcher. Here is a quick \"tutorial\" on how to do it for several platforms.</p>\n\n<p><a href=\"http://java.sys-con.com/node/37130\" rel=\"nofollow noreferrer\">http://java.sys-con.com/node/37130</a></p>\n\n<p>Here is how Eclipse does it. Will probably give you some ideas:</p>\n\n<p><a href=\"http://help.eclipse.org/stable/index.jsp?topic=/org.eclipse.platform.doc.isv/reference/misc/launcher.html\" rel=\"nofollow noreferrer\">http://help.eclipse.org/stable/index.jsp?topic=/org.eclipse.platform.doc.isv/reference/misc/launcher.html</a></p>\n\n<p>Good luck!</p>\n" }, { "answer_id": 262600, "author": "shyam", "author_id": 7616, "author_profile": "https://Stackoverflow.com/users/7616", "pm_score": 0, "selected": false, "text": "<p>As David suggested you can add the <code>Class-Path</code> manifest attribute in your jar for more <a href=\"http://java.sun.com/docs/books/tutorial/deployment/jar/downman.html\" rel=\"nofollow noreferrer\">jar manifest, Class-Path</a></p>\n" }, { "answer_id": 262873, "author": "jb.", "author_id": 7918, "author_profile": "https://Stackoverflow.com/users/7918", "pm_score": 1, "selected": false, "text": "<p>You may want to check: <a href=\"http://commons.apache.org/launcher/\" rel=\"nofollow noreferrer\">commons launcher</a>. It will give you plain executable file that can be made to do all sorts of startup preparations (including setting classpath, etc). Most probably it is overkill for your problem, but you might try it (I would try it in your case just because I hate scripts). </p>\n" } ]
2008/11/04
[ "https://Stackoverflow.com/questions/262362", "https://Stackoverflow.com", "https://Stackoverflow.com/users/25141/" ]
On Ubuntu Linux with Gnome, running my Swing application by double clicking on the jar file in Gnomes file browser leads to errors because required libraries that are dynamically loaded via the Java Plugin Framework (residing in subdirectories) are not found. The base libraries for the framework itself are resolved correctly, as stated in my executable jar's manifest file. However, once the framework launches, no plugins (not even the one specifying my platform) are found. Launching the application from the terminal via ``` java -jar myjar.jar ``` works like a charm, ad does running the application by double-clicking a shell-script. However, I'd like to avoid a terminal window. (I'm a Windows person, maybe it won't annoy linux people as it does annoy those on windows.) The problem is reproducible across several Linux systems. Is there something I need to do so Java resolves the libraries correctly?
I believe if you add to the jar a META-INF/MANIFEST.MF file containing a "Classpath:" attribute, with a value specifying the relative paths to the jars you need (I'm not sure whether they are space or comma separated), that might work.
262,363
<p>I'm working on a stripes app that uses a bit of jQuery to make the UI more dynamic/usable.</p> <p>I set up an Error Resolution, so if an error is thrown, the user is redirected to an error.jsp page.</p> <p>However, if an error is thrown during a jQuery Ajax call, instead of redirecting to the error.jsp page, I get html printed to the page where the result of the call should have been instead.</p> <p>How do I tell jQuery to redirect if an exception was thrown instead of printing to the page?</p> <p>An example of the offending Ajax:</p> <pre><code>$.post("SendStatusEmail.action", {status: newstatus, id : id }, function(data) { column.text(data); column.addClass("redfont"); column.parent().fadeOut(3000, function(){column.parent().remove()}); </code></pre>
[ { "answer_id": 262449, "author": "Craig Stuntz", "author_id": 7714, "author_profile": "https://Stackoverflow.com/users/7714", "pm_score": 3, "selected": true, "text": "<pre><code>$(document).ajaxError(function(event, XMLHttpRequest, ajaxOptions, thrownError) {\n // redirect here.\n}\n</code></pre>\n\n<p>I should add that I don't redirect when there is an exception in an Ajax call. Instead, I have the server return an error description in JSON format and display that in the page.</p>\n" }, { "answer_id": 268759, "author": "kgiannakakis", "author_id": 24054, "author_profile": "https://Stackoverflow.com/users/24054", "pm_score": 2, "selected": false, "text": "<p>What about using $.ajax() instead of $.post()? The more general $.ajax() offers an error callback that you can call in case of an error.</p>\n" } ]
2008/11/04
[ "https://Stackoverflow.com/questions/262363", "https://Stackoverflow.com", "https://Stackoverflow.com/users/31172/" ]
I'm working on a stripes app that uses a bit of jQuery to make the UI more dynamic/usable. I set up an Error Resolution, so if an error is thrown, the user is redirected to an error.jsp page. However, if an error is thrown during a jQuery Ajax call, instead of redirecting to the error.jsp page, I get html printed to the page where the result of the call should have been instead. How do I tell jQuery to redirect if an exception was thrown instead of printing to the page? An example of the offending Ajax: ``` $.post("SendStatusEmail.action", {status: newstatus, id : id }, function(data) { column.text(data); column.addClass("redfont"); column.parent().fadeOut(3000, function(){column.parent().remove()}); ```
``` $(document).ajaxError(function(event, XMLHttpRequest, ajaxOptions, thrownError) { // redirect here. } ``` I should add that I don't redirect when there is an exception in an Ajax call. Instead, I have the server return an error description in JSON format and display that in the page.
262,367
<p>In my spring application context file, I have something like:</p> <pre><code>&lt;util:map id=&quot;someMap&quot; map-class=&quot;java.util.HashMap&quot; key-type=&quot;java.lang.String&quot; value-type=&quot;java.lang.String&quot;&gt; &lt;entry key=&quot;some_key&quot; value=&quot;some value&quot; /&gt; &lt;entry key=&quot;some_key_2&quot; value=&quot;some value&quot; /&gt; &lt;/util:map&gt; </code></pre> <p>In java class, the implementation looks like:</p> <pre><code>private Map&lt;String, String&gt; someMap = new HashMap&lt;String, String&gt;(); someMap = (HashMap&lt;String, String&gt;)getApplicationContext().getBean(&quot;someMap&quot;); </code></pre> <p>In Eclipse, I see a warning that says:</p> <p><strong>Type safety: Unchecked cast from Object to HashMap&lt;String,String&gt;</strong></p> <p>What went wrong?</p>
[ { "answer_id": 262416, "author": "MetroidFan2002", "author_id": 8026, "author_profile": "https://Stackoverflow.com/users/8026", "pm_score": 9, "selected": true, "text": "<p>Well, first of all, you're wasting memory with the new <code>HashMap</code> creation call. Your second line completely disregards the reference to this created hashmap, making it then available to the garbage collector. So, don't do that, use:</p>\n\n<pre><code>private Map&lt;String, String&gt; someMap = (HashMap&lt;String, String&gt;)getApplicationContext().getBean(\"someMap\");\n</code></pre>\n\n<p>Secondly, the compiler is complaining that you cast the object to a <code>HashMap</code> without checking if it is a <code>HashMap</code>. But, even if you were to do:</p>\n\n<pre><code>if(getApplicationContext().getBean(\"someMap\") instanceof HashMap) {\n private Map&lt;String, String&gt; someMap = (HashMap&lt;String, String&gt;)getApplicationContext().getBean(\"someMap\");\n}\n</code></pre>\n\n<p>You would probably still get this warning. The problem is, <code>getBean</code> returns <code>Object</code>, so it is unknown what the type is. Converting it to <code>HashMap</code> directly would not cause the problem with the second case (and perhaps there would not be a warning in the first case, I'm not sure how pedantic the Java compiler is with warnings for Java 5). However, you are converting it to a <code>HashMap&lt;String, String&gt;</code>.</p>\n\n<p>HashMaps are really maps that take an object as a key and have an object as a value, <code>HashMap&lt;Object, Object&gt;</code> if you will. Thus, there is no guarantee that when you get your bean that it can be represented as a <code>HashMap&lt;String, String&gt;</code> because you could have <code>HashMap&lt;Date, Calendar&gt;</code> because the non-generic representation that is returned can have any objects.</p>\n\n<p>If the code compiles, and you can execute <code>String value = map.get(\"thisString\");</code> without any errors, don't worry about this warning. But if the map isn't completely of string keys to string values, you will get a <code>ClassCastException</code> at runtime, because the generics cannot block this from happening in this case.</p>\n" }, { "answer_id": 262417, "author": "David M. Karr", "author_id": 10508, "author_profile": "https://Stackoverflow.com/users/10508", "pm_score": 5, "selected": false, "text": "<p>A warning is just that. A warning. Sometimes warnings are irrelevant, sometimes they're not. They're used to call your attention to something that the compiler thinks could be a problem, but may not be.</p>\n\n<p>In the case of casts, it's always going to give a warning in this case. If you are absolutely certain that a particular cast will be safe, then you should consider adding an annotation like this (I'm not sure of the syntax) just before the line:</p>\n\n<pre><code>@SuppressWarnings (value=\"unchecked\")\n</code></pre>\n" }, { "answer_id": 262418, "author": "David Nehme", "author_id": 14167, "author_profile": "https://Stackoverflow.com/users/14167", "pm_score": 3, "selected": false, "text": "<p>You are getting this message because getBean returns an Object reference and you are casting it to the correct type. Java 1.5 gives you a warning. That's the nature of using Java 1.5 or better with code that works like this. Spring has the typesafe version</p>\n\n<pre><code>someMap=getApplicationContext().getBean&lt;HashMap&lt;String, String&gt;&gt;(\"someMap\");\n</code></pre>\n\n<p>on its todo list.</p>\n" }, { "answer_id": 262539, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 9, "selected": false, "text": "<p>The problem is that a cast is a runtime check - but due to type erasure, at runtime there's actually no difference between a <code>HashMap&lt;String,String&gt;</code> and <code>HashMap&lt;Foo,Bar&gt;</code> for any other <code>Foo</code> and <code>Bar</code>.</p>\n\n<p>Use <code>@SuppressWarnings(\"unchecked\")</code> and hold your nose. Oh, and campaign for reified generics in Java :)</p>\n" }, { "answer_id": 13387897, "author": "Larry Landry", "author_id": 1469526, "author_profile": "https://Stackoverflow.com/users/1469526", "pm_score": 7, "selected": false, "text": "<p>As the messages above indicate, the List cannot be differentiated between a <code>List&lt;Object&gt;</code> and a <code>List&lt;String&gt;</code> or <code>List&lt;Integer&gt;</code>.</p>\n\n<p>I've solved this error message for a similar problem:</p>\n\n<pre><code>List&lt;String&gt; strList = (List&lt;String&gt;) someFunction();\nString s = strList.get(0);\n</code></pre>\n\n<p>with the following:</p>\n\n<pre><code>List&lt;?&gt; strList = (List&lt;?&gt;) someFunction();\nString s = (String) strList.get(0);\n</code></pre>\n\n<p>Explanation: The first type conversion verifies that the object is a List without caring about the types held within (since we cannot verify the internal types at the List level). The second conversion is now required because the compiler only knows the List contains some sort of objects. This verifies the type of each object in the List as it is accessed.</p>\n" }, { "answer_id": 36603684, "author": "Rabbit", "author_id": 1412805, "author_profile": "https://Stackoverflow.com/users/1412805", "pm_score": 3, "selected": false, "text": "<p>If you really want to get rid of the warnings, one thing you can do is create a class that extends from the generic class.</p>\n\n<p>For example, if you're trying to use</p>\n\n<pre><code>private Map&lt;String, String&gt; someMap = new HashMap&lt;String, String&gt;();\n</code></pre>\n\n<p>You can create a new class like such</p>\n\n<pre><code>public class StringMap extends HashMap&lt;String, String&gt;()\n{\n // Override constructors\n}\n</code></pre>\n\n<p>Then when you use</p>\n\n<pre><code>someMap = (StringMap) getApplicationContext().getBean(\"someMap\");\n</code></pre>\n\n<p>The compiler DOES know what the (no longer generic) types are, and there will be no warning. This may not always be the perfect solution, some might argue this kind of defeats the purpose of generic classes, but you're still re-using all of the same code from the generic class, you're just declaring at compile time what type you want to use.</p>\n" }, { "answer_id": 40162894, "author": "Jeremy", "author_id": 160811, "author_profile": "https://Stackoverflow.com/users/160811", "pm_score": 2, "selected": false, "text": "<p>Another solution, if you find yourself casting the same object a lot and you don't want to litter your code with <code>@SupressWarnings(\"unchecked\")</code>, would be to create a method with the annotation. This way you're centralizing the cast, and hopefully reducing the possibility for error.</p>\n\n<pre><code>@SuppressWarnings(\"unchecked\")\npublic static List&lt;String&gt; getFooStrings(Map&lt;String, List&lt;String&gt;&gt; ctx) {\n return (List&lt;String&gt;) ctx.get(\"foos\");\n}\n</code></pre>\n" }, { "answer_id": 41186419, "author": "Andy", "author_id": 2353713, "author_profile": "https://Stackoverflow.com/users/2353713", "pm_score": 2, "selected": false, "text": "<p><strong>Below code causes Type safety Warning</strong></p>\n\n<p><code>Map&lt;String, Object&gt; myInput = (Map&lt;String, Object&gt;) myRequest.get();</code> </p>\n\n<blockquote>\n <p><strong>Workaround</strong></p>\n</blockquote>\n\n<p>Create a new Map Object without mentioning the parameters because the type of object held within the list is not verified.</p>\n\n<p><strong><em>Step 1:</em></strong> Create a new temporary Map</p>\n\n<p><code>Map&lt;?, ?&gt; tempMap = (Map&lt;?, ?&gt;) myRequest.get();</code></p>\n\n<p><strong><em>Step 2:</em></strong> Instantiate the main Map</p>\n\n<pre><code>Map&lt;String, Object&gt; myInput=new HashMap&lt;&gt;(myInputObj.size());\n</code></pre>\n\n<p><strong><em>Step 3:</em></strong> Iterate the temporary Map and set the values into the main Map</p>\n\n<pre><code> for(Map.Entry&lt;?, ?&gt; entry :myInputObj.entrySet()){\n myInput.put((String)entry.getKey(),entry.getValue()); \n }\n</code></pre>\n" }, { "answer_id": 52061219, "author": "ochakov", "author_id": 2210454, "author_profile": "https://Stackoverflow.com/users/2210454", "pm_score": 2, "selected": false, "text": "<p>The solution to avoid the unchecked warning:</p>\n\n<pre><code>class MyMap extends HashMap&lt;String, String&gt; {};\nsomeMap = (MyMap)getApplicationContext().getBean(\"someMap\");\n</code></pre>\n" }, { "answer_id": 57462703, "author": "davidxxx", "author_id": 270371, "author_profile": "https://Stackoverflow.com/users/270371", "pm_score": 2, "selected": false, "text": "<blockquote>\n <p>What did I do wrong? How do I resolve the issue?</p>\n</blockquote>\n\n<p>Here :</p>\n\n<p><code>Map&lt;String,String&gt; someMap = (Map&lt;String,String&gt;)getApplicationContext().getBean(\"someMap\");</code></p>\n\n<p>You use a legacy method that we generally don't want to use since that returns <code>Object</code>: </p>\n\n<pre><code>Object getBean(String name) throws BeansException;\n</code></pre>\n\n<p>The method to favor to get (for singleton) / create (for prototype) a bean from a bean factory is :</p>\n\n<pre><code>&lt;T&gt; T getBean(String name, Class&lt;T&gt; requiredType) throws BeansException;\n</code></pre>\n\n<p>Using it such as : </p>\n\n<pre><code>Map&lt;String,String&gt; someMap = app.getBean(Map.class,\"someMap\");\n</code></pre>\n\n<p>will compile but still with a unchecked conversion warning since all <code>Map</code> objects are not necessarily <code>Map&lt;String, String&gt;</code> objects. </p>\n\n<p>But <code>&lt;T&gt; T getBean(String name, Class&lt;T&gt; requiredType) throws BeansException;</code> is not enough in bean generic classes such as generic collections since that requires to specify more than one class as parameter : the collection type and its generic type(s). </p>\n\n<p>In this kind of scenario and in general, a better approach is not to use directly <code>BeanFactory</code> methods but let the framework to inject the bean. </p>\n\n<p>The bean declaration : </p>\n\n<pre><code>@Configuration\npublic class MyConfiguration{\n\n @Bean\n public Map&lt;String, String&gt; someMap() {\n Map&lt;String, String&gt; someMap = new HashMap();\n someMap.put(\"some_key\", \"some value\");\n someMap.put(\"some_key_2\", \"some value\");\n return someMap;\n }\n}\n</code></pre>\n\n<p>The bean injection : </p>\n\n<pre><code>@Autowired\n@Qualifier(\"someMap\")\nMap&lt;String, String&gt; someMap;\n</code></pre>\n" } ]
2008/11/04
[ "https://Stackoverflow.com/questions/262367", "https://Stackoverflow.com", "https://Stackoverflow.com/users/37740/" ]
In my spring application context file, I have something like: ``` <util:map id="someMap" map-class="java.util.HashMap" key-type="java.lang.String" value-type="java.lang.String"> <entry key="some_key" value="some value" /> <entry key="some_key_2" value="some value" /> </util:map> ``` In java class, the implementation looks like: ``` private Map<String, String> someMap = new HashMap<String, String>(); someMap = (HashMap<String, String>)getApplicationContext().getBean("someMap"); ``` In Eclipse, I see a warning that says: **Type safety: Unchecked cast from Object to HashMap<String,String>** What went wrong?
Well, first of all, you're wasting memory with the new `HashMap` creation call. Your second line completely disregards the reference to this created hashmap, making it then available to the garbage collector. So, don't do that, use: ``` private Map<String, String> someMap = (HashMap<String, String>)getApplicationContext().getBean("someMap"); ``` Secondly, the compiler is complaining that you cast the object to a `HashMap` without checking if it is a `HashMap`. But, even if you were to do: ``` if(getApplicationContext().getBean("someMap") instanceof HashMap) { private Map<String, String> someMap = (HashMap<String, String>)getApplicationContext().getBean("someMap"); } ``` You would probably still get this warning. The problem is, `getBean` returns `Object`, so it is unknown what the type is. Converting it to `HashMap` directly would not cause the problem with the second case (and perhaps there would not be a warning in the first case, I'm not sure how pedantic the Java compiler is with warnings for Java 5). However, you are converting it to a `HashMap<String, String>`. HashMaps are really maps that take an object as a key and have an object as a value, `HashMap<Object, Object>` if you will. Thus, there is no guarantee that when you get your bean that it can be represented as a `HashMap<String, String>` because you could have `HashMap<Date, Calendar>` because the non-generic representation that is returned can have any objects. If the code compiles, and you can execute `String value = map.get("thisString");` without any errors, don't worry about this warning. But if the map isn't completely of string keys to string values, you will get a `ClassCastException` at runtime, because the generics cannot block this from happening in this case.
262,376
<p>After "check-in" of a <code>.docx</code> file to <code>SharePoint</code> and editing it the <code>RevNum</code> property is set to <code>2</code>.</p> <p>This does not make sense, can someone explain why this is?</p>
[ { "answer_id": 262416, "author": "MetroidFan2002", "author_id": 8026, "author_profile": "https://Stackoverflow.com/users/8026", "pm_score": 9, "selected": true, "text": "<p>Well, first of all, you're wasting memory with the new <code>HashMap</code> creation call. Your second line completely disregards the reference to this created hashmap, making it then available to the garbage collector. So, don't do that, use:</p>\n\n<pre><code>private Map&lt;String, String&gt; someMap = (HashMap&lt;String, String&gt;)getApplicationContext().getBean(\"someMap\");\n</code></pre>\n\n<p>Secondly, the compiler is complaining that you cast the object to a <code>HashMap</code> without checking if it is a <code>HashMap</code>. But, even if you were to do:</p>\n\n<pre><code>if(getApplicationContext().getBean(\"someMap\") instanceof HashMap) {\n private Map&lt;String, String&gt; someMap = (HashMap&lt;String, String&gt;)getApplicationContext().getBean(\"someMap\");\n}\n</code></pre>\n\n<p>You would probably still get this warning. The problem is, <code>getBean</code> returns <code>Object</code>, so it is unknown what the type is. Converting it to <code>HashMap</code> directly would not cause the problem with the second case (and perhaps there would not be a warning in the first case, I'm not sure how pedantic the Java compiler is with warnings for Java 5). However, you are converting it to a <code>HashMap&lt;String, String&gt;</code>.</p>\n\n<p>HashMaps are really maps that take an object as a key and have an object as a value, <code>HashMap&lt;Object, Object&gt;</code> if you will. Thus, there is no guarantee that when you get your bean that it can be represented as a <code>HashMap&lt;String, String&gt;</code> because you could have <code>HashMap&lt;Date, Calendar&gt;</code> because the non-generic representation that is returned can have any objects.</p>\n\n<p>If the code compiles, and you can execute <code>String value = map.get(\"thisString\");</code> without any errors, don't worry about this warning. But if the map isn't completely of string keys to string values, you will get a <code>ClassCastException</code> at runtime, because the generics cannot block this from happening in this case.</p>\n" }, { "answer_id": 262417, "author": "David M. Karr", "author_id": 10508, "author_profile": "https://Stackoverflow.com/users/10508", "pm_score": 5, "selected": false, "text": "<p>A warning is just that. A warning. Sometimes warnings are irrelevant, sometimes they're not. They're used to call your attention to something that the compiler thinks could be a problem, but may not be.</p>\n\n<p>In the case of casts, it's always going to give a warning in this case. If you are absolutely certain that a particular cast will be safe, then you should consider adding an annotation like this (I'm not sure of the syntax) just before the line:</p>\n\n<pre><code>@SuppressWarnings (value=\"unchecked\")\n</code></pre>\n" }, { "answer_id": 262418, "author": "David Nehme", "author_id": 14167, "author_profile": "https://Stackoverflow.com/users/14167", "pm_score": 3, "selected": false, "text": "<p>You are getting this message because getBean returns an Object reference and you are casting it to the correct type. Java 1.5 gives you a warning. That's the nature of using Java 1.5 or better with code that works like this. Spring has the typesafe version</p>\n\n<pre><code>someMap=getApplicationContext().getBean&lt;HashMap&lt;String, String&gt;&gt;(\"someMap\");\n</code></pre>\n\n<p>on its todo list.</p>\n" }, { "answer_id": 262539, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 9, "selected": false, "text": "<p>The problem is that a cast is a runtime check - but due to type erasure, at runtime there's actually no difference between a <code>HashMap&lt;String,String&gt;</code> and <code>HashMap&lt;Foo,Bar&gt;</code> for any other <code>Foo</code> and <code>Bar</code>.</p>\n\n<p>Use <code>@SuppressWarnings(\"unchecked\")</code> and hold your nose. Oh, and campaign for reified generics in Java :)</p>\n" }, { "answer_id": 13387897, "author": "Larry Landry", "author_id": 1469526, "author_profile": "https://Stackoverflow.com/users/1469526", "pm_score": 7, "selected": false, "text": "<p>As the messages above indicate, the List cannot be differentiated between a <code>List&lt;Object&gt;</code> and a <code>List&lt;String&gt;</code> or <code>List&lt;Integer&gt;</code>.</p>\n\n<p>I've solved this error message for a similar problem:</p>\n\n<pre><code>List&lt;String&gt; strList = (List&lt;String&gt;) someFunction();\nString s = strList.get(0);\n</code></pre>\n\n<p>with the following:</p>\n\n<pre><code>List&lt;?&gt; strList = (List&lt;?&gt;) someFunction();\nString s = (String) strList.get(0);\n</code></pre>\n\n<p>Explanation: The first type conversion verifies that the object is a List without caring about the types held within (since we cannot verify the internal types at the List level). The second conversion is now required because the compiler only knows the List contains some sort of objects. This verifies the type of each object in the List as it is accessed.</p>\n" }, { "answer_id": 36603684, "author": "Rabbit", "author_id": 1412805, "author_profile": "https://Stackoverflow.com/users/1412805", "pm_score": 3, "selected": false, "text": "<p>If you really want to get rid of the warnings, one thing you can do is create a class that extends from the generic class.</p>\n\n<p>For example, if you're trying to use</p>\n\n<pre><code>private Map&lt;String, String&gt; someMap = new HashMap&lt;String, String&gt;();\n</code></pre>\n\n<p>You can create a new class like such</p>\n\n<pre><code>public class StringMap extends HashMap&lt;String, String&gt;()\n{\n // Override constructors\n}\n</code></pre>\n\n<p>Then when you use</p>\n\n<pre><code>someMap = (StringMap) getApplicationContext().getBean(\"someMap\");\n</code></pre>\n\n<p>The compiler DOES know what the (no longer generic) types are, and there will be no warning. This may not always be the perfect solution, some might argue this kind of defeats the purpose of generic classes, but you're still re-using all of the same code from the generic class, you're just declaring at compile time what type you want to use.</p>\n" }, { "answer_id": 40162894, "author": "Jeremy", "author_id": 160811, "author_profile": "https://Stackoverflow.com/users/160811", "pm_score": 2, "selected": false, "text": "<p>Another solution, if you find yourself casting the same object a lot and you don't want to litter your code with <code>@SupressWarnings(\"unchecked\")</code>, would be to create a method with the annotation. This way you're centralizing the cast, and hopefully reducing the possibility for error.</p>\n\n<pre><code>@SuppressWarnings(\"unchecked\")\npublic static List&lt;String&gt; getFooStrings(Map&lt;String, List&lt;String&gt;&gt; ctx) {\n return (List&lt;String&gt;) ctx.get(\"foos\");\n}\n</code></pre>\n" }, { "answer_id": 41186419, "author": "Andy", "author_id": 2353713, "author_profile": "https://Stackoverflow.com/users/2353713", "pm_score": 2, "selected": false, "text": "<p><strong>Below code causes Type safety Warning</strong></p>\n\n<p><code>Map&lt;String, Object&gt; myInput = (Map&lt;String, Object&gt;) myRequest.get();</code> </p>\n\n<blockquote>\n <p><strong>Workaround</strong></p>\n</blockquote>\n\n<p>Create a new Map Object without mentioning the parameters because the type of object held within the list is not verified.</p>\n\n<p><strong><em>Step 1:</em></strong> Create a new temporary Map</p>\n\n<p><code>Map&lt;?, ?&gt; tempMap = (Map&lt;?, ?&gt;) myRequest.get();</code></p>\n\n<p><strong><em>Step 2:</em></strong> Instantiate the main Map</p>\n\n<pre><code>Map&lt;String, Object&gt; myInput=new HashMap&lt;&gt;(myInputObj.size());\n</code></pre>\n\n<p><strong><em>Step 3:</em></strong> Iterate the temporary Map and set the values into the main Map</p>\n\n<pre><code> for(Map.Entry&lt;?, ?&gt; entry :myInputObj.entrySet()){\n myInput.put((String)entry.getKey(),entry.getValue()); \n }\n</code></pre>\n" }, { "answer_id": 52061219, "author": "ochakov", "author_id": 2210454, "author_profile": "https://Stackoverflow.com/users/2210454", "pm_score": 2, "selected": false, "text": "<p>The solution to avoid the unchecked warning:</p>\n\n<pre><code>class MyMap extends HashMap&lt;String, String&gt; {};\nsomeMap = (MyMap)getApplicationContext().getBean(\"someMap\");\n</code></pre>\n" }, { "answer_id": 57462703, "author": "davidxxx", "author_id": 270371, "author_profile": "https://Stackoverflow.com/users/270371", "pm_score": 2, "selected": false, "text": "<blockquote>\n <p>What did I do wrong? How do I resolve the issue?</p>\n</blockquote>\n\n<p>Here :</p>\n\n<p><code>Map&lt;String,String&gt; someMap = (Map&lt;String,String&gt;)getApplicationContext().getBean(\"someMap\");</code></p>\n\n<p>You use a legacy method that we generally don't want to use since that returns <code>Object</code>: </p>\n\n<pre><code>Object getBean(String name) throws BeansException;\n</code></pre>\n\n<p>The method to favor to get (for singleton) / create (for prototype) a bean from a bean factory is :</p>\n\n<pre><code>&lt;T&gt; T getBean(String name, Class&lt;T&gt; requiredType) throws BeansException;\n</code></pre>\n\n<p>Using it such as : </p>\n\n<pre><code>Map&lt;String,String&gt; someMap = app.getBean(Map.class,\"someMap\");\n</code></pre>\n\n<p>will compile but still with a unchecked conversion warning since all <code>Map</code> objects are not necessarily <code>Map&lt;String, String&gt;</code> objects. </p>\n\n<p>But <code>&lt;T&gt; T getBean(String name, Class&lt;T&gt; requiredType) throws BeansException;</code> is not enough in bean generic classes such as generic collections since that requires to specify more than one class as parameter : the collection type and its generic type(s). </p>\n\n<p>In this kind of scenario and in general, a better approach is not to use directly <code>BeanFactory</code> methods but let the framework to inject the bean. </p>\n\n<p>The bean declaration : </p>\n\n<pre><code>@Configuration\npublic class MyConfiguration{\n\n @Bean\n public Map&lt;String, String&gt; someMap() {\n Map&lt;String, String&gt; someMap = new HashMap();\n someMap.put(\"some_key\", \"some value\");\n someMap.put(\"some_key_2\", \"some value\");\n return someMap;\n }\n}\n</code></pre>\n\n<p>The bean injection : </p>\n\n<pre><code>@Autowired\n@Qualifier(\"someMap\")\nMap&lt;String, String&gt; someMap;\n</code></pre>\n" } ]
2008/11/04
[ "https://Stackoverflow.com/questions/262376", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
After "check-in" of a `.docx` file to `SharePoint` and editing it the `RevNum` property is set to `2`. This does not make sense, can someone explain why this is?
Well, first of all, you're wasting memory with the new `HashMap` creation call. Your second line completely disregards the reference to this created hashmap, making it then available to the garbage collector. So, don't do that, use: ``` private Map<String, String> someMap = (HashMap<String, String>)getApplicationContext().getBean("someMap"); ``` Secondly, the compiler is complaining that you cast the object to a `HashMap` without checking if it is a `HashMap`. But, even if you were to do: ``` if(getApplicationContext().getBean("someMap") instanceof HashMap) { private Map<String, String> someMap = (HashMap<String, String>)getApplicationContext().getBean("someMap"); } ``` You would probably still get this warning. The problem is, `getBean` returns `Object`, so it is unknown what the type is. Converting it to `HashMap` directly would not cause the problem with the second case (and perhaps there would not be a warning in the first case, I'm not sure how pedantic the Java compiler is with warnings for Java 5). However, you are converting it to a `HashMap<String, String>`. HashMaps are really maps that take an object as a key and have an object as a value, `HashMap<Object, Object>` if you will. Thus, there is no guarantee that when you get your bean that it can be represented as a `HashMap<String, String>` because you could have `HashMap<Date, Calendar>` because the non-generic representation that is returned can have any objects. If the code compiles, and you can execute `String value = map.get("thisString");` without any errors, don't worry about this warning. But if the map isn't completely of string keys to string values, you will get a `ClassCastException` at runtime, because the generics cannot block this from happening in this case.
262,379
<p>I've been trying to understand the strict aliasing rules as they apply to the char pointer.</p> <p><a href="http://cellperformance.beyond3d.com/articles/2006/06/understanding-strict-aliasing.html#cast_to_char_pointer" rel="nofollow noreferrer">Here</a> this is stated:</p> <blockquote> <p>It is always presumed that a char* may refer to an alias of any object.</p> </blockquote> <p>Ok so in the context of socket code, I can do this:</p> <pre><code>struct SocketMsg { int a; int b; }; int main(int argc, char** argv) { // Some code... SocketMsg msgToSend; msgToSend.a = 0; msgToSend.b = 1; send(socket, (char*)(&amp;msgToSend), sizeof(msgToSend); }; </code></pre> <p>But then there's this statement</p> <blockquote> <p>The converse is not true. Casting a char* to a pointer of any type other than a char* and dereferencing it is usually in violation of the strict aliasing rule. </p> </blockquote> <p>Does this mean that when I recv a char array, I can't reinterpret cast to a struct when I know the structure of the message:</p> <pre><code>struct SocketMsgToRecv { int a; int b; }; int main() { SocketMsgToRecv* pointerToMsg; char msgBuff[100]; ... recv(socket, msgBuff, 100); // Ommiting make sure we have a complete message from the stream // but lets assume msgBuff[0] has a complete msg, and lets interpret the msg // SAFE!?!?!? pointerToMsg = &amp;msgBuff[0]; printf("Got Msg: a: %i, b: %i", pointerToMsg-&gt;a, pointerToMsg-&gt;b); } </code></pre> <p>Will this second example not work because the base type is a char array and I'm casting it to a struct? How do you handle this situation in a strictly aliased world?</p>
[ { "answer_id": 262401, "author": "Adam Rosenfield", "author_id": 9530, "author_profile": "https://Stackoverflow.com/users/9530", "pm_score": 2, "selected": false, "text": "<p>Correct, the second example is in violation of the strict aliasing rules, so if you compile with the <code>-fstrict-aliasing</code> flag, there's a chance you may get incorrect object code. The fully correct solution would be to use a union here:</p>\n\n<pre><code>union\n{\n SocketMsgToRecv msg;\n char msgBuff[100];\n};\n\nrecv(socket, msgBuff, 100);\n\nprintf(\"Got Msg: a: %i, b: %i\", msg.a, msg.b);\n</code></pre>\n" }, { "answer_id": 263286, "author": "orcmid", "author_id": 33810, "author_profile": "https://Stackoverflow.com/users/33810", "pm_score": 3, "selected": false, "text": "<p>Re @Adam Rosenfield: The union will achieve alignment so long as the supplier of the char* started out doing something similar.</p>\n\n<p>It may be useful to stand back and figure out what this is all about.</p>\n\n<p>The basis for the aliasing rule is the fact that compilers may place values of different simple types on different memory boundaries to improve access and that hardware in some cases may require such alignment to be able to use the pointer at all. This can also show up in structs where there is a variety of different-sized elements. The struct may be started out on a good boundary. In addition, the compiler may still introduce slack bites in the interior of the struct to accomplish proper alignment of the struct elements that require it.</p>\n\n<p>Considering that compilers often have options for controlling how all of this is handled, or not, you can see that there are many ways that surprises can occur. This is particularly important to be aware of when passing pointers to structs (cast as char* or not) into libraries that were compiled to expect different alignment conventions.</p>\n\n<p>What about char*?</p>\n\n<p>The presumption about char* is that sizeof(char) == 1 (relative to the sizes of all other sizable data) and that char* pointers don't have any alignment requirement. So a genuine char* can always be safely passed around and used successfully without concern for alignment, and that goes for any element of a char[] array, performing ++ and -- on the pointers, and so on. (Oddly, void* is not quite the same.)</p>\n\n<p>Now you should be able to see how if you transfer some sort of structure data into a char[] array that was not itself aligned appropriately, attempting to cast back to a pointer that does require alignment(s) can be a serious problem.</p>\n\n<p>If you make a union of a char[] array and a struct, the most-demanding alignment (i.e., that of the struct) will be honored by the compiler. This will work if the supplier and the consumer are effectively using matching unions so that casting of the struct* to char* and back works just fine.</p>\n\n<p>In that case, I would hope that the data was created in a similar union before the pointer to it was cast to char* or it was transferred any other way as an array of sizeof(char) bytes. It is also important to make sure any compiler options are compatible between the libraries relied upon and your own code. </p>\n" } ]
2008/11/04
[ "https://Stackoverflow.com/questions/262379", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8123/" ]
I've been trying to understand the strict aliasing rules as they apply to the char pointer. [Here](http://cellperformance.beyond3d.com/articles/2006/06/understanding-strict-aliasing.html#cast_to_char_pointer) this is stated: > > It is always presumed that a char\* may refer to an alias of any object. > > > Ok so in the context of socket code, I can do this: ``` struct SocketMsg { int a; int b; }; int main(int argc, char** argv) { // Some code... SocketMsg msgToSend; msgToSend.a = 0; msgToSend.b = 1; send(socket, (char*)(&msgToSend), sizeof(msgToSend); }; ``` But then there's this statement > > The converse is not true. Casting a char\* to a pointer of any type other than a char\* and dereferencing it is usually in violation of the strict aliasing rule. > > > Does this mean that when I recv a char array, I can't reinterpret cast to a struct when I know the structure of the message: ``` struct SocketMsgToRecv { int a; int b; }; int main() { SocketMsgToRecv* pointerToMsg; char msgBuff[100]; ... recv(socket, msgBuff, 100); // Ommiting make sure we have a complete message from the stream // but lets assume msgBuff[0] has a complete msg, and lets interpret the msg // SAFE!?!?!? pointerToMsg = &msgBuff[0]; printf("Got Msg: a: %i, b: %i", pointerToMsg->a, pointerToMsg->b); } ``` Will this second example not work because the base type is a char array and I'm casting it to a struct? How do you handle this situation in a strictly aliased world?
Re @Adam Rosenfield: The union will achieve alignment so long as the supplier of the char\* started out doing something similar. It may be useful to stand back and figure out what this is all about. The basis for the aliasing rule is the fact that compilers may place values of different simple types on different memory boundaries to improve access and that hardware in some cases may require such alignment to be able to use the pointer at all. This can also show up in structs where there is a variety of different-sized elements. The struct may be started out on a good boundary. In addition, the compiler may still introduce slack bites in the interior of the struct to accomplish proper alignment of the struct elements that require it. Considering that compilers often have options for controlling how all of this is handled, or not, you can see that there are many ways that surprises can occur. This is particularly important to be aware of when passing pointers to structs (cast as char\* or not) into libraries that were compiled to expect different alignment conventions. What about char\*? The presumption about char\* is that sizeof(char) == 1 (relative to the sizes of all other sizable data) and that char\* pointers don't have any alignment requirement. So a genuine char\* can always be safely passed around and used successfully without concern for alignment, and that goes for any element of a char[] array, performing ++ and -- on the pointers, and so on. (Oddly, void\* is not quite the same.) Now you should be able to see how if you transfer some sort of structure data into a char[] array that was not itself aligned appropriately, attempting to cast back to a pointer that does require alignment(s) can be a serious problem. If you make a union of a char[] array and a struct, the most-demanding alignment (i.e., that of the struct) will be honored by the compiler. This will work if the supplier and the consumer are effectively using matching unions so that casting of the struct\* to char\* and back works just fine. In that case, I would hope that the data was created in a similar union before the pointer to it was cast to char\* or it was transferred any other way as an array of sizeof(char) bytes. It is also important to make sure any compiler options are compatible between the libraries relied upon and your own code.
262,392
<p>In an actionscript function (method) I have access to arguments.caller which returns a Function object but I can't find out the name of the function represented by this Function object. Its toString() simply returns [Function] and I can't find any other useful accessors that give me that... Help :-/</p>
[ { "answer_id": 280205, "author": "fenomas", "author_id": 10651, "author_profile": "https://Stackoverflow.com/users/10651", "pm_score": 1, "selected": false, "text": "<p>A function is just an object like any other - it doesn't have a \"name\" in and of itself; it only has a name in the sense that you might make one or more references to it. If what you're asking is how to get the name of the reference by which the function was called, then there's no general way to do that. (After all the function could be declared anonymously, in which case it has no name at all.)</p>\n\n<p>It would probably be best to examine why you need to know the function's name, and figure out some other way to pass in or access the information you're trying to derive from that name. Passing in an additional parameter might be one approach, but it depends on what you're doing.</p>\n" }, { "answer_id": 285452, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>As far as I know, not in AS2\nAS3 only.</p>\n" }, { "answer_id": 294462, "author": "Ran", "author_id": 10272, "author_profile": "https://Stackoverflow.com/users/10272", "pm_score": 2, "selected": true, "text": "<p>I found an answer and I'll paste it below.</p>\n\n<p>@fenomas: yes, you are right of course, functions are just objects and what I'm looking for is a the name of the reference to them (if exists, i.e. the function is not anonymous). You also right that in general this doesn't look like the best way to do programming ;-) But my scenario is special: I want to implement a Checks class (similar to C CHECK) with methods such as Check.checkTrue and Checks.checkRef in which when the check fails I get a nice trace. The traces will appear only in debug version, not in release.</p>\n\n<p>I'm using MTASC and the code below only works with MTASC. It should also be used only for debugging purposes and not release.\nThe technique is to iterate on _global and find a function that's equal to my calling function. It's a hack that does not always work (anonymous) but it serves me pretty well in most cases.</p>\n\n<pre><code>39: /**\n40: * Checks that cond is true. Use this method to validate that condition\n41: * cond holds.\n42: * If cond is false, traces a severe message and returns false to indicate\n43: * check failure.\n44: *\n45: * @param cond the contition expected to be true\n46: * @param msg the message to emit in case the condition is false.\n47: *\n48: * @return false is cond is false\n49: */\n50: public static function checkTrue(cond:Boolean, msg:String):Boolean {\n51: if (!cond) {\n52: trace(\"severe\", \"CHECK FAILED at \" +\n53: **getFunctionName(arguments.caller)** + \":\\n\" + msg);\n54: }\n55: return cond;\n56: }\n\n\n94: /**\n95: * Gets the name of the function func.\n96: * Warning: Use this only in debug version, not in release\n98: *\n99: * @return The full package path to the function. null if the function\n100: * isn't found.\n101: */\n102: private static function getFunctionName(func:Function):String {\n103: var name:String = getFunctionNameRecursive(func, _global);\n108: return name;\n109: }\n110: \n111: /**\n112: * Gets the name of the function func by recursively iterating over root.\n113: * Warning: Use this only in debug version, not in release\n114: */\n115: private static function getFunctionNameRecursive(func:Function,\n116: root:Object):String {\n117: if (!root) {\n118: return null;\n119: }\n120: \n121: // Iterate over classes in this package\n122: // A class is a function with a prototype object\n123: for (var i:String in root) {\n124: if (root[i] instanceof Function &amp;&amp; root[i].prototype != null) {\n125: // Found a class.\n126: // Iterate over class static members to see if there's a match\n127: for (var f:String in root[i]) {\n128: if(root[i][f] == func) {\n129: return i + \".\" + f;\n130: }\n131: }\n132: // Loop over the class's prototype to look for instance methods\n133: var instance:Object = root[i].prototype;\n134: // Reveal prototype's methods.\n135: // Warning: Not to be used in production code!!!\n136: // The following line make all the instance attributes visible to the\n137: // for-in construct. The \"n\" value is 8 which means \"unhide\"\n138: // See http://osflash.org/flashcoders/undocumented/assetpropflags\n139: // This operation is later undone by setting the \"n\" to 1 which means\n140: // \"hide\"\n141: _global.ASSetPropFlags(instance, null, 8, 1);\n142: for (var f:String in instance) {\n143: if(instance[f] == func) {\n144: return i + \".\" + f;\n145: }\n146: }\n147: // And hide instance methods again\n148: // This line undoes the previous ASSetPropFlags\n149: _global.ASSetPropFlags(instance, null, 1, false);\n150: }\n151: }\n152: \n153: // Iterate over sub packages. Sub packages have type \"object\"\n154: for (var i:String in root) {\n155: if (typeof(root[i]) == \"object\") {\n156: var name:String = getFunctionNameRecursive(func, root[i]);\n157: if (name) {\n158: return i + \".\" + name;\n159: }\n160: }\n161: }\n162: return null;\n163: }\n</code></pre>\n" } ]
2008/11/04
[ "https://Stackoverflow.com/questions/262392", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10272/" ]
In an actionscript function (method) I have access to arguments.caller which returns a Function object but I can't find out the name of the function represented by this Function object. Its toString() simply returns [Function] and I can't find any other useful accessors that give me that... Help :-/
I found an answer and I'll paste it below. @fenomas: yes, you are right of course, functions are just objects and what I'm looking for is a the name of the reference to them (if exists, i.e. the function is not anonymous). You also right that in general this doesn't look like the best way to do programming ;-) But my scenario is special: I want to implement a Checks class (similar to C CHECK) with methods such as Check.checkTrue and Checks.checkRef in which when the check fails I get a nice trace. The traces will appear only in debug version, not in release. I'm using MTASC and the code below only works with MTASC. It should also be used only for debugging purposes and not release. The technique is to iterate on \_global and find a function that's equal to my calling function. It's a hack that does not always work (anonymous) but it serves me pretty well in most cases. ``` 39: /** 40: * Checks that cond is true. Use this method to validate that condition 41: * cond holds. 42: * If cond is false, traces a severe message and returns false to indicate 43: * check failure. 44: * 45: * @param cond the contition expected to be true 46: * @param msg the message to emit in case the condition is false. 47: * 48: * @return false is cond is false 49: */ 50: public static function checkTrue(cond:Boolean, msg:String):Boolean { 51: if (!cond) { 52: trace("severe", "CHECK FAILED at " + 53: **getFunctionName(arguments.caller)** + ":\n" + msg); 54: } 55: return cond; 56: } 94: /** 95: * Gets the name of the function func. 96: * Warning: Use this only in debug version, not in release 98: * 99: * @return The full package path to the function. null if the function 100: * isn't found. 101: */ 102: private static function getFunctionName(func:Function):String { 103: var name:String = getFunctionNameRecursive(func, _global); 108: return name; 109: } 110: 111: /** 112: * Gets the name of the function func by recursively iterating over root. 113: * Warning: Use this only in debug version, not in release 114: */ 115: private static function getFunctionNameRecursive(func:Function, 116: root:Object):String { 117: if (!root) { 118: return null; 119: } 120: 121: // Iterate over classes in this package 122: // A class is a function with a prototype object 123: for (var i:String in root) { 124: if (root[i] instanceof Function && root[i].prototype != null) { 125: // Found a class. 126: // Iterate over class static members to see if there's a match 127: for (var f:String in root[i]) { 128: if(root[i][f] == func) { 129: return i + "." + f; 130: } 131: } 132: // Loop over the class's prototype to look for instance methods 133: var instance:Object = root[i].prototype; 134: // Reveal prototype's methods. 135: // Warning: Not to be used in production code!!! 136: // The following line make all the instance attributes visible to the 137: // for-in construct. The "n" value is 8 which means "unhide" 138: // See http://osflash.org/flashcoders/undocumented/assetpropflags 139: // This operation is later undone by setting the "n" to 1 which means 140: // "hide" 141: _global.ASSetPropFlags(instance, null, 8, 1); 142: for (var f:String in instance) { 143: if(instance[f] == func) { 144: return i + "." + f; 145: } 146: } 147: // And hide instance methods again 148: // This line undoes the previous ASSetPropFlags 149: _global.ASSetPropFlags(instance, null, 1, false); 150: } 151: } 152: 153: // Iterate over sub packages. Sub packages have type "object" 154: for (var i:String in root) { 155: if (typeof(root[i]) == "object") { 156: var name:String = getFunctionNameRecursive(func, root[i]); 157: if (name) { 158: return i + "." + name; 159: } 160: } 161: } 162: return null; 163: } ```
262,407
<p>I need to put the image from an NSProgressIndicator into an NSOutlineView Cell. I have written up code that does this for a determinate indicator and it works just great:</p> <pre><code>NSProgressIndicator *progressIndicator = [[NSProgressIndicator alloc] initWithFrame:NSMakeRect(0, 0, 16, 16)]; [progressIndicator setStyle:NSProgressIndicatorSpinningStyle]; [progressIndicator setIndeterminate:NO]; [progressIndicator setMaxValue:100.0]; [progressIndicator setDoubleValue:somePercentage]; NSImage *updateImage = [[NSImage alloc] initWithData:[progressIndicator dataWithPDFInsideRect:[progressIndicator frame]]]; [progressIndicator release]; return [updateImage autorelease]; </code></pre> <p>I have tried to modify the code to also give me indeterminate indicator images. However for the indeterminate case, I always get a blank 16x16 image. (I have confirmed this by writing the image to a file in each case, the determinate case gives me the progress indicator image, the indeterminate case is always 16x16 white square).</p> <p>The modified code is:</p> <pre><code>if(self.lengthUnknown) { NSProgressIndicator *progressIndicator = [[NSProgressIndicator alloc] initWithFrame:NSMakeRect(0, 0, 16, 16)]; [progressIndicator setStyle:NSProgressIndicatorSpinningStyle]; [progressIndicator setIndeterminate:YES]; NSImage *updateImage = [[NSImage alloc] initWithData:[progressIndicator dataWithPDFInsideRect:[progressIndicator frame]]]; [progressIndicator release]; return [updateImage autorelease]; } else { // Same code as the first listing, this case works fine } </code></pre> <p>Do indeterminate progress indicators use some type of drawing that causes -dataWithPDFInsideRect: to be unable to capture their image?</p> <hr> <p>More information: I tried setting the progress indicator to not use threaded animation as well as trying to grab the contents through NSImage's lockFocus method as suggested below but neither of those attempts made a difference.</p> <p>The progress indicator cell code that Dave mentions below (<a href="http://www.harmless.de/cocoa-code.php" rel="nofollow noreferrer">AMIndeterminateProgressIndicatorCell</a>) is a great workaround, but I would still like to know why I can't use the same technique that works with the determinate mode.</p>
[ { "answer_id": 263239, "author": "Dave Dribin", "author_id": 26825, "author_profile": "https://Stackoverflow.com/users/26825", "pm_score": 4, "selected": true, "text": "<p>I've used <a href=\"https://www.harmless.de/cocoa-code.php\" rel=\"nofollow noreferrer\">AMIndeterminateProgressIndicatorCell</a> for indeterminate progress indicators in cells. It's not a true NSProgressIndicator, as it does it's own drawing, but it's a pretty good replica, IMO.</p>\n\n<p><a href=\"https://i.stack.imgur.com/KcXmM.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/KcXmM.png\" alt=\"alt text\"></a><br>\n<sub>(source: <a href=\"http://www.harmless.de/images/progressindicator.png?harmless=e55652fb0a6b5e2d88a22e9b37c9bbc1\" rel=\"nofollow noreferrer\">harmless.de</a>)</sub> </p>\n" }, { "answer_id": 263256, "author": "Brian Webster", "author_id": 23324, "author_profile": "https://Stackoverflow.com/users/23324", "pm_score": 2, "selected": false, "text": "<p>Progress indicators do use a background thread to keep their animation drawing even if the main thread is busy doing something else, so it's possible that's what's causing the problem. You might try calling setUsesThreadedAnimation:NO on the progress indicator before doing your drawing to see if that makes a difference.</p>\n\n<p>Another tact would be to create a blank NSImage, and then call the progress indicator's drawRect: method to render its contents into the image buffer. That would look something like:</p>\n\n<pre>\nNSProgressIndicator* progressIndicator;\nNSImage* image = [[NSImage alloc] initWithSize:[progressIndicator bounds].size];\n[image lockFocus];\n[progressIndicator drawRect:[progressIndicator bounds]];\n[image unlockFocus];\n</pre>\n" } ]
2008/11/04
[ "https://Stackoverflow.com/questions/262407", "https://Stackoverflow.com", "https://Stackoverflow.com/users/28106/" ]
I need to put the image from an NSProgressIndicator into an NSOutlineView Cell. I have written up code that does this for a determinate indicator and it works just great: ``` NSProgressIndicator *progressIndicator = [[NSProgressIndicator alloc] initWithFrame:NSMakeRect(0, 0, 16, 16)]; [progressIndicator setStyle:NSProgressIndicatorSpinningStyle]; [progressIndicator setIndeterminate:NO]; [progressIndicator setMaxValue:100.0]; [progressIndicator setDoubleValue:somePercentage]; NSImage *updateImage = [[NSImage alloc] initWithData:[progressIndicator dataWithPDFInsideRect:[progressIndicator frame]]]; [progressIndicator release]; return [updateImage autorelease]; ``` I have tried to modify the code to also give me indeterminate indicator images. However for the indeterminate case, I always get a blank 16x16 image. (I have confirmed this by writing the image to a file in each case, the determinate case gives me the progress indicator image, the indeterminate case is always 16x16 white square). The modified code is: ``` if(self.lengthUnknown) { NSProgressIndicator *progressIndicator = [[NSProgressIndicator alloc] initWithFrame:NSMakeRect(0, 0, 16, 16)]; [progressIndicator setStyle:NSProgressIndicatorSpinningStyle]; [progressIndicator setIndeterminate:YES]; NSImage *updateImage = [[NSImage alloc] initWithData:[progressIndicator dataWithPDFInsideRect:[progressIndicator frame]]]; [progressIndicator release]; return [updateImage autorelease]; } else { // Same code as the first listing, this case works fine } ``` Do indeterminate progress indicators use some type of drawing that causes -dataWithPDFInsideRect: to be unable to capture their image? --- More information: I tried setting the progress indicator to not use threaded animation as well as trying to grab the contents through NSImage's lockFocus method as suggested below but neither of those attempts made a difference. The progress indicator cell code that Dave mentions below ([AMIndeterminateProgressIndicatorCell](http://www.harmless.de/cocoa-code.php)) is a great workaround, but I would still like to know why I can't use the same technique that works with the determinate mode.
I've used [AMIndeterminateProgressIndicatorCell](https://www.harmless.de/cocoa-code.php) for indeterminate progress indicators in cells. It's not a true NSProgressIndicator, as it does it's own drawing, but it's a pretty good replica, IMO. [![alt text](https://i.stack.imgur.com/KcXmM.png)](https://i.stack.imgur.com/KcXmM.png) (source: [harmless.de](http://www.harmless.de/images/progressindicator.png?harmless=e55652fb0a6b5e2d88a22e9b37c9bbc1))
262,408
<p>Users are occassionally getting the above error when using our application (VB.Net, Winforms, using v2 of the framework). I'm not able to reproduce it. The callstack is as follows:</p> <p>: System.AccessViolationException: Attempted to read or write protected memory. This is often an indication that other memory is corrupt. at System.Windows.Forms.UnsafeNativeMethods.CallWindowProc(IntPtr wndProc, IntPtr hWnd, Int32 msg, IntPtr wParam, IntPtr lParam) at System.Windows.Forms.NativeWindow.DefWndProc(Message&amp; m) at System.Windows.Forms.Control.DefWndProc(Message&amp; m) at System.Windows.Forms.Control.WndProc(Message&amp; m) at System.Windows.Forms.ComboBox.WndProc(Message&amp; m) at ControlEx.AutoCompleteCombo.WndProc(Message&amp; m) at System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message&amp; m) at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message&amp; m) at System.Windows.Forms.NativeWindow.Callback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)</p> <p>The code for ControlEx.AutoCompleteCombo.WndProc is as follows:</p> <pre><code>Protected Overrides Sub WndProc(ByRef m As System.Windows.Forms.Message) Try If Not m_fReadOnly Then MyBase.WndProc(m) Else Select Case m.Msg Case WM_LBUTTONDOWN, WM_LBUTTONDBLCLK ' do nothing Case Else MyBase.WndProc(m) End Select End If Catch ex As OutOfMemoryException Throw New OutOfMemoryException("Exception during WndProc for combo " &amp; Me.Name, ex) End Try End Sub </code></pre> <p>The error handling was added so we can determine which combo causes the problem when we get an OutOfMemoryException.</p> <p>Any clues as to what causes this would be muchly appreciated! :-)</p>
[ { "answer_id": 262434, "author": "Stu Mackellar", "author_id": 28591, "author_profile": "https://Stackoverflow.com/users/28591", "pm_score": 0, "selected": false, "text": "<p>It looks like you're using a custom combo box control called AutoCompleteCombo. I would suspect that the WndProc override in that class has a bug in it - probably changing the value of the message parameter. Can you post that method's code so we can have a look?</p>\n\n<hr>\n\n<p>There's nothing in the code that you posted that would cause a problem. You should probably look at the rest of AutoCompleteCombo's code for potential bugs. There's not really anything else to go on.</p>\n" }, { "answer_id": 265113, "author": "GvS", "author_id": 11492, "author_profile": "https://Stackoverflow.com/users/11492", "pm_score": 1, "selected": false, "text": "<p>I have a strange non-deterministic feeling with the OutOfMemoryException in your code.</p>\n\n<p>Why do you need that? And if you need it, may this be the cause of your problems? OutOfMemoryExceptions are very rare. If you have these, I would think it is a strong indication something else is wrong.</p>\n" }, { "answer_id": 281040, "author": "Sparky", "author_id": 34248, "author_profile": "https://Stackoverflow.com/users/34248", "pm_score": 0, "selected": false, "text": "<p>Thanks for your input, GvS and Stu. I'm doing a bit more probing re the OutOfMemory and found an interesting way this may happen (adding two items to the combo that return Nothing in their ToString override - <a href=\"http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=247053&amp;SiteID=1\" rel=\"nofollow noreferrer\">http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=247053&amp;SiteID=1</a> )</p>\n" }, { "answer_id": 406896, "author": "pipTheGeek", "author_id": 28552, "author_profile": "https://Stackoverflow.com/users/28552", "pm_score": 0, "selected": false, "text": "<p>I have just found that the original exception (AccessViolationException) is also caused by having an item in the ComboBox whose ToString returns Nothing (null). I don't know why you sometimes get OutOfMemory, sometimes Accessviolation and sometimes a NullReference exception.</p>\n" }, { "answer_id": 2596235, "author": "Special Touch", "author_id": 164306, "author_profile": "https://Stackoverflow.com/users/164306", "pm_score": 0, "selected": false, "text": "<p>Shot in the dark, but maybe you are trying to modify the AutoComplete list during a KeyDown, KeyUp, or KeyPress event?</p>\n\n<p>That can <a href=\"http://support.microsoft.com/kb/952544\" rel=\"nofollow noreferrer\">cause access violations</a> according to Microsoft.</p>\n" } ]
2008/11/04
[ "https://Stackoverflow.com/questions/262408", "https://Stackoverflow.com", "https://Stackoverflow.com/users/34248/" ]
Users are occassionally getting the above error when using our application (VB.Net, Winforms, using v2 of the framework). I'm not able to reproduce it. The callstack is as follows: : System.AccessViolationException: Attempted to read or write protected memory. This is often an indication that other memory is corrupt. at System.Windows.Forms.UnsafeNativeMethods.CallWindowProc(IntPtr wndProc, IntPtr hWnd, Int32 msg, IntPtr wParam, IntPtr lParam) at System.Windows.Forms.NativeWindow.DefWndProc(Message& m) at System.Windows.Forms.Control.DefWndProc(Message& m) at System.Windows.Forms.Control.WndProc(Message& m) at System.Windows.Forms.ComboBox.WndProc(Message& m) at ControlEx.AutoCompleteCombo.WndProc(Message& m) at System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m) at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m) at System.Windows.Forms.NativeWindow.Callback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam) The code for ControlEx.AutoCompleteCombo.WndProc is as follows: ``` Protected Overrides Sub WndProc(ByRef m As System.Windows.Forms.Message) Try If Not m_fReadOnly Then MyBase.WndProc(m) Else Select Case m.Msg Case WM_LBUTTONDOWN, WM_LBUTTONDBLCLK ' do nothing Case Else MyBase.WndProc(m) End Select End If Catch ex As OutOfMemoryException Throw New OutOfMemoryException("Exception during WndProc for combo " & Me.Name, ex) End Try End Sub ``` The error handling was added so we can determine which combo causes the problem when we get an OutOfMemoryException. Any clues as to what causes this would be muchly appreciated! :-)
I have a strange non-deterministic feeling with the OutOfMemoryException in your code. Why do you need that? And if you need it, may this be the cause of your problems? OutOfMemoryExceptions are very rare. If you have these, I would think it is a strong indication something else is wrong.
262,426
<p>This is a strange one... In a windows forms app (VB.NET/VS 2005) I have the need to occasionally check if the application DVD is inserted. <br>In my production machine (and in the majority of our clients) this code takes less than an second to execute. But in some machines, it takes about 8 to 10 seconds. I couldn't find any common ground on those few pcs in which it was slower (different OS, different RAM,different processors, more drives, less drives, etc). <br>It happens on about 4% of our test machines (and a few of our friends machines, by now:) ) <br>Since this funcion it is only called once, I can live with it. But the strange thing, and we stumbled upon this on pure luck, is that if a VMWare Virtual Machine is running, the code (running in the host OS ) will take the expected less than a second!!! <br> Has anyone ever encountered anything similar to this? Can anyone at least offer some explanation for this? </p> <pre><code>i_DrivesArray = GetLogicalDrives() i_DrivesCount = i_DrivesArray.Length For i_DriveNumber = 0 To i_DrivesCount - 1 i_DriveInformation = New DriveInfo(i_DrivesArray(i_DriveNumber)) If (i_DriveInformation.DriveType = i_DriveTargetType And i_DriveInformation.IsReady = True) Then If File.Exists(i_DriveInformation.Name.ToString &amp; ci_CDIdentifiers(i_Counter).ToString) = True Then ci_IsCDInserted = True ci_PathCD = i_DriveInformation.Name.ToString Exit For End If End If Next </code></pre>
[ { "answer_id": 262437, "author": "Joel Coehoorn", "author_id": 3043, "author_profile": "https://Stackoverflow.com/users/3043", "pm_score": 0, "selected": false, "text": "<ul>\n<li><p>Have you considered network mapped drives? They can be very slow to respond for certain things.</p></li>\n<li><p>Have you tried getting the list of drives, and then checking each drive in parallel rather than in serial? Cancel any pending requests when a result is found and return true. Since the real dvd drive will probably return right away, this would prevent any slow volumes from dragging the rest of the processes.</p></li>\n</ul>\n" }, { "answer_id": 441646, "author": "stephbu", "author_id": 12702, "author_profile": "https://Stackoverflow.com/users/12702", "pm_score": 2, "selected": true, "text": "<p>Where's the cost in this code? Profiling would really help on a <em>bad</em> machine</p>\n\n<p>I'd imagine the cost is somewhere in those DriveInfo calls - looking in reflector at the code behind DriveInfo:</p>\n\n<p>.cctor seems pretty innocuous - just validates letter constraints.</p>\n\n<p>.GetDriveType calls straight down into the equivalent Win32 API. Suspect this will try access the directory root since one of it's potential return results is DRIVE_NO_ROOT_DIR.</p>\n\n<blockquote>\n <blockquote>\n <p><a href=\"http://msdn.microsoft.com/en-us/library/aa364939.aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/aa364939.aspx</a></p>\n </blockquote>\n</blockquote>\n\n<p>.IsReady - that appears to attempt \"open\" the drive root directory populate the FILE_ATTRIBUTE structure. Again that looks similar to GetDriveType - possibly expensive.</p>\n\n<p>Both the latter API's have the potential to try and touch the drive filesystem. From there on down you're dependent on the behaviour of the device and it's drivers for the volume as to what \"unmounted\", \"ready, \"not ready\" etc. means. e.g. trying to spin up a disk.</p>\n\n<p>Since the delays are in the order of seconds I equally suspect that enumeration of the slow floppy/dvd/cd volumes is what takes the most time compared to other media types. Floppies especially used to have very long timeouts.</p>\n" } ]
2008/11/04
[ "https://Stackoverflow.com/questions/262426", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15528/" ]
This is a strange one... In a windows forms app (VB.NET/VS 2005) I have the need to occasionally check if the application DVD is inserted. In my production machine (and in the majority of our clients) this code takes less than an second to execute. But in some machines, it takes about 8 to 10 seconds. I couldn't find any common ground on those few pcs in which it was slower (different OS, different RAM,different processors, more drives, less drives, etc). It happens on about 4% of our test machines (and a few of our friends machines, by now:) ) Since this funcion it is only called once, I can live with it. But the strange thing, and we stumbled upon this on pure luck, is that if a VMWare Virtual Machine is running, the code (running in the host OS ) will take the expected less than a second!!! Has anyone ever encountered anything similar to this? Can anyone at least offer some explanation for this? ``` i_DrivesArray = GetLogicalDrives() i_DrivesCount = i_DrivesArray.Length For i_DriveNumber = 0 To i_DrivesCount - 1 i_DriveInformation = New DriveInfo(i_DrivesArray(i_DriveNumber)) If (i_DriveInformation.DriveType = i_DriveTargetType And i_DriveInformation.IsReady = True) Then If File.Exists(i_DriveInformation.Name.ToString & ci_CDIdentifiers(i_Counter).ToString) = True Then ci_IsCDInserted = True ci_PathCD = i_DriveInformation.Name.ToString Exit For End If End If Next ```
Where's the cost in this code? Profiling would really help on a *bad* machine I'd imagine the cost is somewhere in those DriveInfo calls - looking in reflector at the code behind DriveInfo: .cctor seems pretty innocuous - just validates letter constraints. .GetDriveType calls straight down into the equivalent Win32 API. Suspect this will try access the directory root since one of it's potential return results is DRIVE\_NO\_ROOT\_DIR. > > > > > > <http://msdn.microsoft.com/en-us/library/aa364939.aspx> > > > > > > > > > .IsReady - that appears to attempt "open" the drive root directory populate the FILE\_ATTRIBUTE structure. Again that looks similar to GetDriveType - possibly expensive. Both the latter API's have the potential to try and touch the drive filesystem. From there on down you're dependent on the behaviour of the device and it's drivers for the volume as to what "unmounted", "ready, "not ready" etc. means. e.g. trying to spin up a disk. Since the delays are in the order of seconds I equally suspect that enumeration of the slow floppy/dvd/cd volumes is what takes the most time compared to other media types. Floppies especially used to have very long timeouts.
262,427
<p>From the <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map" rel="noreferrer">Mozilla Developer Network</a>:</p> <pre><code>[1,4,9].map(Math.sqrt) </code></pre> <p>will yield:</p> <pre><code>[1,2,3] </code></pre> <p>Why then does this:</p> <pre><code>['1','2','3'].map(parseInt) </code></pre> <p>yield this:</p> <pre><code>[1, NaN, NaN] </code></pre> <p>I have tested in Firefox 3.0.1 and Chrome 0.3 and just as a disclaimer, I know this is not cross-browser functionality (no IE).</p> <p>I found out that the following will accomplish the desired effect. However, it still doesn’t explain the errant behavior of <code>parseInt</code>.</p> <pre><code>['1','2','3'].map(function(i){return +i;}) // returns [1,2,3] </code></pre>
[ { "answer_id": 262468, "author": "Peter Bailey", "author_id": 8815, "author_profile": "https://Stackoverflow.com/users/8815", "pm_score": 4, "selected": false, "text": "<p>I'm going to wager that it's something funky going on with the parseInt's 2nd parameter, the radix. Why it is breaking with the use of Array.map and not when you call it directly, I do not know.</p>\n\n<pre><code>// Works fine\nparseInt( 4 );\nparseInt( 9 );\n\n// Breaks! Why?\n[1,4,9].map( parseInt );\n\n// Fixes the problem\n[1,4,9].map( function( num ){ return parseInt( num, 10 ) } );\n</code></pre>\n" }, { "answer_id": 262511, "author": "Alnitak", "author_id": 6782, "author_profile": "https://Stackoverflow.com/users/6782", "pm_score": 10, "selected": true, "text": "<p>The callback function in <code>Array.map</code> has <em>three</em> parameters:</p>\n\n<p>From the same <a href=\"https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Objects/Array/map\" rel=\"noreferrer\">Mozilla page</a> that you linked to:</p>\n\n<blockquote>\n <p>callback is invoked with three arguments: the value of the element, the index of the element, and the Array object being traversed.\"</p>\n</blockquote>\n\n<p>So if you call a function <code>parseInt</code> which actually expects <em>two</em> arguments, the second argument will be the index of the element.</p>\n\n<p>In this case, you ended up calling <code>parseInt</code> with radix 0, 1 and 2 in turn. The first is the same as not supplying the parameter, so it defaulted based on the input (base 10, in this case). Base 1 is an impossible number base, and 3 is not a valid number in base 2:</p>\n\n<pre><code>parseInt('1', 0); // OK - gives 1\nparseInt('2', 1); // FAIL - 1 isn't a legal radix\nparseInt('3', 2); // FAIL - 3 isn't legal in base 2 \n</code></pre>\n\n<p>So in this case, you need the wrapper function:</p>\n\n<pre><code>['1','2','3'].map(function(num) { return parseInt(num, 10); });\n</code></pre>\n\n<p>or with ES2015+ syntax:</p>\n\n<pre><code>['1','2','3'].map(num =&gt; parseInt(num, 10));\n</code></pre>\n\n<p>(In both cases, it's best to <em>explicitly</em> supply a radix to <code>parseInt</code> as shown, because otherwise it guesses the radix based on the input. In some older browsers, a leading 0 caused it to guess octal, which tended to be problematic. It will still guess hex if the string starts with <code>0x</code>.)</p>\n" }, { "answer_id": 26855210, "author": "philfreo", "author_id": 137067, "author_profile": "https://Stackoverflow.com/users/137067", "pm_score": 5, "selected": false, "text": "<p><code>map</code> is passing along a 2nd argument, which is (in many of the cases) messing up <code>parseInt</code>'s radix parameter.</p>\n\n<p>If you're using underscore you can do:</p>\n\n<p><code>['10','1','100'].map(_.partial(parseInt, _, 10))</code></p>\n\n<p>Or without underscore:</p>\n\n<p><code>['10','1','100'].map(function(x) { return parseInt(x, 10); });</code></p>\n" }, { "answer_id": 31960786, "author": "yonatanmn", "author_id": 4391952, "author_profile": "https://Stackoverflow.com/users/4391952", "pm_score": 2, "selected": false, "text": "<p>another (working) quick fix : </p>\n\n<pre><code>var parseInt10 = function(x){return parseInt(x, 10);}\n\n['0', '1', '2', '10', '15', '57'].map(parseInt10);\n//[0, 1, 2, 10, 15, 57]\n</code></pre>\n" }, { "answer_id": 39005879, "author": "Vlad Bezden", "author_id": 30038, "author_profile": "https://Stackoverflow.com/users/30038", "pm_score": 2, "selected": false, "text": "<p>You can use arrow function ES2015/ES6 and just pass number to the parseInt. Default value for radix will be 10</p>\n\n<pre><code>[10, 20, 30].map(x =&gt; parseInt(x))\n</code></pre>\n\n<p>Or you can explicitly specify radix for better readability of your code.</p>\n\n<pre><code>[10, 20, 30].map(x =&gt; parseInt(x, 10))\n</code></pre>\n\n<p>In example above radix explicitly set to 10</p>\n" }, { "answer_id": 40563484, "author": "acontell", "author_id": 3565885, "author_profile": "https://Stackoverflow.com/users/3565885", "pm_score": 5, "selected": false, "text": "<p>You could solve this problem using <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number\" rel=\"noreferrer\">Number</a> as iteratee function:</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>var a = ['0', '1', '2', '10', '15', '57'].map(Number);\r\n\r\nconsole.log(a);</code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n<p>Without the new operator, Number can be used to perform type conversion. However, it differs from parseInt: it doesn't parse the string and returns NaN if the number cannot be converted. For instance:</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>console.log(parseInt(\"19asdf\"));\r\nconsole.log(Number(\"19asf\"));</code></pre>\r\n</div>\r\n</div>\r\n</p>\n" }, { "answer_id": 46760432, "author": "Doug Coburn", "author_id": 878906, "author_profile": "https://Stackoverflow.com/users/878906", "pm_score": -1, "selected": false, "text": "<p><code>parseInt</code> IMHO should be avoided for this very reason. You can wrap it to make it more safe in these contexts like this:</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>const safe = {\r\n parseInt: (s, opt) =&gt; {\r\n const { radix = 10 } = opt ? opt : {};\r\n return parseInt(s, radix);\r\n }\r\n}\r\n\r\nconsole.log( ['1','2','3'].map(safe.parseInt) );\r\nconsole.log(\r\n ['1', '10', '11'].map(e =&gt; safe.parseInt(e, { radix: 2 }))\r\n);</code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n<p>lodash/fp caps iteratee arguments to 1 by default to avoid these gotchas. Personally I have found these workarounds to create as many bugs as they avoid. Blacklisting <code>parseInt</code> in favor of a safer implementation is, I think, a better approach.</p>\n" }, { "answer_id": 68380302, "author": "Blackjack", "author_id": 13682949, "author_profile": "https://Stackoverflow.com/users/13682949", "pm_score": 1, "selected": false, "text": "<p>You can solve that issue like this:</p>\n<p><code>array.map(x =&gt; parseInt(x))</code></p>\n<p>Example:</p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>var arr = [\"3\", \"5\", \"7\"];\n\nconsole.log(\n arr.map(x =&gt; parseInt(x))\n);</code></pre>\r\n</div>\r\n</div>\r\n</p>\n" } ]
2008/11/04
[ "https://Stackoverflow.com/questions/262427", "https://Stackoverflow.com", "https://Stackoverflow.com/users/208/" ]
From the [Mozilla Developer Network](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map): ``` [1,4,9].map(Math.sqrt) ``` will yield: ``` [1,2,3] ``` Why then does this: ``` ['1','2','3'].map(parseInt) ``` yield this: ``` [1, NaN, NaN] ``` I have tested in Firefox 3.0.1 and Chrome 0.3 and just as a disclaimer, I know this is not cross-browser functionality (no IE). I found out that the following will accomplish the desired effect. However, it still doesn’t explain the errant behavior of `parseInt`. ``` ['1','2','3'].map(function(i){return +i;}) // returns [1,2,3] ```
The callback function in `Array.map` has *three* parameters: From the same [Mozilla page](https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Objects/Array/map) that you linked to: > > callback is invoked with three arguments: the value of the element, the index of the element, and the Array object being traversed." > > > So if you call a function `parseInt` which actually expects *two* arguments, the second argument will be the index of the element. In this case, you ended up calling `parseInt` with radix 0, 1 and 2 in turn. The first is the same as not supplying the parameter, so it defaulted based on the input (base 10, in this case). Base 1 is an impossible number base, and 3 is not a valid number in base 2: ``` parseInt('1', 0); // OK - gives 1 parseInt('2', 1); // FAIL - 1 isn't a legal radix parseInt('3', 2); // FAIL - 3 isn't legal in base 2 ``` So in this case, you need the wrapper function: ``` ['1','2','3'].map(function(num) { return parseInt(num, 10); }); ``` or with ES2015+ syntax: ``` ['1','2','3'].map(num => parseInt(num, 10)); ``` (In both cases, it's best to *explicitly* supply a radix to `parseInt` as shown, because otherwise it guesses the radix based on the input. In some older browsers, a leading 0 caused it to guess octal, which tended to be problematic. It will still guess hex if the string starts with `0x`.)
262,439
<p>I am trying to create wrapper functions for <code>free</code> and <code>malloc</code> in C to help notify me of memory leaks. Does anyone know how to declare these functions so when I call <code>malloc()</code> and <code>free()</code> it will call my custom functions and not the standards lib functions?</p>
[ { "answer_id": 262479, "author": "Roddy", "author_id": 1737, "author_profile": "https://Stackoverflow.com/users/1737", "pm_score": 2, "selected": false, "text": "<p>If you define your own functions for malloc() and free() and explicitly link that with your applications, your functions should be used in preference to those in the library.</p>\n\n<p>However, your function called 'malloc' cannot then call the library malloc function, because in 'c' there's no concept of separate namespaces. In other words, you'd have to implement the internals of malloc and free yourself.</p>\n\n<p>Another approach would be to write functions my_malloc() and my_free(), which call the standard library ones. This would mean that any code calling malloc would have to be changed to call your my_xxx functions.</p>\n" }, { "answer_id": 262481, "author": "Alex B", "author_id": 23643, "author_profile": "https://Stackoverflow.com/users/23643", "pm_score": 6, "selected": false, "text": "<p>You have a few options:</p>\n\n<ol>\n<li><p><strong>GLIBC-specific solution (mostly Linux).</strong> If your compilation environment is <code>glibc</code> with <code>gcc</code>, the preferred way is to use <a href=\"http://www.gnu.org/software/libtool/manual/libc/Hooks-for-Malloc.html\" rel=\"noreferrer\">malloc hooks</a>. Not only it lets you specify custom <code>malloc</code> and <code>free</code>, but will also identify the caller by the return address on the stack.</p></li>\n<li><p><strong>POSIX-specific solution.</strong> Define <code>malloc</code> and <code>free</code> as wrappers to the original allocation routines in your executable, which will \"override\" the version from libc. Inside the wrapper you can call into the original <code>malloc</code> implementation, which you can look up using <a href=\"http://pubs.opengroup.org/onlinepubs/009695399/functions/dlsym.html\" rel=\"noreferrer\"><code>dlsym</code></a> with <code>RTLD_NEXT</code> handle. Your application or library that defines wrapper functions needs to link with <code>-ldl</code>.</p>\n\n<pre><code>#define _GNU_SOURCE\n#include &lt;dlfcn.h&gt;\n#include &lt;stdio.h&gt;\n\nvoid* malloc(size_t sz)\n{\n void *(*libc_malloc)(size_t) = dlsym(RTLD_NEXT, \"malloc\");\n printf(\"malloc\\n\");\n return libc_malloc(sz);\n}\n\nvoid free(void *p)\n{\n void (*libc_free)(void*) = dlsym(RTLD_NEXT, \"free\");\n printf(\"free\\n\");\n libc_free(p);\n}\n\nint main()\n{\n free(malloc(10));\n return 0;\n}\n</code></pre></li>\n<li><p><strong>Linux specific.</strong> You can override functions from dynamic libraries non-invasively by specifying them in the <code>LD_PRELOAD</code> environment variable.</p>\n\n<pre><code>LD_PRELOAD=mymalloc.so ./exe\n</code></pre></li>\n<li><p><strong>Mac OSX specific.</strong></p>\n\n<p>Same as Linux, except you will be using <code>DYLD_INSERT_LIBRARIES</code> environment variable.</p></li>\n</ol>\n" }, { "answer_id": 262528, "author": "Don Wakefield", "author_id": 3778, "author_profile": "https://Stackoverflow.com/users/3778", "pm_score": 2, "selected": false, "text": "<p>If your goal is to eliminate memory leaks, an easier, less intrusive way is to use a tool like <a href=\"http://valgrind.org/\" rel=\"nofollow noreferrer\">Valgrind</a> (free) or <a href=\"http://www-01.ibm.com/software/awdtools/purify/\" rel=\"nofollow noreferrer\">Purify</a> (costly).</p>\n" }, { "answer_id": 262605, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>If you are using Linux, you can use malloc_hook() (with GNU glibc). This function allows you to have malloc call your function prior to calling the actual malloc. The man page has an example on how to use it.</p>\n" }, { "answer_id": 262609, "author": "Raymond Martineau", "author_id": 33952, "author_profile": "https://Stackoverflow.com/users/33952", "pm_score": 3, "selected": false, "text": "<p>In C, the method I used was similar to:</p>\n\n<pre><code>#define malloc(x) _my_malloc(x, __FILE__, __LINE__)\n#define free(x) _my_free(x)\n</code></pre>\n\n<p>This allowed me to detect the line and file of where the memory was allocated without too much difficulty. It should be cross-platform, but will encounter problems if the macro is already defined (which should only be the case if you are using another memory leak detector.) </p>\n\n<p>If you want to implement the same in C++, the procedure is a bit more <a href=\"http://wyw.dcweb.cn/leakage.htm\" rel=\"noreferrer\">complex</a> but uses the same trick. </p>\n" }, { "answer_id": 263035, "author": "quinmars", "author_id": 18687, "author_profile": "https://Stackoverflow.com/users/18687", "pm_score": 0, "selected": false, "text": "<p>If you are only talk about memory that you have under control, i.e. that you malloc and free on your own, you can take a look on <a href=\"http://www.hexco.de/rmdebug/\" rel=\"nofollow noreferrer\" title=\"rmdebug\">rmdebug</a>. Probably it is what you are going to write anyway, so you can save sometime. It has a very liberal licence, if that should be important for you.</p>\n\n<p>I personally use it in a project, to look for memory leaks, the nice things is that it is much faster then valgrind, however it isn't that powerful so you don't get the full calling stack.</p>\n" }, { "answer_id": 267469, "author": "Walter Bright", "author_id": 33949, "author_profile": "https://Stackoverflow.com/users/33949", "pm_score": 3, "selected": false, "text": "<p>Here's a set of wrapper functions I used for years (and still do when I dip into C) to detect unfree'd memory, memory free'd multiple times, references to free'd memory, buffer overflows/underflows, and freeing memory that was not allocated.</p>\n\n<p><a href=\"ftp://ftp.digitalmars.com/ctools.zip\" rel=\"nofollow noreferrer\">ftp://ftp.digitalmars.com/ctools.zip</a></p>\n\n<p>They've been around for 25 years and have proven themselves.</p>\n\n<p>You could use the macro preprocessor to redefine malloc and free to use the mem package ones, but I recommend against it, because it won't redirect library calls to malloc like what strdup does.</p>\n" }, { "answer_id": 4586534, "author": "Grzegorz Wierzowiecki", "author_id": 544721, "author_profile": "https://Stackoverflow.com/users/544721", "pm_score": 4, "selected": false, "text": "<p>You can do wrapper and \"overwrite\" function with LD_PRELOAD - similarly to example shown earlier.</p>\n\n<pre><code>LD_PRELOAD=/path.../lib_fake_malloc.so ./app\n</code></pre>\n\n<p>But I recommend to do this \"slightly\" smarter, I mean <strong>calling dlsym once</strong>.</p>\n\n<pre><code>#define _GNU_SOURCE\n#include &lt;stdio.h&gt;\n#include &lt;stdint.h&gt;\n#include &lt;dlfcn.h&gt;\n\nvoid* malloc(size_t size)\n{\n static void* (*real_malloc)(size_t) = NULL;\n if (!real_malloc)\n real_malloc = dlsym(RTLD_NEXT, \"malloc\");\n\n void *p = real_malloc(size);\n fprintf(stderr, \"malloc(%d) = %p\\n\", size, p);\n return p;\n}\n</code></pre>\n\n<p>example I've found here: <a href=\"http://www.jayconrod.com/cgi/view_post.py?23\" rel=\"noreferrer\">http://www.jayconrod.com/cgi/view_post.py?23</a> post by Jay Conrod.</p>\n\n<p>But what I've found really cool at this page is that: <strong>GNU linker provides</strong> a useful option, <strong>--wrap</strong> . When I check \"man ld\" there is following example:</p>\n\n<pre><code>void *\n__wrap_malloc (size_t c)\n{\n printf (\"malloc called with %zu\\n\", c);\n return __real_malloc (c);\n}\n</code></pre>\n\n<p>I agree with them that's \"trivial example\" :). Even dlsym is not needed. </p>\n\n<p>Let, me cite one more part of my \"man ld\" page:</p>\n\n<pre><code>--wrap=symbol\n Use a wrapper function for symbol.\n Any undefined reference to symbol will be resolved to \"__wrap_symbol\".\n Any undefined reference to \"__real_symbol\" will be resolved to symbol.\n</code></pre>\n\n<p>I hope, description is complete and shows how to use those things.</p>\n" }, { "answer_id": 33820054, "author": "user9869932", "author_id": 1183098, "author_profile": "https://Stackoverflow.com/users/1183098", "pm_score": 4, "selected": false, "text": "<p>In my case I needed to wrap memalign/aligned_malloc under malloc. After trying other solutions I ended up implementing the one listed below. It seems to be working fine.</p>\n<p><a href=\"https://www.cs.cmu.edu/afs/cs/academic/class/15213-s03/src/interposition/mymalloc.c\" rel=\"nofollow noreferrer\">mymalloc.c</a>.</p>\n<pre><code>/* \n * Link-time interposition of malloc and free using the static\n * linker's (ld) &quot;--wrap symbol&quot; flag.\n * \n * Compile the executable using &quot;-Wl,--wrap,malloc -Wl,--wrap,free&quot;.\n * This tells the linker to resolve references to malloc as\n * __wrap_malloc, free as __wrap_free, __real_malloc as malloc, and\n * __real_free as free.\n */\n#include &lt;stdio.h&gt;\n\nvoid *__real_malloc(size_t size);\nvoid __real_free(void *ptr);\n\n\n/* \n * __wrap_malloc - malloc wrapper function \n */\nvoid *__wrap_malloc(size_t size)\n{\n void *ptr = __real_malloc(size);\n printf(&quot;malloc(%d) = %p\\n&quot;, size, ptr);\n return ptr;\n}\n\n/* \n * __wrap_free - free wrapper function \n */\nvoid __wrap_free(void *ptr)\n{\n __real_free(ptr);\n printf(&quot;free(%p)\\n&quot;, ptr);\n}\n \n</code></pre>\n" }, { "answer_id": 63061254, "author": "michaelsnowden", "author_id": 2770572, "author_profile": "https://Stackoverflow.com/users/2770572", "pm_score": 1, "selected": false, "text": "<p>If you are the only client of the custom <code>malloc</code> and <code>free</code> (i.e. you're not trying to monkey patch those methods for code in some other library), then you can use dependency injection.</p>\n<pre class=\"lang-c prettyprint-override\"><code>#ifndef ALLOCATOR_H\n#define ALLOCATOR_H\n\n#include &lt;stddef.h&gt;\n\nstruct Allocator;\n\ntypedef struct {\n void *(*allocate)(struct Allocator *allocator, size_t size);\n\n void (*free)(struct Allocator *allocator, void *object);\n} AllocatorVTable;\n\ntypedef struct Allocator {\n const AllocatorVTable *vptr;\n} Allocator;\n\ntypedef struct {\n Allocator super;\n char *buffer;\n size_t offset;\n size_t capacity;\n} BufferedAllocator;\n\nvoid BufferedAllocator_init(BufferedAllocator *allocator, char *buffer, size_t capacity);\n\ntypedef Allocator MallocAllocator;\n\nvoid MallocAllocator_init(MallocAllocator *allocator);\n\nvoid *Allocator_allocate(Allocator *allocator, size_t size);\n\nvoid Allocator_free(Allocator *allocator, void *object);\n\n#endif\n</code></pre>\n<pre class=\"lang-c prettyprint-override\"><code>#include &quot;allocator.h&quot;\n#include &quot;malloc.h&quot;\n\nvoid *Allocator_allocate(Allocator *allocator, size_t size) {\n return allocator-&gt;vptr-&gt;allocate(allocator, size);\n}\n\nvoid Allocator_free(Allocator *allocator, void *object) {\n allocator-&gt;vptr-&gt;free(allocator, object);\n}\n\nvoid *BufferedAllocator_allocate(Allocator *allocator, size_t size) {\n BufferedAllocator *bufferedAllocator = (BufferedAllocator *) allocator;\n if (bufferedAllocator-&gt;offset + size &gt; bufferedAllocator-&gt;capacity) {\n fprintf(stderr, &quot;buffer overflow: %ld + %ld &gt; %ld\\n&quot;,\n bufferedAllocator-&gt;offset, size, bufferedAllocator-&gt;capacity);\n return NULL;\n }\n bufferedAllocator-&gt;offset += size;\n return bufferedAllocator-&gt;buffer + bufferedAllocator-&gt;offset - size;\n}\n\nvoid BufferedAllocator_free(Allocator *allocator, void *object) {\n\n}\n\nconst AllocatorVTable bufferedAllocatorVTable = {\n .allocate = BufferedAllocator_allocate,\n .free = BufferedAllocator_free,\n};\n\nvoid BufferedAllocator_init(BufferedAllocator *allocator, char *buffer,\n size_t capacity) {\n allocator-&gt;super.vptr = &amp;bufferedAllocatorVTable;\n allocator-&gt;buffer = buffer;\n allocator-&gt;offset = 0;\n allocator-&gt;capacity = capacity;\n}\n\nvoid *MallocAllocator_allocate(Allocator *allocator, size_t size) {\n return malloc(size);\n}\n\nvoid MallocAllocator_free(Allocator *allocator, void *object) {\n free(object);\n}\n\nconst AllocatorVTable mallocAllocatorVTable = {\n .allocate = MallocAllocator_allocate,\n .free = MallocAllocator_free,\n};\n\nvoid MallocAllocator_init(MallocAllocator *allocator) {\n allocator-&gt;vptr = &amp;mallocAllocatorVTable;\n}\n</code></pre>\n<pre class=\"lang-c prettyprint-override\"><code>#include &lt;assert.h&gt;\n#include &quot;allocator_test.h&quot;\n#include &quot;allocator.h&quot;\n\nvoid testAllocator() {\n {\n BufferedAllocator bufferedAllocator;\n char buffer[4];\n size_t capacity = sizeof(buffer);\n BufferedAllocator_init(&amp;bufferedAllocator, buffer, capacity);\n Allocator *allocator = &amp;bufferedAllocator.super;\n\n void *chill = Allocator_allocate(allocator, capacity);\n assert(chill == buffer);\n void *oops = Allocator_allocate(allocator, 1);\n assert(oops == NULL);\n }\n\n {\n MallocAllocator allocator;\n MallocAllocator_init(&amp;allocator);\n\n void *chill = Allocator_allocate(&amp;allocator, 100);\n assert(chill != NULL);\n void *alsoChill = Allocator_allocate(&amp;allocator, 100);\n assert(alsoChill != NULL);\n }\n}\n</code></pre>\n<p>So you would pass around an <code>Allocator *</code> to whichever piece of code you write that wants to allocate stuff (beyond something like <code>char buf[n]</code> on the stack). You can use a <code>MallocAllocator</code> to just use the system <code>malloc</code>/<code>free</code>, or you could use a <code>BufferedAllocator</code> at the very top of your program. A <code>BufferedAllocator</code> is just an example of a really simple malloc/free. It works well in my use-case because I pretty much know how much memory my program will use in advance, and I don't delete any object until the entire program is done. Using this interface, you could write a more complicated algorithm like one of the ones described in <a href=\"https://www2.cs.arizona.edu/%7Ecollberg/Teaching/553/2011/Handouts/Handout-6.pdf\" rel=\"nofollow noreferrer\">this lecture</a>. There are a lot of different strategies for preventing fragmentation and many trade-offs, so rolling your own malloc/free could be really useful.</p>\n" } ]
2008/11/04
[ "https://Stackoverflow.com/questions/262439", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I am trying to create wrapper functions for `free` and `malloc` in C to help notify me of memory leaks. Does anyone know how to declare these functions so when I call `malloc()` and `free()` it will call my custom functions and not the standards lib functions?
You have a few options: 1. **GLIBC-specific solution (mostly Linux).** If your compilation environment is `glibc` with `gcc`, the preferred way is to use [malloc hooks](http://www.gnu.org/software/libtool/manual/libc/Hooks-for-Malloc.html). Not only it lets you specify custom `malloc` and `free`, but will also identify the caller by the return address on the stack. 2. **POSIX-specific solution.** Define `malloc` and `free` as wrappers to the original allocation routines in your executable, which will "override" the version from libc. Inside the wrapper you can call into the original `malloc` implementation, which you can look up using [`dlsym`](http://pubs.opengroup.org/onlinepubs/009695399/functions/dlsym.html) with `RTLD_NEXT` handle. Your application or library that defines wrapper functions needs to link with `-ldl`. ``` #define _GNU_SOURCE #include <dlfcn.h> #include <stdio.h> void* malloc(size_t sz) { void *(*libc_malloc)(size_t) = dlsym(RTLD_NEXT, "malloc"); printf("malloc\n"); return libc_malloc(sz); } void free(void *p) { void (*libc_free)(void*) = dlsym(RTLD_NEXT, "free"); printf("free\n"); libc_free(p); } int main() { free(malloc(10)); return 0; } ``` 3. **Linux specific.** You can override functions from dynamic libraries non-invasively by specifying them in the `LD_PRELOAD` environment variable. ``` LD_PRELOAD=mymalloc.so ./exe ``` 4. **Mac OSX specific.** Same as Linux, except you will be using `DYLD_INSERT_LIBRARIES` environment variable.
262,443
<p>I am having an issue with IEMobile accessing my site. A certain redirect I use has a 302 response code, and the headers (yep, that's app-engine):</p> <pre>Server Development/1.0 Python/2.5.2 Date Tue, 04 Nov 2008 16:47:02 GMT Content-Type text/html; charset=utf-8 Cache-Control no-cache Location http://localhost/games/edit-game.html?game=110&frame_to_edit=3#input-top Content-Length 0</pre> <p>This works fine for most browsers. Enter IEMobile (via Windows Mobile 6.1). Upon receiving this response, IEMobile heads to</p> <pre>http://localhost/games/edit-game.html?game=110&frame_to_edit=3</pre> <p>Note the missing <code>#input-top</code>. What can I do?</p>
[ { "answer_id": 262479, "author": "Roddy", "author_id": 1737, "author_profile": "https://Stackoverflow.com/users/1737", "pm_score": 2, "selected": false, "text": "<p>If you define your own functions for malloc() and free() and explicitly link that with your applications, your functions should be used in preference to those in the library.</p>\n\n<p>However, your function called 'malloc' cannot then call the library malloc function, because in 'c' there's no concept of separate namespaces. In other words, you'd have to implement the internals of malloc and free yourself.</p>\n\n<p>Another approach would be to write functions my_malloc() and my_free(), which call the standard library ones. This would mean that any code calling malloc would have to be changed to call your my_xxx functions.</p>\n" }, { "answer_id": 262481, "author": "Alex B", "author_id": 23643, "author_profile": "https://Stackoverflow.com/users/23643", "pm_score": 6, "selected": false, "text": "<p>You have a few options:</p>\n\n<ol>\n<li><p><strong>GLIBC-specific solution (mostly Linux).</strong> If your compilation environment is <code>glibc</code> with <code>gcc</code>, the preferred way is to use <a href=\"http://www.gnu.org/software/libtool/manual/libc/Hooks-for-Malloc.html\" rel=\"noreferrer\">malloc hooks</a>. Not only it lets you specify custom <code>malloc</code> and <code>free</code>, but will also identify the caller by the return address on the stack.</p></li>\n<li><p><strong>POSIX-specific solution.</strong> Define <code>malloc</code> and <code>free</code> as wrappers to the original allocation routines in your executable, which will \"override\" the version from libc. Inside the wrapper you can call into the original <code>malloc</code> implementation, which you can look up using <a href=\"http://pubs.opengroup.org/onlinepubs/009695399/functions/dlsym.html\" rel=\"noreferrer\"><code>dlsym</code></a> with <code>RTLD_NEXT</code> handle. Your application or library that defines wrapper functions needs to link with <code>-ldl</code>.</p>\n\n<pre><code>#define _GNU_SOURCE\n#include &lt;dlfcn.h&gt;\n#include &lt;stdio.h&gt;\n\nvoid* malloc(size_t sz)\n{\n void *(*libc_malloc)(size_t) = dlsym(RTLD_NEXT, \"malloc\");\n printf(\"malloc\\n\");\n return libc_malloc(sz);\n}\n\nvoid free(void *p)\n{\n void (*libc_free)(void*) = dlsym(RTLD_NEXT, \"free\");\n printf(\"free\\n\");\n libc_free(p);\n}\n\nint main()\n{\n free(malloc(10));\n return 0;\n}\n</code></pre></li>\n<li><p><strong>Linux specific.</strong> You can override functions from dynamic libraries non-invasively by specifying them in the <code>LD_PRELOAD</code> environment variable.</p>\n\n<pre><code>LD_PRELOAD=mymalloc.so ./exe\n</code></pre></li>\n<li><p><strong>Mac OSX specific.</strong></p>\n\n<p>Same as Linux, except you will be using <code>DYLD_INSERT_LIBRARIES</code> environment variable.</p></li>\n</ol>\n" }, { "answer_id": 262528, "author": "Don Wakefield", "author_id": 3778, "author_profile": "https://Stackoverflow.com/users/3778", "pm_score": 2, "selected": false, "text": "<p>If your goal is to eliminate memory leaks, an easier, less intrusive way is to use a tool like <a href=\"http://valgrind.org/\" rel=\"nofollow noreferrer\">Valgrind</a> (free) or <a href=\"http://www-01.ibm.com/software/awdtools/purify/\" rel=\"nofollow noreferrer\">Purify</a> (costly).</p>\n" }, { "answer_id": 262605, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>If you are using Linux, you can use malloc_hook() (with GNU glibc). This function allows you to have malloc call your function prior to calling the actual malloc. The man page has an example on how to use it.</p>\n" }, { "answer_id": 262609, "author": "Raymond Martineau", "author_id": 33952, "author_profile": "https://Stackoverflow.com/users/33952", "pm_score": 3, "selected": false, "text": "<p>In C, the method I used was similar to:</p>\n\n<pre><code>#define malloc(x) _my_malloc(x, __FILE__, __LINE__)\n#define free(x) _my_free(x)\n</code></pre>\n\n<p>This allowed me to detect the line and file of where the memory was allocated without too much difficulty. It should be cross-platform, but will encounter problems if the macro is already defined (which should only be the case if you are using another memory leak detector.) </p>\n\n<p>If you want to implement the same in C++, the procedure is a bit more <a href=\"http://wyw.dcweb.cn/leakage.htm\" rel=\"noreferrer\">complex</a> but uses the same trick. </p>\n" }, { "answer_id": 263035, "author": "quinmars", "author_id": 18687, "author_profile": "https://Stackoverflow.com/users/18687", "pm_score": 0, "selected": false, "text": "<p>If you are only talk about memory that you have under control, i.e. that you malloc and free on your own, you can take a look on <a href=\"http://www.hexco.de/rmdebug/\" rel=\"nofollow noreferrer\" title=\"rmdebug\">rmdebug</a>. Probably it is what you are going to write anyway, so you can save sometime. It has a very liberal licence, if that should be important for you.</p>\n\n<p>I personally use it in a project, to look for memory leaks, the nice things is that it is much faster then valgrind, however it isn't that powerful so you don't get the full calling stack.</p>\n" }, { "answer_id": 267469, "author": "Walter Bright", "author_id": 33949, "author_profile": "https://Stackoverflow.com/users/33949", "pm_score": 3, "selected": false, "text": "<p>Here's a set of wrapper functions I used for years (and still do when I dip into C) to detect unfree'd memory, memory free'd multiple times, references to free'd memory, buffer overflows/underflows, and freeing memory that was not allocated.</p>\n\n<p><a href=\"ftp://ftp.digitalmars.com/ctools.zip\" rel=\"nofollow noreferrer\">ftp://ftp.digitalmars.com/ctools.zip</a></p>\n\n<p>They've been around for 25 years and have proven themselves.</p>\n\n<p>You could use the macro preprocessor to redefine malloc and free to use the mem package ones, but I recommend against it, because it won't redirect library calls to malloc like what strdup does.</p>\n" }, { "answer_id": 4586534, "author": "Grzegorz Wierzowiecki", "author_id": 544721, "author_profile": "https://Stackoverflow.com/users/544721", "pm_score": 4, "selected": false, "text": "<p>You can do wrapper and \"overwrite\" function with LD_PRELOAD - similarly to example shown earlier.</p>\n\n<pre><code>LD_PRELOAD=/path.../lib_fake_malloc.so ./app\n</code></pre>\n\n<p>But I recommend to do this \"slightly\" smarter, I mean <strong>calling dlsym once</strong>.</p>\n\n<pre><code>#define _GNU_SOURCE\n#include &lt;stdio.h&gt;\n#include &lt;stdint.h&gt;\n#include &lt;dlfcn.h&gt;\n\nvoid* malloc(size_t size)\n{\n static void* (*real_malloc)(size_t) = NULL;\n if (!real_malloc)\n real_malloc = dlsym(RTLD_NEXT, \"malloc\");\n\n void *p = real_malloc(size);\n fprintf(stderr, \"malloc(%d) = %p\\n\", size, p);\n return p;\n}\n</code></pre>\n\n<p>example I've found here: <a href=\"http://www.jayconrod.com/cgi/view_post.py?23\" rel=\"noreferrer\">http://www.jayconrod.com/cgi/view_post.py?23</a> post by Jay Conrod.</p>\n\n<p>But what I've found really cool at this page is that: <strong>GNU linker provides</strong> a useful option, <strong>--wrap</strong> . When I check \"man ld\" there is following example:</p>\n\n<pre><code>void *\n__wrap_malloc (size_t c)\n{\n printf (\"malloc called with %zu\\n\", c);\n return __real_malloc (c);\n}\n</code></pre>\n\n<p>I agree with them that's \"trivial example\" :). Even dlsym is not needed. </p>\n\n<p>Let, me cite one more part of my \"man ld\" page:</p>\n\n<pre><code>--wrap=symbol\n Use a wrapper function for symbol.\n Any undefined reference to symbol will be resolved to \"__wrap_symbol\".\n Any undefined reference to \"__real_symbol\" will be resolved to symbol.\n</code></pre>\n\n<p>I hope, description is complete and shows how to use those things.</p>\n" }, { "answer_id": 33820054, "author": "user9869932", "author_id": 1183098, "author_profile": "https://Stackoverflow.com/users/1183098", "pm_score": 4, "selected": false, "text": "<p>In my case I needed to wrap memalign/aligned_malloc under malloc. After trying other solutions I ended up implementing the one listed below. It seems to be working fine.</p>\n<p><a href=\"https://www.cs.cmu.edu/afs/cs/academic/class/15213-s03/src/interposition/mymalloc.c\" rel=\"nofollow noreferrer\">mymalloc.c</a>.</p>\n<pre><code>/* \n * Link-time interposition of malloc and free using the static\n * linker's (ld) &quot;--wrap symbol&quot; flag.\n * \n * Compile the executable using &quot;-Wl,--wrap,malloc -Wl,--wrap,free&quot;.\n * This tells the linker to resolve references to malloc as\n * __wrap_malloc, free as __wrap_free, __real_malloc as malloc, and\n * __real_free as free.\n */\n#include &lt;stdio.h&gt;\n\nvoid *__real_malloc(size_t size);\nvoid __real_free(void *ptr);\n\n\n/* \n * __wrap_malloc - malloc wrapper function \n */\nvoid *__wrap_malloc(size_t size)\n{\n void *ptr = __real_malloc(size);\n printf(&quot;malloc(%d) = %p\\n&quot;, size, ptr);\n return ptr;\n}\n\n/* \n * __wrap_free - free wrapper function \n */\nvoid __wrap_free(void *ptr)\n{\n __real_free(ptr);\n printf(&quot;free(%p)\\n&quot;, ptr);\n}\n \n</code></pre>\n" }, { "answer_id": 63061254, "author": "michaelsnowden", "author_id": 2770572, "author_profile": "https://Stackoverflow.com/users/2770572", "pm_score": 1, "selected": false, "text": "<p>If you are the only client of the custom <code>malloc</code> and <code>free</code> (i.e. you're not trying to monkey patch those methods for code in some other library), then you can use dependency injection.</p>\n<pre class=\"lang-c prettyprint-override\"><code>#ifndef ALLOCATOR_H\n#define ALLOCATOR_H\n\n#include &lt;stddef.h&gt;\n\nstruct Allocator;\n\ntypedef struct {\n void *(*allocate)(struct Allocator *allocator, size_t size);\n\n void (*free)(struct Allocator *allocator, void *object);\n} AllocatorVTable;\n\ntypedef struct Allocator {\n const AllocatorVTable *vptr;\n} Allocator;\n\ntypedef struct {\n Allocator super;\n char *buffer;\n size_t offset;\n size_t capacity;\n} BufferedAllocator;\n\nvoid BufferedAllocator_init(BufferedAllocator *allocator, char *buffer, size_t capacity);\n\ntypedef Allocator MallocAllocator;\n\nvoid MallocAllocator_init(MallocAllocator *allocator);\n\nvoid *Allocator_allocate(Allocator *allocator, size_t size);\n\nvoid Allocator_free(Allocator *allocator, void *object);\n\n#endif\n</code></pre>\n<pre class=\"lang-c prettyprint-override\"><code>#include &quot;allocator.h&quot;\n#include &quot;malloc.h&quot;\n\nvoid *Allocator_allocate(Allocator *allocator, size_t size) {\n return allocator-&gt;vptr-&gt;allocate(allocator, size);\n}\n\nvoid Allocator_free(Allocator *allocator, void *object) {\n allocator-&gt;vptr-&gt;free(allocator, object);\n}\n\nvoid *BufferedAllocator_allocate(Allocator *allocator, size_t size) {\n BufferedAllocator *bufferedAllocator = (BufferedAllocator *) allocator;\n if (bufferedAllocator-&gt;offset + size &gt; bufferedAllocator-&gt;capacity) {\n fprintf(stderr, &quot;buffer overflow: %ld + %ld &gt; %ld\\n&quot;,\n bufferedAllocator-&gt;offset, size, bufferedAllocator-&gt;capacity);\n return NULL;\n }\n bufferedAllocator-&gt;offset += size;\n return bufferedAllocator-&gt;buffer + bufferedAllocator-&gt;offset - size;\n}\n\nvoid BufferedAllocator_free(Allocator *allocator, void *object) {\n\n}\n\nconst AllocatorVTable bufferedAllocatorVTable = {\n .allocate = BufferedAllocator_allocate,\n .free = BufferedAllocator_free,\n};\n\nvoid BufferedAllocator_init(BufferedAllocator *allocator, char *buffer,\n size_t capacity) {\n allocator-&gt;super.vptr = &amp;bufferedAllocatorVTable;\n allocator-&gt;buffer = buffer;\n allocator-&gt;offset = 0;\n allocator-&gt;capacity = capacity;\n}\n\nvoid *MallocAllocator_allocate(Allocator *allocator, size_t size) {\n return malloc(size);\n}\n\nvoid MallocAllocator_free(Allocator *allocator, void *object) {\n free(object);\n}\n\nconst AllocatorVTable mallocAllocatorVTable = {\n .allocate = MallocAllocator_allocate,\n .free = MallocAllocator_free,\n};\n\nvoid MallocAllocator_init(MallocAllocator *allocator) {\n allocator-&gt;vptr = &amp;mallocAllocatorVTable;\n}\n</code></pre>\n<pre class=\"lang-c prettyprint-override\"><code>#include &lt;assert.h&gt;\n#include &quot;allocator_test.h&quot;\n#include &quot;allocator.h&quot;\n\nvoid testAllocator() {\n {\n BufferedAllocator bufferedAllocator;\n char buffer[4];\n size_t capacity = sizeof(buffer);\n BufferedAllocator_init(&amp;bufferedAllocator, buffer, capacity);\n Allocator *allocator = &amp;bufferedAllocator.super;\n\n void *chill = Allocator_allocate(allocator, capacity);\n assert(chill == buffer);\n void *oops = Allocator_allocate(allocator, 1);\n assert(oops == NULL);\n }\n\n {\n MallocAllocator allocator;\n MallocAllocator_init(&amp;allocator);\n\n void *chill = Allocator_allocate(&amp;allocator, 100);\n assert(chill != NULL);\n void *alsoChill = Allocator_allocate(&amp;allocator, 100);\n assert(alsoChill != NULL);\n }\n}\n</code></pre>\n<p>So you would pass around an <code>Allocator *</code> to whichever piece of code you write that wants to allocate stuff (beyond something like <code>char buf[n]</code> on the stack). You can use a <code>MallocAllocator</code> to just use the system <code>malloc</code>/<code>free</code>, or you could use a <code>BufferedAllocator</code> at the very top of your program. A <code>BufferedAllocator</code> is just an example of a really simple malloc/free. It works well in my use-case because I pretty much know how much memory my program will use in advance, and I don't delete any object until the entire program is done. Using this interface, you could write a more complicated algorithm like one of the ones described in <a href=\"https://www2.cs.arizona.edu/%7Ecollberg/Teaching/553/2011/Handouts/Handout-6.pdf\" rel=\"nofollow noreferrer\">this lecture</a>. There are a lot of different strategies for preventing fragmentation and many trade-offs, so rolling your own malloc/free could be really useful.</p>\n" } ]
2008/11/04
[ "https://Stackoverflow.com/questions/262443", "https://Stackoverflow.com", "https://Stackoverflow.com/users/96/" ]
I am having an issue with IEMobile accessing my site. A certain redirect I use has a 302 response code, and the headers (yep, that's app-engine): ``` Server Development/1.0 Python/2.5.2 Date Tue, 04 Nov 2008 16:47:02 GMT Content-Type text/html; charset=utf-8 Cache-Control no-cache Location http://localhost/games/edit-game.html?game=110&frame_to_edit=3#input-top Content-Length 0 ``` This works fine for most browsers. Enter IEMobile (via Windows Mobile 6.1). Upon receiving this response, IEMobile heads to ``` http://localhost/games/edit-game.html?game=110&frame_to_edit=3 ``` Note the missing `#input-top`. What can I do?
You have a few options: 1. **GLIBC-specific solution (mostly Linux).** If your compilation environment is `glibc` with `gcc`, the preferred way is to use [malloc hooks](http://www.gnu.org/software/libtool/manual/libc/Hooks-for-Malloc.html). Not only it lets you specify custom `malloc` and `free`, but will also identify the caller by the return address on the stack. 2. **POSIX-specific solution.** Define `malloc` and `free` as wrappers to the original allocation routines in your executable, which will "override" the version from libc. Inside the wrapper you can call into the original `malloc` implementation, which you can look up using [`dlsym`](http://pubs.opengroup.org/onlinepubs/009695399/functions/dlsym.html) with `RTLD_NEXT` handle. Your application or library that defines wrapper functions needs to link with `-ldl`. ``` #define _GNU_SOURCE #include <dlfcn.h> #include <stdio.h> void* malloc(size_t sz) { void *(*libc_malloc)(size_t) = dlsym(RTLD_NEXT, "malloc"); printf("malloc\n"); return libc_malloc(sz); } void free(void *p) { void (*libc_free)(void*) = dlsym(RTLD_NEXT, "free"); printf("free\n"); libc_free(p); } int main() { free(malloc(10)); return 0; } ``` 3. **Linux specific.** You can override functions from dynamic libraries non-invasively by specifying them in the `LD_PRELOAD` environment variable. ``` LD_PRELOAD=mymalloc.so ./exe ``` 4. **Mac OSX specific.** Same as Linux, except you will be using `DYLD_INSERT_LIBRARIES` environment variable.
262,448
<p>Quick add on requirement in our project. A field in our DB to hold a phone number is set to only allow 10 characters. So, if I get passed "(913)-444-5555" or anything else, is there a quick way to run a string through some kind of special replace function that I can pass it a set of characters to allow?</p> <p>Regex?</p>
[ { "answer_id": 262466, "author": "Joel Coehoorn", "author_id": 3043, "author_profile": "https://Stackoverflow.com/users/3043", "pm_score": 9, "selected": true, "text": "<p>Definitely regex:</p>\n\n<pre><code>string CleanPhone(string phone)\n{\n Regex digitsOnly = new Regex(@\"[^\\d]\"); \n return digitsOnly.Replace(phone, \"\");\n}\n</code></pre>\n\n<p>or within a class to avoid re-creating the regex all the time:</p>\n\n<pre><code>private static Regex digitsOnly = new Regex(@\"[^\\d]\"); \n\npublic static string CleanPhone(string phone)\n{\n return digitsOnly.Replace(phone, \"\");\n}\n</code></pre>\n\n<p>Depending on your real-world inputs, you may want some additional logic there to do things like strip out leading 1's (for long distance) or anything trailing an x or X (for extensions).</p>\n" }, { "answer_id": 262497, "author": "Jon Norton", "author_id": 4797, "author_profile": "https://Stackoverflow.com/users/4797", "pm_score": 2, "selected": false, "text": "<p>I'm sure there's a more efficient way to do it, but I would probably do this:</p>\n\n<pre><code>string getTenDigitNumber(string input)\n{ \n StringBuilder sb = new StringBuilder();\n for(int i - 0; i &lt; input.Length; i++)\n {\n int junk;\n if(int.TryParse(input[i], ref junk))\n sb.Append(input[i]);\n }\n return sb.ToString();\n}\n</code></pre>\n" }, { "answer_id": 262503, "author": "Christian C. Salvadó", "author_id": 5445, "author_profile": "https://Stackoverflow.com/users/5445", "pm_score": 6, "selected": false, "text": "<p>You can do it easily with regex:</p>\n\n<pre><code>string subject = \"(913)-444-5555\";\nstring result = Regex.Replace(subject, \"[^0-9]\", \"\"); // result = \"9134445555\"\n</code></pre>\n" }, { "answer_id": 262533, "author": "Wes Mason", "author_id": 2228202, "author_profile": "https://Stackoverflow.com/users/2228202", "pm_score": 3, "selected": false, "text": "<p>Using the Regex methods in .NET you should be able to match any non-numeric digit using \\D, like so:</p>\n<pre><code>phoneNumber = Regex.Replace(phoneNumber, &quot;\\\\D&quot;, String.Empty);\n</code></pre>\n" }, { "answer_id": 262904, "author": "Charles Bretana", "author_id": 32632, "author_profile": "https://Stackoverflow.com/users/32632", "pm_score": -1, "selected": false, "text": "<p>try this</p>\n\n<pre><code>public static string cleanPhone(string inVal)\n {\n char[] newPhon = new char[inVal.Length];\n int i = 0;\n foreach (char c in inVal)\n if (c.CompareTo('0') &gt; 0 &amp;&amp; c.CompareTo('9') &lt; 0)\n newPhon[i++] = c;\n return newPhon.ToString();\n }\n</code></pre>\n" }, { "answer_id": 7853482, "author": "Aaron", "author_id": 107851, "author_profile": "https://Stackoverflow.com/users/107851", "pm_score": 5, "selected": false, "text": "<p>Here's the extension method way of doing it.</p>\n\n<pre><code>public static class Extensions\n{\n public static string ToDigitsOnly(this string input)\n {\n Regex digitsOnly = new Regex(@\"[^\\d]\");\n return digitsOnly.Replace(input, \"\");\n }\n}\n</code></pre>\n" }, { "answer_id": 21013136, "author": "Usman Zafar", "author_id": 1069757, "author_profile": "https://Stackoverflow.com/users/1069757", "pm_score": 6, "selected": false, "text": "<p>You don't need to use Regex.</p>\n\n<pre><code>phone = new String(phone.Where(c =&gt; char.IsDigit(c)).ToArray())\n</code></pre>\n" }, { "answer_id": 25657036, "author": "Michael Lang", "author_id": 1262398, "author_profile": "https://Stackoverflow.com/users/1262398", "pm_score": 3, "selected": false, "text": "<p>How about an extension method that doesn't use regex.</p>\n\n<p>If you do stick to one of the Regex options at least use <code>RegexOptions.Compiled</code> in the static variable.</p>\n\n<pre><code>public static string ToDigitsOnly(this string input)\n{\n return new String(input.Where(char.IsDigit).ToArray());\n}\n</code></pre>\n\n<p>This builds on Usman Zafar's answer converted to a method group.</p>\n" }, { "answer_id": 34884839, "author": "Max-PC", "author_id": 5774944, "author_profile": "https://Stackoverflow.com/users/5774944", "pm_score": 2, "selected": false, "text": "<p>for the best performance and lower memory consumption , try this:</p>\n\n<pre><code>using System;\nusing System.Diagnostics;\nusing System.Text;\nusing System.Text.RegularExpressions;\n\npublic class Program\n{\n private static Regex digitsOnly = new Regex(@\"[^\\d]\");\n\n public static void Main()\n {\n Console.WriteLine(\"Init...\");\n\n string phone = \"001-12-34-56-78-90\";\n\n var sw = new Stopwatch();\n sw.Start();\n for (int i = 0; i &lt; 1000000; i++)\n {\n DigitsOnly(phone);\n }\n sw.Stop();\n Console.WriteLine(\"Time: \" + sw.ElapsedMilliseconds);\n\n var sw2 = new Stopwatch();\n sw2.Start();\n for (int i = 0; i &lt; 1000000; i++)\n {\n DigitsOnlyRegex(phone);\n }\n sw2.Stop();\n Console.WriteLine(\"Time: \" + sw2.ElapsedMilliseconds);\n\n Console.ReadLine();\n }\n\n public static string DigitsOnly(string phone, string replace = null)\n {\n if (replace == null) replace = \"\";\n if (phone == null) return null;\n var result = new StringBuilder(phone.Length);\n foreach (char c in phone)\n if (c &gt;= '0' &amp;&amp; c &lt;= '9')\n result.Append(c);\n else\n {\n result.Append(replace);\n }\n return result.ToString();\n }\n\n public static string DigitsOnlyRegex(string phone)\n {\n return digitsOnly.Replace(phone, \"\");\n }\n}\n</code></pre>\n\n<p>The result in my computer is:<BR/>\nInit...<BR/>\nTime: 307<BR/>\nTime: 2178<BR/></p>\n" } ]
2008/11/04
[ "https://Stackoverflow.com/questions/262448", "https://Stackoverflow.com", "https://Stackoverflow.com/users/232/" ]
Quick add on requirement in our project. A field in our DB to hold a phone number is set to only allow 10 characters. So, if I get passed "(913)-444-5555" or anything else, is there a quick way to run a string through some kind of special replace function that I can pass it a set of characters to allow? Regex?
Definitely regex: ``` string CleanPhone(string phone) { Regex digitsOnly = new Regex(@"[^\d]"); return digitsOnly.Replace(phone, ""); } ``` or within a class to avoid re-creating the regex all the time: ``` private static Regex digitsOnly = new Regex(@"[^\d]"); public static string CleanPhone(string phone) { return digitsOnly.Replace(phone, ""); } ``` Depending on your real-world inputs, you may want some additional logic there to do things like strip out leading 1's (for long distance) or anything trailing an x or X (for extensions).
262,450
<p>Why is using '*' to build a view bad ?</p> <p>Suppose that you have a complex join and all fields may be used somewhere.</p> <p>Then you just have to chose fields needed.</p> <pre><code>SELECT field1, field2 FROM aview WHERE ... </code></pre> <p>The view "aview" could be <code>SELECT table1.*, table2.* ... FROM table1 INNER JOIN table2 ...</code></p> <p>We have a problem if 2 fields have the same name in table1 and table2.</p> <p>Is this only the reason why using '*' in a view is bad?</p> <p>With '*', you may use the view in a different context because the information is there.</p> <p>What am I missing ?</p> <p>Regards</p>
[ { "answer_id": 262472, "author": "Rich Bradshaw", "author_id": 16511, "author_profile": "https://Stackoverflow.com/users/16511", "pm_score": 2, "selected": false, "text": "<p>It's because you don't always need every variable, and also to make sure that you are thinking about what you specifically need.</p>\n\n<p>There's no point getting all the hashed passwords out of the database when building a list of users on your site for instance, so a select * would be unproductive.</p>\n" }, { "answer_id": 262482, "author": "Martin", "author_id": 1529, "author_profile": "https://Stackoverflow.com/users/1529", "pm_score": 6, "selected": true, "text": "<p>I don't think there's much in software that is \"just bad\", but there's plenty of stuff that is misused in bad ways :-)</p>\n\n<p>The example you give is a reason why * might not give you what you expect, and I think there are others. For example, if the underlying tables change, maybe columns are added or removed, a view that uses * will continue to be valid, but might break any applications that use it. If your view had named the columns explicitly then there was more chance that someone would spot the problem when making the schema change.</p>\n\n<p><strike>On the other hand, you might actually <em>want</em> your view to blithely\naccept all changes to the underlying tables, in which case a * would\nbe just what you want.</strike></p>\n\n<p><em>Update:</em> I don't know if the OP had a specific database vendor in mind, but it is now clear that my last remark does not hold true for all types. I am indebted to user12861 and Jonny Leeds for pointing this out, and sorry it's taken over 6 years for me to edit my answer.</p>\n" }, { "answer_id": 262484, "author": "Amy B", "author_id": 8155, "author_profile": "https://Stackoverflow.com/users/8155", "pm_score": 2, "selected": false, "text": "<p>Once upon a time, I created a view against a table in another database (on the same server) with</p>\n\n<pre><code>Select * From dbname..tablename\n</code></pre>\n\n<p>Then one day, a column was added to the targetted table. The view started returning totally incorrect results until it was redeployed.</p>\n\n<hr>\n\n<p>Totally incorrect : no rows.</p>\n\n<p>This was on Sql Server 2000.</p>\n\n<p>I speculate that this is because of syscolumns values that the view had captured, even though I used *.</p>\n" }, { "answer_id": 262488, "author": "Dave", "author_id": 21294, "author_profile": "https://Stackoverflow.com/users/21294", "pm_score": 4, "selected": false, "text": "<p>Using '*' for anything production is bad. It's great for one-off queries, but in production code you should always be as explicit as possible.</p>\n\n<p>For views in particular, if the underlying tables have columns added or removed, the view will either be wrong or broken until it is recompiled.</p>\n" }, { "answer_id": 262509, "author": "Bill Karwin", "author_id": 20860, "author_profile": "https://Stackoverflow.com/users/20860", "pm_score": 4, "selected": false, "text": "<p>Another reason why \"<code>*</code>\" is risky, not only in views but in queries, is that columns can change name or change position in the underlying tables. Using a wildcard means that your view accommodates such changes easily without needing to be changed. But if your application references columns by position in the result set, or if you use a dynamic language that returns result sets keyed by column name, you could experience problems that are hard to debug.</p>\n\n<p>I avoid using the wildcard at all times. That way if a column changes name, I get an error in the view or query immediately, and I know where to fix it. If a column changes position in the underlying table, specifying the order of the columns in the view or query compensates for this.</p>\n" }, { "answer_id": 262523, "author": "Anne Porosoff", "author_id": 28701, "author_profile": "https://Stackoverflow.com/users/28701", "pm_score": 4, "selected": false, "text": "<p>Although many of the comments here are very good and reference one common problem of using wildcards in queries, such as causing errors or different results if the underlying tables change, another issue that hasn't been covered is optimization. A query that pulls every column of a table tends to not be quite as efficient as a query that pulls only those columns you actually need. Granted, there are those times when you need every column and it's a major PIA having to reference them all, especially in a large table, but if you only need a subset, why bog down your query with more columns than you need.</p>\n" }, { "answer_id": 262575, "author": "bruno conde", "author_id": 31136, "author_profile": "https://Stackoverflow.com/users/31136", "pm_score": 2, "selected": false, "text": "<p>It's generally a bad idea to use *. Some code certification engines mark this as a warning and advise you to explicitly refer only the necessary columns. The use of * can lead to performance louses as you might only need some columns and not all. But, on the other hand, there are some cases where the use of * is ideal. Imagine that, no matter what, using the example you provided, for this view (aview) you would always need all the columns in these tables. In the future, when a column is added, you wouldn't need to alter the view. This can be good or bad depending the case you are dealing with. </p>\n" }, { "answer_id": 262656, "author": "Cade Roux", "author_id": 18255, "author_profile": "https://Stackoverflow.com/users/18255", "pm_score": 2, "selected": false, "text": "<p>Using <code>SELECT *</code> within the view does not incur much of a performance overhead if columns aren't used outside the view - the optimizer will optimize them out; <code>SELECT * FROM TheView</code> can perhaps waste bandwidth, just like any time you pull more columns across a network connection.</p>\n\n<p>In fact, I have found that views which link almost all the columns from a number of huge tables in my datawarehouse have not introduced any performance issues at all, even through relatively few of those columns are requested from outside the view. The optimizer handles that well and is able to push the external filter criteria down into the view very well.</p>\n\n<p>However, for all the reasons given above, I very rarely use <code>SELECT *</code>.</p>\n\n<p>I have some business processes where a number of CTEs are built on top of each other, effectively building derived columns from derived columns from derived columns (which will hopefully one day being refactored as the business rationalizes and simplifies these calculations), and in that case, I need all the columns to drop through each time, and I use <code>SELECT *</code> - but <code>SELECT *</code> is not used at the base layer, only in between the first CTE and the last.</p>\n" }, { "answer_id": 262861, "author": "Brian C. Lane", "author_id": 27461, "author_profile": "https://Stackoverflow.com/users/27461", "pm_score": 2, "selected": false, "text": "<p>I think it depends on the language you are using. I prefer to use select * when the language or DB driver returns a dict(Python, Perl, etc.) or associative array(PHP) of the results. It makes your code alot easier to understand if you are referring to the columns by name instead of as an index in an array.</p>\n" }, { "answer_id": 263320, "author": "user12861", "author_id": 12861, "author_profile": "https://Stackoverflow.com/users/12861", "pm_score": 4, "selected": false, "text": "<p>These other answers all have good points, but on SQL server at least they also have some wrong points. Try this:</p>\n\n<pre><code>create table temp (i int, j int)\ngo\ncreate view vtemp as select * from temp\ngo\ninsert temp select 1, 1\ngo\nalter table temp add k int\ngo\ninsert temp select 1, 1, 1\ngo\nselect * from vtemp\n</code></pre>\n\n<p>SQL Server doesn't learn about the \"new\" column when it is added. Depending on what you want this could be a good thing or a bad thing, but either way it's probably not good to depend on it. So avoiding it just seems like a good idea.</p>\n\n<p>To me this weird behavior is the most compelling reason to avoid select * in views.</p>\n\n<p>The comments have taught me that MySQL has similar behavior and Oracle does not (it will learn about changes to the table). This inconsistency to me is all the more reason not to use select * in views.</p>\n" }, { "answer_id": 267173, "author": "Russ Cam", "author_id": 1831, "author_profile": "https://Stackoverflow.com/users/1831", "pm_score": 2, "selected": false, "text": "<p>No one else seems to have mentioned it, but within SQL Server you can also set up your view with the <a href=\"http://msdn.microsoft.com/en-us/library/ms173846.aspx\" rel=\"nofollow noreferrer\">schemabinding</a> attribute. </p>\n\n<p>This prevents modifications to any of the base tables (including dropping them) that would affect the view definition. </p>\n\n<p>This may be useful to you for some situations. I realise that I haven't exactly answered your question, but thought I would highlight it nonetheless.</p>\n" }, { "answer_id": 267575, "author": "dkretz", "author_id": 31641, "author_profile": "https://Stackoverflow.com/users/31641", "pm_score": 2, "selected": false, "text": "<p>A SQL query is basically a functional unit designed by a programmer for use in some context. For long-term stability and supportability (possibly by someone other than you) everything in a functional unit should be there for a purpose, and it should be reasonably evident (or documented) why it's there - especially every element of data.</p>\n\n<p>If I were to come along two years from now with the need or desire to alter your query, I would expect to grok it pretty thoroughly before I would be confident that I could mess with it. Which means I would need to understand why all the columns are called out. (This is even more obviously true if you are trying to reuse the query in more than one context. Which is problematic in general, for similar reasons.) If I were to see columns in the output that I couldn't relate to some purpose, I'd be pretty sure that I didn't understand what it did, and why, and what the consequences would be of changing it.</p>\n" }, { "answer_id": 4378482, "author": "HLGEM", "author_id": 9034, "author_profile": "https://Stackoverflow.com/users/9034", "pm_score": 1, "selected": false, "text": "<p>And if you have joins using select * automatically means you are returning more data than you need as the data in the join fields is repeated. This is wasteful of database and network resources. </p>\n\n<p>If you are naive enough to use views that call other views, using select * can make them even worse performers (This is technique that is bad for performance on its own, calling mulitple columns you don't need makes it much worse).</p>\n" }, { "answer_id": 33177643, "author": "AHiggins", "author_id": 1225845, "author_profile": "https://Stackoverflow.com/users/1225845", "pm_score": 2, "selected": false, "text": "<p>The situation on SQL Server is actually even worse than the answer by @user12861 implies: if you use <code>SELECT *</code> against multiple tables, adding columns to a table referenced early in the query will actually cause your view to return the values of the new columns under the guise of the old columns. See the example below:</p>\n\n<pre><code>-- create two tables\nCREATE TABLE temp1 (ColumnA INT, ColumnB DATE, ColumnC DECIMAL(2,1))\nCREATE TABLE temp2 (ColumnX INT, ColumnY DATE, ColumnZ DECIMAL(2,1))\nGO\n\n\n-- populate with dummy data\nINSERT INTO temp1 (ColumnA, ColumnB, ColumnC) VALUES (1, '1/1/1900', 0.5)\nINSERT INTO temp2 (ColumnX, ColumnY, ColumnZ) VALUES (1, '1/1/1900', 0.5)\nGO\n\n\n-- create a view with a pair of SELECT * statements\nCREATE VIEW vwtemp AS \nSELECT *\nFROM temp1 INNER JOIN temp2 ON 1=1\nGO\n\n\n-- SELECT showing the columns properly assigned\nSELECT * FROM vwTemp \nGO\n\n\n-- add a few columns to the first table referenced in the SELECT \nALTER TABLE temp1 ADD ColumnD varchar(1)\nALTER TABLE temp1 ADD ColumnE varchar(1)\nALTER TABLE temp1 ADD ColumnF varchar(1)\nGO\n\n\n-- populate those columns with dummy data\nUPDATE temp1 SET ColumnD = 'D', ColumnE = 'E', ColumnF = 'F'\nGO\n\n\n-- notice that the original columns have the wrong data in them now, causing any datatype-specific queries (e.g., arithmetic, dateadd, etc.) to fail\nSELECT *\nFROM vwtemp\nGO\n\n-- clean up\nDROP VIEW vwTemp\nDROP TABLE temp2\nDROP TABLE temp1\n</code></pre>\n" } ]
2008/11/04
[ "https://Stackoverflow.com/questions/262450", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14673/" ]
Why is using '\*' to build a view bad ? Suppose that you have a complex join and all fields may be used somewhere. Then you just have to chose fields needed. ``` SELECT field1, field2 FROM aview WHERE ... ``` The view "aview" could be `SELECT table1.*, table2.* ... FROM table1 INNER JOIN table2 ...` We have a problem if 2 fields have the same name in table1 and table2. Is this only the reason why using '\*' in a view is bad? With '\*', you may use the view in a different context because the information is there. What am I missing ? Regards
I don't think there's much in software that is "just bad", but there's plenty of stuff that is misused in bad ways :-) The example you give is a reason why \* might not give you what you expect, and I think there are others. For example, if the underlying tables change, maybe columns are added or removed, a view that uses \* will continue to be valid, but might break any applications that use it. If your view had named the columns explicitly then there was more chance that someone would spot the problem when making the schema change. On the other hand, you might actually *want* your view to blithely accept all changes to the underlying tables, in which case a \* would be just what you want. *Update:* I don't know if the OP had a specific database vendor in mind, but it is now clear that my last remark does not hold true for all types. I am indebted to user12861 and Jonny Leeds for pointing this out, and sorry it's taken over 6 years for me to edit my answer.
262,451
<p>ShellExecute() allows me to perform simple shell tasks, allowing the system to take care of opening or printing files. I want to take a similar approach to sending an email attachment programmatically.</p> <p>I don't want to manipulate Outlook directly, since I don't want to assume which email client the user uses by default. I don't want to send the email directly, as I want the user to have the opportunity to write the email body using their preferred client. Thus, I really want to accomplish exactly what Windows Explorer does when I right click a file and select Send To -> Mail Recipient.</p> <p>I'm looking for a C++ solution.</p>
[ { "answer_id": 262529, "author": "TcKs", "author_id": 20382, "author_profile": "https://Stackoverflow.com/users/20382", "pm_score": 2, "selected": false, "text": "<p>You can use a standard \"mailto:\" command in windows shell. It will run the default mail client.</p>\n" }, { "answer_id": 262540, "author": "Eclipse", "author_id": 8701, "author_profile": "https://Stackoverflow.com/users/8701", "pm_score": 0, "selected": false, "text": "<p>You'll need to implement a <a href=\"http://msdn.microsoft.com/en-us/library/ms527046.aspx\" rel=\"nofollow noreferrer\">MAPI client.</a> This will let you prefill the document, add attachments, etc.. before presenting the message to the user to send off. You can use the default message store to use their default mail client.</p>\n" }, { "answer_id": 264141, "author": "Craig Lebakken", "author_id": 33130, "author_profile": "https://Stackoverflow.com/users/33130", "pm_score": 1, "selected": false, "text": "<p>The following C++ example shows how to invoke the SendTo mail shortcut used by Windows Explorer:</p>\n\n<p><a href=\"http://www.codeproject.com/KB/shell/sendtomail.aspx\" rel=\"nofollow noreferrer\">http://www.codeproject.com/KB/shell/sendtomail.aspx</a></p>\n" }, { "answer_id": 264725, "author": "Jeff Hillman", "author_id": 3950, "author_profile": "https://Stackoverflow.com/users/3950", "pm_score": 4, "selected": true, "text": "<p>This is my MAPI solution:</p>\n\n<pre><code>#include &lt;tchar.h&gt;\n#include &lt;windows.h&gt;\n#include &lt;mapi.h&gt;\n#include &lt;mapix.h&gt;\n\nint _tmain( int argc, wchar_t *argv[] )\n{\n HMODULE hMapiModule = LoadLibrary( _T( \"mapi32.dll\" ) );\n\n if ( hMapiModule != NULL )\n {\n LPMAPIINITIALIZE lpfnMAPIInitialize = NULL;\n LPMAPIUNINITIALIZE lpfnMAPIUninitialize = NULL;\n LPMAPILOGONEX lpfnMAPILogonEx = NULL;\n LPMAPISENDDOCUMENTS lpfnMAPISendDocuments = NULL;\n LPMAPISESSION lplhSession = NULL;\n\n lpfnMAPIInitialize = (LPMAPIINITIALIZE)GetProcAddress( hMapiModule, \"MAPIInitialize\" );\n lpfnMAPIUninitialize = (LPMAPIUNINITIALIZE)GetProcAddress( hMapiModule, \"MAPIUninitialize\" );\n lpfnMAPILogonEx = (LPMAPILOGONEX)GetProcAddress( hMapiModule, \"MAPILogonEx\" );\n lpfnMAPISendDocuments = (LPMAPISENDDOCUMENTS)GetProcAddress( hMapiModule, \"MAPISendDocuments\" );\n\n if ( lpfnMAPIInitialize &amp;&amp; lpfnMAPIUninitialize &amp;&amp; lpfnMAPILogonEx &amp;&amp; lpfnMAPISendDocuments )\n {\n HRESULT hr = (*lpfnMAPIInitialize)( NULL );\n\n if ( SUCCEEDED( hr ) )\n {\n hr = (*lpfnMAPILogonEx)( 0, NULL, NULL, MAPI_EXTENDED | MAPI_USE_DEFAULT, &amp;lplhSession );\n\n if ( SUCCEEDED( hr ) )\n {\n // this opens the email client with \"C:\\attachment.txt\" as an attachment\n hr = (*lpfnMAPISendDocuments)( 0, \";\", \"C:\\\\attachment.txt\", NULL, NULL );\n\n if ( SUCCEEDED( hr ) )\n {\n hr = lplhSession-&gt;Logoff( 0, 0, 0 );\n hr = lplhSession-&gt;Release();\n lplhSession = NULL;\n }\n }\n }\n\n (*lpfnMAPIUninitialize)();\n }\n\n FreeLibrary( hMapiModule );\n }\n\n return 0;\n}\n</code></pre>\n" } ]
2008/11/04
[ "https://Stackoverflow.com/questions/262451", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8424/" ]
ShellExecute() allows me to perform simple shell tasks, allowing the system to take care of opening or printing files. I want to take a similar approach to sending an email attachment programmatically. I don't want to manipulate Outlook directly, since I don't want to assume which email client the user uses by default. I don't want to send the email directly, as I want the user to have the opportunity to write the email body using their preferred client. Thus, I really want to accomplish exactly what Windows Explorer does when I right click a file and select Send To -> Mail Recipient. I'm looking for a C++ solution.
This is my MAPI solution: ``` #include <tchar.h> #include <windows.h> #include <mapi.h> #include <mapix.h> int _tmain( int argc, wchar_t *argv[] ) { HMODULE hMapiModule = LoadLibrary( _T( "mapi32.dll" ) ); if ( hMapiModule != NULL ) { LPMAPIINITIALIZE lpfnMAPIInitialize = NULL; LPMAPIUNINITIALIZE lpfnMAPIUninitialize = NULL; LPMAPILOGONEX lpfnMAPILogonEx = NULL; LPMAPISENDDOCUMENTS lpfnMAPISendDocuments = NULL; LPMAPISESSION lplhSession = NULL; lpfnMAPIInitialize = (LPMAPIINITIALIZE)GetProcAddress( hMapiModule, "MAPIInitialize" ); lpfnMAPIUninitialize = (LPMAPIUNINITIALIZE)GetProcAddress( hMapiModule, "MAPIUninitialize" ); lpfnMAPILogonEx = (LPMAPILOGONEX)GetProcAddress( hMapiModule, "MAPILogonEx" ); lpfnMAPISendDocuments = (LPMAPISENDDOCUMENTS)GetProcAddress( hMapiModule, "MAPISendDocuments" ); if ( lpfnMAPIInitialize && lpfnMAPIUninitialize && lpfnMAPILogonEx && lpfnMAPISendDocuments ) { HRESULT hr = (*lpfnMAPIInitialize)( NULL ); if ( SUCCEEDED( hr ) ) { hr = (*lpfnMAPILogonEx)( 0, NULL, NULL, MAPI_EXTENDED | MAPI_USE_DEFAULT, &lplhSession ); if ( SUCCEEDED( hr ) ) { // this opens the email client with "C:\attachment.txt" as an attachment hr = (*lpfnMAPISendDocuments)( 0, ";", "C:\\attachment.txt", NULL, NULL ); if ( SUCCEEDED( hr ) ) { hr = lplhSession->Logoff( 0, 0, 0 ); hr = lplhSession->Release(); lplhSession = NULL; } } } (*lpfnMAPIUninitialize)(); } FreeLibrary( hMapiModule ); } return 0; } ```
262,469
<p>How is it possible that .NET is finding the wrong 'MyType' in this scenario?</p> <p>I have a type A.B.C.D.MyType in a project that I'm working on, and I'm referencing a DLL that has a type A.B.MyType? I do not have any 'using A.B;' statements anywhere in my code, and I do have 'using A.B.C.D;'. When I compile, the compiler thinks any naked reference to 'MyType' means 'A.B.MyType'.</p> <p>I know I could just rename the class or use an alias, but I'm wondering how this is even possible.</p> <p>Any ideas?</p> <p>Thanks!</p>
[ { "answer_id": 262498, "author": "Martin", "author_id": 1529, "author_profile": "https://Stackoverflow.com/users/1529", "pm_score": 0, "selected": false, "text": "<p>Just a guess: in your project properties, is the \"default namespace\" set to A.B ?</p>\n" }, { "answer_id": 262532, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 3, "selected": false, "text": "<p>Is your code in namespace <code>A.B</code> or <code>A.B.C</code>? If so, that's probably the issue. Use a using directive like this:</p>\n\n<pre><code>using TheTypeIWant = A.B.C.D.MyType;\n</code></pre>\n\n<p>then just refer to <code>TheTypeIWant</code> in your code.</p>\n\n<p>EDIT: I've just tried the \"<code>using MyType=A.B.C.D.MyType</code>\" option, but that <em>doesn't</em> work. The above is fine though.</p>\n" }, { "answer_id": 262813, "author": "Pop Catalin", "author_id": 4685, "author_profile": "https://Stackoverflow.com/users/4685", "pm_score": 5, "selected": true, "text": "<p>Are you working in a namespace that is under A.B namespace? (for example A.B.X) if so the C# namespace resolutions (<a href=\"http://www.ecma-international.org/publications/files/ECMA-ST/Ecma-334.pdf\" rel=\"noreferrer\">ECMA-334 C# Language Specification : 10.8 10.8 Namespace and type names</a>) says:</p>\n\n<blockquote>\n <p>... for each namespace N, starting\n with the namespace in which the\n namespace-or-typename occurs,\n continuing with each enclosing\n namespace (if any), and ending with\n the global namespace, the following\n steps are evaluated until an entity is\n located...</p>\n</blockquote>\n\n<p>and then followed by: </p>\n\n<blockquote>\n <p>If K is zero and the namespace\n declaration contains an\n extern-alias-directive or\n using-aliasdirective that associates\n the name I with an imported namespace\n or type, then the\n namespace-or-type-name refers to that\n namespace or type</p>\n</blockquote>\n\n<p>This means that name resolution starts at the current namespace and searches all namespaces up to the root, and only after this hierarchical search ends, then the namespaces imported with the <code>using</code> clause are searched.</p>\n\n<p>The following example prints \"Ns1.Foo\"</p>\n\n<pre><code>using Ns1.Foo.Foo2;\n\nnamespace Ns1.Foo\n{\n class Foo\n {\n public void Print()\n {\n System.Console.WriteLine(\"Ns1.Foo\");\n }\n }\n}\n\nnamespace Ns1.Foo.Foo2\n{\n class Foo\n {\n public void Print()\n {\n System.Console.WriteLine(\"Ns1.Foo.Foo2\");\n }\n }\n}\n\nnamespace Ns1.Foo.Bar\n{\n class Bar\n {\n public void Print()\n {\n new Foo().Print();\n }\n\n static void Main()\n {\n new Bar().Print();\n }\n }\n}\n</code></pre>\n\n<p>Edit: Adding a using clause <strong>inside</strong> a namespace, will make so that the namespace is searched before the hierarchical search of current namespace is done is done. Change the example to:</p>\n\n<pre><code>namespace Ns1.Foo.Bar\n{\n using Ns1.Foo.Foo2;\n class Bar\n {\n public void Print()\n {\n new Foo().Print();\n }\n\n static void Main()\n {\n new Bar().Print();\n }\n }\n}\n</code></pre>\n\n<p>and <code>Ns1.Foo.Foo2</code> will be printed.</p>\n\n<p>Edit: changed example</p>\n" } ]
2008/11/04
[ "https://Stackoverflow.com/questions/262469", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7529/" ]
How is it possible that .NET is finding the wrong 'MyType' in this scenario? I have a type A.B.C.D.MyType in a project that I'm working on, and I'm referencing a DLL that has a type A.B.MyType? I do not have any 'using A.B;' statements anywhere in my code, and I do have 'using A.B.C.D;'. When I compile, the compiler thinks any naked reference to 'MyType' means 'A.B.MyType'. I know I could just rename the class or use an alias, but I'm wondering how this is even possible. Any ideas? Thanks!
Are you working in a namespace that is under A.B namespace? (for example A.B.X) if so the C# namespace resolutions ([ECMA-334 C# Language Specification : 10.8 10.8 Namespace and type names](http://www.ecma-international.org/publications/files/ECMA-ST/Ecma-334.pdf)) says: > > ... for each namespace N, starting > with the namespace in which the > namespace-or-typename occurs, > continuing with each enclosing > namespace (if any), and ending with > the global namespace, the following > steps are evaluated until an entity is > located... > > > and then followed by: > > If K is zero and the namespace > declaration contains an > extern-alias-directive or > using-aliasdirective that associates > the name I with an imported namespace > or type, then the > namespace-or-type-name refers to that > namespace or type > > > This means that name resolution starts at the current namespace and searches all namespaces up to the root, and only after this hierarchical search ends, then the namespaces imported with the `using` clause are searched. The following example prints "Ns1.Foo" ``` using Ns1.Foo.Foo2; namespace Ns1.Foo { class Foo { public void Print() { System.Console.WriteLine("Ns1.Foo"); } } } namespace Ns1.Foo.Foo2 { class Foo { public void Print() { System.Console.WriteLine("Ns1.Foo.Foo2"); } } } namespace Ns1.Foo.Bar { class Bar { public void Print() { new Foo().Print(); } static void Main() { new Bar().Print(); } } } ``` Edit: Adding a using clause **inside** a namespace, will make so that the namespace is searched before the hierarchical search of current namespace is done is done. Change the example to: ``` namespace Ns1.Foo.Bar { using Ns1.Foo.Foo2; class Bar { public void Print() { new Foo().Print(); } static void Main() { new Bar().Print(); } } } ``` and `Ns1.Foo.Foo2` will be printed. Edit: changed example
262,480
<p>what's the quickest way to extract a 5 digit number from a string in c#. </p> <p>I've got </p> <pre><code>string.Join(null, System.Text.RegularExpressions.Regex.Split(expression, "[^\\d]")); </code></pre> <p>Any others?</p>
[ { "answer_id": 262491, "author": "Tom Ritter", "author_id": 8435, "author_profile": "https://Stackoverflow.com/users/8435", "pm_score": 2, "selected": false, "text": "<p>Do you mean convert a string to a number? Or find the first 5 digit string and then make it a number? Either way, you'll probably be using <a href=\"http://msdn.microsoft.com/en-us/library/system.decimal.parse.aspx\" rel=\"nofollow noreferrer\">decimal.Parse</a> or int.Parse.</p>\n\n<p>I'm of the opinion that Regular Expressions are the wrong approach. A more efficient approach would simply to walk through the string looking for a digit, and then advancing 4 characters and seeing if they are all digits. If they are, you've got your substring. It's not as robust, no, but it doesn't have the overhead either.</p>\n" }, { "answer_id": 262501, "author": "tvanfosson", "author_id": 12950, "author_profile": "https://Stackoverflow.com/users/12950", "pm_score": 3, "selected": false, "text": "<p>Use a regular expression (\\d{5}) to find the occurrence(s) of the 5 digit number in the string and use int.Parse or decimal.Parse on the match(s).</p>\n\n<p>In the case where there is only one number in <code>text</code>.</p>\n\n<pre><code>int? value = null;\nstring pat = @\"\\d{5}\"\nRegex r = new Regex(pat);\nMatch m = r.Match(text);\nif (m.Success)\n{\n value = int.Parse(m.Value);\n}\n</code></pre>\n" }, { "answer_id": 262512, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 2, "selected": false, "text": "<p>Don't use a regular expression at all. It's way more powerful than you need - and that power is likely to hit performance.</p>\n\n<p>If you can give more details of what you need it to do, we can write the appropriate code... (Test cases would be ideal.)</p>\n" }, { "answer_id": 262513, "author": "Gavin Miller", "author_id": 33226, "author_profile": "https://Stackoverflow.com/users/33226", "pm_score": 1, "selected": false, "text": "<p>If the numbers exist with other characters regular expressions are a good solution. </p>\n\n<p>EG: ([0-9]{5})</p>\n\n<p>will match - asdfkki12345afdkjsdl, 12345adfaksk, or akdkfa12345</p>\n" }, { "answer_id": 262525, "author": "pero", "author_id": 21645, "author_profile": "https://Stackoverflow.com/users/21645", "pm_score": 0, "selected": false, "text": "<p>If you have a simple test case like \"12345\" or even \"12345abcd\" don't use regex at all. They are not known by they speed.</p>\n" }, { "answer_id": 262585, "author": "Keith", "author_id": 905, "author_profile": "https://Stackoverflow.com/users/905", "pm_score": 0, "selected": false, "text": "<p>For most strings a brute force method is going to be quicker than a RegEx.</p>\n\n<p>A fairly noddy example would be:</p>\n\n<pre><code>string strIWantNumFrom = \"qweqwe23qeeq3eqqew9qwer0q\";\n\nint num = int.Parse(\n string.Join( null, (\n from c in strIWantNumFrom.ToCharArray()\n where c == '1' || c == '2' || c == '3' || c == '4' || c == '5' ||\n c == '6' || c == '7' || c == '8' || c == '9' || c == '0'\n select c.ToString()\n ).ToArray() ) );\n</code></pre>\n\n<p>No doubt there are much quicker ways, and lots of optimisations that depend on the exact format of your string.</p>\n" }, { "answer_id": 262743, "author": "alexdej", "author_id": 34304, "author_profile": "https://Stackoverflow.com/users/34304", "pm_score": 4, "selected": true, "text": "<p>The regex approach is probably the quickest to implement but not the quickest to run. I compared a simple regex solution to the following manual search code and found that the manual search code is ~2x-2.5x faster for large input strings and up to 4x faster for small strings:</p>\n\n<pre><code>static string Search(string expression)\n{\n int run = 0;\n for (int i = 0; i &lt; expression.Length; i++)\n {\n char c = expression[i];\n if (Char.IsDigit(c))\n run++;\n else if (run == 5)\n return expression.Substring(i - run, run);\n else\n run = 0;\n }\n return null;\n}\nconst string pattern = @\"\\d{5}\";\nstatic string NotCached(string expression)\n{\n return Regex.Match(expression, pattern, RegexOptions.Compiled).Value;\n}\n\nstatic Regex regex = new Regex(pattern, RegexOptions.Compiled);\nstatic string Cached(string expression)\n{\n return regex.Match(expression).Value;\n}\n</code></pre>\n\n<p>Results for a ~50-char string with a 5-digit string in the middle, over 10^6 iterations, latency per call in microseconds (smaller number is faster):</p>\n\n<p>Simple search: 0.648396us</p>\n\n<p>Cached Regex: 2.1414645us</p>\n\n<p>Non-cached Regex: 3.070116us</p>\n\n<p>Results for a ~40K string with a 5-digit string in the middle over 10^4 iterations, latency per call in microseconds (smaller number is faster):</p>\n\n<p>Simple search: 423.801us</p>\n\n<p>Cached Regex: 1155.3948us</p>\n\n<p>Non-cached Regex: 1220.625us</p>\n\n<p>A little surprising: I would have expected Regex -- which is compiled to IL -- to be comparable to the manual search, at least for very large strings.</p>\n" }, { "answer_id": 262864, "author": "Charles Bretana", "author_id": 32632, "author_profile": "https://Stackoverflow.com/users/32632", "pm_score": 0, "selected": false, "text": "<p>This might be faster...</p>\n\n<pre><code>public static string DigitsOnly(string inVal)\n {\n char[] newPhon = new char[inVal.Length];\n int i = 0;\n foreach (char c in inVal)\n if (c.CompareTo('0') &gt; 0 &amp;&amp; c.CompareTo('9') &lt; 0)\n newPhon[i++] = c;\n return newPhon.ToString();\n }\n</code></pre>\n\n<p>if you want to limit it to at most five digits, then</p>\n\n<pre><code>public static string DigitsOnly(string inVal)\n {\n char[] newPhon = new char[inVal.Length];\n int i = 0;\n foreach (char c in inVal)\n if (c.CompareTo('0') &gt; 0 &amp;&amp; c.CompareTo('9') &lt; 0 &amp;&amp; i &lt; 5)\n newPhon[i++] = c;\n return newPhon.ToString();\n }\n</code></pre>\n" } ]
2008/11/04
[ "https://Stackoverflow.com/questions/262480", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9948/" ]
what's the quickest way to extract a 5 digit number from a string in c#. I've got ``` string.Join(null, System.Text.RegularExpressions.Regex.Split(expression, "[^\\d]")); ``` Any others?
The regex approach is probably the quickest to implement but not the quickest to run. I compared a simple regex solution to the following manual search code and found that the manual search code is ~2x-2.5x faster for large input strings and up to 4x faster for small strings: ``` static string Search(string expression) { int run = 0; for (int i = 0; i < expression.Length; i++) { char c = expression[i]; if (Char.IsDigit(c)) run++; else if (run == 5) return expression.Substring(i - run, run); else run = 0; } return null; } const string pattern = @"\d{5}"; static string NotCached(string expression) { return Regex.Match(expression, pattern, RegexOptions.Compiled).Value; } static Regex regex = new Regex(pattern, RegexOptions.Compiled); static string Cached(string expression) { return regex.Match(expression).Value; } ``` Results for a ~50-char string with a 5-digit string in the middle, over 10^6 iterations, latency per call in microseconds (smaller number is faster): Simple search: 0.648396us Cached Regex: 2.1414645us Non-cached Regex: 3.070116us Results for a ~40K string with a 5-digit string in the middle over 10^4 iterations, latency per call in microseconds (smaller number is faster): Simple search: 423.801us Cached Regex: 1155.3948us Non-cached Regex: 1220.625us A little surprising: I would have expected Regex -- which is compiled to IL -- to be comparable to the manual search, at least for very large strings.
262,493
<p>What would be the best way of inserting functionality into a binary application (3d party, closed source).</p> <p>The target application is on OSX and seems to have been compiled using gcc 3+. I can see the listing of functions implemented in the binary and have debugged and isolated one particular function which I would like to remotely call.</p> <p>Specifically, I would like to call this function - let's call it void <code>zoomByFactor(x,y)</code> - when I receive certain data from a complex HIDevice.</p> <p>I can easily modify or inject instructions into the binary file itself (ie. the patching does not need to occur only in RAM).</p> <p>What would you recommend as a way of "nicely" doing this?</p> <p><strong>Edit:</strong></p> <p>I do indeed need to entire application. So I can't ditch it and use a library. (For those who need an ethical explanation: this is a proprietary piece of CAD software whose company website hasn't been updated since 2006. I have paid for this product (quite a lot of money for what it is, really) and have project data which I can not easily migrate away from it. The product suits me just fine as it is, but I want to use a new HID which I recently got. I've examined the internals of the application, and I'm fairly confident that I can call the correct function with the relevant data and get it to work properly).</p> <p>Here's what I've done so far, and it is quite gheto.</p> <p>I've already modified parts of the application through this process:</p> <pre> xxd -g 0 binary > binary.hex cat binary.hex | awk 'substitute work' > modified.hex xxd -r modified.hex > newbinary chmod 777 newbinary </pre> <p>I'm doing this kind of jumping through hoops because the binary is almost 100 megs large.</p> <p>The jist of what I'm thinking is that I'd jmp somewhere in the main application loop, launch a thread, and return to the main function. </p> <p>Now, the questions are: where can I insert the new code? do I need to modify symbol tables? alternatively, how could I make a dylib load automatically so that the only "hacking" I need to do is inserting a call to a normally loaded dylib into the main function?</p>
[ { "answer_id": 262576, "author": "Mr Fooz", "author_id": 25050, "author_profile": "https://Stackoverflow.com/users/25050", "pm_score": 0, "selected": false, "text": "<p>Interesting problem. If I understand you correctly, you'd like to add the ability to remotely call functions in a running executable. </p>\n\n<p>If you don't really need the whole application, you might be able to strip out the main function and turn it into a library file that you can link against. It'll be up to you to figure out how to make sure all the required initialization occurs. </p>\n\n<p>Another approach could be to act like a virus. Inject a function that handles the remote calls, probably in another thread. You'll need to launch this thread by injecting some code into the main function, or wherever else is appropriate. Most likely you'll run into major issues with initialization, thread safety, and/or maintaining proper program state.</p>\n\n<p>The best option, if its available, is to get the vendor of your application to expose a plugin API that lets you do this cleanly and reliably in a supported manner.</p>\n\n<p>If you go with either hack-the-binary route, it'll be time consuming and brittle, but you'll learn a lot in the process.</p>\n" }, { "answer_id": 262633, "author": "DGentry", "author_id": 4761, "author_profile": "https://Stackoverflow.com/users/4761", "pm_score": 2, "selected": false, "text": "<p>In MacOS X releases prior to 10.5 you'd do this using an Input Manager extension. Input Manager was intended to handle things like input for non-roman languages, where the extension could popup a window to input the appropriate glyphs and then pass the completed text to the app. The application only needed to make sure it was Unicode-clean, and didn't have to worry about the exact details of every language and region.</p>\n\n<p>Input Manager was wildly abused to patch all sorts of unrelated functionality into applications, and often destabilized the app. It was also becoming an attack vector for trojans, such as \"Oompa-Loompa\". MacOS 10.5 tightens restrictions on Input Managers: it won't run them in a process owned by root or wheel, nor in a process which has modified its uid. Most significantly, 10.5 won't load an Input Manager into a 64 bit process and has indicated that even 32 bit use is unsupported and will be removed in a future release.</p>\n\n<p>So if you can live with the restrictions, an Input Manager can do what you want. Future MacOS releases will almost certainly introduce another (safer, more limited) way to do this, as the functionality really is needed for language input support.</p>\n" }, { "answer_id": 275216, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 4, "selected": false, "text": "<p>For those interested in what I've ended up doing, here's a summary:</p>\n\n<p>I've looked at several possibilities. They fall into runtime patching, and static binary file patching.</p>\n\n<p>As far as file patching is concerned, I essentially tried two approaches:</p>\n\n<ol>\n<li><p>modifying the assembly in the code\nsegments (__TEXT) of the binary.</p></li>\n<li><p>modifying the load commands in the\nmach header.</p></li>\n</ol>\n\n<p>The first method requires there to be free space, or methods you can overwrite. It also suffers from extremely poor maintainability. Any new binaries will require hand patching them once again, especially if their source code has even slightly changed.</p>\n\n<p>The second method was to try and add a LC_ LOAD_ DYLIB entry into the mach header. There aren't many mach-o editors out there, so it's hairy, but I actually modified the structures so that my entry was visible by <code>otool -l</code>. However, this didn't actually work as there was a <code>dyld: bad external relocation length</code> at runtime. I'm assuming I need to muck around with import tables etc. And this is way too much effort to get right without an editor.</p>\n\n<p>Second path was to inject code at runtime. There isn't much out there to do this. Even for apps you have control over (ie. a child application you launch). Maybe there's a way to <code>fork()</code> and get the initialization process launched, but I never go that.</p>\n\n<p>There is SIMBL, but this requires your app to be Cocoa because SIMBL will pose as a system wide InputManager and selectively load bundles. I dismissed this because my app was not Cocoa, and besides, I dislike system wide stuff.</p>\n\n<p>Next up was mach_ inject and the mach_star project. There is also a newer project called \nPlugSuit hosted at google which seems to be nothing more than a thin wrapper around mach_inject.</p>\n\n<p>Mach_inject provides an API to do what the name implies. I did find a problem in the code though. On 10.5.4, the mmap method in the mach_inject.c file requires there to be a MAP_ SHARED or'd with the MAP_READ or else the mmap will fail.</p>\n\n<p>Aside from that, the whole thing actually works as advertised. I ended up using mach_ inject_ bundle to do what I had intended to do with the static addition of a DYLIB to the mach header: namely launching a new thread on module init that does its dirty business.</p>\n\n<p>Anyways, I've made this a wiki. Feel free to add, correct or update information. There's practically no information available on this kind of work on OSX. The more info, the better.</p>\n" }, { "answer_id": 1551037, "author": "Vladimir Panteleev", "author_id": 21501, "author_profile": "https://Stackoverflow.com/users/21501", "pm_score": 0, "selected": false, "text": "<p>On Windows, this is simple to do, is actually very widely done and is known as DLL/code injection. </p>\n\n<p>There is a commercial SDK for OSX which allows doing this: <a href=\"http://unsanity.com/haxies/ape\" rel=\"nofollow noreferrer\">Application Enhancer</a> (free for non-commercial use).</p>\n" }, { "answer_id": 3743859, "author": "karlphillip", "author_id": 176769, "author_profile": "https://Stackoverflow.com/users/176769", "pm_score": 2, "selected": false, "text": "<p>I believe you could also use the <a href=\"http://tlrobinson.net/blog/2007/12/21/overriding-library-functions-in-mac-os-x-the-easy-way-dyld_insert_libraries/\" rel=\"nofollow noreferrer\">DYLD_INSERT_LIBRARIES method</a>.</p>\n\n<p><a href=\"https://stackoverflow.com/questions/3270281/can-gdb-make-a-function-pointer-point-to-another-location\">This post</a> is also related to what you were trying to do;</p>\n" }, { "answer_id": 23497928, "author": "jar", "author_id": 183677, "author_profile": "https://Stackoverflow.com/users/183677", "pm_score": 1, "selected": false, "text": "<p>I recently took a stab at injection/overriding using the <code>mach_star</code> sources. I ended up writing a tutorial for it since documentation for this stuff is always so sketchy and often out of date.</p>\n\n<p><a href=\"http://soundly.me/osx-injection-override-tutorial-hello-world/\" rel=\"nofollow\">http://soundly.me/osx-injection-override-tutorial-hello-world/</a></p>\n" } ]
2008/11/04
[ "https://Stackoverflow.com/questions/262493", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
What would be the best way of inserting functionality into a binary application (3d party, closed source). The target application is on OSX and seems to have been compiled using gcc 3+. I can see the listing of functions implemented in the binary and have debugged and isolated one particular function which I would like to remotely call. Specifically, I would like to call this function - let's call it void `zoomByFactor(x,y)` - when I receive certain data from a complex HIDevice. I can easily modify or inject instructions into the binary file itself (ie. the patching does not need to occur only in RAM). What would you recommend as a way of "nicely" doing this? **Edit:** I do indeed need to entire application. So I can't ditch it and use a library. (For those who need an ethical explanation: this is a proprietary piece of CAD software whose company website hasn't been updated since 2006. I have paid for this product (quite a lot of money for what it is, really) and have project data which I can not easily migrate away from it. The product suits me just fine as it is, but I want to use a new HID which I recently got. I've examined the internals of the application, and I'm fairly confident that I can call the correct function with the relevant data and get it to work properly). Here's what I've done so far, and it is quite gheto. I've already modified parts of the application through this process: ``` xxd -g 0 binary > binary.hex cat binary.hex | awk 'substitute work' > modified.hex xxd -r modified.hex > newbinary chmod 777 newbinary ``` I'm doing this kind of jumping through hoops because the binary is almost 100 megs large. The jist of what I'm thinking is that I'd jmp somewhere in the main application loop, launch a thread, and return to the main function. Now, the questions are: where can I insert the new code? do I need to modify symbol tables? alternatively, how could I make a dylib load automatically so that the only "hacking" I need to do is inserting a call to a normally loaded dylib into the main function?
For those interested in what I've ended up doing, here's a summary: I've looked at several possibilities. They fall into runtime patching, and static binary file patching. As far as file patching is concerned, I essentially tried two approaches: 1. modifying the assembly in the code segments (\_\_TEXT) of the binary. 2. modifying the load commands in the mach header. The first method requires there to be free space, or methods you can overwrite. It also suffers from extremely poor maintainability. Any new binaries will require hand patching them once again, especially if their source code has even slightly changed. The second method was to try and add a LC\_ LOAD\_ DYLIB entry into the mach header. There aren't many mach-o editors out there, so it's hairy, but I actually modified the structures so that my entry was visible by `otool -l`. However, this didn't actually work as there was a `dyld: bad external relocation length` at runtime. I'm assuming I need to muck around with import tables etc. And this is way too much effort to get right without an editor. Second path was to inject code at runtime. There isn't much out there to do this. Even for apps you have control over (ie. a child application you launch). Maybe there's a way to `fork()` and get the initialization process launched, but I never go that. There is SIMBL, but this requires your app to be Cocoa because SIMBL will pose as a system wide InputManager and selectively load bundles. I dismissed this because my app was not Cocoa, and besides, I dislike system wide stuff. Next up was mach\_ inject and the mach\_star project. There is also a newer project called PlugSuit hosted at google which seems to be nothing more than a thin wrapper around mach\_inject. Mach\_inject provides an API to do what the name implies. I did find a problem in the code though. On 10.5.4, the mmap method in the mach\_inject.c file requires there to be a MAP\_ SHARED or'd with the MAP\_READ or else the mmap will fail. Aside from that, the whole thing actually works as advertised. I ended up using mach\_ inject\_ bundle to do what I had intended to do with the static addition of a DYLIB to the mach header: namely launching a new thread on module init that does its dirty business. Anyways, I've made this a wiki. Feel free to add, correct or update information. There's practically no information available on this kind of work on OSX. The more info, the better.
262,508
<p>I am using some code which was originally taken from the Apple sample ViewTransitions to swap two views with each other.</p> <pre><code>CATransition *animation = [CATransition animation]; [animation setDelegate:self]; [animation setType:kCATransitionFade]; [animation setDuration:0.3f]; [animation setTimingFunction:[CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionLinear]]; [[container layer] addAnimation:animation forKey:@"swap"]; </code></pre> <p>When my transition executes on the devlice, I sometimes get a single frame flash of the final frame of the transition animation and then the animation plays smoothly. This gives a very jarring effect of the 2nd view which flickers in and then out again before the smooth animation executes.</p> <p>The main difference between my example and the Apple example is that my views are not full screen, I have a container UIView which contains both sub-views and I am applying my animation to the container layer instead the root view layer. I can not see that this should make much difference though.</p> <p>This issue does not happen at all in the simulator and is intermittent (about 60-70% of the time) on the device. Is anyone else seeing this behaviour and if so, how did you work around it?</p> <p><strong>Updated with more information:</strong> The code was originally part of a multi part animation but I moved it to be triggered by a button to isolate the problem. The issue occurs in both situations.</p> <p>The animation delegates were implemented but have been removed to try and isolate the problem.</p> <p>The views are not changing during the animation and in fact <code>[container setUserInteractionEnabled:NO]</code> is being called (but the problem also happens without user interaction being disabled).</p> <p>I have tried starting the animation from the middle of the transition and ending before the end using <code>setStartProgress</code> and <code>setEndProgress</code>, again the problem persists.</p> <p>I have tried slowing the animation duration right down as well with no effect.</p>
[ { "answer_id": 262576, "author": "Mr Fooz", "author_id": 25050, "author_profile": "https://Stackoverflow.com/users/25050", "pm_score": 0, "selected": false, "text": "<p>Interesting problem. If I understand you correctly, you'd like to add the ability to remotely call functions in a running executable. </p>\n\n<p>If you don't really need the whole application, you might be able to strip out the main function and turn it into a library file that you can link against. It'll be up to you to figure out how to make sure all the required initialization occurs. </p>\n\n<p>Another approach could be to act like a virus. Inject a function that handles the remote calls, probably in another thread. You'll need to launch this thread by injecting some code into the main function, or wherever else is appropriate. Most likely you'll run into major issues with initialization, thread safety, and/or maintaining proper program state.</p>\n\n<p>The best option, if its available, is to get the vendor of your application to expose a plugin API that lets you do this cleanly and reliably in a supported manner.</p>\n\n<p>If you go with either hack-the-binary route, it'll be time consuming and brittle, but you'll learn a lot in the process.</p>\n" }, { "answer_id": 262633, "author": "DGentry", "author_id": 4761, "author_profile": "https://Stackoverflow.com/users/4761", "pm_score": 2, "selected": false, "text": "<p>In MacOS X releases prior to 10.5 you'd do this using an Input Manager extension. Input Manager was intended to handle things like input for non-roman languages, where the extension could popup a window to input the appropriate glyphs and then pass the completed text to the app. The application only needed to make sure it was Unicode-clean, and didn't have to worry about the exact details of every language and region.</p>\n\n<p>Input Manager was wildly abused to patch all sorts of unrelated functionality into applications, and often destabilized the app. It was also becoming an attack vector for trojans, such as \"Oompa-Loompa\". MacOS 10.5 tightens restrictions on Input Managers: it won't run them in a process owned by root or wheel, nor in a process which has modified its uid. Most significantly, 10.5 won't load an Input Manager into a 64 bit process and has indicated that even 32 bit use is unsupported and will be removed in a future release.</p>\n\n<p>So if you can live with the restrictions, an Input Manager can do what you want. Future MacOS releases will almost certainly introduce another (safer, more limited) way to do this, as the functionality really is needed for language input support.</p>\n" }, { "answer_id": 275216, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 4, "selected": false, "text": "<p>For those interested in what I've ended up doing, here's a summary:</p>\n\n<p>I've looked at several possibilities. They fall into runtime patching, and static binary file patching.</p>\n\n<p>As far as file patching is concerned, I essentially tried two approaches:</p>\n\n<ol>\n<li><p>modifying the assembly in the code\nsegments (__TEXT) of the binary.</p></li>\n<li><p>modifying the load commands in the\nmach header.</p></li>\n</ol>\n\n<p>The first method requires there to be free space, or methods you can overwrite. It also suffers from extremely poor maintainability. Any new binaries will require hand patching them once again, especially if their source code has even slightly changed.</p>\n\n<p>The second method was to try and add a LC_ LOAD_ DYLIB entry into the mach header. There aren't many mach-o editors out there, so it's hairy, but I actually modified the structures so that my entry was visible by <code>otool -l</code>. However, this didn't actually work as there was a <code>dyld: bad external relocation length</code> at runtime. I'm assuming I need to muck around with import tables etc. And this is way too much effort to get right without an editor.</p>\n\n<p>Second path was to inject code at runtime. There isn't much out there to do this. Even for apps you have control over (ie. a child application you launch). Maybe there's a way to <code>fork()</code> and get the initialization process launched, but I never go that.</p>\n\n<p>There is SIMBL, but this requires your app to be Cocoa because SIMBL will pose as a system wide InputManager and selectively load bundles. I dismissed this because my app was not Cocoa, and besides, I dislike system wide stuff.</p>\n\n<p>Next up was mach_ inject and the mach_star project. There is also a newer project called \nPlugSuit hosted at google which seems to be nothing more than a thin wrapper around mach_inject.</p>\n\n<p>Mach_inject provides an API to do what the name implies. I did find a problem in the code though. On 10.5.4, the mmap method in the mach_inject.c file requires there to be a MAP_ SHARED or'd with the MAP_READ or else the mmap will fail.</p>\n\n<p>Aside from that, the whole thing actually works as advertised. I ended up using mach_ inject_ bundle to do what I had intended to do with the static addition of a DYLIB to the mach header: namely launching a new thread on module init that does its dirty business.</p>\n\n<p>Anyways, I've made this a wiki. Feel free to add, correct or update information. There's practically no information available on this kind of work on OSX. The more info, the better.</p>\n" }, { "answer_id": 1551037, "author": "Vladimir Panteleev", "author_id": 21501, "author_profile": "https://Stackoverflow.com/users/21501", "pm_score": 0, "selected": false, "text": "<p>On Windows, this is simple to do, is actually very widely done and is known as DLL/code injection. </p>\n\n<p>There is a commercial SDK for OSX which allows doing this: <a href=\"http://unsanity.com/haxies/ape\" rel=\"nofollow noreferrer\">Application Enhancer</a> (free for non-commercial use).</p>\n" }, { "answer_id": 3743859, "author": "karlphillip", "author_id": 176769, "author_profile": "https://Stackoverflow.com/users/176769", "pm_score": 2, "selected": false, "text": "<p>I believe you could also use the <a href=\"http://tlrobinson.net/blog/2007/12/21/overriding-library-functions-in-mac-os-x-the-easy-way-dyld_insert_libraries/\" rel=\"nofollow noreferrer\">DYLD_INSERT_LIBRARIES method</a>.</p>\n\n<p><a href=\"https://stackoverflow.com/questions/3270281/can-gdb-make-a-function-pointer-point-to-another-location\">This post</a> is also related to what you were trying to do;</p>\n" }, { "answer_id": 23497928, "author": "jar", "author_id": 183677, "author_profile": "https://Stackoverflow.com/users/183677", "pm_score": 1, "selected": false, "text": "<p>I recently took a stab at injection/overriding using the <code>mach_star</code> sources. I ended up writing a tutorial for it since documentation for this stuff is always so sketchy and often out of date.</p>\n\n<p><a href=\"http://soundly.me/osx-injection-override-tutorial-hello-world/\" rel=\"nofollow\">http://soundly.me/osx-injection-override-tutorial-hello-world/</a></p>\n" } ]
2008/11/04
[ "https://Stackoverflow.com/questions/262508", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4496/" ]
I am using some code which was originally taken from the Apple sample ViewTransitions to swap two views with each other. ``` CATransition *animation = [CATransition animation]; [animation setDelegate:self]; [animation setType:kCATransitionFade]; [animation setDuration:0.3f]; [animation setTimingFunction:[CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionLinear]]; [[container layer] addAnimation:animation forKey:@"swap"]; ``` When my transition executes on the devlice, I sometimes get a single frame flash of the final frame of the transition animation and then the animation plays smoothly. This gives a very jarring effect of the 2nd view which flickers in and then out again before the smooth animation executes. The main difference between my example and the Apple example is that my views are not full screen, I have a container UIView which contains both sub-views and I am applying my animation to the container layer instead the root view layer. I can not see that this should make much difference though. This issue does not happen at all in the simulator and is intermittent (about 60-70% of the time) on the device. Is anyone else seeing this behaviour and if so, how did you work around it? **Updated with more information:** The code was originally part of a multi part animation but I moved it to be triggered by a button to isolate the problem. The issue occurs in both situations. The animation delegates were implemented but have been removed to try and isolate the problem. The views are not changing during the animation and in fact `[container setUserInteractionEnabled:NO]` is being called (but the problem also happens without user interaction being disabled). I have tried starting the animation from the middle of the transition and ending before the end using `setStartProgress` and `setEndProgress`, again the problem persists. I have tried slowing the animation duration right down as well with no effect.
For those interested in what I've ended up doing, here's a summary: I've looked at several possibilities. They fall into runtime patching, and static binary file patching. As far as file patching is concerned, I essentially tried two approaches: 1. modifying the assembly in the code segments (\_\_TEXT) of the binary. 2. modifying the load commands in the mach header. The first method requires there to be free space, or methods you can overwrite. It also suffers from extremely poor maintainability. Any new binaries will require hand patching them once again, especially if their source code has even slightly changed. The second method was to try and add a LC\_ LOAD\_ DYLIB entry into the mach header. There aren't many mach-o editors out there, so it's hairy, but I actually modified the structures so that my entry was visible by `otool -l`. However, this didn't actually work as there was a `dyld: bad external relocation length` at runtime. I'm assuming I need to muck around with import tables etc. And this is way too much effort to get right without an editor. Second path was to inject code at runtime. There isn't much out there to do this. Even for apps you have control over (ie. a child application you launch). Maybe there's a way to `fork()` and get the initialization process launched, but I never go that. There is SIMBL, but this requires your app to be Cocoa because SIMBL will pose as a system wide InputManager and selectively load bundles. I dismissed this because my app was not Cocoa, and besides, I dislike system wide stuff. Next up was mach\_ inject and the mach\_star project. There is also a newer project called PlugSuit hosted at google which seems to be nothing more than a thin wrapper around mach\_inject. Mach\_inject provides an API to do what the name implies. I did find a problem in the code though. On 10.5.4, the mmap method in the mach\_inject.c file requires there to be a MAP\_ SHARED or'd with the MAP\_READ or else the mmap will fail. Aside from that, the whole thing actually works as advertised. I ended up using mach\_ inject\_ bundle to do what I had intended to do with the static addition of a DYLIB to the mach header: namely launching a new thread on module init that does its dirty business. Anyways, I've made this a wiki. Feel free to add, correct or update information. There's practically no information available on this kind of work on OSX. The more info, the better.
262,510
<p>Is there a way to search Microsoft Visual SourceSafe 6.0d for all files tagged with a specific label?</p>
[ { "answer_id": 272905, "author": "Axel", "author_id": 34778, "author_profile": "https://Stackoverflow.com/users/34778", "pm_score": 1, "selected": false, "text": "<p>I don't think you can search by label, but you can get by label.</p>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/kh8hd2cw(VS.80).aspx\" rel=\"nofollow noreferrer\">From MSDN:</a></p>\n\n<p>To get a version by label:</p>\n\n<ol>\n<li>Make sure that you have set a working folder in Visual SourceSafe Explorer. See How to: Set the Working Folder.</li>\n<li>Ensure that you have set the history options. See How to: View History.</li>\n<li>Select the project that contains the file to retrieve.</li>\n<li>On the Tools menu, click Show History.</li>\n<li>In the History Options dialog box, select the version of the file to retrieve and click OK.</li>\n<li>In the History of dialog box, click Get to retrieve the version of the file that you have chosen.</li>\n<li>In the Get dialog box, make any additional entries needed and click OK to retrieve the file.</li>\n</ol>\n" }, { "answer_id": 316751, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<p>It does seem to be a failure on Microsofts part not to put in a simple search feature on the comments of checkins/checkouts.</p>\n\n<p>I have found this\n<a href=\"http://www.codeproject.com/KB/cpp/Schiott_SourceReport.aspx\" rel=\"nofollow noreferrer\">http://www.codeproject.com/KB/cpp/Schiott_SourceReport.aspx</a></p>\n\n<p>It extracts all the comments you want to a text file. </p>\n" }, { "answer_id": 334423, "author": "AJ.", "author_id": 7211, "author_profile": "https://Stackoverflow.com/users/7211", "pm_score": 0, "selected": false, "text": "<p>You can get by label.<br>\nThis may not be the same as searching by label. </p>\n\n<p>Sourcesafe accepts a label as a valid version number, so it's the same syntax: </p>\n\n<pre><code>ss get -V\"my label\" $\\myproject -R \n</code></pre>\n\n<p>this will get everything labelled <code>my label</code> from the <code>myproject</code> project. </p>\n" }, { "answer_id": 714770, "author": "another average joe", "author_id": 52599, "author_profile": "https://Stackoverflow.com/users/52599", "pm_score": 3, "selected": true, "text": "<p>AJ had the right idea, but you just need to use the \"dir\" command instead of get:</p>\n\n<pre><code>ss dir -v\"LABEL\" $\\PROJECT -R\n</code></pre>\n\n<p>This will output each file with version that is at that label in the format of:</p>\n\n<pre><code>someFile.c;23\nsomeOtherFile.h;3\n&lt;filename&gt;;&lt;version&gt;\n</code></pre>\n\n<p>For those interested if you want to quickly tell what the latest version of a file is you can do:</p>\n\n<pre><code>ss dir -v. $\\PROJECT -R\n</code></pre>\n\n<p>Have a great time!</p>\n" } ]
2008/11/04
[ "https://Stackoverflow.com/questions/262510", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2831/" ]
Is there a way to search Microsoft Visual SourceSafe 6.0d for all files tagged with a specific label?
AJ had the right idea, but you just need to use the "dir" command instead of get: ``` ss dir -v"LABEL" $\PROJECT -R ``` This will output each file with version that is at that label in the format of: ``` someFile.c;23 someOtherFile.h;3 <filename>;<version> ``` For those interested if you want to quickly tell what the latest version of a file is you can do: ``` ss dir -v. $\PROJECT -R ``` Have a great time!
262,527
<p>I need to programmatically enable READ COMMITTED SNAPSHOT in SQL Server. How can I do that?</p>
[ { "answer_id": 262541, "author": "João Vieira", "author_id": 2267, "author_profile": "https://Stackoverflow.com/users/2267", "pm_score": 4, "selected": true, "text": "<pre><code>ALTER DATABASE [dbname] SET READ_COMMITTED_SNAPSHOT ON WITH ROLLBACK AFTER 20 SECONDS \n</code></pre>\n" }, { "answer_id": 2785127, "author": "Bill Paetzke", "author_id": 192210, "author_profile": "https://Stackoverflow.com/users/192210", "pm_score": 5, "selected": false, "text": "<p>I recommend switching to <code>single-user</code> mode first. That ensures you're the only connection. Otherwise, the query might be suspended.</p>\n\n<p>From: <a href=\"http://msdn.microsoft.com/en-us/library/ms175095.aspx\" rel=\"noreferrer\">http://msdn.microsoft.com/en-us/library/ms175095.aspx</a></p>\n\n<blockquote>\n <p>When setting the\n READ_COMMITTED_SNAPSHOT option, only\n the connection executing the ALTER\n DATABASE command is allowed in the\n database. There must be no other open\n connection in the database until ALTER\n DATABASE is complete.</p>\n</blockquote>\n\n<p>So, use this SQL:</p>\n\n<pre><code>ALTER DATABASE &lt;dbname&gt; SET SINGLE_USER WITH ROLLBACK IMMEDIATE;\nALTER DATABASE &lt;dbname&gt; SET READ_COMMITTED_SNAPSHOT ON;\nALTER DATABASE &lt;dbname&gt; SET MULTI_USER;\n</code></pre>\n" } ]
2008/11/04
[ "https://Stackoverflow.com/questions/262527", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2267/" ]
I need to programmatically enable READ COMMITTED SNAPSHOT in SQL Server. How can I do that?
``` ALTER DATABASE [dbname] SET READ_COMMITTED_SNAPSHOT ON WITH ROLLBACK AFTER 20 SECONDS ```
262,534
<p>I want to use the same functionality available when a Panel.AutoScroll is true, but with the scrollbars invisible.</p> <p>To do so I need to know how can I scroll to left/right up/down using functions in my code.</p>
[ { "answer_id": 263590, "author": "bobwienholt", "author_id": 24257, "author_profile": "https://Stackoverflow.com/users/24257", "pm_score": 4, "selected": false, "text": "<p>You should be able to use the VerticalScroll and HorizontalScroll properties of the component:</p>\n\n<pre><code>c.HorizontalScroll.Value += 100;\nc.VerticalScroll.Value = c.VerticalScroll.Maximum;\n</code></pre>\n" }, { "answer_id": 419865, "author": "sindre j", "author_id": 37119, "author_profile": "https://Stackoverflow.com/users/37119", "pm_score": -1, "selected": false, "text": "<p>There's probably a property on the panel to do this, alternatively you can loop through all the panels children and adjust their positions.</p>\n\n<p>Eg. to move all controls 10 px:</p>\n\n<pre><code>int xoffset = 10;\n\nforeach(Control c in panel1.Controls)\n c.Location.X += xoffset;\n</code></pre>\n\n<p>The controls can be moved to negative positions to make them move out of the panel, similarly they can have location values bigger than the panels size to make them move out of the panel.</p>\n" }, { "answer_id": 419953, "author": "Cyril Gupta", "author_id": 33052, "author_profile": "https://Stackoverflow.com/users/33052", "pm_score": 3, "selected": false, "text": "<p>Well if you don't want to use the Autoscroll property, there's a way that I used a long time ago.</p>\n\n<ul>\n<li>Put a panel inside the panel. Put the scrollbar control on the parent panel, and then use the scrollbar to change the Top property of the panel inside.</li>\n</ul>\n\n<p>It's simple and works beautifully.</p>\n" } ]
2008/11/04
[ "https://Stackoverflow.com/questions/262534", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10833/" ]
I want to use the same functionality available when a Panel.AutoScroll is true, but with the scrollbars invisible. To do so I need to know how can I scroll to left/right up/down using functions in my code.
You should be able to use the VerticalScroll and HorizontalScroll properties of the component: ``` c.HorizontalScroll.Value += 100; c.VerticalScroll.Value = c.VerticalScroll.Maximum; ```
262,535
<p>In C# some of default name space such as System.Collections are listed without typing in using blah. In visual basic, they are not imports for you. Is there a way to force vb to auto imports some of default name space or VB work differently than C#?</p>
[ { "answer_id": 262544, "author": "John Rudy", "author_id": 14048, "author_profile": "https://Stackoverflow.com/users/14048", "pm_score": 2, "selected": false, "text": "<p>I'm not sure what you're asking. I can see potentially two questions there:</p>\n\n<ol>\n<li>Can you change the VB auto-imports?</li>\n<li>Can you get auto-import behavior in C#?</li>\n</ol>\n\n<p>For #1, yes you can. Assuming Visual Studio 2005 or higher, go into your project properties, and select the References tab. The auto-imports are listed under \"Imported Namespaces\" at the bottom of the view.</p>\n\n<p>For #2, not that I'm aware of. I've never seen that behavior in Visual C#.</p>\n" }, { "answer_id": 262570, "author": "Joel Coehoorn", "author_id": 3043, "author_profile": "https://Stackoverflow.com/users/3043", "pm_score": 3, "selected": true, "text": "<p>I think the first item posted by John Rudy is what you're looking for- add them in the project properties.</p>\n\n<p>However, VB.Net does also work differently than C#, in that it means a different thing in VB to import a namespace than it does in C#. When you import a namespace in VB, it also brings child namespaces 'in scope', in a manner of speaking. </p>\n\n<p>Take the <code>System</code> namespace, for example, which is imported by default. Because the System namespace is imported, you don't have to first type <code>System.</code> to reference a child namespace like <code>IO</code>, like you would in C#. So, right out of the box you can say something like this in VB:</p>\n\n<pre><code>If IO.File.Exists(MyFile) Then ....\n</code></pre>\n\n<p>That just isn't possible in C# right now. You either have to also import <code>System.IO</code> and then just say <code>File.Exists()</code> or list out the System namespace as well: <code>System.IO.File.Exists()</code>. </p>\n\n<p>It may not seem very significant, but you really get used to this VB feature after a while, and it comes in handy more than you'd think. I bring all this up because the end result of this feature is that you often don't want to import as many namespaces in VB as you do in C#.</p>\n" }, { "answer_id": 683890, "author": "Jonathan Holloway", "author_id": 82865, "author_profile": "https://Stackoverflow.com/users/82865", "pm_score": 0, "selected": false, "text": "<p>I don't believe Visual Studio does this by default for C#or VB.</p>\n\n<p>However, the Jetbrains Resharper plugin will auto import namespaces for you, in the same that Eclipse does when you use CTRL+SHIFT+O.</p>\n" } ]
2008/11/04
[ "https://Stackoverflow.com/questions/262535", "https://Stackoverflow.com", "https://Stackoverflow.com/users/28647/" ]
In C# some of default name space such as System.Collections are listed without typing in using blah. In visual basic, they are not imports for you. Is there a way to force vb to auto imports some of default name space or VB work differently than C#?
I think the first item posted by John Rudy is what you're looking for- add them in the project properties. However, VB.Net does also work differently than C#, in that it means a different thing in VB to import a namespace than it does in C#. When you import a namespace in VB, it also brings child namespaces 'in scope', in a manner of speaking. Take the `System` namespace, for example, which is imported by default. Because the System namespace is imported, you don't have to first type `System.` to reference a child namespace like `IO`, like you would in C#. So, right out of the box you can say something like this in VB: ``` If IO.File.Exists(MyFile) Then .... ``` That just isn't possible in C# right now. You either have to also import `System.IO` and then just say `File.Exists()` or list out the System namespace as well: `System.IO.File.Exists()`. It may not seem very significant, but you really get used to this VB feature after a while, and it comes in handy more than you'd think. I bring all this up because the end result of this feature is that you often don't want to import as many namespaces in VB as you do in C#.
262,555
<p>You can define a number in various ways in C#,</p> <pre><code>1F // a float with the value 1 1L // a long with the value 1 1D // a double with the value 1 </code></pre> <p>personally I'm looking for which would a <code>short</code>, however to make the question a better reference for people, what are all the other post-fix's to number literals you can apply?</p>
[ { "answer_id": 262589, "author": "Gulzar Nazim", "author_id": 4337, "author_profile": "https://Stackoverflow.com/users/4337", "pm_score": 2, "selected": false, "text": "<p>for money:</p>\n\n<pre><code>decimal mon = 1m;\n</code></pre>\n\n<p>for output:</p>\n\n<pre><code>string curr = String.Format(\"{0:C}\", mon); //output $1.00\n</code></pre>\n" }, { "answer_id": 262639, "author": "Skizz", "author_id": 1898, "author_profile": "https://Stackoverflow.com/users/1898", "pm_score": 2, "selected": false, "text": "<h1>Integer</h1>\n<p>Suffix - Description</p>\n<p>none - first of int, uint, long and ulong</p>\n<p>U or u - first of uint, ulong</p>\n<p>L or l - first of long, ulong</p>\n<p>UL, Ul, uL, ul, LU, Lu, lU, or lu - ulong</p>\n<h1>Real</h1>\n<p>Suffix - Description</p>\n<p>none - double</p>\n<p>F or f - float</p>\n<p>D or d - double</p>\n<p>M or m - decimal</p>\n" }, { "answer_id": 262679, "author": "Scott Dorman", "author_id": 1559, "author_profile": "https://Stackoverflow.com/users/1559", "pm_score": 5, "selected": false, "text": "<pre><code>Type Suffix .NET Framework Type \n-------------------------------------------------------------------------------------\ndecimal M or m System.Decimal\ndouble D or d System.Double\nfloat F or f System.Single\nint [1] System.Int32\nlong L or l System.Int64\n</code></pre>\n\n<p>[1] When an integer literal has no suffix, its type is the first of these types in which its value can be represented: int, uint, long, ulong. </p>\n\n<p>When an integer literal specifies only a U or u suffix, its type is the first of these types in which its value can be represnted: uint, ulong.</p>\n\n<p>When an integer literal specifies only a L or l suffix, its type is the first of these types in which its value can be represnted: long, ulong.</p>\n\n<p>When an integer literal specifies both a U or u and L or l suffix, its type is the first of these types in which its value can be represnted: ulong.</p>\n" } ]
2008/11/04
[ "https://Stackoverflow.com/questions/262555", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1610/" ]
You can define a number in various ways in C#, ``` 1F // a float with the value 1 1L // a long with the value 1 1D // a double with the value 1 ``` personally I'm looking for which would a `short`, however to make the question a better reference for people, what are all the other post-fix's to number literals you can apply?
``` Type Suffix .NET Framework Type ------------------------------------------------------------------------------------- decimal M or m System.Decimal double D or d System.Double float F or f System.Single int [1] System.Int32 long L or l System.Int64 ``` [1] When an integer literal has no suffix, its type is the first of these types in which its value can be represented: int, uint, long, ulong. When an integer literal specifies only a U or u suffix, its type is the first of these types in which its value can be represnted: uint, ulong. When an integer literal specifies only a L or l suffix, its type is the first of these types in which its value can be represnted: long, ulong. When an integer literal specifies both a U or u and L or l suffix, its type is the first of these types in which its value can be represnted: ulong.
262,561
<p>We have built an application that receives several files in different formats, pdf, tiff, jpeg, doc, etc. After received, they are converted to tiff files using a third party printing driver which is installed locally on the server and set up as the default printer. In order to do that we open a System.Diagnostics.Process with the command line and arguments to print the file with the appropriate application.</p> <p>Now the new version needs to be a Windows Service and so far everything is working fine, except the printing part. Whenever the process starts, it never raises an exception and everything seems to be working fine, but the file is never printed out. If I open Task Manager I can see that MS Paint was executed (in case of a jpeg file), but no output tiff file.</p> <p>As a side note, the final file needs to be a tiff file because of another third party tool our customer uses and that is the only format it supports.</p> <p>Any help will be greatly appreciated. Sergio Romero</p> <p>The code we're using is as follows:</p> <pre><code>private const string PROCESS_COMMAND = "mspaint.exe"; private const string PROCESS_ARGUMENTS = @"""{0}"""; Process proc = new Process(); ProcessStartInfo startInfo = new ProcessStartInfo(); string error = string.Empty; startInfo.FileName = PROCESS_COMMAND; startInfo.Arguments = string.Format(PROCESS_ARGUMENTS, fileFullPath); startInfo.UseShellExecute = false; startInfo.RedirectStandardError = true; proc.EnableRaisingEvents = false; proc.StartInfo = startInfo; proc.Start(); using(StreamReader errorReader = proc.StandardError) { string standardError = string.Empty; while((standardError = errorReader.ReadLine()) != null) { error += standardError + " "; } } proc.WaitForExit(); </code></pre>
[ { "answer_id": 262601, "author": "bobwienholt", "author_id": 24257, "author_profile": "https://Stackoverflow.com/users/24257", "pm_score": 0, "selected": false, "text": "<p>I'm not sure about the part about MSPaint... but if your app works as a console app but not as a service, chances are that the server doesn't have permission to do something that your user account does. </p>\n\n<p>You might want try having the service log on as you to rule out permissions issues.</p>\n" }, { "answer_id": 262625, "author": "Oscar Cabrero", "author_id": 14440, "author_profile": "https://Stackoverflow.com/users/14440", "pm_score": 0, "selected": false, "text": "<p>Check if the user used to install the service has the proper printing permissions AND/OR access to the files, i would also recomend using event logging </p>\n" }, { "answer_id": 262649, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>Does MSPaint open when you run this from a console app? If so, its probably because your service is running headless; it doesn't have rights to display UI. So, MSPaint basically bails as it can't open its UI up without erroring.</p>\n\n<p>Why not just print it directly from .NET? You can do this from a service. There are some warnings about System.Printing not designed for use by a service, however. I'm not sure why, tho. I've done it without issues before...</p>\n" }, { "answer_id": 262665, "author": "Kevin Fairchild", "author_id": 3743, "author_profile": "https://Stackoverflow.com/users/3743", "pm_score": 2, "selected": false, "text": "<p>First thing I'd suggest is to <strong>have the service run under the context of a specific user</strong>. Then log into the server as that user and make sure that the printer is installed, set as the default, etc.</p>\n\n<p>Secondly, <strong>ditch the MS Paint solution</strong> to simplify things. You can load the image in .NET using System.Drawing.Image.FromFile(YourImageFilePath) and use PrintDocument to do the rest...</p>\n\n<p>Create a PrintDocument object, define your settings (which printer to use, margins, etc.), add a handler for the document's PrintPage event which does something along the lines of e.Graphics.DrawImage(YourTiffImageObject, New Rectangle(0, 0, e.MarginBounds.Width, e.MarginBounds.Height)) to draw the TIFF image onto the page. Finally, you call your PrintDocument object's .Print method and away it goes.</p>\n\n<p>This way, .NET is handling the printing -- not some random third-party app.</p>\n\n<p>There are some minor code changes when you're dealing with more than one page at a time (primarily calling SelectActiveFrom to change the page on multi-page TIFFs and setting e.HasMorePages = True in the PrintPage event until you read the last page) but it's all fairly easily and well-documented.</p>\n\n<p><em>UPDATE:</em>\nJust for completeness, I guess I should add what others have already mentioned... Some applications <strong>may require desktop access to function properly</strong>. If you stick with MS Paint, you may need to enable 'Allow service to interact with desktop' in the service properties.</p>\n" }, { "answer_id": 262931, "author": "Douglas Anderson", "author_id": 5678, "author_profile": "https://Stackoverflow.com/users/5678", "pm_score": 0, "selected": false, "text": "<p>We've run into all sorts of issues with Services trying to launch apps. Often it's security/credentials being used, or it can also be something like enabling 'Allow service to interact with desktop' as the app (in this case mspaint) might need that.</p>\n\n<p>That being said, I agree with Kevin, ditch MSPaint and either print natively within .NET or if it's just a matter of conversion, convert using .NET. The other is to look into something a little more sophisticate then MSPaint with libraries such as LibTIFF or even things like like Ghostscript to handle the formats that may not be supported natively inside .NET such as PDF.</p>\n" } ]
2008/11/04
[ "https://Stackoverflow.com/questions/262561", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
We have built an application that receives several files in different formats, pdf, tiff, jpeg, doc, etc. After received, they are converted to tiff files using a third party printing driver which is installed locally on the server and set up as the default printer. In order to do that we open a System.Diagnostics.Process with the command line and arguments to print the file with the appropriate application. Now the new version needs to be a Windows Service and so far everything is working fine, except the printing part. Whenever the process starts, it never raises an exception and everything seems to be working fine, but the file is never printed out. If I open Task Manager I can see that MS Paint was executed (in case of a jpeg file), but no output tiff file. As a side note, the final file needs to be a tiff file because of another third party tool our customer uses and that is the only format it supports. Any help will be greatly appreciated. Sergio Romero The code we're using is as follows: ``` private const string PROCESS_COMMAND = "mspaint.exe"; private const string PROCESS_ARGUMENTS = @"""{0}"""; Process proc = new Process(); ProcessStartInfo startInfo = new ProcessStartInfo(); string error = string.Empty; startInfo.FileName = PROCESS_COMMAND; startInfo.Arguments = string.Format(PROCESS_ARGUMENTS, fileFullPath); startInfo.UseShellExecute = false; startInfo.RedirectStandardError = true; proc.EnableRaisingEvents = false; proc.StartInfo = startInfo; proc.Start(); using(StreamReader errorReader = proc.StandardError) { string standardError = string.Empty; while((standardError = errorReader.ReadLine()) != null) { error += standardError + " "; } } proc.WaitForExit(); ```
First thing I'd suggest is to **have the service run under the context of a specific user**. Then log into the server as that user and make sure that the printer is installed, set as the default, etc. Secondly, **ditch the MS Paint solution** to simplify things. You can load the image in .NET using System.Drawing.Image.FromFile(YourImageFilePath) and use PrintDocument to do the rest... Create a PrintDocument object, define your settings (which printer to use, margins, etc.), add a handler for the document's PrintPage event which does something along the lines of e.Graphics.DrawImage(YourTiffImageObject, New Rectangle(0, 0, e.MarginBounds.Width, e.MarginBounds.Height)) to draw the TIFF image onto the page. Finally, you call your PrintDocument object's .Print method and away it goes. This way, .NET is handling the printing -- not some random third-party app. There are some minor code changes when you're dealing with more than one page at a time (primarily calling SelectActiveFrom to change the page on multi-page TIFFs and setting e.HasMorePages = True in the PrintPage event until you read the last page) but it's all fairly easily and well-documented. *UPDATE:* Just for completeness, I guess I should add what others have already mentioned... Some applications **may require desktop access to function properly**. If you stick with MS Paint, you may need to enable 'Allow service to interact with desktop' in the service properties.
262,579
<p>I have a simple POJO web service published with Axis2 on Tomcat5.5 I try to consume it with ATL C++ client and it fails. Doing the same with a C# client works. The problem is that ATL client sends soap body which looks like </p> <pre><code>&lt;soap:Body&gt;&lt; xmlns="http://fa.test.com/xsd"&gt;&lt;/&gt;&lt;/soap:Body&gt;&lt;/soap:Envelope&gt; </code></pre> <p>Notice the invalid element in the middle. I suspect it has something to do with UTF-8 because C# sends a header of </p> <pre><code>&lt;?xml version='1.0' encoding='utf-8'?&gt; </code></pre> <p>and ATL client doesn't. Also when I look into some of the ATL SOAP internals I notice that a structure has two members: szName and szwName. The first one is empty and produces the element, the second one has a valid (?) name of testResponse (the method I'm calling is called "test").</p> <p>Need advice as to where to go from here?</p> <p>More details: full message from ATL client:</p> <pre><code>POST /axis2/services/EnterpriseService.EnterpriseServiceHttpSoap11Endpoint/ HTTP/1.1 Content-Length: 304 Content-Type: text/xml; charset=utf-8 SOAPAction: "urn:test" Accept: text/xml Host: xxxxxxx User-Agent: Microsoft-ATL-Native/8.00 &lt;soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soapenc="http://schemas.xmlsoap.org/soap/encoding/"&gt;&lt;soap:Body&gt;&lt; xmlns="http://fa.test.com/xsd"&gt;&lt;/&gt;&lt;/soap:Body&gt;&lt;/soap:Envelope&gt; </code></pre> <p>Response from Axis2:</p> <pre><code>HTTP/1.1 500 Internal Server Error Server: Apache-Coyote/1.1 Content-Type: text/xml;charset=utf-8 Transfer-Encoding: chunked Date: Tue, 04 Nov 2008 15:31:57 GMT Connection: close &lt;?xml version='1.0' encoding='utf-8'?&gt;&lt;soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"&gt;&lt;soapenv:Body&gt;&lt;soapenv:Fault&gt;&lt;faultcode&gt;soapenv:Server&lt;/faultcode&gt;&lt;faultstring&gt;com.ctc.wstx.exc.WstxUnexpectedCharException: Unexpected character '&gt;' (code 62); expected an element name.&amp;#xd; at [row,col {unknown-source}]: [1,276]&lt;/faultstring&gt;&lt;detail /&gt;&lt;/soapenv:Fault&gt;&lt;/soapenv:Body&gt;&lt;/soapenv:Envelope&gt; </code></pre> <p>Oh, and here is the good request coming from C# client:</p> <pre><code>POST /axis2/services/EnterpriseService.EnterpriseServiceHttpSoap11Endpoint/ HTTP/1.1 Via: 1.1 ANGEL-ISLAND Content-Type: text/xml; charset=utf-8 User-Agent: Mozilla/4.0 (compatible; MSIE 6.0; MS Web Services Client Protocol 2.0.50727.1433) Host: xxxxxxx:8080 SOAPAction: "urn:test" Connection: Keep-Alive Content-Length: 236 &lt;?xml version="1.0" encoding="utf-8"?&gt;&lt;soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"&gt;&lt;soap:Body /&gt;&lt;/soap:Envelope&gt; </code></pre> <p>In C# case the soap:body is blank.</p>
[ { "answer_id": 274231, "author": "David Norman", "author_id": 34502, "author_profile": "https://Stackoverflow.com/users/34502", "pm_score": 0, "selected": false, "text": "<p>I don't think it has anything to do with UTF-8.</p>\n\n<p>The valid message from C# doesn't have anything inside the soap:Body, while the invalid message has . It looks like the ATL C++ client is trying to force something inside the SOAP body when there shouldn't be anything there at all.</p>\n\n<p>Note also that the C# client doesn't include a testResponse element in its message.</p>\n\n<p>I'd look the code some more where it uses szName and see if that's where it's generating the . It shouldn't be doing that.</p>\n" }, { "answer_id": 274833, "author": "Sunlight", "author_id": 33650, "author_profile": "https://Stackoverflow.com/users/33650", "pm_score": 2, "selected": false, "text": "<p>ATL Server is entirely capable of generating the request correctly. Looks like there's some issue with the WSDL. My cursory test generates the request:</p>\n\n<pre><code>&lt;soap:Envelope xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\"\n xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" \n xmlns:soapenc=\"http://schemas.xmlsoap.org/soap/encoding/\"&gt;\n &lt;soap:Body&gt;&lt;/soap:Body&gt;&lt;/soap:Envelope&gt;\n</code></pre>\n\n<p>for an ASP.NET Web service with <code>SoapParameterStyle.Bare</code>. Do you have a <code>&lt;wsdl:part&gt;</code> element in the input message? Can you post the WSDL service description?</p>\n" } ]
2008/11/04
[ "https://Stackoverflow.com/questions/262579", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I have a simple POJO web service published with Axis2 on Tomcat5.5 I try to consume it with ATL C++ client and it fails. Doing the same with a C# client works. The problem is that ATL client sends soap body which looks like ``` <soap:Body>< xmlns="http://fa.test.com/xsd"></></soap:Body></soap:Envelope> ``` Notice the invalid element in the middle. I suspect it has something to do with UTF-8 because C# sends a header of ``` <?xml version='1.0' encoding='utf-8'?> ``` and ATL client doesn't. Also when I look into some of the ATL SOAP internals I notice that a structure has two members: szName and szwName. The first one is empty and produces the element, the second one has a valid (?) name of testResponse (the method I'm calling is called "test"). Need advice as to where to go from here? More details: full message from ATL client: ``` POST /axis2/services/EnterpriseService.EnterpriseServiceHttpSoap11Endpoint/ HTTP/1.1 Content-Length: 304 Content-Type: text/xml; charset=utf-8 SOAPAction: "urn:test" Accept: text/xml Host: xxxxxxx User-Agent: Microsoft-ATL-Native/8.00 <soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soapenc="http://schemas.xmlsoap.org/soap/encoding/"><soap:Body>< xmlns="http://fa.test.com/xsd"></></soap:Body></soap:Envelope> ``` Response from Axis2: ``` HTTP/1.1 500 Internal Server Error Server: Apache-Coyote/1.1 Content-Type: text/xml;charset=utf-8 Transfer-Encoding: chunked Date: Tue, 04 Nov 2008 15:31:57 GMT Connection: close <?xml version='1.0' encoding='utf-8'?><soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"><soapenv:Body><soapenv:Fault><faultcode>soapenv:Server</faultcode><faultstring>com.ctc.wstx.exc.WstxUnexpectedCharException: Unexpected character '>' (code 62); expected an element name.&#xd; at [row,col {unknown-source}]: [1,276]</faultstring><detail /></soapenv:Fault></soapenv:Body></soapenv:Envelope> ``` Oh, and here is the good request coming from C# client: ``` POST /axis2/services/EnterpriseService.EnterpriseServiceHttpSoap11Endpoint/ HTTP/1.1 Via: 1.1 ANGEL-ISLAND Content-Type: text/xml; charset=utf-8 User-Agent: Mozilla/4.0 (compatible; MSIE 6.0; MS Web Services Client Protocol 2.0.50727.1433) Host: xxxxxxx:8080 SOAPAction: "urn:test" Connection: Keep-Alive Content-Length: 236 <?xml version="1.0" encoding="utf-8"?><soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"><soap:Body /></soap:Envelope> ``` In C# case the soap:body is blank.
ATL Server is entirely capable of generating the request correctly. Looks like there's some issue with the WSDL. My cursory test generates the request: ``` <soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soapenc="http://schemas.xmlsoap.org/soap/encoding/"> <soap:Body></soap:Body></soap:Envelope> ``` for an ASP.NET Web service with `SoapParameterStyle.Bare`. Do you have a `<wsdl:part>` element in the input message? Can you post the WSDL service description?
262,593
<pre><code> $('input[type=checkbox]').unbind().click(function(e){ $(this).attr('checked', true) return false; }); </code></pre> <p>I NEED to return false because I have an event on its parent and I don't want to trigger that. It just WON'T check that checkbox.</p>
[ { "answer_id": 262606, "author": "Gareth", "author_id": 31582, "author_profile": "https://Stackoverflow.com/users/31582", "pm_score": 1, "selected": false, "text": "<p>You're missing a ] at the end of your jQuery selector</p>\n" }, { "answer_id": 262766, "author": "eyelidlessness", "author_id": 17964, "author_profile": "https://Stackoverflow.com/users/17964", "pm_score": 3, "selected": true, "text": "<pre><code>$('input[type=checkbox]').unbind().click(function(e){\n e.stopPropagation();\n});\n</code></pre>\n\n<p>Edit: I'm not sure what you need <code>.unbind()</code> for, but you should beware that that is canceling any other events you've put on those checkboxes.</p>\n" } ]
2008/11/04
[ "https://Stackoverflow.com/questions/262593", "https://Stackoverflow.com", "https://Stackoverflow.com/users/23810/" ]
``` $('input[type=checkbox]').unbind().click(function(e){ $(this).attr('checked', true) return false; }); ``` I NEED to return false because I have an event on its parent and I don't want to trigger that. It just WON'T check that checkbox.
``` $('input[type=checkbox]').unbind().click(function(e){ e.stopPropagation(); }); ``` Edit: I'm not sure what you need `.unbind()` for, but you should beware that that is canceling any other events you've put on those checkboxes.
262,597
<p>I'm new to Linux and have inherited keeping our single linux server running. It's our SVN server so it's relatively important.</p> <p>Turns out the guy who maintained it before me had a cron task to email him when there are too many svnserve processes running, as they seem to be left dangling instead of terminating correctly.</p> <p>First part of the question is, given that I run</p> <pre><code>ps -fu cvsuser </code></pre> <p>and get a list of the processes, how can I kill the ones that have an STIME not today? For example, something like</p> <pre><code>kill where STIME = Oct30 </code></pre> <p>The other question is, does anyone know how to avoid having these dangling svnserve processes? <a href="https://stackoverflow.com/questions/262767/dangling-svnserve-processes">(Here's the other question.)</a></p>
[ { "answer_id": 262651, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>Off the top of my head, I would do something like this:</p>\n\n<blockquote>\n <p>ps -fu username | awk '$5 !~ /[0-9]:[0-9]/ { print $2 }' | xargs kill</p>\n</blockquote>\n\n<p>Since the fifth field of the ps output shows day-old processes with the month/day (e.g. Oct31) and without the time (e.g. 12:32), the regex with awk simply excludes those processes whose fifth field is still a time. I am assuming, possibly wrongly, that ps starts to show the date only for processes that have been running for more than 24 hours.</p>\n" }, { "answer_id": 262668, "author": "Tim Howland", "author_id": 4276, "author_profile": "https://Stackoverflow.com/users/4276", "pm_score": 2, "selected": false, "text": "<p>At the risk of suggesting you re-engineer your infrastructure, I've had great results using Apache and mod dav svn instead of svnserve - Apache's httpd is pretty darn bulletproof after the last decade or so of production usage.</p>\n" }, { "answer_id": 262683, "author": "Robert Gamble", "author_id": 25222, "author_profile": "https://Stackoverflow.com/users/25222", "pm_score": 0, "selected": false, "text": "<p>To identify and kill the processes:</p>\n\n<pre><code>ps h -u csvuser -o pid,lstart | grep 'May 29' | sed 's/^ \\+//' | \ncut -d ' ' -f 1 | xargs -n 1 kill\n</code></pre>\n\n<p>The ps command will find all processes owned by csvuser and output the pid and start time:</p>\n\n<pre><code>16324 Thu May 29 04:02:06 2008\n22144 Tue Jul 22 04:02:05 2008\n11315 Wed Oct 8 04:02:00 2008\n</code></pre>\n\n<p>The grep command will find the date you are looking for</p>\n\n<pre><code>16324 Thu May 29 04:02:06 2008\n</code></pre>\n\n<p>The sed command will remove leading spaces for cut,</p>\n\n<p>The cut command will output only the first field:</p>\n\n<pre><code>16324\n</code></pre>\n\n<p>And the xargs command will run the kill command once for each line passing the pid as the argument. Replace the grep statement as needed to match whatever you need.</p>\n\n<p>As for why the svnserve processes are not exiting properly, I don't know, I haven't seen this on my subversion servers, you probably should open a separate question for this.</p>\n" }, { "answer_id": 262804, "author": "Ken", "author_id": 20074, "author_profile": "https://Stackoverflow.com/users/20074", "pm_score": 3, "selected": true, "text": "<p>Just for the fun of it (GNU bash, version 3.2.39)</p>\n\n<pre><code>ps h -u cvsuser -o pid,start # h - no header, only output pid and start\n | grep -v ':' # exclude entries from the last 24 hours\n | egrep -o '^\\ *[0-9]+' # get the pid (handling possible leading space)\n | xargs -i echo kill \"{}\" # pretend to kill - take out the echo if you're happy\n</code></pre>\n\n<p>This relies on the following from 'man ps' STANDARD FORMAT SPECIFIERS:</p>\n\n<blockquote>\n <p>If the process was started less than\n 24 hours ago, the output format is\n \"HH:MM:SS\", else it is \" mmm dd\"\n (where mmm is a three-letter month\n name).</p>\n</blockquote>\n" }, { "answer_id": 8634341, "author": "Mike Frysinger", "author_id": 1116096, "author_profile": "https://Stackoverflow.com/users/1116096", "pm_score": 1, "selected": false, "text": "<p>for our cvs/svn/git server, rather than using a cronjob that looked for old processes by relying on the output of <code>ps</code>, we used the <code>timeout</code> program.</p>\n\n<pre><code>$ grep server /etc/xinetd.d/svnserve\nserver = /usr/bin/timeout\nserver_args = 12h /usr/bin/svnserve -i -R -r /svnroot\n</code></pre>\n\n<p>replace \"12h\" with an appropriate timeout for your site (although i can't imagine most people needing more than 12 hours to checkout a single repo)</p>\n" } ]
2008/11/04
[ "https://Stackoverflow.com/questions/262597", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9861/" ]
I'm new to Linux and have inherited keeping our single linux server running. It's our SVN server so it's relatively important. Turns out the guy who maintained it before me had a cron task to email him when there are too many svnserve processes running, as they seem to be left dangling instead of terminating correctly. First part of the question is, given that I run ``` ps -fu cvsuser ``` and get a list of the processes, how can I kill the ones that have an STIME not today? For example, something like ``` kill where STIME = Oct30 ``` The other question is, does anyone know how to avoid having these dangling svnserve processes? [(Here's the other question.)](https://stackoverflow.com/questions/262767/dangling-svnserve-processes)
Just for the fun of it (GNU bash, version 3.2.39) ``` ps h -u cvsuser -o pid,start # h - no header, only output pid and start | grep -v ':' # exclude entries from the last 24 hours | egrep -o '^\ *[0-9]+' # get the pid (handling possible leading space) | xargs -i echo kill "{}" # pretend to kill - take out the echo if you're happy ``` This relies on the following from 'man ps' STANDARD FORMAT SPECIFIERS: > > If the process was started less than > 24 hours ago, the output format is > "HH:MM:SS", else it is " mmm dd" > (where mmm is a three-letter month > name). > > >
262,603
<p>See question above.</p>
[ { "answer_id": 262622, "author": "FlySwat", "author_id": 1965, "author_profile": "https://Stackoverflow.com/users/1965", "pm_score": 5, "selected": false, "text": "<p>Yes, use IKVM.</p>\n\n<p><a href=\"http://www.ikvm.net/\" rel=\"noreferrer\">http://www.ikvm.net/</a></p>\n\n<p>And it's incredibly easy to use:</p>\n\n<pre><code>ikvmc myjar.jar\n</code></pre>\n\n<p>outputs myjar.dll</p>\n" }, { "answer_id": 263143, "author": "James Van Huis", "author_id": 31828, "author_profile": "https://Stackoverflow.com/users/31828", "pm_score": 2, "selected": false, "text": "<p>There is also <a href=\"http://gcc.gnu.org/java/\" rel=\"nofollow noreferrer\">gcj</a> which will compile classes into native format.</p>\n" }, { "answer_id": 7051832, "author": "Chris", "author_id": 869127, "author_profile": "https://Stackoverflow.com/users/869127", "pm_score": -1, "selected": false, "text": "<p>It is better to create a c++ loader which</p>\n\n<p>1)Hides the console</p>\n\n<p>2)runs your application</p>\n" } ]
2008/11/04
[ "https://Stackoverflow.com/questions/262603", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
See question above.
Yes, use IKVM. <http://www.ikvm.net/> And it's incredibly easy to use: ``` ikvmc myjar.jar ``` outputs myjar.dll
262,636
<p>I'm trying to implement the "Writing Information to UserData" section of <a href="http://www.asp.net/LEARN/security/tutorial-03-cs.aspx" rel="nofollow noreferrer">this article</a>, but it doesn't work properly when the cookie is part of the URI.</p> <p>My code:</p> <pre><code>// Create the cookie that contains the forms authentication ticket HttpCookie authCookie = FormsAuthentication.GetAuthCookie( userName, createPersistantCookie ); // Get the FormsAuthenticationTicket out of the encrypted cookie FormsAuthenticationTicket ticket = FormsAuthentication.Decrypt( authCookie.Value ); // Create a new FormsAuthenticationTicket that includes our custom User Data FormsAuthenticationTicket newTicket = new FormsAuthenticationTicket( ticket.Version, ticket.Name, ticket.IssueDate, ticket.Expiration, ticket.IsPersistent, "foo"); // Update the authCookie's Value to use the encrypted version of newTicket authCookie.Value = FormsAuthentication.Encrypt( newTicket ); // Manually add the authCookie to the Cookies collection HttpContext.Current.Response.Cookies.Add( authCookie ); // Determine redirect URL and send user there string redirUrl = FormsAuthentication.GetRedirectUrl( userName, createPersistantCookie ); HttpContext.Current.Response.Redirect( redirUrl, false ); </code></pre> <p>When cookieless is used, the page redirects but doesn't get the correct URI with the cookie information in it, so it loops back to my Login page where Request.IsAuthenticated returns false. An endless loop ensues.</p> <p>How do I redirect to the proper URI?</p>
[ { "answer_id": 264633, "author": "Stephen M. Redd", "author_id": 10115, "author_profile": "https://Stackoverflow.com/users/10115", "pm_score": 3, "selected": true, "text": "<p>I found this to be an interesting problem, so I set about doing some digging, testing, and a little bit of debugging into the .net framework source.</p>\n\n<p>Basically, what you are trying to do will not work. Anything you put into the Response.Cookies collection will just be ignored if the browser doesn't support cookies. You can check Request.Browser.Cookies to see if cookies are supported.</p>\n\n<p>In asp.net, both session state and authentication support a cookieless mode, but this does not extend to other cookies. In fact, it seems that session and authentication can be set to different modes of operation themselves even. </p>\n\n<p>The authentication system can store it's own data in the URI, but it does so by directly manipulating the URI itself. Sadly, Microsoft doesn't appear to have exposed these capabilities to code outside the authentication module. </p>\n\n<p>Basically, if you use the methods like FormsAuthentication.GetAuthCookie() and FormsAuthentication.SetAuthCookie() then the authentication system will take care of putting that information into the URI for you automagically... but it doesn't allow you to supply a customized authentication ticket to these methods... so you are stuck with the default auth ticket.In these cases, you are on your own for storing any custom data.</p>\n\n<p>Anyway...</p>\n\n<p>There really isn't much advantage to storing custom data directly in an authentication ticket if the authentication system has gone cookieless... in cookieless mode, things like \"persistant cookie\" have no meaning so you'll be regenerating the data at least once per session anyway.</p>\n\n<p>The most common suggestion for cases where you are cookieless but still need custom data like this is to enable cookieless sessions, and just store your custom data as a session variable. The session ID will get put into the URI, but the custom data will stay in memory on the server. The usage pattern is identical no matter if your sessions are cookieless or not. </p>\n\n<p>If you really wanted to, you could come up with a system of storing the custom data in the URI manually. The easiest thing to do would be to put the custom data into query strings or use pathdata. I can't see any real advantage to this over sessions variables unless you are just deperate not to use server memory (adding a little memory to a server is cheap, ugly URLs and manually writing code to deal with them is not cheap).</p>\n" }, { "answer_id": 265321, "author": "Greg", "author_id": 12601, "author_profile": "https://Stackoverflow.com/users/12601", "pm_score": 1, "selected": false, "text": "<p>Thank you for the great explanation, Stephen. In cases where the user does not allow cookies, I'm just going to have to avoid the UserData and load the data from the database.</p>\n\n<p>Before the code listed above I'll do:</p>\n\n<pre><code>if( !HttpContext.Current.Request.Browser.Cookies || !FormsAuthentication.CookiesSupported )\n{\n FormsAuthentication.RedirectFromLoginPage( userName, false);\n return;\n}\n</code></pre>\n" } ]
2008/11/04
[ "https://Stackoverflow.com/questions/262636", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12601/" ]
I'm trying to implement the "Writing Information to UserData" section of [this article](http://www.asp.net/LEARN/security/tutorial-03-cs.aspx), but it doesn't work properly when the cookie is part of the URI. My code: ``` // Create the cookie that contains the forms authentication ticket HttpCookie authCookie = FormsAuthentication.GetAuthCookie( userName, createPersistantCookie ); // Get the FormsAuthenticationTicket out of the encrypted cookie FormsAuthenticationTicket ticket = FormsAuthentication.Decrypt( authCookie.Value ); // Create a new FormsAuthenticationTicket that includes our custom User Data FormsAuthenticationTicket newTicket = new FormsAuthenticationTicket( ticket.Version, ticket.Name, ticket.IssueDate, ticket.Expiration, ticket.IsPersistent, "foo"); // Update the authCookie's Value to use the encrypted version of newTicket authCookie.Value = FormsAuthentication.Encrypt( newTicket ); // Manually add the authCookie to the Cookies collection HttpContext.Current.Response.Cookies.Add( authCookie ); // Determine redirect URL and send user there string redirUrl = FormsAuthentication.GetRedirectUrl( userName, createPersistantCookie ); HttpContext.Current.Response.Redirect( redirUrl, false ); ``` When cookieless is used, the page redirects but doesn't get the correct URI with the cookie information in it, so it loops back to my Login page where Request.IsAuthenticated returns false. An endless loop ensues. How do I redirect to the proper URI?
I found this to be an interesting problem, so I set about doing some digging, testing, and a little bit of debugging into the .net framework source. Basically, what you are trying to do will not work. Anything you put into the Response.Cookies collection will just be ignored if the browser doesn't support cookies. You can check Request.Browser.Cookies to see if cookies are supported. In asp.net, both session state and authentication support a cookieless mode, but this does not extend to other cookies. In fact, it seems that session and authentication can be set to different modes of operation themselves even. The authentication system can store it's own data in the URI, but it does so by directly manipulating the URI itself. Sadly, Microsoft doesn't appear to have exposed these capabilities to code outside the authentication module. Basically, if you use the methods like FormsAuthentication.GetAuthCookie() and FormsAuthentication.SetAuthCookie() then the authentication system will take care of putting that information into the URI for you automagically... but it doesn't allow you to supply a customized authentication ticket to these methods... so you are stuck with the default auth ticket.In these cases, you are on your own for storing any custom data. Anyway... There really isn't much advantage to storing custom data directly in an authentication ticket if the authentication system has gone cookieless... in cookieless mode, things like "persistant cookie" have no meaning so you'll be regenerating the data at least once per session anyway. The most common suggestion for cases where you are cookieless but still need custom data like this is to enable cookieless sessions, and just store your custom data as a session variable. The session ID will get put into the URI, but the custom data will stay in memory on the server. The usage pattern is identical no matter if your sessions are cookieless or not. If you really wanted to, you could come up with a system of storing the custom data in the URI manually. The easiest thing to do would be to put the custom data into query strings or use pathdata. I can't see any real advantage to this over sessions variables unless you are just deperate not to use server memory (adding a little memory to a server is cheap, ugly URLs and manually writing code to deal with them is not cheap).
262,652
<p>I can't stand HTML intermixed with other code. I'm working on a codebase that has to remain in PHP, and I don't want to touch an HTML template with a proverbial pole. So what I'm currently doing looks like this:</p> <pre><code>&lt;?php $page = new html_page('My wonderful page'); $page-&gt;add_contents(new html_tag('p', 'It works', array('id' =&gt; 'helloworld', 'class' =&gt; 'somecssclass'))); echo $page-&gt;render(); ?&gt; </code></pre> <p>Everything belongs to a nice hierarchy of objects, which is good and dandy. Of course I have a lot of smaller classes, and I'm thinking of using dynamic classes (for example, 'html_a' will automagically create an html_tag object of type 'a'.)</p> <p>It seems that nobody else is doing this. Why not? What am I missing?</p> <p>(I clearly remember an open source library that did exactly this, but can't find it anymore. So unless I'm actually imagining things, I'm not the only one who thought of this approach to render HTML)</p> <p>Do you have any thoughts on this?</p> <p>Here are some additional details:</p> <ol> <li>I'm the only developer in this project.</li> <li>How I'm mixing code with HTML: an &quot;html_tag&quot; object from my library is pretty similar to, say, a node in the DOM. The &quot;render&quot; method is the one that creates HTML, but I don't write any opening or closing tag anywhere.</li> <li>I create small objects for several tasks. These objects have methods to build tag objects; these resulting objects are then inserted into, say, tables or pages.</li> <li>My library have some primitive access methods to find objects. So the iterator example posted in <a href="https://stackoverflow.com/questions/262652/php-tag-library#262881">26288</a> can be implemented with relative ease.</li> <li>I'm not worried about performance (yet).</li> </ol>
[ { "answer_id": 262672, "author": "Javier", "author_id": 11649, "author_profile": "https://Stackoverflow.com/users/11649", "pm_score": 1, "selected": false, "text": "<p>PHP <em>is</em> a template language. therefore, it's natural that all PHP fans are using template-like design.</p>\n\n<p>there are some LISP libraries that do things like you put there. IMHO, this is a big turn-off when i approach LISP languages.</p>\n" }, { "answer_id": 262696, "author": "Owen", "author_id": 4853, "author_profile": "https://Stackoverflow.com/users/4853", "pm_score": 3, "selected": false, "text": "<p>Well, the bottom line is, you're still mixing your HTML with your code. If you wanted to change that \"p\" tag to a \"div\", you'd have to wander through your code just to do it. Think about what your method offers:</p>\n\n<ul>\n<li>mixes code with HTML</li>\n<li>adds overhead to parse all the requests</li>\n<li>introduces a new \"language\" over HTML</li>\n</ul>\n\n<p>In essence, while the approach may be different, it has the same issues the template languages you are trying to get away from has.</p>\n\n<p>Wouldn't it be easier, if you're working alone (or in a group), to just let PHP be the template language?</p>\n\n<pre><code>$page = new Page('test.html');\n$page-&gt;load($data);\n$page-&gt;render();\n</code></pre>\n\n<p>and in your test.html \"template\"</p>\n\n<pre><code>&lt;html&gt;\n&lt;head&gt;\n &lt;title&gt;&lt;?php echo $title ?&gt;&lt;/title&gt;\n&lt;/head&gt;\n&lt;body&gt;\n &lt;p&gt;&lt;?php echo $hello ?&gt;&lt;/p&gt;\n&lt;/body&gt;\n&lt;/html&gt;\n</code></pre>\n\n<p>What other template engines do really is formalize the above code. but if you stick to basics (echoing variables, basic conditionals, looping), you essentially have all the power of a template language, but in familiar PHP, and with no performance overhead.</p>\n\n<p>Plus, unlike your example, you can alter the HTML (i know you didn't want to touch it, but changing a \"p\" to a \"div\" in code really isn't that different from change <code>&lt;p&gt;</code> to <code>&lt;div&gt;</code>), without having to delve into the code.</p>\n" }, { "answer_id": 262713, "author": "Peter Bailey", "author_id": 8815, "author_profile": "https://Stackoverflow.com/users/8815", "pm_score": 0, "selected": false, "text": "<p>Nobody else is doing it because it's quite a bit more work than just escaping in and out of PHP mode for a template file, not to mention it just adds overhead purely to satisfy your preference for code aesthetics.</p>\n\n<p>This doesn't mean you can separate logic from display, such as a simple system like Owen suggested. But to shy away from the convention of php mixed with HTML just because you don't like it is a little silly - it's how the language was made to be used.</p>\n" }, { "answer_id": 262746, "author": "Roel", "author_id": 11449, "author_profile": "https://Stackoverflow.com/users/11449", "pm_score": 2, "selected": false, "text": "<p>I'm not sure what you're talking about. Are you looking for a template library for php? There are plenty, and although it's fashionable to hate on Smarty (just like it's fashionable to hate on php itself), it's a great library.</p>\n\n<p>Are you asking why 'everybody' mixes html in their php code? The answer to that is that only beginnners and idiots do that. Everybody who has real-world php experience uses a template engine.</p>\n\n<p>If you are asking why nobody adds every html tage in code like in your example, well that's obvious: because it's a maintenance nightmare. Are you going to give your code to a designer and tell him good luck with it? Are you going to manually convert every html page to pages and pages of code?</p>\n" }, { "answer_id": 262818, "author": "Dave Sherohman", "author_id": 18914, "author_profile": "https://Stackoverflow.com/users/18914", "pm_score": 2, "selected": false, "text": "<p>So, if I understand correctly, you're saying that you hate having code mixed into your HTML so much that you've decided to mix HTML into your code instead? I fail to see how that improves anything - the code and HTML are still mixed - and it's the less natural/more complex way of approaching PHP, which seems to provide an obvious explanation for why nobody else is doing it.</p>\n\n<p>Use a proper templating system which actually separates the code from the HTML instead of just toying with which one is embedded within the other. I would suggest HTML::Template or Template::Toolkit, since you share my taste for Perl, but you've already said that non-PHP languages aren't viable options.</p>\n" }, { "answer_id": 262881, "author": "Kent Fredric", "author_id": 15614, "author_profile": "https://Stackoverflow.com/users/15614", "pm_score": 1, "selected": false, "text": "<p><a href=\"https://stackoverflow.com/questions/261338/what-is-the-best-way-to-insert-html-via-php\">Question 261338</a> has some colinerarity with this, but my response there was more targeted at the php people whom are new to this whole programming \"seperation of concerns? whats that?\" people. ( sorry php people, largely this is the case )</p>\n\n<p>You could be a good perl player and use perl to generate your html templatey crap that gets loaded in php, I'm still new to perl, but php reeks and I've used it for far too long, surely there has to be a way to write a site in perl that runs on php. </p>\n\n<p>Thirdly, I'd like to see something that does augmentative substitution beyond variables.</p>\n\n<p>Sort of like jQuery style dom matching but without the bloat, java( rhino ), or the whole web browsery thing. </p>\n\n<pre><code>$page = new Page(\"FakePage.html\"); \n$page-&gt;find(\"div#foobar\")-&gt;text = \"Hahah! I rock\" ; \n/* Give All H1's a numeric lead in */ \nforeach( $page-&gt;find(\"h1\")-&gt;iterator() as $index =&gt; $node )\n{\n $node-&gt;text = ($index + 1 ) . \". \" $node.text;\n};\n$page-&gt;render();\n</code></pre>\n\n<p>I'd really love something that did that nicely and didn't suck too hard. Note my use of structures that probably wont be entirely loved by php. </p>\n\n<p>Dreams are free. </p>\n\n<p>( That is the /only/ syntax that truely seperates design and logic, all the other templatey stuff is just recursively diminishing programming languages ) </p>\n\n<p>The extra cool part here is:</p>\n\n<ol>\n<li>No need to santise html, its DOM AWARE! </li>\n<li>No need for weird special template markup that sucks and won't work in 90% of editors and can't be validated on its own without bleeding a chicken over it. </li>\n</ol>\n" }, { "answer_id": 263329, "author": "troelskn", "author_id": 18180, "author_profile": "https://Stackoverflow.com/users/18180", "pm_score": 3, "selected": true, "text": "<p>Slightly different, but yet similar. I wrote an <a href=\"http://www.sitepoint.com/blogs/2008/09/25/dom-vs-template/\" rel=\"nofollow noreferrer\">article about using DOM for binding variables to templates</a>. You may find it interesting.</p>\n\n<p>Basic use-case:</p>\n\n<pre><code>$t = new Domling('&lt;p class=\"hello\"&gt;&lt;/p&gt;'); \n$t-&gt;capture('hello')-&gt;bind(\"Hello World\"); \necho $t-&gt;render();\n</code></pre>\n\n<p>Which produces:</p>\n\n<pre><code>&lt;p class=\"hello\"&gt;Hello World&lt;/p&gt; \n</code></pre>\n" }, { "answer_id": 266566, "author": "Leonardo Herrera", "author_id": 7841, "author_profile": "https://Stackoverflow.com/users/7841", "pm_score": 2, "selected": false, "text": "<p>Well, it seems that people got upset about the \"loathe PHP\" quote. That's not the intended spirit of the question, sorry if I put your favorite language off.</p>\n\n<p>At the end, there are some really valid points made by several people;</p>\n\n<ol>\n<li>The unfortunate naming convention: having the name of the HTML element as the name of the object rings a bell. </li>\n<li>I'm reinventing Lisp, and the worst part of it at that.</li>\n<li>This is just another template system, and a bad one to boot.</li>\n</ol>\n\n<p>The accepted answer for me was the nice article posted by troelskn. I came into the conclusion that I need my own document model, and that I should refrain to use the html entity names on it. As I said before, this is a small side project; that article and some pointers I got from its comments gave me new ideas to explore.</p>\n\n<p>(About the reinventing Lisp part: I'm the only person I know that enjoyed programming the DOM. So there.)</p>\n\n<p>Thank you all for your comments.</p>\n" }, { "answer_id": 921935, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>I'm using the xml, xsl approach to develop my forms, using a single xls template to render any form I use in my portal. At the beginning it was little hard to find out the right format of xls file, but after it was done, it was very easy to render my forms. In php I just have to create a XML object and render it.</p>\n\n<p>Obviously, there will be 'special' things that I don't want to render with xls, in that cases I render them the normal way.</p>\n\n<p>I don't like to mix to much thing with php code, that is why I developed this libraries...</p>\n" } ]
2008/11/04
[ "https://Stackoverflow.com/questions/262652", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7841/" ]
I can't stand HTML intermixed with other code. I'm working on a codebase that has to remain in PHP, and I don't want to touch an HTML template with a proverbial pole. So what I'm currently doing looks like this: ``` <?php $page = new html_page('My wonderful page'); $page->add_contents(new html_tag('p', 'It works', array('id' => 'helloworld', 'class' => 'somecssclass'))); echo $page->render(); ?> ``` Everything belongs to a nice hierarchy of objects, which is good and dandy. Of course I have a lot of smaller classes, and I'm thinking of using dynamic classes (for example, 'html\_a' will automagically create an html\_tag object of type 'a'.) It seems that nobody else is doing this. Why not? What am I missing? (I clearly remember an open source library that did exactly this, but can't find it anymore. So unless I'm actually imagining things, I'm not the only one who thought of this approach to render HTML) Do you have any thoughts on this? Here are some additional details: 1. I'm the only developer in this project. 2. How I'm mixing code with HTML: an "html\_tag" object from my library is pretty similar to, say, a node in the DOM. The "render" method is the one that creates HTML, but I don't write any opening or closing tag anywhere. 3. I create small objects for several tasks. These objects have methods to build tag objects; these resulting objects are then inserted into, say, tables or pages. 4. My library have some primitive access methods to find objects. So the iterator example posted in [26288](https://stackoverflow.com/questions/262652/php-tag-library#262881) can be implemented with relative ease. 5. I'm not worried about performance (yet).
Slightly different, but yet similar. I wrote an [article about using DOM for binding variables to templates](http://www.sitepoint.com/blogs/2008/09/25/dom-vs-template/). You may find it interesting. Basic use-case: ``` $t = new Domling('<p class="hello"></p>'); $t->capture('hello')->bind("Hello World"); echo $t->render(); ``` Which produces: ``` <p class="hello">Hello World</p> ```
262,675
<p>We currently use VSS 6, this is not going to change I am afraid.</p> <p>I am attempting to write a script that will allow a user to quickly copy all files that they have checked out to another directory tree. In order to do this I need to get a list of all the files that the user has checked out, and the directory that the file is checked out to. This is easy enough to do using status search in the GUI. But I need a way of doing it from the command line utility ss.exe.</p>
[ { "answer_id": 262755, "author": "Panos", "author_id": 8049, "author_profile": "https://Stackoverflow.com/users/8049", "pm_score": 1, "selected": false, "text": "<p>See <a href=\"http://msdn.microsoft.com/en-us/library/d6kac9fd(VS.80).aspx\" rel=\"nofollow noreferrer\">here</a> for the command line usage of Status command. The command </p>\n\n<pre><code>ss.exe Status $/ -R -U\n</code></pre>\n\n<p>shows every file in the system that is checked out by the current user.</p>\n" }, { "answer_id": 262768, "author": "Brian Schmitt", "author_id": 30492, "author_profile": "https://Stackoverflow.com/users/30492", "pm_score": 4, "selected": true, "text": "<p>Two links that may be of use:</p>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/003ssz4z(VS.80).aspx\" rel=\"noreferrer\">VSS CommandLine Commands</a></p>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/hsxzf2az(VS.80).aspx\" rel=\"noreferrer\">VSS CommandLine Options</a></p>\n\n<p>To expand on Panos reply</p>\n\n<pre><code>ss.exe Status $/ -R -U&lt;Username&gt;\n</code></pre>\n\n<p>Will get you the files of a particular user.</p>\n" }, { "answer_id": 5197793, "author": "Bill Paetzke", "author_id": 192210, "author_profile": "https://Stackoverflow.com/users/192210", "pm_score": 2, "selected": false, "text": "<p><strong>From the command line:</strong></p>\n\n<ol>\n<li><code>cd C:\\Program Files\\Microsoft Visual SourceSafe</code></li>\n<li><code>SET SSDIR=&lt;path to folder containing srcsafe.ini&gt;</code></li>\n<li><code>ss Status $/ -R -U&lt;username&gt; &gt; checked-out-by-username.txt</code></li>\n</ol>\n\n<p>And then check the contents of checked-out-by-username.txt for your check-outs.</p>\n\n<p><strong>For example:</strong> </p>\n\n<p>My <code>srcsafe.ini</code> was in <code>C:\\Program Files\\Microsoft Visual SourceSafe\\MasterDatabase</code>. And my username was <code>bpaetzke</code>.</p>\n\n<p>So, my command line looked like this:</p>\n\n<ol>\n<li><code>cd C:\\Program Files\\Microsoft Visual SourceSafe</code></li>\n<li><code>SET SSDIR=MasterDatabase</code></li>\n<li><code>ss Status $/ -R -Ubpaetzke &gt; checked-out-by-bpaetzke.txt</code></li>\n</ol>\n\n<p>If you want to get all users' check-outs, remove the -U and give the output file a generic name.</p>\n\n<p><strong>Other command line info:</strong></p>\n\n<ul>\n<li><a href=\"http://msdn.microsoft.com/en-us/library/003ssz4z%28VS.80%29.aspx\" rel=\"nofollow\">commands</a></li>\n<li><a href=\"http://msdn.microsoft.com/en-us/library/hsxzf2az%28VS.80%29.aspx\" rel=\"nofollow\">options</a></li>\n</ul>\n" }, { "answer_id": 32868430, "author": "Habib", "author_id": 961113, "author_profile": "https://Stackoverflow.com/users/961113", "pm_score": 2, "selected": false, "text": "<p>I came here looking for the same thing but with Visual Source Safe version >= 8.0, the command doesn't seem to work for me, instead I found an easier way to search using menu:</p>\n\n<blockquote>\n <p>View -> Search -> Status Search</p>\n</blockquote>\n\n<p>There select the option to search by user and specify the user name</p>\n\n<p><a href=\"https://i.stack.imgur.com/8HG2h.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/8HG2h.png\" alt=\"enter image description here\"></a></p>\n" } ]
2008/11/04
[ "https://Stackoverflow.com/questions/262675", "https://Stackoverflow.com", "https://Stackoverflow.com/users/28882/" ]
We currently use VSS 6, this is not going to change I am afraid. I am attempting to write a script that will allow a user to quickly copy all files that they have checked out to another directory tree. In order to do this I need to get a list of all the files that the user has checked out, and the directory that the file is checked out to. This is easy enough to do using status search in the GUI. But I need a way of doing it from the command line utility ss.exe.
Two links that may be of use: [VSS CommandLine Commands](http://msdn.microsoft.com/en-us/library/003ssz4z(VS.80).aspx) [VSS CommandLine Options](http://msdn.microsoft.com/en-us/library/hsxzf2az(VS.80).aspx) To expand on Panos reply ``` ss.exe Status $/ -R -U<Username> ``` Will get you the files of a particular user.
262,691
<p>I feel like I'm missing a fairly fundamental concept to WPF when it comes to databinding, but I can't seem to find the right combination of Google keywords to locate what I'm after, so maybe the SO Community can help. :)</p> <p>I've got a WPF usercontrol that needs to databind to two separate objects in order to display properly. Both objects must be dynamically set from an outside source. Thus far I've simply been using the DataContext property of the form for dynamic object binding, but that only allows for one object to be referenced. I feel like this is a simple problem and that I must be missing something obvious.</p> <p>My previous attempt looks something like this:</p> <pre><code>&lt;UserControl.Resources&gt; &lt;src:Person x:Key="personSource" /&gt; &lt;src:Job x:Key="jobSource" /&gt; &lt;/UserControl.Resources&gt; &lt;TextBox Text="{Binding Source={StaticResource personSource}, Path=Name" /&gt; &lt;TextBox Text="{Binding Source={StaticResource jobSource}, Path=Address" /&gt; </code></pre> <p>This will bind to any defaults I give the classes just fine, but If I try to dynamically set the objects in code (as I show below) I don't see any change.</p> <pre><code>Person personSource = FindResource("personSource") as Person; personSource = externalPerson; Job jobSource= FindResource("jobSource") as Job; jobSource = externalJob; </code></pre> <p>What am I missing?</p>
[ { "answer_id": 262794, "author": "Todd White", "author_id": 30833, "author_profile": "https://Stackoverflow.com/users/30833", "pm_score": 4, "selected": true, "text": "<p>I would probably use a CustomControl with two DependencyProperties. Then the external site that uses your custom control could bind the data that they want to that control, also by using a custom control you can template the way the control looks in different situations.</p>\n\n<p>Custom control code would look something like:</p>\n\n<pre><code>public class CustomControl : Control\n{\n public static readonly DependencyProperty PersonProperty =\n DependencyProperty.Register(\"Person\", typeof(Person), typeof(CustomControl), new UIPropertyMetadata(null));\n public Person Person\n {\n get { return (Person) GetValue(PersonProperty); }\n set { SetValue(PersonProperty, value); }\n }\n\n\n public static readonly DependencyProperty JobProperty =\n DependencyProperty.Register(\"Job\", typeof(Job), typeof(CustomControl), new UIPropertyMetadata(null));\n public Job Job\n {\n get { return (Job) GetValue(JobProperty); }\n set { SetValue(JobProperty, value); }\n }\n\n static CustomControl()\n {\n DefaultStyleKeyProperty.OverrideMetadata(typeof(CustomControl), new FrameworkPropertyMetadata(typeof(CustomControl)));\n }\n}\n</code></pre>\n\n<p>Generic.xaml is a file that should be created for you and could have a Style that looks something like this:</p>\n\n<pre><code>&lt;ResourceDictionary\n xmlns=\"http://schemas.microsoft.com/winfx/2006/xaml/presentation\"\n xmlns:x=\"http://schemas.microsoft.com/winfx/2006/xaml\"\n xmlns:local=\"clr-namespace:WpfApplication3\"&gt;\n\n\n &lt;Style TargetType=\"{x:Type local:CustomControl}\"&gt;\n &lt;Setter Property=\"Template\"&gt;\n &lt;Setter.Value&gt;\n &lt;ControlTemplate TargetType=\"{x:Type local:CustomControl}\"&gt;\n &lt;Border Background=\"{TemplateBinding Background}\"\n BorderBrush=\"{TemplateBinding BorderBrush}\"\n BorderThickness=\"{TemplateBinding BorderThickness}\"&gt;\n &lt;StackPanel&gt;\n &lt;TextBox Text=\"{TemplateBinding Person.Name}\" /&gt;\n &lt;TextBox Text=\"{TemplateBinding Job.Address}\" /&gt;\n &lt;/StackPanel&gt;\n &lt;/Border&gt;\n &lt;/ControlTemplate&gt;\n &lt;/Setter.Value&gt;\n &lt;/Setter&gt;\n &lt;/Style&gt;\n&lt;/ResourceDictionary&gt;\n</code></pre>\n\n<p>Finally, when you go to use your control you would do something like this.</p>\n\n<pre><code>&lt;src:CustomControl Person=\"{Binding Person}\" Job=\"{Binding Job}\" /&gt;\n</code></pre>\n" }, { "answer_id": 263310, "author": "Ian Oakes", "author_id": 21606, "author_profile": "https://Stackoverflow.com/users/21606", "pm_score": 1, "selected": false, "text": "<p>The reason your text boxes don't update is that you are binding them to a StaticResource. As the name implies these resources are static and don't post change notifications. And because Binding is a MarkupExtension and does not derive from DependencyObject you can't use a DynamicResource.</p>\n\n<p>Try creating depedency properties on your control to reference the Person and Job objects. </p>\n\n<p>Then set the DataContext of the UserControl to reference itself.</p>\n\n<pre><code>DataContext=\"{Binding RelativeSource={RelativeSource Self}}\"\n</code></pre>\n\n<p>Then you can use dot notation to reference the required properties.</p>\n\n<pre><code>&lt;TextBox Text=\"{Binding Path=Person.Name\" /&gt;\n&lt;TextBox Text=\"{Binding Path=Job.Address\" /&gt;\n</code></pre>\n\n<p>Or use the source parameter</p>\n\n<pre><code>&lt;TextBox Text=\"{Binding Source=Person, Path=Name\" /&gt;\n&lt;TextBox Text=\"{Binding Source=Job, Path=Address\" /&gt;\n</code></pre>\n" } ]
2008/11/04
[ "https://Stackoverflow.com/questions/262691", "https://Stackoverflow.com", "https://Stackoverflow.com/users/25968/" ]
I feel like I'm missing a fairly fundamental concept to WPF when it comes to databinding, but I can't seem to find the right combination of Google keywords to locate what I'm after, so maybe the SO Community can help. :) I've got a WPF usercontrol that needs to databind to two separate objects in order to display properly. Both objects must be dynamically set from an outside source. Thus far I've simply been using the DataContext property of the form for dynamic object binding, but that only allows for one object to be referenced. I feel like this is a simple problem and that I must be missing something obvious. My previous attempt looks something like this: ``` <UserControl.Resources> <src:Person x:Key="personSource" /> <src:Job x:Key="jobSource" /> </UserControl.Resources> <TextBox Text="{Binding Source={StaticResource personSource}, Path=Name" /> <TextBox Text="{Binding Source={StaticResource jobSource}, Path=Address" /> ``` This will bind to any defaults I give the classes just fine, but If I try to dynamically set the objects in code (as I show below) I don't see any change. ``` Person personSource = FindResource("personSource") as Person; personSource = externalPerson; Job jobSource= FindResource("jobSource") as Job; jobSource = externalJob; ``` What am I missing?
I would probably use a CustomControl with two DependencyProperties. Then the external site that uses your custom control could bind the data that they want to that control, also by using a custom control you can template the way the control looks in different situations. Custom control code would look something like: ``` public class CustomControl : Control { public static readonly DependencyProperty PersonProperty = DependencyProperty.Register("Person", typeof(Person), typeof(CustomControl), new UIPropertyMetadata(null)); public Person Person { get { return (Person) GetValue(PersonProperty); } set { SetValue(PersonProperty, value); } } public static readonly DependencyProperty JobProperty = DependencyProperty.Register("Job", typeof(Job), typeof(CustomControl), new UIPropertyMetadata(null)); public Job Job { get { return (Job) GetValue(JobProperty); } set { SetValue(JobProperty, value); } } static CustomControl() { DefaultStyleKeyProperty.OverrideMetadata(typeof(CustomControl), new FrameworkPropertyMetadata(typeof(CustomControl))); } } ``` Generic.xaml is a file that should be created for you and could have a Style that looks something like this: ``` <ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:local="clr-namespace:WpfApplication3"> <Style TargetType="{x:Type local:CustomControl}"> <Setter Property="Template"> <Setter.Value> <ControlTemplate TargetType="{x:Type local:CustomControl}"> <Border Background="{TemplateBinding Background}" BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}"> <StackPanel> <TextBox Text="{TemplateBinding Person.Name}" /> <TextBox Text="{TemplateBinding Job.Address}" /> </StackPanel> </Border> </ControlTemplate> </Setter.Value> </Setter> </Style> </ResourceDictionary> ``` Finally, when you go to use your control you would do something like this. ``` <src:CustomControl Person="{Binding Person}" Job="{Binding Job}" /> ```
262,740
<p>Is there a canonical way to set up a JS onHover event with the existing onmouseover, onmouseout and some kind of timers? Or just any method to fire an arbitrary function if and only if user has hovered over element for certain amount of time.</p>
[ { "answer_id": 262752, "author": "eyelidlessness", "author_id": 17964, "author_profile": "https://Stackoverflow.com/users/17964", "pm_score": 4, "selected": false, "text": "<p>Can you clarify your question? What is \"ohHover\" in this case and how does it correspond to a delay in hover time?</p>\n\n<p>That said, I think what you probably want is...</p>\n\n<pre><code>var timeout;\nelement.onmouseover = function(e) {\n timeout = setTimeout(function() {\n // ...\n }, delayTimeMs)\n};\nelement.onmouseout = function(e) {\n if(timeout) {\n clearTimeout(timeout);\n }\n};\n</code></pre>\n\n<p>Or <code>addEventListener</code>/<code>attachEvent</code> or your favorite library's event abstraction method.</p>\n" }, { "answer_id": 263058, "author": "scunliffe", "author_id": 6144, "author_profile": "https://Stackoverflow.com/users/6144", "pm_score": 2, "selected": false, "text": "<p>I don't think you need/want the timeout.</p>\n\n<p>onhover (hover) would be defined as the time period while \"over\" something. IMHO</p>\n\n<pre><code>onmouseover = start...\n\nonmouseout = ...end\n</code></pre>\n\n<p>For the record I've done some stuff with this to \"fake\" the hover event in IE6. It was rather expensive and in the end I ditched it in favor of performance.</p>\n" }, { "answer_id": 263194, "author": "Peter Bailey", "author_id": 8815, "author_profile": "https://Stackoverflow.com/users/8815", "pm_score": 5, "selected": false, "text": "<p>How about something like this?</p>\n\n<pre><code>&lt;html&gt;\n&lt;head&gt;\n&lt;script type=\"text/javascript\"&gt;\n\nvar HoverListener = {\n addElem: function( elem, callback, delay )\n {\n if ( delay === undefined )\n {\n delay = 1000;\n }\n\n var hoverTimer;\n\n addEvent( elem, 'mouseover', function()\n {\n hoverTimer = setTimeout( callback, delay );\n } );\n\n addEvent( elem, 'mouseout', function()\n {\n clearTimeout( hoverTimer );\n } );\n }\n}\n\nfunction tester()\n{\n alert( 'hi' );\n}\n\n// Generic event abstractor\nfunction addEvent( obj, evt, fn )\n{\n if ( 'undefined' != typeof obj.addEventListener )\n {\n obj.addEventListener( evt, fn, false );\n }\n else if ( 'undefined' != typeof obj.attachEvent )\n {\n obj.attachEvent( \"on\" + evt, fn );\n }\n}\n\naddEvent( window, 'load', function()\n{\n HoverListener.addElem(\n document.getElementById( 'test' )\n , tester \n );\n HoverListener.addElem(\n document.getElementById( 'test2' )\n , function()\n {\n alert( 'Hello World!' );\n }\n , 2300\n );\n} );\n\n&lt;/script&gt;\n&lt;/head&gt;\n&lt;body&gt;\n&lt;div id=\"test\"&gt;Will alert \"hi\" on hover after one second&lt;/div&gt;\n&lt;div id=\"test2\"&gt;Will alert \"Hello World!\" on hover 2.3 seconds&lt;/div&gt;\n&lt;/body&gt;\n&lt;/html&gt;\n</code></pre>\n" }, { "answer_id": 951662, "author": "MikeN", "author_id": 36680, "author_profile": "https://Stackoverflow.com/users/36680", "pm_score": 4, "selected": false, "text": "<p>If you use the JQuery library you can use the .hover() event which merges the mouseover and mouseout event and helps you with the timing and child elements:</p>\n\n<pre><code>$(this).hover(function(){},function(){});\n</code></pre>\n\n<p>The first function is the start of the hover and the next is the end. Read more at:\n<a href=\"http://docs.jquery.com/Events/hover\" rel=\"noreferrer\">http://docs.jquery.com/Events/hover</a></p>\n" } ]
2008/11/04
[ "https://Stackoverflow.com/questions/262740", "https://Stackoverflow.com", "https://Stackoverflow.com/users/29574/" ]
Is there a canonical way to set up a JS onHover event with the existing onmouseover, onmouseout and some kind of timers? Or just any method to fire an arbitrary function if and only if user has hovered over element for certain amount of time.
How about something like this? ``` <html> <head> <script type="text/javascript"> var HoverListener = { addElem: function( elem, callback, delay ) { if ( delay === undefined ) { delay = 1000; } var hoverTimer; addEvent( elem, 'mouseover', function() { hoverTimer = setTimeout( callback, delay ); } ); addEvent( elem, 'mouseout', function() { clearTimeout( hoverTimer ); } ); } } function tester() { alert( 'hi' ); } // Generic event abstractor function addEvent( obj, evt, fn ) { if ( 'undefined' != typeof obj.addEventListener ) { obj.addEventListener( evt, fn, false ); } else if ( 'undefined' != typeof obj.attachEvent ) { obj.attachEvent( "on" + evt, fn ); } } addEvent( window, 'load', function() { HoverListener.addElem( document.getElementById( 'test' ) , tester ); HoverListener.addElem( document.getElementById( 'test2' ) , function() { alert( 'Hello World!' ); } , 2300 ); } ); </script> </head> <body> <div id="test">Will alert "hi" on hover after one second</div> <div id="test2">Will alert "Hello World!" on hover 2.3 seconds</div> </body> </html> ```
262,802
<p>I'm working on a project and I want to store some easily enumerated information in a table. MySql's enum data type does exactly what I want: <a href="http://dev.mysql.com/doc/refman/5.0/en/enum.html" rel="noreferrer">http://dev.mysql.com/doc/refman/5.0/en/enum.html</a> . Is there an equivalent in SQL Server 2005?</p> <p>I know I could store the possible values in a type table with a key, but I'd rather not have to link back to it for descriptions. Our database standards don't allow us to link on non-integer or uniqueidentifier fields, so storing the possible keys as characters is out as well.</p>
[ { "answer_id": 262812, "author": "Nikki9696", "author_id": 456669, "author_profile": "https://Stackoverflow.com/users/456669", "pm_score": 6, "selected": true, "text": "<p>Does this work for you?</p>\n\n<p>From <a href=\"http://blechie.com/wtilton/archive/2007/08/24/303.aspx\" rel=\"noreferrer\">http://blechie.com/wtilton/archive/2007/08/24/303.aspx</a></p>\n\n<p>Create table...</p>\n\n<p><strong>MySQL:</strong></p>\n\n<pre><code>ColumnName ENUM('upload', 'open', 'close', 'delete', 'edit', 'add')\n DEFAULT 'open'\n</code></pre>\n\n<p><strong>SQL Server:</strong></p>\n\n<pre><code>ColumnName varchar(10) \n CHECK(ColumnName IN ('upload', 'open', 'close', 'delete', 'edit', 'add')) \n DEFAULT 'open'\n</code></pre>\n" }, { "answer_id": 262845, "author": "Bill Karwin", "author_id": 20860, "author_profile": "https://Stackoverflow.com/users/20860", "pm_score": 4, "selected": false, "text": "<p>One characteristic of MySQL's ENUM data type is that it stores only a numeric index into the list of values, not the string itself, on each row. So it's usually more storage-efficient. Also the default behavior when you sort by an ENUM column is to sort by the numeric index, therefore by the order of elements in the ENUM.</p>\n\n<p>Nikki9696 suggests using a VARCHAR column with a CHECK constraint. This satisfies the restriction of values to a certain short list of permitted values, but it doesn't simulate the storage efficiency or the special sort order.</p>\n\n<p>One way to get both behaviors is to declare the column as an integer foreign key into a lookup table, in which you store each permitted string.</p>\n" } ]
2008/11/04
[ "https://Stackoverflow.com/questions/262802", "https://Stackoverflow.com", "https://Stackoverflow.com/users/30407/" ]
I'm working on a project and I want to store some easily enumerated information in a table. MySql's enum data type does exactly what I want: <http://dev.mysql.com/doc/refman/5.0/en/enum.html> . Is there an equivalent in SQL Server 2005? I know I could store the possible values in a type table with a key, but I'd rather not have to link back to it for descriptions. Our database standards don't allow us to link on non-integer or uniqueidentifier fields, so storing the possible keys as characters is out as well.
Does this work for you? From <http://blechie.com/wtilton/archive/2007/08/24/303.aspx> Create table... **MySQL:** ``` ColumnName ENUM('upload', 'open', 'close', 'delete', 'edit', 'add') DEFAULT 'open' ``` **SQL Server:** ``` ColumnName varchar(10) CHECK(ColumnName IN ('upload', 'open', 'close', 'delete', 'edit', 'add')) DEFAULT 'open' ```
262,826
<p>A k-ary necklace of length n is an ordered list of length n whose items are drawn from an alphabet of length k, which is the lexicographically first list in a sort of all lists sharing an ordering under rotation.</p> <p>Example: (1 2 3) and (1 3 2) are the necklaces of length 3 from the alphabet {1 2 3}.</p> <p>More info: <a href="http://en.wikipedia.org/wiki/Necklace_(combinatorics)" rel="nofollow noreferrer">http://en.wikipedia.org/wiki/Necklace_(combinatorics)</a></p> <p>I'd like to generate these in Scheme (or a Lisp of your choice). I've found some papers...<br> Savage - A New Algorithm for Generating Necklaces<br> Sawada - Generating Bracelets in Constant Amortized Time<br> Sawada - Generating Necklaces with Forbidden Substrings<br> ...but the code presented in them is opaque to me. Mainly because they don't seem to be passing in either the alphabet or the length (n) desired. The scheme procedure I'm looking for is of the form (necklaces n '(a b c...)).</p> <p>I can generate these easy enough by first generating k^n lists and then filtering out the rotations. But it's terribly memory-inefficient...</p> <p>Thanks!</p>
[ { "answer_id": 263020, "author": "Andru Luvisi", "author_id": 5922, "author_profile": "https://Stackoverflow.com/users/5922", "pm_score": 0, "selected": false, "text": "<p>I would do a two step process. First, find each combination of n elements from the alphabet. Then, for each combination, pick the lowest value, and generate all permutations of the remaining items.</p>\n\n<p>Edit: Here is some code. It assumes that the input list is already sorted and that it contains no duplicates.</p>\n\n<pre><code>(define (choose n l)\n (let ((len (length l)))\n (cond ((= n 0) '(()))\n ((&gt; n len) '())\n ((= n len) (list l))\n (else (append (map (lambda (x) (cons (car l) x))\n (choose (- n 1) (cdr l)))\n (choose n (cdr l)))))))\n\n(define (filter pred l)\n (cond ((null? l) '())\n ((pred (car l)) (cons (car l) (filter pred (cdr l))))\n (else (filter pred (cdr l)))))\n\n(define (permute l)\n (cond ((null? l) '(()))\n (else (apply append \n (map (lambda (x)\n (let ((rest (filter (lambda (y) (not (= x y))) l)))\n (map (lambda (subperm) (cons x subperm))\n (permute rest))))\n l)))))\n\n(define (necklaces n l)\n (apply\n append\n (map\n (lambda (combination)\n (map (lambda (permutation)\n (cons (car combination) permutation))\n (permute (cdr combination))))\n (choose n l))))\n\n\n(display (choose 1 '(1 2 3 4 5))) (newline)\n(display (choose 2 '(1 2 3 4 5))) (newline)\n(display (permute '(1 2))) (newline)\n(display (permute '(1 2 3))) (newline)\n(display (necklaces 3 '(1 2 3 4))) (newline)\n(display (necklaces 2 '(1 2 3 4))) (newline)\n</code></pre>\n" }, { "answer_id": 263292, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<blockquote>\n <p>Example: (1 2 3) and (1 3 2) are the necklaces of length 3 from the alphabet {1 2 3}.</p>\n</blockquote>\n\n<p>You forgot (1 1 1) (1 1 2) (1 1 3) (1 2 2) (1 3 3) (2 2 2) (2 2 3) (2 3 3) (3 3 3). Necklaces can contain duplicates.</p>\n\n<p>If you were only looking for necklaces of length N, drawn from an alphabet of size N, that contain <em>no</em> duplicates, then it's pretty easy: there will be (N-1)! necklaces, and each necklace will be of the form <code>(1 :: perm)</code> where <code>perm</code> is any permutation of {2 .. N}. For example, the necklaces of {1 .. 4} would be (1 2 3 4) (1 2 4 3) (1 3 2 4) (1 3 4 2) (1 4 2 3) (1 4 3 2). Extending this method to deal with no-duplicates necklaces of length K &lt; N is left as an exercise for the reader.</p>\n\n<p>But if you want to find real necklaces, which may contain duplicate elements, then it's not so simple.</p>\n" }, { "answer_id": 263307, "author": "Jay Kominek", "author_id": 32878, "author_profile": "https://Stackoverflow.com/users/32878", "pm_score": 2, "selected": false, "text": "<p>The FKM algorithm for generating necklaces. PLT Scheme. Not so hot on the performance. It'll take anything as an alphabet and maps the internal numbers onto whatever you provided. Seems to be correct; no guarantees. I was lazy when translating the loops, so you get this weird mix of for loops and escape continuations.</p>\n\n<pre><code>(require srfi/43)\n\n(define (gennecklaces n alphabet)\n (let* ([necklaces '()]\n [alphavec (list-&gt;vector alphabet)]\n [convert-necklace\n (lambda (vec)\n (map (lambda (x) (vector-ref alphavec x)) (cdr (vector-&gt;list vec))))]\n [helper\n (lambda (n k)\n (let ([a (make-vector (+ n 1) 0)]\n [i n])\n (set! necklaces (cons (convert-necklace a) necklaces))\n (let/ec done\n (for ([X (in-naturals)])\n (vector-set! a i (add1 (vector-ref a i)))\n (for ([j (in-range 1 (add1 (- n i)))])\n (vector-set! a (+ j i)\n (vector-ref a j)))\n (when (= 0 (modulo n i))\n (set! necklaces (cons (convert-necklace a) necklaces)))\n (set! i n)\n (let/ec done\n (for ([X (in-naturals)])\n (unless (= (vector-ref a i)\n (- k 1))\n (done))\n (set! i (- i 1))))\n (when (= i 0)\n (done))))))])\n (helper n (length alphabet))\n necklaces))\n</code></pre>\n" }, { "answer_id": 265044, "author": "Svante", "author_id": 31615, "author_profile": "https://Stackoverflow.com/users/31615", "pm_score": 0, "selected": false, "text": "<p>As a first idea, you can do the obvious, but inefficient: step through all combinations and check if they are a necklace, i.e. if they are the lexically smallest rotation of the elements (formal definition on p 5 in above paper). This would be like the way you proposed, but you would throw away all non-necklaces as soon as they are generated.</p>\n\n<p>Other than that, I think that you will have to understand this article (<a href=\"http://citeseer.ist.psu.edu/old/wang90new.html\" rel=\"nofollow noreferrer\">http://citeseer.ist.psu.edu/old/wang90new.html</a>):</p>\n\n<p>T. Wang and C. Savage, \"A new algorithm for generating necklaces,\" Report\n TR-90-20, Department of Computer Science, North Carolina State University\n (1990).</p>\n\n<p>It is not too hard, you can break it down by implementing the <code>tau</code> and <code>sigma</code> functions as described and then applying them in the order outlined in the article.</p>\n" } ]
2008/11/04
[ "https://Stackoverflow.com/questions/262826", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
A k-ary necklace of length n is an ordered list of length n whose items are drawn from an alphabet of length k, which is the lexicographically first list in a sort of all lists sharing an ordering under rotation. Example: (1 2 3) and (1 3 2) are the necklaces of length 3 from the alphabet {1 2 3}. More info: <http://en.wikipedia.org/wiki/Necklace_(combinatorics)> I'd like to generate these in Scheme (or a Lisp of your choice). I've found some papers... Savage - A New Algorithm for Generating Necklaces Sawada - Generating Bracelets in Constant Amortized Time Sawada - Generating Necklaces with Forbidden Substrings ...but the code presented in them is opaque to me. Mainly because they don't seem to be passing in either the alphabet or the length (n) desired. The scheme procedure I'm looking for is of the form (necklaces n '(a b c...)). I can generate these easy enough by first generating k^n lists and then filtering out the rotations. But it's terribly memory-inefficient... Thanks!
The FKM algorithm for generating necklaces. PLT Scheme. Not so hot on the performance. It'll take anything as an alphabet and maps the internal numbers onto whatever you provided. Seems to be correct; no guarantees. I was lazy when translating the loops, so you get this weird mix of for loops and escape continuations. ``` (require srfi/43) (define (gennecklaces n alphabet) (let* ([necklaces '()] [alphavec (list->vector alphabet)] [convert-necklace (lambda (vec) (map (lambda (x) (vector-ref alphavec x)) (cdr (vector->list vec))))] [helper (lambda (n k) (let ([a (make-vector (+ n 1) 0)] [i n]) (set! necklaces (cons (convert-necklace a) necklaces)) (let/ec done (for ([X (in-naturals)]) (vector-set! a i (add1 (vector-ref a i))) (for ([j (in-range 1 (add1 (- n i)))]) (vector-set! a (+ j i) (vector-ref a j))) (when (= 0 (modulo n i)) (set! necklaces (cons (convert-necklace a) necklaces))) (set! i n) (let/ec done (for ([X (in-naturals)]) (unless (= (vector-ref a i) (- k 1)) (done)) (set! i (- i 1)))) (when (= i 0) (done))))))]) (helper n (length alphabet)) necklaces)) ```
262,853
<p>The following code says that passing the map as <code>const</code> into the <code>operator[]</code> method discards qualifiers:</p> <pre><code>#include &lt;iostream&gt; #include &lt;map&gt; #include &lt;string&gt; using namespace std; class MapWrapper { public: const int &amp;get_value(const int &amp;key) const { return _map[key]; } private: map&lt;int, int&gt; _map; }; int main() { MapWrapper mw; cout &lt;&lt; mw.get_value(42) &lt;&lt; endl; return 0; } </code></pre> <p>Is this because of the possible allocation that occurs on the map access? Can no functions with map accesses be declared const?</p> <pre><code>MapWrapper.cpp:10: error: passing const std::map&lt;int, int, std::less&lt;int&gt;, std::allocator&lt;std::pair&lt;const int, int&gt; &gt; &gt; as this argument of _Tp&amp; std::map&lt;_Key, _Tp, _Compare, _Alloc&gt;::operator[](const _Key&amp;) [with _Key = int, _Tp = int, _Compare = std::less&lt;int&gt;, _Alloc = std::allocator&lt;std::pair&lt;const int, int&gt; &gt;] discards qualifiers </code></pre>
[ { "answer_id": 262863, "author": "nlativy", "author_id": 33635, "author_profile": "https://Stackoverflow.com/users/33635", "pm_score": 4, "selected": false, "text": "<p>You cannot use <code>operator[]</code> on a map that is <code>const</code> as that method is not <code>const</code> as it allows you to modify the map (you can assign to <code>_map[key]</code>). Try using the <code>find</code> method instead.</p>\n" }, { "answer_id": 262872, "author": "luke", "author_id": 16434, "author_profile": "https://Stackoverflow.com/users/16434", "pm_score": 8, "selected": true, "text": "<p><a href=\"http://en.cppreference.com/w/cpp/container/map/operator_at\" rel=\"noreferrer\"><code>std::map</code>'s <code>operator []</code> is not declared as <code>const</code>, and cannot be due to its behavior:</a></p>\n\n<blockquote>\n <p>T&amp; operator[] (const Key&amp; key)</p>\n \n <p>Returns a reference to the value that is mapped to a key equivalent to key, performing insertion if such key does not already exist. </p>\n</blockquote>\n\n<p>As a result, your function cannot be declared <code>const</code>, and use the map's <code>operator[]</code>. </p>\n\n<p><a href=\"http://en.cppreference.com/w/cpp/container/map/find\" rel=\"noreferrer\"><code>std::map</code>'s <code>find()</code></a> function allows you to look up a key without modifying the map.</p>\n\n<p><a href=\"http://en.cppreference.com/w/cpp/container/map/find\" rel=\"noreferrer\"><code>find()</code></a> returns an <code>iterator</code>, or <code>const_iterator</code> to an <a href=\"http://en.cppreference.com/w/cpp/utility/pair\" rel=\"noreferrer\"><code>std::pair</code></a> containing both the key (<code>.first</code>) and the value (<code>.second</code>).</p>\n\n<p>In C++11, you could also use <a href=\"http://en.cppreference.com/w/cpp/container/map/at\" rel=\"noreferrer\"><code>at()</code></a> for <code>std::map</code>. If element doesn't exist the function throws a <code>std::out_of_range</code> exception, in contrast to <code>operator []</code>.</p>\n" }, { "answer_id": 262973, "author": "Nathan Kitchen", "author_id": 31000, "author_profile": "https://Stackoverflow.com/users/31000", "pm_score": 3, "selected": false, "text": "<p>Some newer versions of the GCC headers (4.1 and 4.2 on my machine) have non-standard member functions map::at() which are declared const and throw std::out_of_range if the key is not in the map.</p>\n\n<pre><code>const mapped_type&amp; at(const key_type&amp; __k) const\n</code></pre>\n\n<p>From a reference in the function's comment, it appears that this has been suggested as a new member function in the standard library.</p>\n" }, { "answer_id": 2477751, "author": "Dov", "author_id": 233928, "author_profile": "https://Stackoverflow.com/users/233928", "pm_score": 0, "selected": false, "text": "<p>First, you should not be using symbols beginning with _ because they are reserved to the language implementation/compiler writer. It would be very easy for _map to be a syntax error on someone's compiler, and you would have no one to blame but yourself.</p>\n\n<p>If you want to use an underscore, put it at the end, not the beginning. You probably made this mistake because you saw some Microsoft code doing it. Remember, they write their own compiler, so they may be able to get away with it. Even so, it's a bad idea.</p>\n\n<p>the operator [] not only returns a reference, it actually creates the entry in the map. So you aren't just getting a mapping, if there is none, you are creating one. That's not what you intended.</p>\n" }, { "answer_id": 21320644, "author": "Richard", "author_id": 752843, "author_profile": "https://Stackoverflow.com/users/752843", "pm_score": 5, "selected": false, "text": "<p>Since <a href=\"http://www.cplusplus.com/reference/map/map/operator%5b%5d/\"><code>operator[]</code></a> does not have a const-qualified overload, it cannot be safely used in a const-qualified function. This is probably because the current overload was built with the goal of both returning and setting key values.</p>\n\n<p>Instead, you can use:</p>\n\n<pre><code>VALUE = map.find(KEY)-&gt;second;\n</code></pre>\n\n<p>or, in C++11, you can use the <a href=\"http://www.cplusplus.com/reference/map/map/at/\"><code>at()</code></a> operator:</p>\n\n<pre><code>VALUE = map.at(KEY);\n</code></pre>\n" } ]
2008/11/04
[ "https://Stackoverflow.com/questions/262853", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3594/" ]
The following code says that passing the map as `const` into the `operator[]` method discards qualifiers: ``` #include <iostream> #include <map> #include <string> using namespace std; class MapWrapper { public: const int &get_value(const int &key) const { return _map[key]; } private: map<int, int> _map; }; int main() { MapWrapper mw; cout << mw.get_value(42) << endl; return 0; } ``` Is this because of the possible allocation that occurs on the map access? Can no functions with map accesses be declared const? ``` MapWrapper.cpp:10: error: passing const std::map<int, int, std::less<int>, std::allocator<std::pair<const int, int> > > as this argument of _Tp& std::map<_Key, _Tp, _Compare, _Alloc>::operator[](const _Key&) [with _Key = int, _Tp = int, _Compare = std::less<int>, _Alloc = std::allocator<std::pair<const int, int> >] discards qualifiers ```
[`std::map`'s `operator []` is not declared as `const`, and cannot be due to its behavior:](http://en.cppreference.com/w/cpp/container/map/operator_at) > > T& operator[] (const Key& key) > > > Returns a reference to the value that is mapped to a key equivalent to key, performing insertion if such key does not already exist. > > > As a result, your function cannot be declared `const`, and use the map's `operator[]`. [`std::map`'s `find()`](http://en.cppreference.com/w/cpp/container/map/find) function allows you to look up a key without modifying the map. [`find()`](http://en.cppreference.com/w/cpp/container/map/find) returns an `iterator`, or `const_iterator` to an [`std::pair`](http://en.cppreference.com/w/cpp/utility/pair) containing both the key (`.first`) and the value (`.second`). In C++11, you could also use [`at()`](http://en.cppreference.com/w/cpp/container/map/at) for `std::map`. If element doesn't exist the function throws a `std::out_of_range` exception, in contrast to `operator []`.
262,887
<p>I'm developing a web app with java servlet, I hope to get the user ip info by calling <code>request.getRemoteAddr()</code> from inside <code>processRequest(HttpServletRequest request,HttpServletResponse response)</code>.</p> <p>But it returns a wrong IP. Since I'm not very knowledgeable about this area, I don't know what it is displaying, maybe a proxy, I got this:</p> <pre> RemoteAddr : 127.0.0.1 RemoteHost : 127.0.0.1 x-forwarded-for : null </pre> <p>127.0.0.1 is not my IP.</p> <p>Yet when I go to: <code>http://www.javascriptkit.com/script/script2/displayip.shtml</code> it will display the right one, since I'm using servlet, I don't have the .shtml to my dynamically generated html page, what can I do? And why the script on that site can display it correctly while <code>request.getRemoteAddr()</code> can't do it?</p> <p>Thanks for all the answers, I have a clue now, after deploying it to the server, it works as expected. Showed the correct address.</p> <p>But even when I develop it on my local machine, how to ask it to display the absolute IP as if it running on a real server? Or is it doable?</p>
[ { "answer_id": 262915, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 4, "selected": false, "text": "<p>What IP address is it displaying? My guess is there's some proxy or something changing things. (For instance, that script page displayed my ADSL router's IP address - not the one inside my LAN - for obvious reasons.)</p>\n\n<p>EDIT: Now that you've shown that the IP address you're seeing is 127.0.0.1 the answer is fairly clear - you're seeing your loopback adapter (i.e. the shortcut to the same machine) presumably because you're testing on the same machine you're developing on. The answer is entirely correct.</p>\n\n<p>Try it from a different machine and you'll get a more useful IP address.</p>\n" }, { "answer_id": 262939, "author": "Vijay Dev", "author_id": 27474, "author_profile": "https://Stackoverflow.com/users/27474", "pm_score": 3, "selected": false, "text": "<p>Check the X-Forwarded-For header by calling request.getHeader(\"X-Forwarded-For\") and see what IP does it return.</p>\n" }, { "answer_id": 263006, "author": "Huntrods", "author_id": 33977, "author_profile": "https://Stackoverflow.com/users/33977", "pm_score": 2, "selected": false, "text": "<p>The returned IP that you are showing is the localhost IP. This raises the question - where are you testing, and how are you accessing the servlet to test?</p>\n\n<p>If you are running the servlet on your local (development) machine, and also calling it up from a browser on the same machine, then this output is absolutely correct.</p>\n\n<p>Cheers,</p>\n\n<p>-R</p>\n" }, { "answer_id": 263008, "author": "masto", "author_id": 11974, "author_profile": "https://Stackoverflow.com/users/11974", "pm_score": 1, "selected": false, "text": "<p>You're running your test server on your local computer and connecting to it on <a href=\"http://localhost/\" rel=\"nofollow noreferrer\">http://localhost/</a>. Since you're connecting on the local interface, the source of the connection is also localhost, aka 127.0.0.1.</p>\n" }, { "answer_id": 263638, "author": "mfx", "author_id": 8015, "author_profile": "https://Stackoverflow.com/users/8015", "pm_score": 1, "selected": false, "text": "<p>If you call your servlet using <a href=\"http://localhost:8080/servlet\" rel=\"nofollow noreferrer\">http://localhost:8080/servlet</a>, you will usually get \"localhost\" as the remote addr. If you use the name of your machine, i.e. <a href=\"http://yourmachine/servlet\" rel=\"nofollow noreferrer\">http://yourmachine/servlet</a>, you will usally get the \"correct\" address.</p>\n" } ]
2008/11/04
[ "https://Stackoverflow.com/questions/262887", "https://Stackoverflow.com", "https://Stackoverflow.com/users/32834/" ]
I'm developing a web app with java servlet, I hope to get the user ip info by calling `request.getRemoteAddr()` from inside `processRequest(HttpServletRequest request,HttpServletResponse response)`. But it returns a wrong IP. Since I'm not very knowledgeable about this area, I don't know what it is displaying, maybe a proxy, I got this: ``` RemoteAddr : 127.0.0.1 RemoteHost : 127.0.0.1 x-forwarded-for : null ``` 127.0.0.1 is not my IP. Yet when I go to: `http://www.javascriptkit.com/script/script2/displayip.shtml` it will display the right one, since I'm using servlet, I don't have the .shtml to my dynamically generated html page, what can I do? And why the script on that site can display it correctly while `request.getRemoteAddr()` can't do it? Thanks for all the answers, I have a clue now, after deploying it to the server, it works as expected. Showed the correct address. But even when I develop it on my local machine, how to ask it to display the absolute IP as if it running on a real server? Or is it doable?
What IP address is it displaying? My guess is there's some proxy or something changing things. (For instance, that script page displayed my ADSL router's IP address - not the one inside my LAN - for obvious reasons.) EDIT: Now that you've shown that the IP address you're seeing is 127.0.0.1 the answer is fairly clear - you're seeing your loopback adapter (i.e. the shortcut to the same machine) presumably because you're testing on the same machine you're developing on. The answer is entirely correct. Try it from a different machine and you'll get a more useful IP address.
262,891
<p>A PHP array can have arrays for its elements. And those arrays can have arrays and so on and so forth. Is there a way to find out the maximum nesting that exists in a PHP array? An example would be a function that returns 1 if the initial array does not have arrays as elements, 2 if at least one element is an array, and so on.</p>
[ { "answer_id": 262909, "author": "KernelM", "author_id": 22328, "author_profile": "https://Stackoverflow.com/users/22328", "pm_score": 1, "selected": false, "text": "<p>I don't think there's anything built in. A simple recursive function could easily find out though.</p>\n" }, { "answer_id": 262944, "author": "Paige Ruten", "author_id": 813, "author_profile": "https://Stackoverflow.com/users/813", "pm_score": 7, "selected": true, "text": "<p>This should do it:</p>\n\n<pre><code>&lt;?php\n\nfunction array_depth(array $array) {\n $max_depth = 1;\n\n foreach ($array as $value) {\n if (is_array($value)) {\n $depth = array_depth($value) + 1;\n\n if ($depth &gt; $max_depth) {\n $max_depth = $depth;\n }\n }\n }\n\n return $max_depth;\n}\n\n?&gt;\n</code></pre>\n\n<p>Edit: Tested it very quickly and it appears to work.</p>\n" }, { "answer_id": 263007, "author": "Kent Fredric", "author_id": 15614, "author_profile": "https://Stackoverflow.com/users/15614", "pm_score": 6, "selected": false, "text": "<p><strong>Beware</strong> of the examples that just do it recursively.</p>\n<p>Php can create arrays with references to other places in that array, and can contain objects with likewise recursive referencing, and any purely recursive algorithm could be considered in such a case a <em>DANGEROUSLY</em> naive one, in that it will overflow stack depth recursing, and never terminate.</p>\n<p>( well, it will terminate when it exceeds stack depth, and at that point your program will fatally terminate, not what I think you want )</p>\n<p>In past, I have tried serialise -&gt; replacing reference markers with strings -&gt; deserialise for my needs, ( Often debugging backtraces with loads of recursive references in them ) which seems to work OK, you get holes everywhere, but it works for that task.</p>\n<p>For your task, if you find your array/structure has recursive references cropping up in it, you may want to take a look at the user contributed comments here: <a href=\"http://php.net/manual/en/language.references.spot.php\" rel=\"nofollow noreferrer\">http://php.net/manual/en/language.references.spot.php</a></p>\n<p>and then somehow find a way to count the depth of a recursive path.</p>\n<p>You may need to get out your CS books on algorithms and hit up these babies:</p>\n<ul>\n<li><a href=\"http://en.wikipedia.org/wiki/Depth-limited_search\" rel=\"nofollow noreferrer\">Wiki:Depth-limited-search</a></li>\n<li><a href=\"http://en.wikipedia.org/wiki/Depth-first_search\" rel=\"nofollow noreferrer\">Wiki:Depth-first search</a></li>\n</ul>\n<p>( Sorry for being so brief, but delving into graph theory is a bit more than suited for this format ;) )</p>\n" }, { "answer_id": 263621, "author": "Paige Ruten", "author_id": 813, "author_profile": "https://Stackoverflow.com/users/813", "pm_score": 6, "selected": false, "text": "<p>Here's another alternative that avoids the problem Kent Fredric pointed out. It gives <a href=\"http://php.net/print_r\" rel=\"noreferrer\">print_r()</a> the task of checking for infinite recursion (which it does well) and uses the indentation in the output to find the depth of the array.</p>\n\n<pre><code>function array_depth($array) {\n $max_indentation = 1;\n\n $array_str = print_r($array, true);\n $lines = explode(\"\\n\", $array_str);\n\n foreach ($lines as $line) {\n $indentation = (strlen($line) - strlen(ltrim($line))) / 4;\n\n if ($indentation &gt; $max_indentation) {\n $max_indentation = $indentation;\n }\n }\n\n return ceil(($max_indentation - 1) / 2) + 1;\n}\n</code></pre>\n" }, { "answer_id": 2629589, "author": "dave1010", "author_id": 315435, "author_profile": "https://Stackoverflow.com/users/315435", "pm_score": 2, "selected": false, "text": "<p>Here's my slightly modified version of jeremy Ruten's function</p>\n\n<pre><code>// you never know if a future version of PHP will have this in core\nif (!function_exists('array_depth')) {\nfunction array_depth($array) {\n // some functions that usually return an array occasionally return false\n if (!is_array($array)) {\n return 0;\n }\n\n $max_indentation = 1;\n // PHP_EOL in case we're running on Windows\n $lines = explode(PHP_EOL, print_r($array, true));\n\n foreach ($lines as $line) {\n $indentation = (strlen($line) - strlen(ltrim($line))) / 4;\n $max_indentation = max($max_indentation, $indentation);\n }\n return ceil(($max_indentation - 1) / 2) + 1;\n}\n}\n</code></pre>\n\n<p>Things like <code>print array_depth($GLOBALS)</code> won't error due to the recursion, but you may not get the result you expected.</p>\n" }, { "answer_id": 3673129, "author": "Asim", "author_id": 442975, "author_profile": "https://Stackoverflow.com/users/442975", "pm_score": 1, "selected": false, "text": "<pre><code>// very simple and clean approach \nfunction array_depth($a) {\n static $depth = 0;\n if(!is_array($a)) {\n return $depth;\n }else{\n $depth++;\n array_map(\"array_depth\", $a);\n return $depth;\n }\n }\nprint \"depth:\" . array_depth(array('k9' =&gt; 'dog')); // return 1\n</code></pre>\n" }, { "answer_id": 3899541, "author": "fncomp", "author_id": 455581, "author_profile": "https://Stackoverflow.com/users/455581", "pm_score": 2, "selected": false, "text": "<p>I had just worked out an answer to this question when I noticed this post. Here was my solution. I haven't tried this on a ton of different array sizes, but it was faster than the 2008 answer for the data I was working with ~30 pieces depth >4.</p>\n\n<pre><code>function deepness(array $arr){\n $exploded = explode(',', json_encode($arr, JSON_FORCE_OBJECT).\"\\n\\n\");\n $longest = 0;\n foreach($exploded as $row){\n $longest = (substr_count($row, ':')&gt;$longest)?\n substr_count($row, ':'):$longest;\n }\n return $longest;\n}\n</code></pre>\n\n<p><strong>Warning</strong>: this doesn't handle <em>any</em> edge cases. If you need a robust solution look elsewhere, but for the simple case I found this to be pretty fast.</p>\n" }, { "answer_id": 3909129, "author": "Jonathan H", "author_id": 472610, "author_profile": "https://Stackoverflow.com/users/472610", "pm_score": 1, "selected": false, "text": "<p>I believe the problem highlighted by Kent Frederic is crucial. \nThe answer suggested by yjerem and Asim are vulnerable to this problem.</p>\n\n<p>The approaches by indentation suggested by yjerem again, and dave1010 are not stable enough to me because it relies on the number of spaces that represent an indentation with the print_r function. It might vary with time/server/platform.</p>\n\n<p>The approach suggested by JoshN might be correct, but I think mine is faster :</p>\n\n<pre><code>function array_depth($arr)\n{\n if (!is_array($arr)) { return 0; }\n $arr = json_encode($arr);\n\n $varsum = 0; $depth = 0;\n for ($i=0;$i&lt;strlen($arr);$i++)\n {\n $varsum += intval($arr[$i] == '[') - intval($arr[$i] == ']');\n if ($varsum &gt; $depth) { $depth = $varsum; }\n }\n\n return $depth;\n}\n</code></pre>\n\n<p>Post a message if you undertake any testing comparing the different methods.\nJ</p>\n" }, { "answer_id": 5056433, "author": "shachibista", "author_id": 2654307, "author_profile": "https://Stackoverflow.com/users/2654307", "pm_score": 2, "selected": false, "text": "<p>\n\n<pre><code>function createDeepArray(){\n static $depth;\n $depth++;\n $a = array();\n if($depth &lt;= 10000){\n $a[] = createDeepArray();\n }\n return $a;\n}\n$deepArray = createDeepArray();\n\nfunction deepness(array $arr){\n $exploded = explode(',', json_encode($arr, JSON_FORCE_OBJECT).\"\\n\\n\");\n $longest = 0;\n foreach($exploded as $row){\n $longest = (substr_count($row, ':')&gt;$longest)?\n substr_count($row, ':'):$longest;\n }\n return $longest;\n}\n\nfunction array_depth($arr)\n{\n if (!is_array($arr)) { return 0; }\n $arr = json_encode($arr);\n\n $varsum = 0; $depth = 0;\n for ($i=0;$i&lt;strlen($arr);$i++)\n {\n $varsum += intval($arr[$i] == '[') - intval($arr[$i] == ']');\n if ($varsum &gt; $depth) { $depth = $varsum; }\n }\n\n return $depth;\n}\n\necho 'deepness():', \"\\n\";\n\n$start_time = microtime(TRUE);\n$start_memory = memory_get_usage();\nvar_dump(deepness($deepArray));\n$end_time = microtime(TRUE);\n$end_memory = memory_get_usage();\necho 'Memory: ', ($end_memory - $start_memory), \"\\n\";\necho 'Time: ', ($end_time - $start_time), \"\\n\";\n\necho \"\\n\";\necho 'array_depth():', \"\\n\";\n\n$start_time = microtime(TRUE);\n$start_memory = memory_get_usage();\nvar_dump(array_depth($deepArray));\n$end_time = microtime(TRUE);\n$end_memory = memory_get_usage();\necho 'Memory: ', ($end_memory - $start_memory), \"\\n\";\necho 'Time: ', ($end_time - $start_time), \"\\n\";\n</code></pre>\n\n<p>The function proposed by Josh was definitely faster:</p>\n\n<pre><code>$ for i in `seq 1 10`; do php test.php; echo '-------------------------';done\ndeepness():\nint(10000)\nMemory: 164\nTime: 0.0079939365386963\n\narray_depth():\nint(10001)\nMemory: 0\nTime: 0.043087005615234\n-------------------------\ndeepness():\nint(10000)\nMemory: 164\nTime: 0.0076408386230469\n\narray_depth():\nint(10001)\nMemory: 0\nTime: 0.042832851409912\n-------------------------\ndeepness():\nint(10000)\nMemory: 164\nTime: 0.0080249309539795\n\narray_depth():\nint(10001)\nMemory: 0\nTime: 0.042320966720581\n-------------------------\ndeepness():\nint(10000)\nMemory: 164\nTime: 0.0076301097869873\n\narray_depth():\nint(10001)\nMemory: 0\nTime: 0.041887998580933\n-------------------------\ndeepness():\nint(10000)\nMemory: 164\nTime: 0.0079131126403809\n\narray_depth():\nint(10001)\nMemory: 0\nTime: 0.04217004776001\n-------------------------\ndeepness():\nint(10000)\nMemory: 164\nTime: 0.0078539848327637\n\narray_depth():\nint(10001)\nMemory: 0\nTime: 0.04179310798645\n-------------------------\ndeepness():\nint(10000)\nMemory: 164\nTime: 0.0080208778381348\n\narray_depth():\nint(10001)\nMemory: 0\nTime: 0.04272198677063\n-------------------------\ndeepness():\nint(10000)\nMemory: 164\nTime: 0.0077919960021973\n\narray_depth():\nint(10001)\nMemory: 0\nTime: 0.041619062423706\n-------------------------\ndeepness():\nint(10000)\nMemory: 164\nTime: 0.0080950260162354\n\narray_depth():\nint(10001)\nMemory: 0\nTime: 0.042663097381592\n-------------------------\ndeepness():\nint(10000)\nMemory: 164\nTime: 0.0076849460601807\n\narray_depth():\nint(10001)\nMemory: 0\nTime: 0.042278051376343\n</code></pre>\n" }, { "answer_id": 8420027, "author": "cmosversion", "author_id": 1086213, "author_profile": "https://Stackoverflow.com/users/1086213", "pm_score": 1, "selected": false, "text": "<p>I believe you forgot to filter '[' and ']' or ',' and ':' and the data type of the array's key(s) and value(s). Here's an update of your array_depth plus a bonus array_sort_by_depth.</p>\n\n<pre><code>function array_depth($arr){\nif (is_array($arr)) {\n array_walk($arr, \n function($val, $key) use(&amp;$arr) {\n if ((! is_string($val)) &amp;&amp; (! is_array($val))) {\n $val = json_encode($val, JSON_FORCE_OBJECT);\n }\n\n if (is_string($val)) {\n $arr[$key] = preg_replace('/[:,]+/', '', $val);\n }\n }\n );\n\n $json_strings = explode(',', json_encode($arr, JSON_FORCE_OBJECT));\n\n $max_depth = 0;\n\n foreach ($json_strings as $json_string){\n var_dump($json_string); echo \"&lt;br/&gt;\";\n $json_string = preg_replace('/[^:]{1}/', '', $json_string);\n var_dump($json_string); echo \"&lt;br/&gt;&lt;br/&gt;\";\n $depth = strlen($json_string);\n\n if ($depth &gt; $max_depth) {\n $max_depth = $depth;\n }\n }\n\n return $max_depth;\n }\n\n return FALSE;\n }\n\n\n function array_sort_by_depth(&amp;$arr_val, $reverse = FALSE) {\n\n if ( is_array($arr_val)) { \n $temp_arr = array();\n $result_arr = array();\n\n foreach ($arr_val as $key =&gt; $val) {\n $temp_arr[$key] = array_depth($val);\n }\n\n if (is_bool($reverse) &amp;&amp; $reverse == TRUE) {\n arsort($temp_arr);\n }\n else {\n asort($temp_arr);\n }\n\n foreach ($temp_arr as $key =&gt; $val) {\n $result_arr[$key] = $arr_val[$key];\n }\n\n $arr_val = $result_arr;\n\n return TRUE;\n }\n\n return FALSE;\n }\n</code></pre>\n\n<p>Feel free to improve the code :D!</p>\n" }, { "answer_id": 10858631, "author": "Sasan", "author_id": 1431772, "author_profile": "https://Stackoverflow.com/users/1431772", "pm_score": 1, "selected": false, "text": "<p>I think this would solve the recursion problem, and also give the depth without relying on other php functions like serialize or print_r (which is risky at best and can lead to intractable bugs):</p>\n\n<pre><code>function array_depth(&amp;$array) {\n $max_depth = 1;\n $array['__compute_array_depth_flag_ZXCNADJHHDKAQP'] = 1;\n\n foreach ($array as $value) {\n if (is_array($value) &amp;&amp;\n !isset($value['__compute_array_depth_flag_ZXCNADJHHDKAQP'])) {\n $depth = array_depth($value) + 1;\n\n if ($depth &gt; $max_depth) {\n $max_depth = $depth;\n }\n }\n }\n unset($array['__compute_array_depth_flag_ZXCNADJHHDKAQP']);\n\n return $max_depth;\n}\n</code></pre>\n" }, { "answer_id": 11164010, "author": "Pranaya", "author_id": 1475927, "author_profile": "https://Stackoverflow.com/users/1475927", "pm_score": -1, "selected": false, "text": "<p>A quicker way: </p>\n\n<pre><code>max(array_map('count', $array));\n</code></pre>\n" }, { "answer_id": 13107456, "author": "Amir Syafrudin", "author_id": 1780509, "author_profile": "https://Stackoverflow.com/users/1780509", "pm_score": 2, "selected": false, "text": "<p>An old question, yet remain relevant to this date. :)</p>\n\n<p>Might as well contribute a minor modification to the answer from Jeremy Ruten.</p>\n\n<pre><code>function array_depth($array, $childrenkey)\n{\n $max_depth = 1;\n\n if (!empty($array[$childrenkey]))\n {\n foreach ($array[$childrenkey] as $value)\n {\n if (is_array($value))\n {\n $depth = array_depth($value, $childrenkey) + 1;\n\n if ($depth &gt; $max_depth)\n {\n $max_depth = $depth;\n }\n }\n }\n }\n\n return $max_depth;\n}\n</code></pre>\n\n<p>I added a second parameter called <strong>$childrenkey</strong> because I store the child elements in a specific key.</p>\n\n<p>An example of the function call is:</p>\n\n<pre><code>$my_array_depth = array_depth($my_array, 'the_key_name_storing_child_elements');\n</code></pre>\n" }, { "answer_id": 13108304, "author": "Amir Syafrudin", "author_id": 1780603, "author_profile": "https://Stackoverflow.com/users/1780603", "pm_score": 2, "selected": false, "text": "<p>Another (better) modification to the function from Jeremy Ruten:</p>\n\n<pre><code>function array_depth($array, $childrenkey = \"_no_children_\")\n{\n if (!empty($array[$childrenkey]))\n {\n $array = $array[$childrenkey];\n }\n\n $max_depth = 1;\n\n foreach ($array as $value)\n {\n if (is_array($value))\n {\n $depth = array_depth($value, $childrenkey) + 1;\n\n if ($depth &gt; $max_depth)\n {\n $max_depth = $depth;\n }\n }\n }\n\n return $max_depth;\n}\n</code></pre>\n\n<p>Adding <em>a default value</em> to <strong>$childrenkey</strong> allows the function to work for simple array with no keys for child elements, i.e. it will work for simple multi-dimensional arrays.</p>\n\n<p>This function can now be called using:</p>\n\n<pre><code>$my_array_depth = array_depth($my_array, 'the_key_name_storing_child_elements');\n</code></pre>\n\n<p>or</p>\n\n<pre><code>$my_array_depth = array_depth($my_array);\n</code></pre>\n\n<p>when <strong>$my_array</strong> doesn't have any specific key for storing its child elements.</p>\n" }, { "answer_id": 19036761, "author": "Erick Briseño", "author_id": 2820877, "author_profile": "https://Stackoverflow.com/users/2820877", "pm_score": 3, "selected": false, "text": "<p>Hi This is an alternative solution.</p>\n\n<pre><code>/*** IN mixed (any value),OUT (string)maxDepth ***/\n/*** Retorna la profundidad maxima de un array ***/\nfunction getArrayMaxDepth($input){\n if( ! canVarLoop($input) ) { return \"0\"; }\n $arrayiter = new RecursiveArrayIterator($input);\n $iteriter = new RecursiveIteratorIterator($arrayiter);\n foreach ($iteriter as $value) {\n //getDepth() start is 0, I use 0 for not iterable values\n $d = $iteriter-&gt;getDepth() + 1;\n $result[] = \"$d\";\n }\n return max( $result );\n}\n/*** IN mixed (any value),OUT (bool)true/false, CHECK if can be used by foreach ***/\n/*** Revisa si puede ser iterado con foreach ***/\nfunction canVarLoop($input) {\n return (is_array($input) || $input instanceof Traversable) ? true : false;\n}\n</code></pre>\n" }, { "answer_id": 39840810, "author": "Linguisto", "author_id": 5157563, "author_profile": "https://Stackoverflow.com/users/5157563", "pm_score": 2, "selected": false, "text": "<p>This one seems to work fine for me</p>\n\n<pre><code>&lt;?php\nfunction array_depth(array $array)\n{\n $depth = 1;\n foreach ($array as $value) {\n if (is_array($value)) {\n $depth += array_depth($value);\n break;\n }\n }\n\n return $depth;\n}\n</code></pre>\n" }, { "answer_id": 40725952, "author": "TwystO", "author_id": 1219011, "author_profile": "https://Stackoverflow.com/users/1219011", "pm_score": 3, "selected": false, "text": "<p>After taking a little bit of inspiration here and after finding this <a href=\"http://php.net/manual/en/class.recursiveiteratoriterator.php\" rel=\"noreferrer\"><strong><em>RecursiveIteratorIterator</em></strong></a> thing in PHP Documentation, I came to this solution.</p>\n\n<p>You should use this one, pretty neat :</p>\n\n<pre><code>function getArrayDepth($array) {\n $depth = 0;\n $iteIte = new RecursiveIteratorIterator(new RecursiveArrayIterator($array));\n\n foreach ($iteIte as $ite) {\n $d = $iteIte-&gt;getDepth();\n $depth = $d &gt; $depth ? $d : $depth;\n }\n\n return $depth;\n}\n</code></pre>\n\n<p>Works on both PHP5 and PHP7, hope this helps.</p>\n" }, { "answer_id": 51337703, "author": "tonix", "author_id": 3019105, "author_profile": "https://Stackoverflow.com/users/3019105", "pm_score": 0, "selected": false, "text": "<p>I would use the following code:</p>\n\n<pre><code>function maxDepth($array) {\n $iterator = new \\RecursiveIteratorIterator(new \\RecursiveArrayIterator($array), \\RecursiveIteratorIterator::CHILD_FIRST);\n $iterator-&gt;rewind();\n $maxDepth = 0;\n foreach ($iterator as $k =&gt; $v) {\n $depth = $iterator-&gt;getDepth();\n if ($depth &gt; $maxDepth) {\n $maxDepth = $depth;\n }\n }\n return $maxDepth;\n}\n</code></pre>\n" }, { "answer_id": 59994664, "author": "jspit", "author_id": 7271221, "author_profile": "https://Stackoverflow.com/users/7271221", "pm_score": 0, "selected": false, "text": "<pre><code>//Get the dimension or depth of an array\nfunction array_depth($arr)\n{\n if (!is_array($arr)) return 0;\n if (empty($arr)) return 1;\n return max(array_map(__FUNCTION__,$arr))+1;\n}\n</code></pre>\n" }, { "answer_id": 68595201, "author": "Stackoverflow", "author_id": 7180968, "author_profile": "https://Stackoverflow.com/users/7180968", "pm_score": 1, "selected": false, "text": "<p>in my solution, I evaluate dimension of ARRAY(), not contents/values:</p>\n<pre><code>function Dim_Ar($A, $i){\n if(!is_array($A))return 0;\n $t[] = 1;\n foreach($A AS $e)if(is_array($e))$t[] = Dim_Ar($e, ++ $i) + 1;\n return max($t);\n }\n\n$Q = ARRAY(); // dimension one\n$Q = ARRAY(1); // dimension one\n$Q = ARRAY(ARRAY(ARRAY()), ARRAY(1, 1, 1)); // dimension is two\n$Q = ARRAY(ARRAY()); // dimension is two\n$Q = ARRAY(1, 1, 1, ARRAY(), ARRAY(), ARRAY(1)); // dimension is two\n$Q = ARRAY(1, 2, 3, ARRAY(ARRAY(1, 1, 1))); // dimension is two\n$Q = ARRAY(ARRAY(ARRAY()), ARRAY()); // dimension is three\n$Q = ARRAY(ARRAY(ARRAY()), ARRAY()); // dimension three\n$Q = ARRAY(ARRAY(ARRAY()), ARRAY(ARRAY())); // dimension is three\n$Q = ARRAY('1', '2', '3', ARRAY('Q', 'W'), ARRAY('Q', 'W'), ARRAY('Q', 'W'), ARRAY('Q', 'W'), 'pol, y juan', 'sam, y som', '1', '2', 'OPTIONS1' =&gt; ARRAY('1', '2', '9'), 'OOO' =&gt; ARRAY('1', '2', '9'), 'OPTIONS3' =&gt; ARRAY('1', '2', '9', '1', '2', '9', '1', '2', '9', '1', '2', '9', '1', '2', '9'), '3', ARRAY('Q', 'W'), 'OPTIONS2' =&gt; ARRAY('1', '2'));\n$Q = ARRAY('1', '2', '3', '', ARRAY('Q, sam', 'W', '', '0'), 'ppppppol, y juan', 'sam, y som', '1', '2', 'OPTIONS1' =&gt; ARRAY('1', '2', 'ss, zz'), '3', 'PP' =&gt; ARRAY('Q', 'WWW', 'Q', 'BMW'), ARRAY('Q', 'YYWW'), 'OPTIONS2' =&gt; ARRAY('1', '2', '9'), ARRAY('1', '2', '3'), '33', '33', '33', ARRAY('1', '2', '3', ARRAY(1, 2)));\n\necho Dim_Ar($Q, 0);\n</code></pre>\n<p>for me is speed, and low complex</p>\n" } ]
2008/11/04
[ "https://Stackoverflow.com/questions/262891", "https://Stackoverflow.com", "https://Stackoverflow.com/users/572/" ]
A PHP array can have arrays for its elements. And those arrays can have arrays and so on and so forth. Is there a way to find out the maximum nesting that exists in a PHP array? An example would be a function that returns 1 if the initial array does not have arrays as elements, 2 if at least one element is an array, and so on.
This should do it: ``` <?php function array_depth(array $array) { $max_depth = 1; foreach ($array as $value) { if (is_array($value)) { $depth = array_depth($value) + 1; if ($depth > $max_depth) { $max_depth = $depth; } } } return $max_depth; } ?> ``` Edit: Tested it very quickly and it appears to work.
262,924
<p>In MySql's interpreter, it's very easy to dump a table to the screen along with its field names. </p> <p>There seems to be no simple way to export a table to a tab-delimted or CSV outfile <em>including</em> its column headers.</p> <p>I'm trying to do this using only SQL or the Linux command line, without writing a program in another language.</p> <p>Thank you</p>
[ { "answer_id": 263000, "author": "Vinko Vrsalovic", "author_id": 5190, "author_profile": "https://Stackoverflow.com/users/5190", "pm_score": 5, "selected": true, "text": "<p>Piping the query to the commandline client outputs a tab separated list with the column names as the first line</p>\n\n<pre><code>$ echo \"select * from surveys limit 5\" | mysql -uroot -pGandalf surveys\nphone param1 param2 param3 param4 p0 p1 p2 p3 audio4 code time\nXXXXXXXXX 2008-07-02 11:17:23 XXXXXXXX SAT - - - - - ERROR 2008-07-02 12:18:32\nXXXXXXXXX 2008-07-02 11:22:52 XXXXXXXX SAT - - - - - COLGADO 2008-07-02 12:04:29\nXXXXXXXXX 2008-07-02 11:41:29 XXXXXXXX SAT - - - - - COLGADO 2008-07-02 12:07:22\nXXXXXXXXX 2008-07-02 12:16:19 XXXXXXXX SAT 1 1 1 9 XXXXXXXXX_4.wav OK 2008-07-02 16:14:27\nXXXXXXXXX 2008-07-02 08:21:25 XXXXXXXX SAT 1 1 1 1 XXXXXXXXX_4.wav OK 2008-07-02 12:29:40\n</code></pre>\n" }, { "answer_id": 263001, "author": "Dana the Sane", "author_id": 2567, "author_profile": "https://Stackoverflow.com/users/2567", "pm_score": 1, "selected": false, "text": "<p>You can do this with the <a href=\"http://dev.mysql.com/doc/refman/5.0/en/mysqldump.html\" rel=\"nofollow noreferrer\">mysqldump</a> command. Have a look at the --tab and --xml options.</p>\n" }, { "answer_id": 9976449, "author": "cafe876", "author_id": 1308011, "author_profile": "https://Stackoverflow.com/users/1308011", "pm_score": 3, "selected": false, "text": "<p>This little script should do it:</p>\n\n<p>-- 1. choose the table and the output file here / this should be the only input</p>\n\n<pre><code>select 'mytable' into @tableName;\nselect 'c://temp/test.csv' into @outputFile;\n</code></pre>\n\n<p>-- 2. get the column names in a format that will fit the query</p>\n\n<pre><code>select group_concat(concat(\"'\",column_name, \"'\")) into @columnNames from information_schema.columns\nwhere table_name=@tableName;\n</code></pre>\n\n<p>-- 3. build the query</p>\n\n<pre><code>SET @query = CONCAT(\n\"select * from\n((SELECT \",@columnNames,\")\nUNION\n(SELECT * FROM `\",@tableName,\"`)) as a\nINTO OUTFILE '\", @outputFile, \"'\");\n</code></pre>\n\n<p>-- 4. execute the query</p>\n\n<pre><code>PREPARE stmt FROM @query;\nEXECUTE stmt;\n</code></pre>\n" }, { "answer_id": 11160933, "author": "aizquier", "author_id": 998421, "author_profile": "https://Stackoverflow.com/users/998421", "pm_score": 2, "selected": false, "text": "<p>I achieved that in this way:</p>\n\n<pre><code>echo \"select * from table\"| mysql database -B -udbuser -puser_passwd | sed s/\\\\t/,/g &gt; query_output.csv\n</code></pre>\n\n<p>The -B option of mysql separates the columns by tabs, which are converted into commas using sed. Note that the headers are generated too.</p>\n" }, { "answer_id": 11172666, "author": "Lifeboy", "author_id": 1477308, "author_profile": "https://Stackoverflow.com/users/1477308", "pm_score": 0, "selected": false, "text": "<p>I have created a procedure to automate the exporting of the contents of a larger number of tables to .csv file by using <code>SELECT ... INTO OUTFILE</code>. Please refer to the following if you have need for something like this</p>\n\n<p><a href=\"http://lifeboysays.wordpress.com/2012/06/23/mysql-how-to-export-data-to-csv-with-column-headers/\" rel=\"nofollow\">http://lifeboysays.wordpress.com/2012/06/23/mysql-how-to-export-data-to-csv-with-column-headers/</a>.</p>\n\n<p>It uses the method described by cafe876, but will work for one or a whole series of tables, plus you can set the delimiter and quote character to be used.</p>\n" }, { "answer_id": 48380146, "author": "aiffin", "author_id": 7539689, "author_profile": "https://Stackoverflow.com/users/7539689", "pm_score": 0, "selected": false, "text": "<p><strong>I used the above command and modified according to my requirement.<br>\nI needed to get passwords column from the wordpress mysql database in a text file , to do that i used the following below command</strong></p>\n\n<pre><code>echo \"select user_pass from wp_users\"| mysql -uroot -proot wp_database &gt; passwordList.txt\n</code></pre>\n" } ]
2008/11/04
[ "https://Stackoverflow.com/questions/262924", "https://Stackoverflow.com", "https://Stackoverflow.com/users/23929/" ]
In MySql's interpreter, it's very easy to dump a table to the screen along with its field names. There seems to be no simple way to export a table to a tab-delimted or CSV outfile *including* its column headers. I'm trying to do this using only SQL or the Linux command line, without writing a program in another language. Thank you
Piping the query to the commandline client outputs a tab separated list with the column names as the first line ``` $ echo "select * from surveys limit 5" | mysql -uroot -pGandalf surveys phone param1 param2 param3 param4 p0 p1 p2 p3 audio4 code time XXXXXXXXX 2008-07-02 11:17:23 XXXXXXXX SAT - - - - - ERROR 2008-07-02 12:18:32 XXXXXXXXX 2008-07-02 11:22:52 XXXXXXXX SAT - - - - - COLGADO 2008-07-02 12:04:29 XXXXXXXXX 2008-07-02 11:41:29 XXXXXXXX SAT - - - - - COLGADO 2008-07-02 12:07:22 XXXXXXXXX 2008-07-02 12:16:19 XXXXXXXX SAT 1 1 1 9 XXXXXXXXX_4.wav OK 2008-07-02 16:14:27 XXXXXXXXX 2008-07-02 08:21:25 XXXXXXXX SAT 1 1 1 1 XXXXXXXXX_4.wav OK 2008-07-02 12:29:40 ```
262,940
<p>I'm trying to convert my sites from CF8 to openBD. I have a cfloop in a site that loops over a date range.</p> <p>In essence, I want to insert a new record into the db for every 2 weeks (step) of a date range (from and to)</p> <p>my loop looks like this... </p> <pre><code>&lt;cfloop from = "#form.startDate#" to = "#form.endDate#" index = "i" step = "#theStep#" &gt; </code></pre> <p>This works perfectly in CF8, in openBD, I get this error... Data not supported: value [11/05/09] is not a number</p> <p>Any ideas of a work around?</p> <p>Thx</p>
[ { "answer_id": 263254, "author": "Ben Doom", "author_id": 12267, "author_profile": "https://Stackoverflow.com/users/12267", "pm_score": 0, "selected": false, "text": "<p>I can't see your code, but here's my first suggestion:</p>\n\n<pre><code>&lt;cfset current = [your begin date]&gt;\n&lt;cfloop condition = \"datecompare(enddate, current)\"&gt;\n [do stuff]\n &lt;cfset current = dateadd('d', 14, current)&gt;\n&lt;/cfloop&gt;\n</code></pre>\n\n<p>HTH.</p>\n" }, { "answer_id": 263808, "author": "Peter Boughton", "author_id": 9360, "author_profile": "https://Stackoverflow.com/users/9360", "pm_score": 0, "selected": false, "text": "<p>As Ben says, your code isn't there - you need to use the 101 010 icon to create a code block for it.</p>\n\n<p>Here's another solution which should work:</p>\n\n<pre><code>&lt;cfloop index=\"Current\" from=\"#parseDateTime(StartDate)#\" to=\"#parseDateTime(EndDate)#\" step=\"14\"&gt;\n [do stuff]\n&lt;/cfloop&gt;\n</code></pre>\n" }, { "answer_id": 266843, "author": "Tomalak", "author_id": 18771, "author_profile": "https://Stackoverflow.com/users/18771", "pm_score": 1, "selected": false, "text": "<p>Your problem lies in not checking for ambiguous locale dependent date strings from your FORM.</p>\n\n<p>A more robust version would be this:</p>\n\n<pre><code>&lt;cfset SetLocale(\"English (US)\")&gt; &lt;!--- set expected input locale here ---&gt;\n\n&lt;cfif LSIsDate(form.startDate) and LSIsDate(form.endDate)&gt;\n &lt;cfset theStep = 14&gt;\n\n &lt;cfloop \n from = \"#LSParseDate(form.startDate)#\" \n to = \"#LSParseDate(form.endDate)#\" \n index = \"i\" \n step = \"#theStep#\"\n &gt;\n &lt;!--- do stuff ---&gt;\n &lt;/cfloop&gt;\n&lt;cfelse&gt;\n &lt;!--- output some error message ---&gt;\n&lt;/cfif&gt;\n</code></pre>\n\n<p>It would be helpful to restrict people to entering unambiguous date formats into the FORM, like \"yyyy-mm-dd\".</p>\n\n<p>The \"value is not a number\" error comes from the fact that the loop still goes over numbers, even if you feed it dates. It uses a numerical representation of these dates then, but they must be <em>valid</em> and intelligible for that to work. </p>\n" } ]
2008/11/04
[ "https://Stackoverflow.com/questions/262940", "https://Stackoverflow.com", "https://Stackoverflow.com/users/26121/" ]
I'm trying to convert my sites from CF8 to openBD. I have a cfloop in a site that loops over a date range. In essence, I want to insert a new record into the db for every 2 weeks (step) of a date range (from and to) my loop looks like this... ``` <cfloop from = "#form.startDate#" to = "#form.endDate#" index = "i" step = "#theStep#" > ``` This works perfectly in CF8, in openBD, I get this error... Data not supported: value [11/05/09] is not a number Any ideas of a work around? Thx
Your problem lies in not checking for ambiguous locale dependent date strings from your FORM. A more robust version would be this: ``` <cfset SetLocale("English (US)")> <!--- set expected input locale here ---> <cfif LSIsDate(form.startDate) and LSIsDate(form.endDate)> <cfset theStep = 14> <cfloop from = "#LSParseDate(form.startDate)#" to = "#LSParseDate(form.endDate)#" index = "i" step = "#theStep#" > <!--- do stuff ---> </cfloop> <cfelse> <!--- output some error message ---> </cfif> ``` It would be helpful to restrict people to entering unambiguous date formats into the FORM, like "yyyy-mm-dd". The "value is not a number" error comes from the fact that the loop still goes over numbers, even if you feed it dates. It uses a numerical representation of these dates then, but they must be *valid* and intelligible for that to work.
262,949
<p>I have a RegEx that is working for me but I don't know WHY it is working for me. I'll explain.</p> <pre><code>RegEx: \s*&lt;in.*="(&lt;?.*?&gt;)"\s*/&gt;\s* </code></pre> <p><br> Text it finds (it finds the white-space before and after the input tag):</p> <pre><code>&lt;td class="style9"&gt; &lt;input name="guarantor4" id="guarantor4" size="50" type="text" tabindex="10" value="&lt;?php echo $data[guarantor4]; ?&gt;" /&gt; &lt;/td&gt; &lt;/tr&gt; </code></pre> <p><br>The part I don't understand:</p> <pre><code>&lt;in.*=" &lt;--- As I understand it, this should only find up to the first =" as in it should only find &lt;input name=" It actually finds: &lt;input name="guarantor4" id="guarantor4" size="50" type="text" tabindex="10" value=" which happened to be what I was trying to do. </code></pre> <p>What am I not understanding about this RegEx?</p>
[ { "answer_id": 262959, "author": "eyelidlessness", "author_id": 17964, "author_profile": "https://Stackoverflow.com/users/17964", "pm_score": 3, "selected": false, "text": "<p><code>.*</code> is greedy. You want <code>.*?</code> to find up to only the first <code>=</code>.</p>\n" }, { "answer_id": 262964, "author": "Stavros Korokithakis", "author_id": 28196, "author_profile": "https://Stackoverflow.com/users/28196", "pm_score": 2, "selected": false, "text": "<p>.* is greedy, so it'll find up to the last =. If you want it non-greedy, add a question mark, like so: .*?</p>\n" }, { "answer_id": 262968, "author": "Kent Fredric", "author_id": 15614, "author_profile": "https://Stackoverflow.com/users/15614", "pm_score": 4, "selected": true, "text": "<p>You appear to be using 'greedy' matching. </p>\n\n<p>Greedy matching says \"eat as much as possible to make this work\" </p>\n\n<p>try with </p>\n\n<pre><code>&lt;in[^=]*= \n</code></pre>\n\n<p>for starters, that will stop it matching the \"=\" as part of \".*\" </p>\n\n<p>but in future, you might want to read up on the </p>\n\n<pre><code>.*? \n</code></pre>\n\n<p>and</p>\n\n<pre><code>.+?\n</code></pre>\n\n<p>notation, which stops at the first possible condtion that matches instead of the last. </p>\n\n<p>The use of 'non-greedy' syntax would be better if you were trying to only stop when you saw <strong>TWO</strong> characters, </p>\n\n<p>ie: </p>\n\n<pre><code>&lt;in.*?=id\n</code></pre>\n\n<p>which would stop on the first '=id' regardless of whether or not there are '=' in between. </p>\n" }, { "answer_id": 262991, "author": "Ross Patterson", "author_id": 241753, "author_profile": "https://Stackoverflow.com/users/241753", "pm_score": 2, "selected": false, "text": "<blockquote>\n <p>As I understand it, this should only\n find up to the first =\" as in it\n should only find &lt;input name=\"</p>\n</blockquote>\n\n<p>You don't say what language you're writing in, but almost all regular expression systems are \"greedy matchers\" - that is, they match the longest possible substring of the input. In your case, that means everything everying from the start of the input tag to the last equal-quote sequence.</p>\n\n<p>Most regex systems have a way to specify that the patter only match the shortest possible substring, not the longest - \"non-greedy matching\".</p>\n\n<p>As an aside, don't assume the first parameter will be name= unless you have full control over the construction of the input. Both HTML and XML allow attributes to be specified in any order.</p>\n" }, { "answer_id": 60834067, "author": "regeXGuru4", "author_id": 13116827, "author_profile": "https://Stackoverflow.com/users/13116827", "pm_score": 2, "selected": false, "text": "<p>Your greedy approach is causing confusion. You want <code>.*?</code>\nConsider the input <code>101000000000100</code>.</p>\n\n<p>Using <code>1.*1</code>, <code>*</code> is greedy - it will match all the way to the end, and then backtrack until it can match <code>1</code>, leaving you with <code>1010000000001</code>.\n<code>.*?</code> is non-greedy. <code>*</code> will match nothing, but then will try to match extra characters until it matches <code>1</code>, eventually matching <code>101</code>.</p>\n" } ]
2008/11/04
[ "https://Stackoverflow.com/questions/262949", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16292/" ]
I have a RegEx that is working for me but I don't know WHY it is working for me. I'll explain. ``` RegEx: \s*<in.*="(<?.*?>)"\s*/>\s* ``` Text it finds (it finds the white-space before and after the input tag): ``` <td class="style9"> <input name="guarantor4" id="guarantor4" size="50" type="text" tabindex="10" value="<?php echo $data[guarantor4]; ?>" /> </td> </tr> ``` The part I don't understand: ``` <in.*=" <--- As I understand it, this should only find up to the first =" as in it should only find <input name=" It actually finds: <input name="guarantor4" id="guarantor4" size="50" type="text" tabindex="10" value=" which happened to be what I was trying to do. ``` What am I not understanding about this RegEx?
You appear to be using 'greedy' matching. Greedy matching says "eat as much as possible to make this work" try with ``` <in[^=]*= ``` for starters, that will stop it matching the "=" as part of ".\*" but in future, you might want to read up on the ``` .*? ``` and ``` .+? ``` notation, which stops at the first possible condtion that matches instead of the last. The use of 'non-greedy' syntax would be better if you were trying to only stop when you saw **TWO** characters, ie: ``` <in.*?=id ``` which would stop on the first '=id' regardless of whether or not there are '=' in between.